@juicesharp/rpiv-pi 2.6.3 → 2.7.0

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.
Files changed (33) hide show
  1. package/docs/workflows.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +10 -13
  3. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  4. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  5. package/extensions/rpiv-core/built-in-workflows.ts +233 -3514
  6. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  7. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  8. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  10. package/extensions/rpiv-core/built-ins/index.ts +46 -0
  11. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  15. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  16. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  17. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  18. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  19. package/extensions/rpiv-core/constants.ts +5 -1
  20. package/extensions/rpiv-core/lane-console.ts +9 -2
  21. package/extensions/rpiv-core/lane-list.ts +10 -1
  22. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  23. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  24. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  25. package/package.json +2 -2
  26. package/skills/elaborate/SKILL.md +1 -1
  27. package/skills/grade/SKILL.md +1 -1
  28. package/skills/implement/SKILL.md +1 -0
  29. package/skills/plan/SKILL.md +3 -1
  30. package/skills/remediate/SKILL.md +1 -0
  31. package/skills/synthesize/SKILL.md +1 -0
  32. package/skills/validate/SKILL.md +25 -19
  33. package/skills/validate/templates/validation.md +1 -1
package/docs/workflows.md CHANGED
@@ -49,7 +49,7 @@ code is elaborated into it. Three automated gates plus one human checkpoint.
49
49
 
50
50
  `goal → research → plan → plan-cite-check → grade → implement → implement-scope-check → reconcile → validate → commit`
51
51
 
