logicsrc/packages/openprd/src/tasks.ts
Anthony Ettinger 296775e003
feat(openprd): implement the OpenPRD standard — engine, CLI, conformance bundle (#100)
OpenPRD has existed as a document (docs/openprd.md), a front-matter schema, a
template, and this repo's prd/ collection. Nothing enforced it. This adds the
reference implementation.

@logicsrc/openprd
  - parser: front-matter + the eight `##` sections + numbered requirements.
    `###` stays content so a long Requirements section can be organized, and
    headings or R#-shaped lines inside code fences are ignored
  - validation splits the standard's four conformance rules (filename,
    front-matter schema, id-matches-prefix, eight sections in order) from
    lint (empty section, missing priority tag, numbering gaps, duplicate R#,
    date order, one-sided supersession, stale index). Conformance failures are
    errors; --strict promotes the rest. Stable codes, file, line, hint
  - collection rules the per-file view cannot see: unique ids, monotonic
    numbering with no gaps, 0000 reserved for the template, cross-references
    that resolve
  - lifecycle enforced rather than advisory: Draft cannot jump to Final,
    terminal statuses do not resume, Superseded must name its replacement
  - deterministic index generation, so `prd index` is idempotent and CI can
    diff it
  - front-matter rewriting that leaves the body byte-identical
  - the optional LogicSRC task bridge the standard describes: each R# becomes
    one logicsrc.task, validated against logicsrc-task.schema.json before it
    is emitted; creator DID derived from the author email

CLI: logicsrc prd init|new|list|show|validate|lint|index|status|next|tasks|
export. Exit codes stable for CI (0 ok, 1 invalid, 2 usage, 3 not found).

Conformance bundle: packages/schemas/fixtures/openprd/ — 6 documents that must
validate and 12 that must fail, each naming the error code it must produce.
Several rules depend on the filename, so every fixture records the name it is
validated as.

Docs: an Implementation section in docs/openprd.md (CLI, validation model,
task bridge, conformance bundle), the spec added to the site's docs surface,
nav and sitemap entries, and a README section.

Verification: 76 new tests; full monorepo build and all 451 workspace tests
pass. The suite dogfoods this repo — prd/ validates with zero errors and zero
warnings, the embedded template is byte-identical to docs/openprd/0000-
template.md, and all 210 requirements in PRD 0001 map to schema-valid tasks.
prd/README.md is regenerated by the tool it now ships.

Refs: docs/openprd.md

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 04:11:07 -07:00

156 lines
4.8 KiB
TypeScript

import { validate as validateSchema } from "@logicsrc/validators";
import type { PrdDocument, Priority, Requirement } from "./types.js";
/**
* The optional LogicSRC bridge described in docs/openprd.md:
*
* "a PRD's Requirements map cleanly onto LogicSRC task documents
* (each R# → one task), and owner/repo reuse LogicSRC identity and repo
* conventions. That bridge is optional and lives in tooling."
*
* So it lives here, in tooling — the standard itself stays a file format with
* no service behind it.
*/
export interface TaskDocument {
type: "logicsrc.task";
version: string;
title: string;
description: string;
board: string;
creator_did: string;
status: string;
skills?: string[];
github_repo?: string;
external_links?: string[];
logicsrc_version?: string;
}
export interface ToTasksOptions {
/** LogicSRC DID. Derived from the first author when omitted. */
creator?: string;
/** Board path. Defaults to `/prd/<id>`. */
board?: string;
status?: string;
/** Only convert requirements at these priorities. */
priorities?: Priority[];
}
export interface ToTasksResult {
tasks: TaskDocument[];
skipped: Array<{ requirement: string; reason: string }>;
}
/**
* LogicSRC DIDs look like `name.namespace`. An author email maps onto that
* shape predictably: `anthony@profullstack.com` → `anthony.profullstack`.
*/
export function deriveCreatorDid(author: string | undefined): string {
if (!author) return "openprd.local";
const trimmed = author.trim();
if (/^[a-z0-9][a-z0-9._-]*\.[a-z0-9][a-z0-9._-]*$/.test(trimmed) && !trimmed.includes("@")) {
return trimmed;
}
const at = trimmed.indexOf("@");
if (at > 0) {
const local = sanitize(trimmed.slice(0, at));
const domain = trimmed.slice(at + 1);
const org = sanitize(domain.split(".")[0] ?? "local");
if (local && org) return `${local}.${org}`;
}
const fallback = sanitize(trimmed);
return fallback ? `${fallback}.local` : "openprd.local";
}
function sanitize(value: string): string {
return value
.toLowerCase()
.replace(/[^a-z0-9._-]/g, "-")
.replace(/^[^a-z0-9]+/, "")
.replace(/[^a-z0-9]+$/, "");
}
export function prdToTasks(doc: PrdDocument, options: ToTasksOptions = {}): ToTasksResult {
const fm = doc.frontMatter;
const id = fm.id ?? doc.filePrefix ?? "0000";
const creator = options.creator ?? deriveCreatorDid(fm.owner ?? fm.authors?.[0]);
const board = options.board ?? `/prd/${id}`;
const tasks: TaskDocument[] = [];
const skipped: ToTasksResult["skipped"] = [];
for (const requirement of doc.requirements) {
if (options.priorities && (!requirement.priority || !options.priorities.includes(requirement.priority))) {
skipped.push({
requirement: requirement.id,
reason: `priority ${requirement.priority ?? "none"} not in the requested set`
});
continue;
}
if (!requirement.text) {
skipped.push({ requirement: requirement.id, reason: "requirement has no text" });
continue;
}
tasks.push(toTask(doc, requirement, { creator, board, status: options.status ?? "draft", id }));
}
return { tasks, skipped };
}
function toTask(
doc: PrdDocument,
requirement: Requirement,
ctx: { creator: string; board: string; status: string; id: string }
): TaskDocument {
const fm = doc.frontMatter;
const plain = stripMarkdown(requirement.text);
const prefix = `${ctx.id} ${requirement.id}`;
const title = truncate(`${prefix}: ${plain}`, 160);
const task: TaskDocument = {
type: "logicsrc.task",
version: "0.1",
title,
description: `${plain}\n\nFrom OpenPRD ${ctx.id} "${fm.title}" (${doc.file}, line ${requirement.line}).`,
board: ctx.board,
creator_did: ctx.creator,
status: ctx.status
};
if (requirement.priority) task.skills = [requirement.priority.toLowerCase()];
if (fm.repo) task.github_repo = fm.repo;
const links = [fm.discussion, fm.implementation].filter((link): link is string => Boolean(link));
if (links.length) task.external_links = links;
return task;
}
function stripMarkdown(text: string): string {
return text
.replace(/\*\*(.*?)\*\*/g, "$1")
.replace(/`([^`]*)`/g, "$1")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.trim();
}
function truncate(value: string, max: number): string {
return value.length <= max ? value : `${value.slice(0, max - 1).trimEnd()}`;
}
/** Validate emitted tasks against the LogicSRC task schema. */
export function validateTasks(tasks: TaskDocument[]): Array<{ index: number; errors: string[] }> {
const problems: Array<{ index: number; errors: string[] }> = [];
tasks.forEach((task, index) => {
const result = validateSchema("task", task);
if (result.ok) return;
problems.push({
index,
errors: result.errors.map((error) => `${error.instancePath || "/"} ${error.message ?? "invalid"}`)
});
});
return problems;
}