@juicesharp/rpiv-pi 2.13.4 → 2.13.5

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 (29) hide show
  1. package/README.md +1 -1
  2. package/extensions/rpiv-core/agents-allowlist.ts +47 -0
  3. package/extensions/rpiv-core/agents-inject.ts +151 -0
  4. package/extensions/rpiv-core/agents-manifest.ts +102 -0
  5. package/extensions/rpiv-core/agents-sync.ts +405 -0
  6. package/extensions/rpiv-core/agents-types.ts +115 -0
  7. package/extensions/rpiv-core/agents.ts +35 -773
  8. package/extensions/rpiv-core/built-in-workflows.ts +13 -1426
  9. package/extensions/rpiv-core/built-ins/citations.ts +1 -1
  10. package/extensions/rpiv-core/built-ins/gate-passes.ts +498 -0
  11. package/extensions/rpiv-core/built-ins/gate-rosters.ts +275 -0
  12. package/extensions/rpiv-core/built-ins/gates.ts +34 -951
  13. package/extensions/rpiv-core/built-ins/index.ts +5 -3
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +1 -1
  15. package/extensions/rpiv-core/built-ins/slice-checks.ts +3 -3
  16. package/extensions/rpiv-core/built-ins/verdict-core.ts +202 -0
  17. package/extensions/rpiv-core/outcome-derivation.ts +2 -1
  18. package/extensions/rpiv-core/pi-compat.ts +59 -0
  19. package/extensions/rpiv-core/run-lane-registry.ts +28 -225
  20. package/extensions/rpiv-core/run-lane-types.ts +240 -0
  21. package/extensions/rpiv-core/sdk-workflow-host.ts +46 -18
  22. package/extensions/rpiv-core/workflows/build.ts +695 -0
  23. package/extensions/rpiv-core/workflows/polish.ts +62 -0
  24. package/extensions/rpiv-core/workflows/shared.ts +300 -0
  25. package/extensions/rpiv-core/workflows/ship.ts +329 -0
  26. package/extensions/rpiv-core/workflows/vet.ts +133 -0
  27. package/package.json +3 -2
  28. package/skills/_shared/stitch-elaborations.mjs +1 -1
  29. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +7 -5
package/README.md CHANGED
@@ -117,7 +117,7 @@ no overrides.
117
117
 
118
118
  | Requirement | Why |
119
119
  | --- | --- |