52
- Ship a small, well-understood task in one lightweight forward pass. The verbatim brief is the goal artifact; a trimmed research stage (at most two `codebase-analyzer` dispatches — not a full `/skill:research` pass) grounds a single unsliced plan from `quick-plan`, which receives the verbatim goal alongside the research doc and must explicitly defer any goal ask it narrows out; a deterministic citation floor and one tier-independent three-dimension grade (correctness, completeness, architecture-fit — architecture-fit cannot be dropped from a light roster) gate the plan before `implement`. The citation floor stops the run only on a fabrication-shaped defect — a cited path that resolves to no tree file by any strategy, or a phase body edit missing from its `files:` declaration; citation ambiguity and line drift are advisory (recorded on the verdict, severity `low`) and ride to the grade panel, whose correctness unit receives the floor's verdict as `--cite-check` and adjudicates each finding by symbol instead of the run dying over a path-prefix omission. Every gate is stop-on-fail — no fix loops, confirm panels, snapshots, or code-elaboration lane — and a red gate surfaces as `stopped at <gate>: <reason>` in the end-of-run toast and lane recap (never a ✓); a goal-anchored `validate` judges the landing before `commit`. Best for tasks small enough to plan in one pass; prefer `build` for anything needing decomposition.
52
+ Ship a small, well-understood task in one lightweight forward pass. The verbatim brief is the goal artifact; a trimmed research stage (at most two `codebase-analyzer` dispatches — not a full `/skill:research` pass) grounds a single unsliced plan from `quick-plan`, which receives the verbatim goal alongside the research doc and must explicitly defer any goal ask it narrows out; a deterministic citation floor and one tier-independent three-dimension grade (correctness, completeness, architecture-fit — architecture-fit cannot be dropped from a light roster) gate the plan before `implement`. The citation floor stops the run only on a phase body edit missing from its `files:` declaration (an undeclared write corrupts implement's dependency derivation); every citation-resolution finding — unresolved path, ambiguity, line drift — is advisory (recorded on the verdict, severity `low`) and rides to the grade panel, whose correctness unit receives the floor's verdict as `--cite-check` and adjudicates each finding by symbol instead of the run dying over a resolver limitation. Every gate is stop-on-fail — no fix loops, confirm panels, snapshots, or code-elaboration lane — and a red gate surfaces as `stopped at <gate>: <reason>` in the end-of-run toast and lane recap (never a ✓); a goal-anchored `validate` judges the landing before `commit`. Best for tasks small enough to plan in one pass; prefer `build` for anything needing decomposition.
53
53
 
54
54
  ## Review loops
55
55
 
@@ -9,7 +9,7 @@
9
9
  * the read-modify-write lost-update problem remains: two sessions both reading
10
10
  * the manifest before either writes will race, and the second writer overwrites
11
11
  * the first's entries with its own stale snapshot. Advisory locking is a
12
- * deferred follow-up (see CHANGELOG known-limitations). The path allowlist in
12
+ * deferred follow-up. The path allowlist in
13
13
  * readManifest neutralises the worst-case (arbitrary-path unlink) regardless of
14
14
  * concurrency.
15
15
  */
@@ -275,7 +275,7 @@ export function isSafeDestructiveOp(opts: { knownHash: string; destHash: string
275
275
  // ---------------------------------------------------------------------------
276
276
 
277
277
  /**
278
- * Step 1: Enumerate source .md files from the bundled agents directory.
278
+ * Enumerate source .md files from the bundled agents directory.
279
279
  * Returns null (with error pushed) on failure.
280
280
  */
281
281
  function enumerateSourceFiles(result: SyncResult): string[] | null {
@@ -362,7 +362,7 @@ export function injectModelFrontmatter(content: string, agentFile: string, confi
362
362
  }
363
363
 
364
364
  /**
365
- * Step 2: Process each source file — copy new, record unchanged, update or gate.
365
+ * Process each source file — copy new, record unchanged, update or gate.
366
366
  * Returns the new manifest built from source entries.
367
367
  */
368
368
  function processSourceEntries(
@@ -450,7 +450,7 @@ function processSourceEntries(
450
450
  }
451
451
 
452
452
  /**
453
- * Step 3A: Classify stale entries (in manifest but absent from source).
453
+ * Classify stale entries (in manifest but absent from source).
454
454
  * Returns entries to unlink; pushes pendingRemove for gated entries.
455
455
  */
456
456
  function classifyStaleEntries(
@@ -500,7 +500,7 @@ function classifyStaleEntries(
500
500
  }
501
501
 
502
502
  /**
503
- * Step 3C: Commit unlink operations after the manifest is durable.
503
+ * Commit unlink operations after the manifest is durable.
504
504
  * Re-introduces failed entries into newManifest so a future run retries.
505
505
  */
506
506
  function commitStaleUnlinks(
@@ -568,23 +568,20 @@ export function syncBundledAgents(apply: boolean): SyncResult {
568
568
  return result;
569
569
  }
570
570
 
571
- // 1. Enumerate source files
572
571
  const sourceEntries = enumerateSourceFiles(result);
573
572
  if (sourceEntries === null) return result;
574
573
 
575
574
  const sourceNames = new Set(sourceEntries);
576
575
  const manifest = readManifest(targetDir);
577
576
 
578
- // 2. Process each source file
579
577
  const newManifest = processSourceEntries(sourceEntries, targetDir, manifest, apply, result);
580
578
 
581
- // 3. Stale-removal: Pass A (classify) → Pass B (write manifest) → Pass C (commit unlinks).
582
579
  const toUnlink = classifyStaleEntries(manifest, sourceNames, targetDir, apply, newManifest, result);
583
580
 
584
- // Pass B — persist manifest before destructive ops.
581
+ // Persist the manifest before destructive ops.
585
582
  writeManifest(targetDir, newManifest, result);
586
583
 
587
- // Pass C — commit unlinks after the manifest is durable.
584
+ // Commit unlinks after the manifest is durable.
588
585
  commitStaleUnlinks(toUnlink, manifest, newManifest, targetDir, result);
589
586
 
590
587
  return result;
@@ -608,12 +605,12 @@ export function cleanupPerCwdAgents(cwd: string): CleanupResult {
608
605
  if (!existsSync(perCwdDir)) return result;
609
606
  const manifest = readManifest(perCwdDir);
610
607
  if (Object.keys(manifest).length === 0) {
611
- // Edge state 1: no manifest (never synced by us, or hand-managed)
608
+ // No manifest (never synced by us, or hand-managed)
612
609
  result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.UNMANAGED });
613
610
  return result;
614
611
  }
615
612
 
616
- // Edge state 2: verify all managed files match current source content.
613
+ // Verify all managed files match current source content.
617
614
  // Hoisted config read (same reasoning as processSourceEntries): one JSON
618
615
  // read for the whole cleanup pass, not one per managed file.
619
616
  const cleanupConfig = loadModelsConfig();
@@ -661,7 +658,7 @@ export function cleanupPerCwdAgents(cwd: string): CleanupResult {
661
658
  }
662
659
  }
663
660
 
664
- // Edge state 3: check for non-managed files
661
+ // Check for non-managed files
665
662
  try {
666
663
  const allFiles = readdirSync(perCwdDir);
667
664
  const managedNames = new Set(Object.keys(manifest));
@@ -14,6 +14,12 @@
14
14
  * (`research`, `plans`, etc.) — the collector halts the chain if the
15
15
  * agent strayed.
16
16
  *
17
+ * Both collectors carry a disk-corroborated basename fallback: when the
18
+ * full-path transcript scan misses (agent mangled the directory prefix in
19
+ * prose), a bare `<file>.md` token from the transcript is accepted iff it
20
+ * resolves to exactly one existing file under `.rpiv/artifacts/` — see the
21
+ * fallback section below.
22
+ *
17
23
  * One parser: `frontmatterParser` parses YAML frontmatter from the
18
24
  * primary fs artifact into `Record<string, unknown>` — what
19
25
  * `outputSchema` validates against for typed downstream narrowing.
@@ -24,13 +30,16 @@
24
30
  * `produces()` stage.
25
31
  */
26
32
 
27
- import { existsSync, readFileSync } from "node:fs";
33
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
28
34
  import { isAbsolute, join } from "node:path";
29
35
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
30
36
  import {
31
37
  type ArtifactCollector,
32
38
  type ArtifactParser,
39
+ type BranchEntry,
40
+ defineCollector,
33
41
  defineParser,
42
+ fs as fsHandle,
34
43
  type Outcome,
35
44
  type ParseContext,
36
45
  transcriptPathCollector,
@@ -41,16 +50,112 @@ import {
41
50
  // Collectors — text-scan over assistant transcript
42
51
  // ---------------------------------------------------------------------------
43
52
 
44
- const RPIV_ARTIFACT_PATTERN = /\.rpiv\/artifacts\/[\w.-]+\/[\w.-]+\.md/g;
53
+ // A prose ellipsis is a valid `[\w.-]+` string, so an agent's ELIDED reference to
54
+ // a sibling artifact ("`.rpiv/artifacts/elaborations/...__phase-4.md`") placed
55
+ // after its real announcement used to win the last-match scan and fatal the stage
56
+ // on a path that never existed. The tempered class below refuses ".." anywhere in
57
+ // a segment — the same hazard `FILE_LINE_CITATION_RE` guards with its
58
+ // lookbehinds. Under the documented slug conventions (timestamps, kebab-cased
59
+ // topics, "__phase-N" — prompt-enforced, not code-enforced) no legitimate path
60
+ // carries consecutive dots; a skill that ever emitted one would fail collection
61
+ // LOUDLY (fatal no-match), never silently.
62
+ //
63
+ // ONE encoding, shared by both collectors — the bucket-narrowed pattern is built
64
+ // from the same string so the two can never drift.
65
+ const TEMPERED_SEGMENT = String.raw`(?:(?!\.\.)[\w.-])+`;
66
+ const RPIV_ARTIFACT_PATTERN = new RegExp(String.raw`\.rpiv/artifacts/${TEMPERED_SEGMENT}/${TEMPERED_SEGMENT}\.md`, "g");
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // Disk-corroborated basename fallback
70
+ // ---------------------------------------------------------------------------
71
+ //
72
+ // Regression: run 2026-08-21_12-15-19-ec5e, code (phase 1/7). The agent wrote
73
+ // its elaboration to the correct `.rpiv/artifacts/elaborations/...` path, but
74
+ // its final message announced the path as `.elaborations/<file>.md` — the
75
+ // directory prefix mangled in prose. The full-path scan missed, the stage
76
+ // fataled, and a verified-green 38KB artifact was orphaned: the transcript
77
+ // (the report of the work) was the only channel checked, never the filesystem
78
+ // (the work itself).
79
+ //
80
+ // The fallback closes that gap WITHOUT weakening the announcement contract:
81
+ // on a full-path miss, scan the transcript for bare `<file>.md` tokens
82
+ // (tempered — an elided `...__phase-N.md` still never resolves) and accept a
83
+ // candidate ONLY when it names exactly one existing file under
84
+ // `.rpiv/artifacts/<bucket>/` (the collector's bucket, or any bucket for the
85
+ // agnostic collector). The agent's own announcement still drives collection —
86
+ // disk existence corroborates it, so a stray prose mention of `README.md` or
87
+ // a sibling's elided path can never be collected. Ambiguity (same basename in
88
+ // two buckets) refuses that candidate; no unique resolution → the original
89
+ // fatal stands.
90
+ const BASENAME_PATTERN = new RegExp(String.raw`${TEMPERED_SEGMENT}\.md`, "g");
91
+
92
+ /** Bare `<file>.md` tokens from assistant text, last-mentioned first, deduped. */
93
+ function basenameCandidates(branch: BranchEntry[], offsetStart?: number): string[] {
94
+ const out: string[] = [];
95
+ const seen = new Set<string>();
96
+ const start = Math.max(offsetStart ?? 0, 0);
97
+ for (let i = branch.length - 1; i >= start; i--) {
98
+ const entry = branch[i]!;
99
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
100
+ const content = entry.message.content;
101
+ if (!Array.isArray(content)) continue;
102
+ for (let j = content.length - 1; j >= 0; j--) {
103
+ const part = content[j]!;
104
+ if (part.type !== "text" || typeof part.text !== "string") continue;
105
+ const matches = part.text.match(BASENAME_PATTERN) ?? [];
106
+ for (let k = matches.length - 1; k >= 0; k--) {
107
+ const m = matches[k]!;
108
+ if (!seen.has(m)) {
109
+ seen.add(m);
110
+ out.push(m);
111
+ }
112
+ }
113
+ }
114
+ }
115
+ return out;
116
+ }
117
+
118
+ /** Existing `.rpiv/artifacts/<bucket>/<basename>` paths (repo-relative). */
119
+ function resolveUnderArtifacts(cwd: string, basename: string, bucket?: string): string[] {
120
+ const root = join(cwd, ".rpiv", "artifacts");
121
+ if (!existsSync(root)) return [];
122
+ const buckets = bucket
123
+ ? [bucket]
124
+ : readdirSync(root, { withFileTypes: true })
125
+ .filter((e) => e.isDirectory())
126
+ .map((e) => e.name);
127
+ return buckets.filter((b) => existsSync(join(root, b, basename))).map((b) => `.rpiv/artifacts/${b}/${basename}`);
128
+ }
129
+
130
+ /** Full-path scan first; on miss, the disk-corroborated basename fallback. */
131
+ function withDiskFallback(primary: ArtifactCollector, bucket?: string): ArtifactCollector {
132
+ return defineCollector({
133
+ collect: async (ctx) => {
134
+ const scanned = await primary.collect(ctx);
135
+ if (scanned.kind === "ok") return scanned;
136
+ for (const basename of basenameCandidates(ctx.branch, ctx.branchOffset)) {
137
+ const hits = resolveUnderArtifacts(ctx.cwd, basename, bucket);
138
+ if (hits.length === 1) {
139
+ return { kind: "ok", artifacts: [{ handle: fsHandle(hits[0]!), role: "primary" }] };
140
+ }
141
+ }
142
+ return scanned; // the original fatal — no unique on-disk corroboration
143
+ },
144
+ });
145
+ }
45
146
 
46
147
  /** Bucket-agnostic — accepts any `.rpiv/artifacts/<bucket>/...md`. */
47
- export const rpivArtifactCollector: ArtifactCollector = transcriptPathCollector({ pattern: RPIV_ARTIFACT_PATTERN });
148
+ export const rpivArtifactCollector: ArtifactCollector = withDiskFallback(
149
+ transcriptPathCollector({ pattern: RPIV_ARTIFACT_PATTERN }),
150
+ );
48
151
 
49
- /** Bucket-narrowed — accepts only `.rpiv/artifacts/<bucket>/...md`. */
152
+ /** Bucket-narrowed — accepts only `.rpiv/artifacts/<bucket>/...md`. The filename
153
+ * segment is `TEMPERED_SEGMENT`, so an elided prose path never outranks the
154
+ * real announcement here either. */
50
155
  export function rpivBucketCollector(bucket: string): ArtifactCollector {
51
156
  const escaped = bucket.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
52
- const pattern = new RegExp(`\\.rpiv/artifacts/${escaped}/[\\w.-]+\\.md`, "g");
53
- return transcriptPathCollector({ pattern });
157
+ const pattern = new RegExp(String.raw`\.rpiv/artifacts/${escaped}/${TEMPERED_SEGMENT}\.md`, "g");
158
+ return withDiskFallback(transcriptPathCollector({ pattern }), bucket);
54
159
  }
55
160
 
56
161
  // ---------------------------------------------------------------------------
@@ -32,7 +32,7 @@ type WatchableSession = Pick<AgentSession, "subscribe" | "abort">;
32
32
 
33
33
  const DEFAULT_BASH_TOOL_TIMEOUT_MS = 180_000; // 3 min — tight enough to cut a wedged scan well before it strands a gate.
34
34
  const MIN_BASH_TOOL_TIMEOUT_MS = 5_000; // a sub-5s ceiling would scythe ordinary commands.
35
- const MAX_BASH_TOOL_TIMEOUT_MS = 30 * 60_000; // 30 min — the hard upper bound (mirrors the workflow validation-retry cap).
35
+ const MAX_BASH_TOOL_TIMEOUT_MS = 30 * 60_000; // 30 min — the hard upper bound; mirrors MAX_VALIDATION_RETRY_TIMEOUT_MS in packages/rpiv-workflow/validation-bounds.ts (same 30-min value, separately owned).
36
36
 
37
37
  /**
38
38
  * The resolved per-command ceiling: the 3-minute default, overridable via
@@ -48,10 +48,20 @@ export function resolveBashTimeoutMs(raw: string | undefined): number {
48
48
  return Math.min(Math.max(parsed, MIN_BASH_TOOL_TIMEOUT_MS), MAX_BASH_TOOL_TIMEOUT_MS);
49
49
  }
50
50
 
51
+ /**
52
+ * `bashTimeoutReason` echoes the offending command capped at SNIPPET_MAX_LEN chars — the reason is
53
+ * operator-grade one-line row text, so the command is truncated instead of flooding the row with a
54
+ * runaway pipeline. The cap INCLUDES the trailing ellipsis; SNIPPET_ELLIPSIS_LEN is that ellipsis's
55
+ * length — the ASCII three-period form (`...`), never the single-glyph one, for byte-stable row text.
56
+ */
57
+ const SNIPPET_MAX_LEN = 120;
58
+ const SNIPPET_ELLIPSIS_LEN = 3;
59
+
51
60
  /** Operator-grade row text — names the ceiling and echoes the offending command (truncated). */
52
61
  export function bashTimeoutReason(command: string, timeoutMs: number): string {
53
62
  const secs = Math.round(timeoutMs / 1000);
54
- const snippet = command.length > 120 ? `${command.slice(0, 117)}...` : command;
63
+ const snippet =
64
+ command.length > SNIPPET_MAX_LEN ? `${command.slice(0, SNIPPET_MAX_LEN - SNIPPET_ELLIPSIS_LEN)}...` : command;
55
65
  return `bash command exceeded the ${secs}s per-command timeout and was aborted${snippet ? `: \`${snippet}\`` : ""}`;
56
66
  }
57
67