@gonrocca/zero-pi 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,6 +46,12 @@ Run it with the `/forge <feature>` prompt. The orchestrator drives phase order
46
46
  and enforces a hard build/veredicto iteration cap. Each phase has its own prompt
47
47
  under `prompts/phases/` so it can be delegated to a dedicated sub-agent.
48
48
 
49
+ Besides the explicit `/forge` command, an SDD run can also be started from
50
+ natural language: describe the work and signal SDD intent — e.g. "hacelo con
51
+ sdd" or "usá el pipeline" — and the `sdd-routing` skill routes the request into
52
+ `/forge` for you. It triggers only on a clear signal phrase and stays out of the
53
+ way for ordinary requests; `/forge` remains the primary, explicit entry point.
54
+
49
55
  **Review Workload Forecast** — the plan phase keeps tasks reviewable. Every
50
56
  planned task carries a `review: ~N changed lines` estimate, and `tasks.md` gains
51
57
  a `## Review Workload` section with the per-task estimates and a bold run total.
@@ -80,6 +86,47 @@ correction rounds, and the gotchas — under `topic_key: zero-run/<slug>`. The
80
86
  next run on related work starts from what the last one learned. With `--no-mcp`
81
87
  the loop degrades silently.
82
88
 
89
+ ### Canonical specs & `/zero-sync`
90
+
91
+ zero keeps a **canonical, project-wide spec store** that accumulates accepted
92
+ requirements across runs, so each `/forge` run builds on the last instead of
93
+ starting from a blank spec.
94
+
95
+ **The canonical store — `.sdd/specs/requirements.md`.** A single flat markdown
96
+ file: a `# ` title followed by `### REQ: <stable-unique-name>` requirement
97
+ blocks. It is the project's source of truth. The `plan` phase reads it as the
98
+ baseline; a fresh project has no store yet, and that absence simply means an
99
+ empty store.
100
+
101
+ **The granular plan artifacts.** Every run's `plan` phase writes four files
102
+ into `.sdd/<slug>/`:
103
+
104
+ - `proposal.md` — the change intent: scope and rationale, in prose.
105
+ - `spec.md` — the **delta** against the canonical store, never a full spec. Up
106
+ to three `H2` sections — `## ADDED`, `## MODIFIED`, `## REMOVED` — each
107
+ holding `### REQ:` blocks. `## MODIFIED` carries the complete updated text of
108
+ an existing block (not a diff); `## REMOVED` needs only the name line.
109
+ - `design.md` — how it is built.
110
+ - `tasks.md` — the ordered task list with its `## Review Workload` section.
111
+
112
+ **`/zero-sync` — folding the delta into the store.** `/zero-sync <slug>` is a
113
+ real pi command — a deterministic, unit-tested merge, not an LLM prompt — that
114
+ reads the store and the run's delta `spec.md`, applies the ADDED/MODIFIED/REMOVED
115
+ changes, and writes the store atomically. Guardrails reject a bad delta before
116
+ anything is written: a duplicate name, an ADDED collision with an existing
117
+ block, a MODIFIED or REMOVED of a missing block, or malformed input. On a
118
+ guardrail failure it writes nothing and reports the offending requirement; the
119
+ store is never left half-merged. After a `pasa` verdict the SDD orchestrator
120
+ invokes `/zero-sync <slug>` automatically — a `corregir`, `replantear`, or
121
+ cap-reached run never syncs.
122
+
123
+ **The archive — `.sdd/archive/`.** Each successful sync appends a dated,
124
+ slug-named entry `.sdd/archive/<YYYY-MM-DD>-<slug>/` containing a copy of the
125
+ run's `proposal.md` and `spec.md` plus a `sync.md` report listing every added,
126
+ modified, and removed requirement. The archive is append-only — a new entry
127
+ never rewrites a prior one — so it is a full audit trail of how the canonical
128
+ store evolved.
129
+
83
130
  ### Adaptive model profiles
84
131
 
85
132
  zero learns which model fits each SDD phase from your own run history and can