120
- | [Pi Agent](https://github.com/badlogic/pi-mono) | The host. Install it globally so `pi` is on your PATH |
120
+ | [Pi Agent](https://github.com/badlogic/pi-mono) 0.80.x or 1.x | The host. Install it globally so `pi` is on your PATH. Workflow child sessions are tested against Pi 0.80.6, 1.0.4, and 1.1.0 |
121
121
  | A model provider | Pi's own `/login` or `~/.pi/agent/models.json` — see [docs/models-config.md](./docs/models-config.md) |
122
122
  | [`@tintinweb/pi-subagents`](https://www.npmjs.com/package/@tintinweb/pi-subagents) | Supplies the `Agent` tool. Without it the parallel-analysis skills cannot dispatch. Installed by `/rpiv-setup` |
123
123
  | [`@juicesharp/rpiv-workflow`](https://www.npmjs.com/package/@juicesharp/rpiv-workflow) | Supplies `/wf`. Without it the four built-in workflows do not register. Installed by `/rpiv-setup` |
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Agent sync — path-traversal allowlist.
3
+ *
4
+ * Layer 2 of the agents-*.ts family: imports only node:path. Hardens the
5
+ * manifest reader boundary (agents-manifest) and the destination-path
6
+ * construction in the sync engine (agents-sync).
7
+ */
8
+
9
+ import { isAbsolute, resolve, sep } from "node:path";
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Path-traversal allowlist (hardens the manifest reader boundary)
13
+ // ---------------------------------------------------------------------------
14
+
15
+ /**
16
+ * Allowlist for managed-agent filenames.
17
+ *
18
+ * Hardens the manifest reader against crafted keys that would otherwise drive
19
+ * `readFileSync` / `unlinkSync` to a path-traversed target. Required: the value
20
+ * must be a single basename (no separators), must not contain `..` or NUL, must
21
+ * not be absolute, and must end in `.md`.
22
+ */
23
+ export function isManagedAgentName(name: string): boolean {
24
+ if (typeof name !== "string" || name.length === 0) return false;
25
+ if (name.includes("\0")) return false;
26
+ if (name.includes("/") || name.includes("\\")) return false;
27
+ if (name === "." || name === "..") return false;
28
+ if (name.includes("..")) return false;
29
+ if (isAbsolute(name)) return false;
30
+ if (!name.endsWith(".md")) return false;
31
+ return true;
32
+ }
33
+
34
+ /**
35
+ * Resolve a managed-agent destination path under targetDir, asserting it stays
36
+ * within targetDir. Defence-in-depth alongside `isManagedAgentName` — if a
37
+ * future code path constructs a destPath without going through `readManifest`,
38
+ * this still blocks the traversal.
39
+ *
40
+ * Returns `null` if the resolved path escapes `targetDir`.
41
+ */
42
+ export function safeJoin(targetDir: string, name: string): string | null {
43
+ const resolved = resolve(targetDir, name);
44
+ const root = resolve(targetDir) + sep;
45
+ if (!resolved.startsWith(root)) return null;
46
+ return resolved;
47
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Agent sync — frontmatter injection (pure transform).
3
+ *
4
+ * Layer 4 of the agents-*.ts family: string-in/string-out only. Consumes the
5
+ * enablement map (agent-enablement), the frontmatter scanner (frontmatter), and
6
+ * the models.json override reader (models-config). The sync engine
7
+ * (agents-sync) applies this transform before hashing so the manifest records
8
+ * hash-after-transform.
9
+ */
10
+
11
+ import { mergeCsvAdditions, mergeFlowSeqAdditions, resolveAgentEnablement } from "./agent-enablement.js";
12
+ import { parseFrontmatterBounds, readFrontmatterKey } from "./frontmatter.js";
13
+ import { getAgentModelConfig, type ModelsConfig } from "./models-config.js";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Frontmatter injection — pure transform
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /**
20
+ * Apply key-value updates to frontmatter lines.
21
+ *
22
+ * For each key in `keysToSet`, replaces the existing line if present
23
+ * (within the frontmatter bounds), or inserts a new line before the
24
+ * closing `---`. Returns the (possibly modified) lines array.
25
+ *
26
+ * The closing-fence index (`bounds.end`) is stable across in-place
27
+ * replacements — only the value changes, not the line count — so the
28
+ * insertion point remains correct without re-scanning.
29
+ */
30
+ function applyKeyUpdates(
31
+ lines: string[],
32
+ bounds: { start: number; end: number },
33
+ keysToSet: { key: string; value: string }[],
34
+ ): string[] {
35
+ const result = [...lines];
36
+ const insertLines: string[] = [];
37
+
38
+ for (const { key, value } of keysToSet) {
39
+ const prefix = `${key}: `;
40
+ const existingIdx = result.findIndex((line, i) => i > 0 && i < bounds.end && line.startsWith(prefix));
41
+ if (existingIdx !== -1) {
42
+ result[existingIdx] = `${prefix}${value}`;
43
+ } else {
44
+ insertLines.push(`${prefix}${value}`);
45
+ }
46
+ }
47
+
48
+ if (insertLines.length > 0) {
49
+ result.splice(bounds.end, 0, ...insertLines);
50
+ }
51
+
52
+ return result;
53
+ }
54
+
55
+ /**
56
+ * Install-gate context for conditional frontmatter injection.
57
+ *
58
+ * `installedExtensions` is the set of installed sibling extension names,
59
+ * derived from ONE settings read per sync pass. An absent context closes
60
+ * the enablement gate entirely — today's model/thinking-only behavior,
61
+ * byte-for-byte.
62
+ */
63
+ export interface AgentInjectionContext {
64
+ readonly installedExtensions: ReadonlySet<string>;
65
+ }
66
+
67
+ /**
68
+ * Inject model/thinking + conditional enablement frontmatter into agent .md content.
69
+ *
70
+ * Idempotent: re-injecting produces identical bytes, with the gate open or
71
+ * closed. The function finds the closing `---` of the YAML frontmatter
72
+ * block and deterministically inserts or replaces keys.
73
+ *
74
+ * Enablement (fourth arg): when the context names every sibling provider an
75
+ * agent's enablement requires as installed, the agent additionally gains
76
+ * the merged `tools` CSV, an `extensions: [...]` flow sequence, and — only
77
+ * when the shipped file carries `isolated: true` — the `isolated: false` +
78
+ * `skills: false` pair. No override and no active enablement ⇒ content
79
+ * unchanged.
80
+ *
81
+ * Exported so the idempotency invariant can be unit-tested directly:
82
+ * `inject(inject(x)) === inject(x)` (see Verification Notes).
83
+ */
84
+ export function injectModelFrontmatter(
85
+ content: string,
86
+ agentFile: string,
87
+ config: ModelsConfig,
88
+ injection?: AgentInjectionContext,
89
+ ): string {
90
+ // Strip .md extension — source entries are filenames like "codebase-analyzer.md"
91
+ // but models.json keys are agent names like "codebase-analyzer".
92
+ const agentKey = agentFile.replace(/\.md$/, "");
93
+ const override = getAgentModelConfig(config, agentKey);
94
+ const enablement = resolveAgentEnablement(agentKey, override, injection?.installedExtensions);
95
+ // Tools-only entries must not be skipped: enablement alone proceeds.
96
+ const hasModelKeys = override?.model !== undefined || override?.thinking !== undefined;
97
+ if (!hasModelKeys && enablement === undefined) {
98
+ return content;
99
+ }
100
+
101
+ const lines = content.split("\n");
102
+ const bounds = parseFrontmatterBounds(lines);
103
+ if (!bounds) return content;
104
+
105
+ const keysToSet: { key: string; value: string }[] = [];
106
+ // (post-slash-canonical migration): models.json values are byte-equal to
107
+ // the agent frontmatter form (both `provider/modelId`). No translation step
108
+ // — re-injecting produces identical bytes by construction; the idempotency
109
+ // invariant at injectModelFrontmatter's JSDoc strengthens from "deterministic
110
+ // translation" to "byte pass-through".
111
+ if (override?.model !== undefined) keysToSet.push({ key: "model", value: override.model });
112
+ if (override?.thinking !== undefined) keysToSet.push({ key: "thinking", value: override.thinking });
113
+
114
+ if (enablement !== undefined) {
115
+ // Fixed order [model?, thinking?, tools, extensions, isolated?, skills?]:
116
+ // in-place replacements keep their shipped position; absent keys append
117
+ // before the closing fence in this order.
118
+ const mergedTools = mergeCsvAdditions(readFrontmatterKey(lines, bounds, "tools"), enablement.tools);
119
+ const mergedExtensions = mergeFlowSeqAdditions(
120
+ readFrontmatterKey(lines, bounds, "extensions"),
121
+ enablement.extensions,
122
+ );
123
+ // ATOMIC transform (review 2026-08-31 I2): a merge that fail-soft-skips
124
+ // an unmergeable frontmatter form (block-sequence, sentinel) while its
125
+ // additions are non-empty means the grant CANNOT land — applying the
126
+ // remaining keys anyway would flip `isolated`/`skills` off while
127
+ // granting nothing, silently un-scoping the agent on every sync. Skip
128
+ // the whole enablement key set and warn loudly instead.
129
+ const toolsMergeFailed = enablement.tools.length > 0 && mergedTools === undefined;
130
+ const extensionsMergeFailed = enablement.extensions.length > 0 && mergedExtensions === undefined;
131
+ if (toolsMergeFailed || extensionsMergeFailed) {
132
+ console.warn(
133
+ `[rpiv-pi] agent enablement skipped for ${agentFile}: the ${toolsMergeFailed ? "tools" : "extensions"} frontmatter form is not mergeable (block sequence or sentinel value) — rewrite it as a ${toolsMergeFailed ? "single-line CSV scalar" : "flow sequence"} to receive the grant`,
134
+ );
135
+ } else {
136
+ if (mergedTools !== undefined) keysToSet.push({ key: "tools", value: mergedTools });
137
+ if (mergedExtensions !== undefined) keysToSet.push({ key: "extensions", value: mergedExtensions });
138
+ // Flipping isolation is the point of enablement (`ext:` selectors are
139
+ // dropped while isolated) — but derive the pair only when the source
140
+ // declares `isolated: true`: re-injecting an already-injected form pushes
141
+ // neither key (idempotency), and non-isolated agents stay untouched.
142
+ if (readFrontmatterKey(lines, bounds, "isolated")?.toLowerCase() === "true") {
143
+ keysToSet.push({ key: "isolated", value: "false" });
144
+ keysToSet.push({ key: "skills", value: "false" });
145
+ }
146
+ }
147
+ }
148
+
149
+ const updated = applyKeyUpdates(lines, bounds, keysToSet);
150
+ return updated.join("\n");
151
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Agent sync — managed-file manifest (filename → sha256 of installed content).
3
+ *
4
+ * Layer 3 of the agents-*.ts family: builds on the allowlist (agents-allowlist)
5
+ * and the result shapes (agents-types). Atomic tmp+rename writes keep the
6
+ * on-disk manifest always-parseable.
7
+ *
8
+ * Concurrency: NOT safe across multiple Pi sessions sharing one target dir.
9
+ * The temp+rename atomic write in writeManifest guarantees the on-disk manifest
10
+ * file is always a complete valid JSON (no truncated/half-written content), but
11
+ * the read-modify-write lost-update problem remains: two sessions both reading
12
+ * the manifest before either writes will race, and the second writer overwrites
13
+ * the first's entries with its own stale snapshot. Advisory locking is a
14
+ * deferred follow-up. The path allowlist in
15
+ * readManifest neutralises the worst-case (arbitrary-path unlink) regardless of
16
+ * concurrency.
17
+ */
18
+
19
+ import { createHash } from "node:crypto";
20
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { isManagedAgentName } from "./agents-allowlist.js";
23
+ import { SYNC_OP, type SyncResult } from "./agents-types.js";
24
+ import { isPlainObject, toErrorMessage } from "./utils.js";
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Manifest
28
+ // ---------------------------------------------------------------------------
29
+
30
+ export const MANIFEST_FILE = ".rpiv-managed.json";
31
+
32
+ /** Filename → sha256 hex of the content we last installed. Empty string = unknown. */
33
+ export type Manifest = Record<string, string>;
34
+
35
+ export function sha256(buf: Buffer | string): string {
36
+ return createHash("sha256").update(buf).digest("hex");
37
+ }
38
+
39
+ /**
40
+ * Read the managed-file manifest (`Record<filename, sha256>`) from the target
41
+ * directory. Any other shape (missing, corrupt JSON, non-object) reads as `{}`.
42
+ *
43
+ * Hardened against path-traversal: keys failing `isManagedAgentName` are dropped
44
+ * silently. A subsequent `writeManifest` rewrites the on-disk manifest without
45
+ * the rejected keys.
46
+ *
47
+ * Fail-soft: never throws.
48
+ */
49
+ export function readManifest(targetDir: string): Manifest {
50
+ const manifestPath = join(targetDir, MANIFEST_FILE);
51
+ if (!existsSync(manifestPath)) return {};
52
+ try {
53
+ const raw = readFileSync(manifestPath, "utf-8");
54
+ const parsed = JSON.parse(raw);
55
+ if (isPlainObject(parsed)) {
56
+ const out: Manifest = {};
57
+ for (const [k, v] of Object.entries(parsed)) {
58
+ if (typeof v === "string" && isManagedAgentName(k)) out[k] = v;
59
+ }
60
+ return out;
61
+ }
62
+ return {};
63
+ } catch {
64
+ return {};
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Write the managed-file manifest to the target directory.
70
+ * Pushes a `{ op: "manifest-write" }` SyncError on failure so consumers
71
+ * (notifyAgentSyncDrift, /rpiv-update-agents) can surface it instead of
72
+ * silently swallowing permission / disk-full errors.
73
+ */
74
+ export function writeManifest(targetDir: string, manifest: Manifest, result: SyncResult): void {
75
+ const manifestPath = join(targetDir, MANIFEST_FILE);
76
+ try {
77
+ const ordered: Manifest = {};
78
+ for (const k of Object.keys(manifest).sort()) ordered[k] = manifest[k];
79
+ const content = `${JSON.stringify(ordered, null, 2)}\n`;
80
+ // Atomic write: tmp file in same dir + renameSync (POSIX same-filesystem guarantee).
81
+ // Prevents write-write corruption under widened concurrency (global target).
82
+ // Pid-suffixed so concurrent sessions don't unlink each other's in-flight tmp files
83
+ // on the failure path (see catch's unlinkSync below).
84
+ const tmpFile = join(targetDir, `${MANIFEST_FILE}.${process.pid}.tmp`);
85
+ try {
86
+ writeFileSync(tmpFile, content, "utf-8");
87
+ renameSync(tmpFile, manifestPath);
88
+ } catch (inner) {
89
+ try {
90
+ unlinkSync(tmpFile);
91
+ } catch {
92
+ /* ignore */
93
+ }
94
+ throw inner;
95
+ }
96
+ } catch (e) {
97
+ result.errors.push({
98
+ op: SYNC_OP.MANIFEST_WRITE,
99
+ message: toErrorMessage(e),
100
+ });
101
+ }
102
+ }