@@ -0,0 +1,286 @@
1
+ // zero-pi — the /zero-sync command.
2
+ //
3
+ // A real pi command — a code handler, not an LLM prompt — that folds a
4
+ // `/forge` run's delta `spec.md` into the project's canonical spec store and
5
+ // archives the change. It is deterministic: every parsing, guardrail, and
6
+ // merge decision lives in the pure-logic `spec-merge.ts`; this file only reads
7
+ // and writes the filesystem and reports the result.
8
+ //
9
+ // /zero-sync canonical-specs sync the named run's delta into the store
10
+ // /zero-sync resolve the single candidate run, or ask
11
+ //
12
+ // The SDD orchestrator invokes `/zero-sync <slug>` after a `pasa` verdict. On a
13
+ // guardrail failure the command writes NOTHING and reports the failing
14
+ // requirement name(s); on success it writes the store atomically (`.tmp` +
15
+ // `rename`) and appends an entry to `.sdd/archive/`.
16
+ //
17
+ // All decisions live in `spec-merge.ts`; the package stays dependency-free:
18
+ // `node:fs`/`node:os`/`node:path` only, plus minimal local interfaces for the
19
+ // pi API. The whole handler is wrapped in a swallowing `try/catch`, exactly
20
+ // like `autotune-extension.ts` — a failure must never break a pi session.
21
+
22
+ import {
23
+ copyFileSync,
24
+ existsSync,
25
+ mkdirSync,
26
+ readdirSync,
27
+ readFileSync,
28
+ renameSync,
29
+ writeFileSync,
30
+ } from "node:fs";
31
+ import { join } from "node:path";
32
+
33
+ import { isEmptyDelta, mergeDelta, parseDelta, type MergeSummary } from "./spec-merge.ts";
34
+
35
+ /** The canonical store path, relative to the project root. */
36
+ const STORE_DIR = join(".sdd", "specs");
37
+ const STORE_FILE = join(STORE_DIR, "requirements.md");
38
+
39
+ /** The per-run artifacts directory root. */
40
+ const SDD_DIR = ".sdd";
41
+
42
+ /** The audit-trail archive root. */
43
+ const ARCHIVE_DIR = join(".sdd", "archive");
44
+
45
+ /** Read a UTF-8 file, returning `null` when it is absent or unreadable. */
46
+ function readFileOrNull(path: string): string | null {
47
+ try {
48
+ return readFileSync(path, "utf8");
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ /** Today's date as `YYYY-MM-DD`, for the archive directory name. */
55
+ function todayStamp(): string {
56
+ return new Date().toISOString().slice(0, 10);
57
+ }
58
+
59
+ /**
60
+ * Resolve the run slug to sync.
61
+ *
62
+ * The orchestrator always passes an explicit slug, so this is a convenience
63
+ * path. With an explicit arg it is used verbatim. With no arg it lists the
64
+ * `.sdd/` subdirectories that carry a `spec.md` (sync candidates) and, when
65
+ * exactly one exists, returns it; otherwise it returns `null` so the caller
66
+ * can ask or report.
67
+ */
68
+ function resolveSlug(arg: string): string | null {
69
+ const explicit = arg.trim();
70
+ if (explicit !== "") return explicit;
71
+
72
+ let entries: string[];
73
+ try {
74
+ entries = readdirSync(SDD_DIR, { withFileTypes: true })
75
+ .filter((e) => e.isDirectory() && e.name !== "specs" && e.name !== "archive")
76
+ .map((e) => e.name);
77
+ } catch {
78
+ return null;
79
+ }
80
+
81
+ const candidates = entries.filter((name) => existsSync(join(SDD_DIR, name, "spec.md")));
82
+ return candidates.length === 1 ? candidates[0] : null;
83
+ }
84
+
85
+ /**
86
+ * Pick a unique archive directory for `<date>-<slug>`.
87
+ *
88
+ * The archive is append-only: a new entry never rewrites a prior one. When a
89
+ * slug syncs twice on the same date the bare `<date>-<slug>` is already taken,
90
+ * so a numeric `-2`, `-3` … suffix is appended until the name is free.
91
+ */
92
+ function uniqueArchiveDir(date: string, slug: string): string {
93
+ const base = `${date}-${slug}`;
94
+ let dir = join(ARCHIVE_DIR, base);
95
+ let n = 2;
96
+ while (existsSync(dir)) {
97
+ dir = join(ARCHIVE_DIR, `${base}-${n}`);
98
+ n += 1;
99
+ }
100
+ return dir;
101
+ }
102
+
103
+ /** Render a `MergeSummary` as the archive `sync.md` audit report. */
104
+ function renderSyncReport(slug: string, date: string, summary: MergeSummary): string {
105
+ const section = (title: string, names: string[]): string =>
106
+ names.length === 0
107
+ ? `## ${title}\n\n(none)\n`
108
+ : `## ${title}\n\n${names.map((n) => `- ${n}`).join("\n")}\n`;
109
+
110
+ return [
111
+ `# Spec sync — ${slug}`,
112
+ "",
113
+ `Date: ${date}`,
114
+ "",
115
+ section("Added", summary.added),
116
+ section("Modified", summary.modified),
117
+ section("Removed", summary.removed),
118
+ ].join("\n");
119
+ }
120
+
121
+ /** Render the human-facing one-shot report of a `MergeSummary`. */
122
+ function describeSummary(summary: MergeSummary): string {
123
+ const lines: string[] = [];
124
+ if (summary.added.length > 0) lines.push(` added: ${summary.added.join(", ")}`);
125
+ if (summary.modified.length > 0) {
126
+ lines.push(` modified: ${summary.modified.join(", ")} (replaces existing spec text)`);
127
+ }
128
+ if (summary.removed.length > 0) {
129
+ lines.push(` removed: ${summary.removed.join(", ")} (deletes from the store)`);
130
+ }
131
+ return lines.join("\n");
132
+ }
133
+
134
+ /** The slice of pi's extension API this command uses. */
135
+ interface PiUI {
136
+ notify(message: string, type?: "info" | "warning" | "error"): void;
137
+ }
138
+ interface PiCommandContext {
139
+ ui: PiUI;
140
+ }
141
+ interface PiExtensionAPI {
142
+ registerCommand(
143
+ name: string,
144
+ options: {
145
+ description?: string;
146
+ handler: (args: string, ctx: PiCommandContext) => Promise<void> | void;
147
+ },
148
+ ): void;
149
+ }
150
+
151
+ /**
152
+ * The `/zero-sync` handler — folds a run's delta into the canonical store.
153
+ *
154
+ * Wrapped in a swallowing `try/catch` so a failure can never break a pi
155
+ * session. On a guardrail error or any read failure it writes nothing and
156
+ * reports the problem; only a clean `mergeDelta` result reaches the atomic
157
+ * store write and the archive step.
158
+ */
159
+ function runSync(args: string, ctx: PiCommandContext): void {
160
+ const notify = (message: string, type?: "info" | "warning" | "error"): void => {
161
+ try {
162
+ ctx.ui.notify(message, type);
163
+ } catch {
164
+ // A notification failure must not break the session.
165
+ }
166
+ };
167
+
168
+ const slug = resolveSlug(args);
169
+ if (slug === null) {
170
+ notify(
171
+ "zero-sync: no run slug given and no single sync candidate found — " +
172
+ "run /zero-sync <slug> (the slug of the run's .sdd/<slug>/ directory)",
173
+ "warning",
174
+ );
175
+ return;
176
+ }
177
+
178
+ const deltaPath = join(SDD_DIR, slug, "spec.md");
179
+ const deltaText = readFileOrNull(deltaPath);
180
+ if (deltaText === null) {
181
+ // A legacy run produced no delta `spec.md` — nothing to sync. This is not
182
+ // an error: legacy runs finish in legacy mode (additive design).
183
+ notify(
184
+ `zero-sync: ${deltaPath} not found — this run produced no delta spec.md, nothing to sync`,
185
+ "warning",
186
+ );
187
+ return;
188
+ }
189
+
190
+ // An empty delta (no blocks in any section) is valid — report and stop
191
+ // before touching the store.
192
+ if (isEmptyDelta(parseDelta(deltaText))) {
193
+ notify(`zero-sync: empty delta in ${deltaPath} — nothing to sync, store left untouched`, "info");
194
+ return;
195
+ }
196
+
197
+ // The store is absent on a fresh project — `mergeDelta` treats "" as the
198
+ // empty store, so an all-ADDED delta bootstraps it.
199
+ const storeText = readFileOrNull(STORE_FILE) ?? "";
200
+
201
+ const result = mergeDelta(storeText, deltaText);
202
+ if (!result.ok) {
203
+ // Guardrail failure — write NOTHING. The `pasa` verdict still stands, but
204
+ // the store is flagged out of sync for a manual fix.
205
+ const detail = result.errors.map((e) => ` - [${e.kind}] ${e.message}`).join("\n");
206
+ notify(
207
+ `zero-sync: store NOT updated — the delta has guardrail errors:\n${detail}`,
208
+ "error",
209
+ );
210
+ return;
211
+ }
212
+
213
+ // Success — write the store atomically: `.tmp` then `rename`. `mkdir -p`
214
+ // `.sdd/specs/` so a fresh project gets its first store file.
215
+ try {
216
+ mkdirSync(STORE_DIR, { recursive: true });
217
+ const tmp = `${STORE_FILE}.tmp`;
218
+ writeFileSync(tmp, result.store, "utf8");
219
+ renameSync(tmp, STORE_FILE);
220
+ } catch (err) {
221
+ notify(
222
+ `zero-sync: failed to write the store at ${STORE_FILE}: ${
223
+ err instanceof Error ? err.message : String(err)
224
+ }`,
225
+ "error",
226
+ );
227
+ return;
228
+ }
229
+
230
+ // Archive step. The store is already the source of truth; an archive failure
231
+ // here does NOT revert the merge — it is reported so the gap is visible.
232
+ const date = todayStamp();
233
+ let archiveNote = "";
234
+ try {
235
+ const archiveDir = uniqueArchiveDir(date, slug);
236
+ mkdirSync(archiveDir, { recursive: true });
237
+
238
+ for (const name of ["proposal.md", "spec.md"]) {
239
+ const src = join(SDD_DIR, slug, name);
240
+ if (existsSync(src)) copyFileSync(src, join(archiveDir, name));
241
+ }
242
+ writeFileSync(join(archiveDir, "sync.md"), renderSyncReport(slug, date, result.summary), "utf8");
243
+ archiveNote = `archived to ${archiveDir}`;
244
+ } catch (err) {
245
+ archiveNote = `WARNING: store updated but archive step failed: ${
246
+ err instanceof Error ? err.message : String(err)
247
+ }`;
248
+ }
249
+
250
+ const detail = describeSummary(result.summary);
251
+ notify(
252
+ `zero-sync: canonical store updated (${STORE_FILE})\n${detail}\n${archiveNote}`,
253
+ "info",
254
+ );
255
+ }
256
+
257
+ /**
258
+ * The pi extension entry point — registers the `/zero-sync` command.
259
+ *
260
+ * Called with no or an invalid `pi`, it no-ops cleanly. The handler body is
261
+ * wrapped again in a swallowing `try/catch` so neither registration nor a
262
+ * later failure can break a pi session.
263
+ */
264
+ export default function register(pi?: PiExtensionAPI): void {
265
+ if (!pi || typeof pi.registerCommand !== "function") return;
266
+
267
+ pi.registerCommand("zero-sync", {
268
+ description:
269
+ "Fold a /forge run's delta spec.md into the canonical .sdd/specs/ store — /zero-sync <slug>",
270
+ handler: (args: string, ctx: PiCommandContext): void => {
271
+ try {
272
+ if (!ctx || !ctx.ui || typeof ctx.ui.notify !== "function") return;
273
+ runSync(args, ctx);
274
+ } catch (err) {
275
+ try {
276
+ ctx.ui.notify(
277
+ `zero-sync: ${err instanceof Error ? err.message : String(err)}`,
278
+ "error",
279
+ );
280
+ } catch {
281
+ // A notification failure must never break a pi session.
282
+ }
283
+ }
284
+ },
285
+ });
286
+ }
@@ -0,0 +1,373 @@
1
+ // zero-pi — canonical spec store delta-merge engine, pure-logic module.
2
+ //
3
+ // zero keeps a project-wide canonical spec store under `.sdd/specs/`. Every
4
+ // `/forge` run produces a *delta* (`.sdd/<slug>/spec.md`) and, once the run
5
+ // reaches a `pasa` verdict, the delta is folded into the store. The merge
6
+ // *must* be deterministic and reproducible (the same delta against the same
7
+ // store always yields the same result) — so every parsing, guardrail, and
8
+ // merge decision lives here in plain, dependency-free TypeScript, exactly like
9
+ // `autotune.ts`. The pi wiring lives in `spec-merge-extension.ts`.
10
+ //
11
+ // This file has no pi imports, no filesystem access, and no side-effecting
12
+ // top-level code: parsing and merging are pure string work. It never throws on
13
+ // malformed input — a bad emission degrades to a surfaced `MergeError`, never
14
+ // a corrupted store.
15
+
16
+ /** One named requirement: stable name + raw body text (criteria included). */
17
+ export interface RequirementBlock {
18
+ name: string;
19
+ /** Verbatim block body, trimmed; `""` allowed for a REMOVED entry. */
20
+ body: string;
21
+ }
22
+
23
+ /** A parsed delta — three buckets, any may be empty. */
24
+ export interface SpecDelta {
25
+ added: RequirementBlock[];
26
+ modified: RequirementBlock[];
27
+ removed: RequirementBlock[];
28
+ }
29
+
30
+ /** A guardrail violation. `kind` drives the human message. */
31
+ export interface MergeError {
32
+ kind:
33
+ | "duplicate-in-delta" // same name twice across/within delta sections
34
+ | "added-name-collision" // ADDED name already in the store
35
+ | "modified-missing" // MODIFIED names a block absent from the store
36
+ | "removed-missing" // REMOVED names a block absent from the store
37
+ | "parse-error"; // malformed store or delta input
38
+ /** Offending requirement name (`""` for a `parse-error`). */
39
+ name: string;
40
+ /** Ready-to-surface explanation. */
41
+ message: string;
42
+ }
43
+
44
+ /** What a successful merge changed — drives the sync report. */
45
+ export interface MergeSummary {
46
+ added: string[]; // names appended
47
+ modified: string[]; // names replaced
48
+ removed: string[]; // names deleted
49
+ }
50
+
51
+ /** Result of a merge attempt: either the new store text, or the errors. */
52
+ export type MergeResult =
53
+ | { ok: true; store: string; summary: MergeSummary }
54
+ | { ok: false; errors: MergeError[] };
55
+
56
+ /** The pinned `# ` title line of `.sdd/specs/requirements.md`. A stable title
57
+ * keeps `renderStore` ↔ `parseStore` a clean round-trip. */
58
+ export const STORE_TITLE = "Canonical specs";
59
+
60
+ /** Matches a requirement-block header: `### REQ: <name>`. The name is
61
+ * everything after `REQ:`, captured for trimming by the caller. */
62
+ const REQ_HEADER = /^###\s+REQ:\s*(.*)$/;
63
+
64
+ /** Matches a delta section header: `## ADDED` / `## MODIFIED` / `## REMOVED`
65
+ * (case-insensitive on the keyword). */
66
+ const SECTION_HEADER = /^##\s+(ADDED|MODIFIED|REMOVED)\s*$/i;
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // Parsing
70
+ // ---------------------------------------------------------------------------
71
+
72
+ /**
73
+ * Split a run of text lines into `### REQ:` blocks.
74
+ *
75
+ * Each block starts at a `### REQ:` header and runs up to (but not including)
76
+ * the next `### REQ:` header or the end of the input. The name is everything
77
+ * after `REQ:`, trimmed; the body is every following line up to the next
78
+ * header, joined and trimmed. Lines before the first header are ignored — they
79
+ * are a title or a section heading the caller already consumed. A header with
80
+ * an empty name still produces a block (with `name === ""`); the caller's
81
+ * guardrails decide whether that is acceptable.
82
+ */
83
+ function parseBlocks(lines: readonly string[]): RequirementBlock[] {
84
+ const blocks: RequirementBlock[] = [];
85
+ let current: { name: string; body: string[] } | null = null;
86
+
87
+ const flush = (): void => {
88
+ if (current !== null) {
89
+ blocks.push({ name: current.name, body: current.body.join("\n").trim() });
90
+ }
91
+ };
92
+
93
+ for (const line of lines) {
94
+ const header = line.match(REQ_HEADER);
95
+ if (header !== null) {
96
+ flush();
97
+ current = { name: header[1].trim(), body: [] };
98
+ } else if (current !== null) {
99
+ current.body.push(line);
100
+ }
101
+ }
102
+ flush();
103
+
104
+ return blocks;
105
+ }
106
+
107
+ /**
108
+ * Parse a canonical store file into ordered blocks.
109
+ *
110
+ * The store is a `# ` title line followed by a sequence of `### REQ:` blocks —
111
+ * there are no `## ADDED` etc. headings in the *store*. Any line before the
112
+ * first `### REQ:` header (the title, blank lines) is ignored. Never throws:
113
+ * malformed input simply yields whatever blocks could be recognized — the
114
+ * caller's `parse-error` guardrail decides whether the result is usable.
115
+ * Empty or whitespace-only text yields `[]`.
116
+ */
117
+ export function parseStore(text: string): RequirementBlock[] {
118
+ if (typeof text !== "string") return [];
119
+ return parseBlocks(text.split(/\r?\n/));
120
+ }
121
+
122
+ /**
123
+ * Parse a delta `spec.md` into a `SpecDelta`.
124
+ *
125
+ * Walks the file line by line, switching the active bucket on each
126
+ * `## ADDED` / `## MODIFIED` / `## REMOVED` header and collecting the
127
+ * `### REQ:` blocks that follow into that bucket. Lines outside any section
128
+ * (the `# ` title, blank lines) are ignored. An absent or empty section simply
129
+ * yields an empty bucket. Never throws — missing/non-string text yields an
130
+ * empty delta. A `### REQ:` block that appears before any section header is
131
+ * dropped (it belongs to no bucket); the caller treats a delta with zero
132
+ * blocks as "empty delta — nothing to sync", not an error.
133
+ */
134
+ export function parseDelta(text: string): SpecDelta {
135
+ const delta: SpecDelta = { added: [], modified: [], removed: [] };
136
+ if (typeof text !== "string") return delta;
137
+
138
+ let section: keyof SpecDelta | null = null;
139
+ let buffer: string[] = [];
140
+
141
+ const flush = (): void => {
142
+ if (section !== null && buffer.length > 0) {
143
+ delta[section].push(...parseBlocks(buffer));
144
+ }
145
+ buffer = [];
146
+ };
147
+
148
+ for (const line of text.split(/\r?\n/)) {
149
+ const sectionHeader = line.match(SECTION_HEADER);
150
+ if (sectionHeader !== null) {
151
+ flush();
152
+ const keyword = sectionHeader[1].toUpperCase();
153
+ section =
154
+ keyword === "ADDED" ? "added" : keyword === "MODIFIED" ? "modified" : "removed";
155
+ continue;
156
+ }
157
+ if (section !== null) buffer.push(line);
158
+ }
159
+ flush();
160
+
161
+ return delta;
162
+ }
163
+
164
+ /** Total block count across the three delta buckets. */
165
+ function deltaBlockCount(delta: SpecDelta): number {
166
+ return delta.added.length + delta.modified.length + delta.removed.length;
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Guardrails
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /**
174
+ * Run every guardrail check against a parsed store + delta.
175
+ *
176
+ * Returns a `MergeError[]` — empty when the merge is safe to apply. Each error
177
+ * carries the offending `name` and a ready-to-surface `message`. The checks,
178
+ * in order:
179
+ *
180
+ * - `parse-error` — a block (store or delta) carries an empty name; the
181
+ * input could not be structurally understood.
182
+ * - `duplicate-in-delta` — the same name appears more than once across (or
183
+ * within) the ADDED/MODIFIED/REMOVED sections.
184
+ * - `added-name-collision` — an ADDED name already exists in the store (to
185
+ * *change* a block the run must use MODIFIED).
186
+ * - `modified-missing` — a MODIFIED block names a requirement absent from
187
+ * the store.
188
+ * - `removed-missing` — a REMOVED block names a requirement absent from the
189
+ * store.
190
+ *
191
+ * Pure, never throws. `mergeDelta` runs this before applying *any* change, so
192
+ * a non-empty result means the whole delta is rejected and the store is left
193
+ * untouched.
194
+ */
195
+ export function checkGuardrails(
196
+ store: readonly RequirementBlock[],
197
+ delta: SpecDelta,
198
+ ): MergeError[] {
199
+ const errors: MergeError[] = [];
200
+
201
+ // parse-error — any block (store or delta) with an empty name is malformed.
202
+ for (const block of store) {
203
+ if (block.name === "") {
204
+ errors.push({
205
+ kind: "parse-error",
206
+ name: "",
207
+ message:
208
+ "malformed store: a `### REQ:` block has an empty name — the store could not be parsed",
209
+ });
210
+ break;
211
+ }
212
+ }
213
+ for (const block of [...delta.added, ...delta.modified, ...delta.removed]) {
214
+ if (block.name === "") {
215
+ errors.push({
216
+ kind: "parse-error",
217
+ name: "",
218
+ message:
219
+ "malformed delta: a `### REQ:` block has an empty name — the delta could not be parsed",
220
+ });
221
+ break;
222
+ }
223
+ }
224
+
225
+ // duplicate-in-delta — the same name twice across all three delta sections.
226
+ const seen = new Set<string>();
227
+ const flagged = new Set<string>();
228
+ for (const block of [...delta.added, ...delta.modified, ...delta.removed]) {
229
+ if (block.name === "") continue; // already reported as a parse-error
230
+ if (seen.has(block.name)) {
231
+ if (!flagged.has(block.name)) {
232
+ flagged.add(block.name);
233
+ errors.push({
234
+ kind: "duplicate-in-delta",
235
+ name: block.name,
236
+ message: `duplicate requirement "${block.name}": it appears more than once in the delta — each requirement may appear at most once across ADDED/MODIFIED/REMOVED`,
237
+ });
238
+ }
239
+ } else {
240
+ seen.add(block.name);
241
+ }
242
+ }
243
+
244
+ const storeNames = new Set(store.map((b) => b.name));
245
+
246
+ // added-name-collision — an ADDED name already exists in the store.
247
+ for (const block of delta.added) {
248
+ if (block.name === "") continue;
249
+ if (storeNames.has(block.name)) {
250
+ errors.push({
251
+ kind: "added-name-collision",
252
+ name: block.name,
253
+ message: `ADDED requirement "${block.name}" already exists in the store — use MODIFIED to change an existing requirement`,
254
+ });
255
+ }
256
+ }
257
+
258
+ // modified-missing — a MODIFIED name is absent from the store.
259
+ for (const block of delta.modified) {
260
+ if (block.name === "") continue;
261
+ if (!storeNames.has(block.name)) {
262
+ errors.push({
263
+ kind: "modified-missing",
264
+ name: block.name,
265
+ message: `MODIFIED requirement "${block.name}" is not in the store — only an existing requirement can be modified`,
266
+ });
267
+ }
268
+ }
269
+
270
+ // removed-missing — a REMOVED name is absent from the store.
271
+ for (const block of delta.removed) {
272
+ if (block.name === "") continue;
273
+ if (!storeNames.has(block.name)) {
274
+ errors.push({
275
+ kind: "removed-missing",
276
+ name: block.name,
277
+ message: `REMOVED requirement "${block.name}" is not in the store — only an existing requirement can be removed`,
278
+ });
279
+ }
280
+ }
281
+
282
+ return errors;
283
+ }
284
+
285
+ // ---------------------------------------------------------------------------
286
+ // Render
287
+ // ---------------------------------------------------------------------------
288
+
289
+ /**
290
+ * Render an ordered block list back to canonical store markdown.
291
+ *
292
+ * The output is a `# ` title line, a blank line, then every block as a
293
+ * `### REQ: <name>` header followed by its body. Blocks are separated by a
294
+ * blank line. Round-trips with `parseStore`: `parseStore(renderStore(blocks))`
295
+ * yields the same names and (trimmed) bodies. `title` defaults to the pinned
296
+ * `STORE_TITLE`. The result always ends with a single trailing newline.
297
+ */
298
+ export function renderStore(blocks: readonly RequirementBlock[], title: string = STORE_TITLE): string {
299
+ const parts: string[] = [`# ${title}`];
300
+ for (const block of blocks) {
301
+ const body = block.body.trim();
302
+ parts.push(body === "" ? `### REQ: ${block.name}` : `### REQ: ${block.name}\n\n${body}`);
303
+ }
304
+ return `${parts.join("\n\n")}\n`;
305
+ }
306
+
307
+ // ---------------------------------------------------------------------------
308
+ // Merge entry point
309
+ // ---------------------------------------------------------------------------
310
+
311
+ /**
312
+ * The whole pipeline: parse both inputs, run every guardrail, and — only when
313
+ * there are zero errors — apply the delta and render the new store.
314
+ *
315
+ * This is the single entry point the `/zero-sync` wiring calls. It is pure: no
316
+ * filesystem, no pi, never throws.
317
+ *
318
+ * On any guardrail error it returns `{ ok: false, errors }` and **no store
319
+ * text is produced** — a partially-applied store is structurally impossible,
320
+ * because the merge runs after *all* guardrails pass. On success it returns
321
+ * `{ ok: true, store, summary }` where the delta has been applied as:
322
+ *
323
+ * - ADDED → appended to the end of the store, in delta order;
324
+ * - MODIFIED → the matching store block's body is replaced in place;
325
+ * - REMOVED → the matching store block is deleted.
326
+ *
327
+ * An empty delta (zero blocks in every section) is *not* an error: it returns
328
+ * `ok: true` with the store unchanged and an empty `summary`, so the caller
329
+ * can report "empty delta — nothing to sync".
330
+ */
331
+ export function mergeDelta(storeText: string, deltaText: string): MergeResult {
332
+ const store = parseStore(storeText);
333
+ const delta = parseDelta(deltaText);
334
+
335
+ const errors = checkGuardrails(store, delta);
336
+ if (errors.length > 0) {
337
+ return { ok: false, errors };
338
+ }
339
+
340
+ // Apply the delta. Guardrails have proven every name resolves, so the
341
+ // mutations below cannot fail or leave the store half-applied.
342
+ const removedNames = new Set(delta.removed.map((b) => b.name));
343
+ const modifiedByName = new Map(delta.modified.map((b) => [b.name, b]));
344
+
345
+ const merged: RequirementBlock[] = [];
346
+ for (const block of store) {
347
+ if (removedNames.has(block.name)) continue; // REMOVED — drop it
348
+ const replacement = modifiedByName.get(block.name);
349
+ merged.push(replacement ?? block); // MODIFIED — replace; else keep
350
+ }
351
+ for (const block of delta.added) {
352
+ merged.push(block); // ADDED — append in delta order
353
+ }
354
+
355
+ const summary: MergeSummary = {
356
+ added: delta.added.map((b) => b.name),
357
+ modified: delta.modified.map((b) => b.name),
358
+ removed: delta.removed.map((b) => b.name),
359
+ };
360
+
361
+ return { ok: true, store: renderStore(merged), summary };
362
+ }
363
+
364
+ /**
365
+ * Whether a parsed delta carries no blocks at all.
366
+ *
367
+ * The `/zero-sync` command uses this to report "empty delta — nothing to sync"
368
+ * before touching the store: a zero-block delta is valid (not a `MergeError`),
369
+ * it simply has nothing to apply.
370
+ */
371
+ export function isEmptyDelta(delta: SpecDelta): boolean {
372
+ return deltaBlockCount(delta) === 0;
373
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gonrocca/zero-pi",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "zero-pi — an installable layer for pi (pi.dev): the zero spec-driven development workflow, skill auto-learning, and an animated ZERO startup banner. Adds capability to pi without modifying pi.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -22,7 +22,8 @@
22
22
  "extensions": [
23
23
  "./extensions/startup-banner.ts",
24
24
  "./extensions/zero-models.ts",
25
- "./extensions/autotune-extension.ts"
25
+ "./extensions/autotune-extension.ts",
26
+ "./extensions/spec-merge-extension.ts"
26
27
  ]
27
28
  },
28
29
  "files": [
@@ -32,6 +33,8 @@
32
33
  "extensions/zero-models.ts",
33
34
  "extensions/autotune.ts",
34
35
  "extensions/autotune-extension.ts",
36
+ "extensions/spec-merge.ts",
37
+ "extensions/spec-merge-extension.ts",
35
38
  "README.md",
36
39
  "LICENSE"
37
40
  ],
@@ -199,3 +199,41 @@ Rules:
199
199
  - **No record without a verdict.** If the run was aborted before `veredicto`
200
200
  ever produced a verdict, write nothing — only a `pasa` or `cap-reached` run
201
201
  is recorded.
202
+
203
+ ## Spec sync & archive
204
+
205
+ The project keeps a **canonical spec store** at `.sdd/specs/requirements.md` —
206
+ the accepted requirements of every prior run. A `/forge` run's `plan` phase
207
+ emits a delta `spec.md` against that store; once the run reaches a `pasa`
208
+ verdict the delta is folded back into the store.
209
+
210
+ **After a `pasa` verdict — and only then.** Alongside the Cortex save and the
211
+ `zero-runs.jsonl` append, invoke the **`/zero-sync <slug>`** command, passing
212
+ the run's feature slug explicitly. `/zero-sync` is a real pi command — a
213
+ deterministic, unit-tested merge, not a prompt instruction — that reads
214
+ `.sdd/specs/requirements.md` and `.sdd/<slug>/spec.md`, folds the delta into the
215
+ store, writes the store atomically, and archives the change. You only call it;
216
+ you never edit the store yourself.
217
+
218
+ **Never sync on a non-`pasa` outcome.** Do **not** invoke `/zero-sync` for a
219
+ `corregir` or `replantear` verdict, or when the iteration cap was reached
220
+ without a `pasa` — the store is changed by a `pasa` run only, and no archive
221
+ entry is created otherwise. Likewise skip it for a **legacy resumed run** whose
222
+ `.sdd/<slug>/` has no `spec.md` (the older artifact shape) — that run has no
223
+ delta to fold, and `/zero-sync` will report it has nothing to sync.
224
+
225
+ **On a guardrail error, surface — do not claim a sync.** If `/zero-sync`
226
+ reports a guardrail failure (a duplicate name, an ADDED collision, a MODIFIED or
227
+ REMOVED of a missing block, or a malformed store/delta) it writes **nothing**.
228
+ Relay the failing requirement name(s) and reason to the user and state plainly
229
+ that the canonical store was **not** updated and is out of sync for a manual
230
+ fix. The `pasa` verdict still stands — the build shipped; only the store fold
231
+ was rejected. Never report the store as updated when `/zero-sync` did not
232
+ update it.
233
+
234
+ **On success, relay the report.** When `/zero-sync` succeeds it writes the new
235
+ store and creates an archive entry at `.sdd/archive/<YYYY-MM-DD>-<slug>/` — a
236
+ copy of the run's `proposal.md` and `spec.md` plus a `sync.md` report listing
237
+ every added, modified, and removed requirement. Include `/zero-sync`'s report in
238
+ the run's final summary, calling out the destructive effects (replacements,
239
+ deletions) explicitly.
@@ -6,12 +6,13 @@ You run the **plan** phase of a zero SDD pipeline.
6
6
 
7
7
  **Locating artifacts.** If you are invoked with a feature slug, operate on
8
8
  `.sdd/<slug>/`. With no slug and exactly one candidate run on disk, use it; with
9
- no slug and an ambiguous target, ask which run before acting. You write
10
- `requirements.md`, `design.md`, and `tasks.md` into that directory. If invoked
11
- standalone with the explore findings absent, gather the context you need first
12
- rather than failing. On a resumed run, sanity-check any `requirements.md` or
13
- `design.md` you depend on — if one is obviously incomplete (truncated
14
- mid-write), rebuild it instead of trusting it.
9
+ no slug and an ambiguous target, ask which run before acting. You write four
10
+ artifacts into that directory — `proposal.md`, `spec.md`, `design.md`, and
11
+ `tasks.md` (see *Artifacts*). If invoked standalone with the explore findings
12
+ absent, gather the context you need first rather than failing. On a resumed run,
13
+ sanity-check any `proposal.md`, `spec.md`, or `design.md` you depend on — if one
14
+ is obviously incomplete (truncated mid-write), rebuild it instead of trusting
15
+ it.
15
16
 
16
17
  Using the explore findings, write the plan: the requirements (what must be
17
18
  true), the design (how it will be built), and an ordered list of small,
@@ -19,7 +20,43 @@ independently verifiable tasks.
19
20
 
20
21
  Do not write implementation code in this phase — only the plan. Keep each task
21
22
  scoped tightly enough that the build phase can implement and check it on its
22
- own.
23
+ own. `plan` stays a single phase — read the store, write all four artifacts in
24
+ this one pass.
25
+
26
+ ## Reading the canonical store
27
+
28
+ The project keeps a **canonical spec store** at `.sdd/specs/requirements.md` —
29
+ the accumulated, accepted requirements of every prior run. Read it as the
30
+ baseline before writing this run's requirements.
31
+
32
+ - **Absent** (`.sdd/specs/` or the file does not exist) → treat it as an empty
33
+ store: every requirement this run proposes is new, so the whole `spec.md`
34
+ delta is `## ADDED`.
35
+ - **Present and well-formed** → it is a `# ` title followed by `### REQ: <name>`
36
+ blocks. Use the existing block names as the identities you may MODIFY or
37
+ REMOVE.
38
+ - **Unreadable or malformed** → surface the error and stop before producing a
39
+ delta. Do **not** overwrite the store and do **not** guess — a bad store is a
40
+ blocker for the human, not something `plan` repairs.
41
+
42
+ ## Artifacts
43
+
44
+ Write all four into `.sdd/<slug>/`:
45
+
46
+ - **`proposal.md`** — the change intent: what this run adds or changes, its
47
+ scope, and the rationale. Prose, no requirement blocks.
48
+ - **`spec.md`** — the **delta** against the canonical store, never a full spec.
49
+ Up to three `H2` sections — `## ADDED`, `## MODIFIED`, `## REMOVED` — each
50
+ holding `### REQ: <stable-unique-name>` blocks (one named requirement: prose
51
+ followed by an `Acceptance criteria:` list). `## ADDED` carries brand-new
52
+ requirements; `## MODIFIED` carries the **complete** updated text of an
53
+ existing block (full new body, not a diff); `## REMOVED` needs only the
54
+ `### REQ:` name line. Any section may be empty or absent; a block name must be
55
+ unique within and across the delta's sections and not collide with an existing
56
+ store name unless it is the target of MODIFIED/REMOVED.
57
+ - **`design.md`** — how it is built (unchanged from before).
58
+ - **`tasks.md`** — the ordered task list, keeping its `## Review Workload`
59
+ section (see below).
23
60
 
24
61
  Honour the prior-run lessons carried in the explore findings: when a past run
25
62
  was sent back with `replantear`, do not repeat the plan mistake it recorded.
@@ -0,0 +1,54 @@
1
+ ---
2
+ description: Route a natural-language request into the zero SDD pipeline when the user signals SDD intent
3
+ ---
4
+
5
+ # zero — Natural-language SDD routing
6
+
7
+ zero's spec-driven development pipeline is normally started with the explicit
8
+ `/forge <feature>` command. This skill adds one purely additive convenience:
9
+ when the user **describes work** and **explicitly signals** that they want it
10
+ run through the disciplined SDD pipeline, route the request into the `/forge`
11
+ workflow instead of handling it ad-hoc.
12
+
13
+ `/forge` stays the primary, deliberate entry point. This skill never replaces
14
+ it — it only catches the case where the user expressed SDD intent in plain
15
+ language rather than typing the command.
16
+
17
+ ## When to route
18
+
19
+ Route to `/forge` only when **both** of these hold:
20
+
21
+ 1. The message describes **non-trivial work** — a feature, a refactor, a
22
+ multi-step change worth a spec.
23
+ 2. The message contains a **clear SDD intent signal** — an explicit phrase
24
+ asking for the pipeline. Recognised signals (Spanish or English), and close
25
+ equivalents:
26
+ - "hacelo con sdd" / "do it with sdd"
27
+ - "usá el pipeline" / "use the pipeline"
28
+ - "con sdd" / "with sdd"
29
+ - "andá con forge" / "run forge" / "go with forge"
30
+ - "spec-driven" / "spec driven development"
31
+
32
+ When both hold, invoke the `/forge` workflow with the user's described work as
33
+ the feature request. Pass that described work **verbatim** — do not rephrase,
34
+ summarize, translate, or interpret it. The existing `/forge` workflow does the
35
+ rest: an ordinary SDD run with all four phases (explore, plan, build,
36
+ veredicto), the round cap, and the veredicto verdict, exactly as an explicit
37
+ `/forge` invocation behaves.
38
+
39
+ ## When NOT to route — be conservative
40
+
41
+ This skill must **not** hijack ordinary interaction. Do nothing (handle the
42
+ request normally) when:
43
+
44
+ - The message has **no clear SDD intent signal** — description of work alone is
45
+ never enough.
46
+ - The user asks a **question**, requests a **small or one-off fix**, or makes
47
+ any routine request without an SDD signal.
48
+ - The SDD intent is **ambiguous or uncertain** in any way.
49
+
50
+ When in doubt, do nothing. Default to normal handling and leave the user to
51
+ invoke `/forge` explicitly. A missed natural-language route is harmless — the
52
+ user can still type `/forge`. A wrong route forces routine work through the
53
+ heavy pipeline, which is not. Triggering only on a clear signal phrase is the
54
+ rule; `/forge` remains the explicit primary entry point.