@tduyng/pi-devos 0.0.0-stage → 0.13.6

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 (138) hide show
  1. package/CHANGELOG.md +1398 -0
  2. package/LICENSE +201 -0
  3. package/README.md +213 -2
  4. package/package.json +45 -4
  5. package/plugins/devos/agents/reader.md +27 -0
  6. package/plugins/devos/agents/verifier.md +181 -0
  7. package/plugins/devos/pi/extension/devos.ts +615 -0
  8. package/plugins/devos/scripts/check-evidence-router.sh +134 -0
  9. package/plugins/devos/scripts/evidence-router.py +252 -0
  10. package/plugins/devos/scripts/gates/check-dod-core.sh +283 -0
  11. package/plugins/devos/scripts/gates/check-dod.sh +38 -0
  12. package/plugins/devos/scripts/gates/check-handoff.sh +215 -0
  13. package/plugins/devos/scripts/gates/check-implementation-boundary.sh +99 -0
  14. package/plugins/devos/scripts/gates/check-port-source.sh +134 -0
  15. package/plugins/devos/scripts/gates/check-report-locations.sh +148 -0
  16. package/plugins/devos/scripts/gates/check-scenario-coverage.sh +102 -0
  17. package/plugins/devos/scripts/gates/gate-check.mjs +204 -0
  18. package/plugins/devos/scripts/gates/phase-gate.sh +208 -0
  19. package/plugins/devos/scripts/gates/plan-template-check.py +147 -0
  20. package/plugins/devos/scripts/gates/run-gate.sh +148 -0
  21. package/plugins/devos/scripts/gates/spec-template-check.py +165 -0
  22. package/plugins/devos/scripts/gates/test-gates.sh +4306 -0
  23. package/plugins/devos/scripts/gates/test-integrity-rubric.sh +152 -0
  24. package/plugins/devos/scripts/gates/test-phase-gate.sh +116 -0
  25. package/plugins/devos/skills/absorb/SKILL.md +75 -0
  26. package/plugins/devos/skills/absorb/references/distill.md +67 -0
  27. package/plugins/devos/skills/absorb/scripts/check-refs.sh +108 -0
  28. package/plugins/devos/skills/absorb/scripts/knowledge.py +258 -0
  29. package/plugins/devos/skills/build/SKILL.md +71 -0
  30. package/plugins/devos/skills/build/references/advanced-routing.md +19 -0
  31. package/plugins/devos/skills/build/references/defect.md +17 -0
  32. package/plugins/devos/skills/build/references/exposure.md +28 -0
  33. package/plugins/devos/skills/build/references/hard.md +39 -0
  34. package/plugins/devos/skills/build/references/refactor.md +66 -0
  35. package/plugins/devos/skills/build/references/routes.md +56 -0
  36. package/plugins/devos/skills/build/references/scale.md +84 -0
  37. package/plugins/devos/skills/build/references/spike.md +19 -0
  38. package/plugins/devos/skills/build/scripts/construct-census.py +204 -0
  39. package/plugins/devos/skills/build/scripts/dep-order.py +297 -0
  40. package/plugins/devos/skills/build/scripts/ledger.sh +228 -0
  41. package/plugins/devos/skills/build/scripts/route.sh +5 -0
  42. package/plugins/devos/skills/build/scripts/secret-scan.sh +121 -0
  43. package/plugins/devos/skills/build/scripts/toolchain-preflight.py +302 -0
  44. package/plugins/devos/skills/design-taste/SKILL.md +55 -0
  45. package/plugins/devos/skills/design-taste/references/tells.md +85 -0
  46. package/plugins/devos/skills/design-taste/scripts/slop-scan.py +305 -0
  47. package/plugins/devos/skills/docs/SKILL.md +22 -0
  48. package/plugins/devos/skills/docs/references/backfill.md +54 -0
  49. package/plugins/devos/skills/docs/references/init.md +43 -0
  50. package/plugins/devos/skills/docs/references/status.md +71 -0
  51. package/plugins/devos/skills/docs/references/update.md +80 -0
  52. package/plugins/devos/skills/explain/SKILL.md +45 -0
  53. package/plugins/devos/skills/explain/references/quiz.md +21 -0
  54. package/plugins/devos/skills/frame/SKILL.md +71 -0
  55. package/plugins/devos/skills/frame/references/boundaries.md +53 -0
  56. package/plugins/devos/skills/frame/references/decompose.md +96 -0
  57. package/plugins/devos/skills/frame/references/impact.md +43 -0
  58. package/plugins/devos/skills/frame/references/interrogate.md +68 -0
  59. package/plugins/devos/skills/frame/scripts/survey.sh +44 -0
  60. package/plugins/devos/skills/implement/SKILL.md +36 -0
  61. package/plugins/devos/skills/implement/references/conditional-plan.md +17 -0
  62. package/plugins/devos/skills/implement/references/debug-loop.md +7 -0
  63. package/plugins/devos/skills/implement/references/dod.md +32 -0
  64. package/plugins/devos/skills/implement/references/implement.md +52 -0
  65. package/plugins/devos/skills/implement/references/manual-gates.md +16 -0
  66. package/plugins/devos/skills/implement/references/plan.md +160 -0
  67. package/plugins/devos/skills/implement/references/resume.md +9 -0
  68. package/plugins/devos/skills/implement/references/scale.md +86 -0
  69. package/plugins/devos/skills/implement/references/verify-close.md +61 -0
  70. package/plugins/devos/skills/implement/references/visual-verification.md +7 -0
  71. package/plugins/devos/skills/implement/scripts/check-converge.sh +147 -0
  72. package/plugins/devos/skills/implement/scripts/equivalence-check.sh +140 -0
  73. package/plugins/devos/skills/implement/scripts/manifest-queue.sh +185 -0
  74. package/plugins/devos/skills/implement/scripts/ops-log.sh +58 -0
  75. package/plugins/devos/skills/implement/scripts/pilot-consistency.py +173 -0
  76. package/plugins/devos/skills/implement/scripts/validate-spec.sh +268 -0
  77. package/plugins/devos/skills/init/SKILL.md +100 -0
  78. package/plugins/devos/skills/init/references/archetype-sections.md +15 -0
  79. package/plugins/devos/skills/init/references/context.md +42 -0
  80. package/plugins/devos/skills/init/references/conventions-template.md +153 -0
  81. package/plugins/devos/skills/init/references/reverse-engineer.md +3 -0
  82. package/plugins/devos/skills/init/references/rule-format.md +58 -0
  83. package/plugins/devos/skills/init/references/shape-model.md +29 -0
  84. package/plugins/devos/skills/init/scripts/detect-archetype.py +461 -0
  85. package/plugins/devos/skills/init/scripts/render-rule.py +114 -0
  86. package/plugins/devos/skills/init/scripts/reverse-engineer.sh +162 -0
  87. package/plugins/devos/skills/learn/SKILL.md +29 -0
  88. package/plugins/devos/skills/learn/references/destinations.md +43 -0
  89. package/plugins/devos/skills/learn/references/scoring.md +26 -0
  90. package/plugins/devos/skills/product/SKILL.md +40 -0
  91. package/plugins/devos/skills/product/references/planner.md +54 -0
  92. package/plugins/devos/skills/review/SKILL.md +77 -0
  93. package/plugins/devos/skills/review/references/gaps.md +26 -0
  94. package/plugins/devos/skills/spec/SKILL.md +58 -0
  95. package/plugins/devos/skills/spec/references/prototype.md +21 -0
  96. package/plugins/devos/skills/spec/references/question-craft.md +47 -0
  97. package/plugins/devos/skills/spec/references/roadmap-link.md +5 -0
  98. package/plugins/devos/skills/spec/references/write-spec.md +143 -0
  99. package/plugins/devos/skills/spec/scripts/clarify.sh +173 -0
  100. package/plugins/devos/skills/status/SKILL.md +67 -0
  101. package/plugins/devos/skills/status/references/cost.md +38 -0
  102. package/plugins/devos/skills/status/scripts/artifact-budgets.sh +88 -0
  103. package/plugins/devos/skills/status/scripts/check-requires.py +556 -0
  104. package/plugins/devos/skills/status/scripts/context-cost.sh +89 -0
  105. package/plugins/devos/skills/status/scripts/convention-usage.sh +184 -0
  106. package/plugins/devos/skills/status/scripts/findings-summary.sh +112 -0
  107. package/plugins/devos/skills/status/scripts/quality-correlation.sh +282 -0
  108. package/plugins/devos/skills/status/scripts/sizing-calibration.sh +71 -0
  109. package/plugins/devos/skills/status/scripts/spec-diff.sh +137 -0
  110. package/plugins/devos/skills/surgical-diff/SKILL.md +23 -0
  111. package/plugins/devos/skills/test-integrity/SKILL.md +26 -0
  112. package/plugins/devos/skills/verification-evidence/SKILL.md +17 -0
  113. package/plugins/devos/workflows/common/backlog-file-structure.md +44 -0
  114. package/plugins/devos/workflows/common/category-file-structure.md +41 -0
  115. package/plugins/devos/workflows/common/feature-line-format.md +10 -0
  116. package/plugins/devos/workflows/common/roadmap-file-structure.md +51 -0
  117. package/plugins/devos/workflows/common/suggest-categories.md +76 -0
  118. package/plugins/devos/workflows/common/suggest-milestones.md +92 -0
  119. package/plugins/devos/workflows/doc/doc-health.md +137 -0
  120. package/plugins/devos/workflows/doc/doc-writer.md +44 -0
  121. package/plugins/devos/workflows/doc/init-documentation.md +196 -0
  122. package/plugins/devos/workflows/doc/retro-documentation.md +304 -0
  123. package/plugins/devos/workflows/doc/templates/library.md +58 -0
  124. package/plugins/devos/workflows/doc/templates/service.md +61 -0
  125. package/plugins/devos/workflows/doc/update-documentation.md +194 -0
  126. package/plugins/devos/workflows/doc/write-documentation.md +137 -0
  127. package/plugins/devos/workflows/product/create-product-mission.md +45 -0
  128. package/plugins/devos/workflows/product/create-product-roadmap.md +106 -0
  129. package/plugins/devos/workflows/product/create-product-tech-stack.md +19 -0
  130. package/plugins/devos/workflows/product/gather-product-info.md +25 -0
  131. package/plugins/devos/workflows/product/resume-detection.md +70 -0
  132. package/plugins/devos/workflows/product/reverse-backlog.md +118 -0
  133. package/plugins/devos/workflows/product/reverse-domain-model.md +86 -0
  134. package/plugins/devos/workflows/product/reverse-product-plan.md +81 -0
  135. package/plugins/devos/workflows/product/reverse-tech-stack.md +73 -0
  136. package/plugins/devos/workflows/product/scan-deep.md +113 -0
  137. package/plugins/devos/workflows/product/scan-git.md +122 -0
  138. package/plugins/devos/workflows/product/scan-light.md +154 -0
@@ -0,0 +1,615 @@
1
+ // @ts-nocheck
2
+ // DevOS gates for Pi, the one real-code piece of this adapter.
3
+ //
4
+ // Verified against the installed @earendil-works/pi-coding-agent 1.4.0 type
5
+ // definitions on this machine (dist/core/extensions/types.d.ts and
6
+ // dist/core/tools/{edit,write}.js), not against docs:
7
+ //
8
+ // - test-integrity: `tool_call` fires before every tool runs and its result
9
+ // type is `ToolCallEventResult { block?, reason?, terminate? }`. Returning
10
+ // `{block: true}` denies the call outright, so this gate is a HARD BLOCK
11
+ // here, the same guarantee Claude Code's PreToolUse exit-2 gives. Unlike
12
+ // every other adapter, the payload
13
+ // field names are typed rather than guessed: `edit` is
14
+ // `{path, edits: [{oldText, newText}]}` and `write` is `{path, content}`.
15
+ // - Definition-of-Done + handoff: no blocking turn-end event exists
16
+ // (`turn_end` / `agent_end` / `agent_settled` all return void), so these
17
+ // gates enforce at the close protocol's own chokepoints instead: a
18
+ // `tool_call` hard block denies `ops-log.sh <spec> closed` while the spec
19
+ // lacks its verification report, and denies phase transitions that fail
20
+ // check-handoff.sh. On top of that, `turn_end` carries `message` directly
21
+ // and `pi.sendUserMessage()` injects a follow-up correction for a false
22
+ // DONE claim, as a backstop with a progress-aware budget.
23
+ //
24
+ // No import from the pi package or typebox: this file is installed from a
25
+ // git checkout that has no node_modules, so a bare-specifier import would not
26
+ // resolve (the test runs the file under plain node). registerTool accepts a
27
+ // plain JSON Schema object; verified live against 0.84.2 that pi registers it,
28
+ // validates tool calls against it and executes it. Node builtins only, same
29
+ // posture as the herdr integration's extension.
30
+ import fs from "node:fs";
31
+ import os from "node:os";
32
+ import path from "node:path";
33
+ import { spawnSync } from "node:child_process";
34
+ import { fileURLToPath } from "node:url";
35
+
36
+ // The extension ships inside the plugin at plugins/devos/pi/extension, which is
37
+ // four levels below the repo root. GATES must point at this DevOS checkout
38
+ // wherever `pi install` resolved the package from.
39
+ const HERE = path.dirname(fs.realpathSync(fileURLToPath(import.meta.url)));
40
+ const DEVOS_ROOT = path.join(HERE, "../../../..");
41
+ const GATES = path.join(DEVOS_ROOT, "plugins/devos/scripts/gates");
42
+
43
+ // Claude Code expands `${CLAUDE_PLUGIN_ROOT}` (a plugin's root) and
44
+ // `${CLAUDE_SKILL_DIR}` (the running skill's own directory); Pi expands
45
+ // neither, so skill lines carrying them reach the shell literally. Nine
46
+ // skills use them. Each variable gets a candidate list, and a reference
47
+ // resolves to the first candidate where the referenced path actually exists.
48
+ // DevOS ships one plugin, so the list has one root.
49
+ const PLUGIN_ROOTS = [path.join(DEVOS_ROOT, "plugins", "devos")].filter((p) => fs.existsSync(p));
50
+
51
+ const SKILL_DIRS = PLUGIN_ROOTS.flatMap((root) => {
52
+ const dir = path.join(root, "skills");
53
+ try {
54
+ return fs
55
+ .readdirSync(dir, { withFileTypes: true })
56
+ .filter((e) => e.isDirectory())
57
+ .map((e) => path.join(dir, e.name));
58
+ } catch {
59
+ return [];
60
+ }
61
+ });
62
+
63
+ const VAR_BASES = {
64
+ CLAUDE_PLUGIN_ROOT: PLUGIN_ROOTS,
65
+ CLAUDE_SKILL_DIR: SKILL_DIRS,
66
+ };
67
+
68
+ // The field each built-in tool carries a path-shaped argument on. A skill puts
69
+ // a variable in a `bash` command or a file path, and the model reaches for the
70
+ // narrower tool whenever it can, so every one of them gets the same rewrite.
71
+ const VAR_FIELD = {
72
+ bash: "command",
73
+ powershell: "command",
74
+ read: "path",
75
+ edit: "path",
76
+ write: "path",
77
+ grep: "path",
78
+ find: "path",
79
+ ls: "path",
80
+ };
81
+
82
+ const DEVOS_SKILL_NAMES = new Set(SKILL_DIRS.map((d) => path.basename(d)));
83
+
84
+ // A tool that wraps a DevOS skill in a command file says "read and follow
85
+ // this now" there. Pi expands
86
+ // `/skill:<name>` itself, into a bare `<skill>…</skill>` block with no
87
+ // instruction attached, so the model reads an injected document and answers
88
+ // "what would you like to work on?" instead of running step 1. Verified
89
+ // against pi 0.85.1: `input` fires before the expansion and anything after
90
+ // the command name is appended below the block, so the wrapper rides in as
91
+ // the skill's arguments.
92
+ const RUN_NOW =
93
+ "The skill above was injected because you were invoked as a DevOS command. It is this " +
94
+ "command's instruction set: follow it as written, in this conversation, starting at its " +
95
+ "first step, before any other action. The repository and the " +
96
+ "text under **Input** (absent when the command takes none) are the whole input; asking what " +
97
+ "to work on instead of starting is the one failure this wrapper exists to prevent. A literal " +
98
+ "`$ARGUMENTS` in the skill is that same **Input**: read it there, never ask for it again.\n\n" +
99
+ "Read each file the skill sends you to whole, with the read tool. A `sed -n` or `head` slice " +
100
+ "drops the gate a reference states at its end. The phases and gates are the work, not ceremony " +
101
+ "to trim for a task that looks simple. Once you write a spec, project edits stay blocked until the user approves its plan.\n\n" +
102
+ "Four names reach this harness differently, and taking the skill literally on any of them " +
103
+ "is a stall:\n" +
104
+ "- A DevOS command written `/devos:<name>` is `/skill:<name>` here. Use that spelling when " +
105
+ "you suggest one to the user; where the skill tells you to run one yourself, read " +
106
+ "`../<name>/SKILL.md` relative to this skill's own directory and follow it in full, since " +
107
+ "running that step from memory is how its gates get skipped.\n" +
108
+ "- `${CLAUDE_SKILL_DIR}` and `${CLAUDE_PLUGIN_ROOT}` are rewritten inside a bash command and " +
109
+ "stay literal in prose: keep them in the command, do not guess a path.\n" +
110
+ "- A dispatch to a fresh context is the `subagent` tool here (agent, task, optional cwd). " +
111
+ "If no such tool is among yours, run that step in this conversation and carry the marker the " +
112
+ "skill gives for it, rather than skipping the step.\n" +
113
+ "- A question asked through `AskUserQuestion` is the `ask_user` tool here. If `ask_user` is not " +
114
+ "among your tools, ask the same question in plain text and end the turn.";
115
+
116
+ /** Text for a `/skill:<devos-skill>` invocation, with the run-now wrapper
117
+ * appended as the skill's arguments. Null for anything else. */
118
+ export function wrapSkillCommand(text) {
119
+ if (!text.startsWith("/skill:")) return null;
120
+ const space = text.indexOf(" ");
121
+ const name = space === -1 ? text.slice(7) : text.slice(7, space);
122
+ if (!DEVOS_SKILL_NAMES.has(name)) return null;
123
+ const args = space === -1 ? "" : text.slice(space + 1).trim();
124
+ const input = args ? `**Input:** ${args}\n\n` : "";
125
+ return `/skill:${name} ${input}${RUN_NOW}`;
126
+ }
127
+
128
+ // Single-plugin references that never reach the rewriter (a subshell, an env
129
+ // lookup) still expand to something real.
130
+ if (PLUGIN_ROOTS.length > 0) process.env.CLAUDE_PLUGIN_ROOT = PLUGIN_ROOTS[0];
131
+
132
+ const VAR_RE =
133
+ /\$\{(CLAUDE_PLUGIN_ROOT|CLAUDE_SKILL_DIR)\}([\w./-]*)|\$(CLAUDE_PLUGIN_ROOT|CLAUDE_SKILL_DIR)([\w./-]*)/g;
134
+
135
+ /** Rewrite `${VAR}/rel` and `$VAR/rel` to the first candidate base where
136
+ * `base/rel` exists. No candidate matches -> first base, so the failure is a
137
+ * missing file with a real path in it, not an unexpanded variable. */
138
+ export function resolveClaudeVars(text) {
139
+ return text.replace(VAR_RE, (match, braced, bracedRel, bare, bareRel) => {
140
+ const name = braced || bare;
141
+ const rel = (braced ? bracedRel : bareRel) || "";
142
+ const bases = VAR_BASES[name] || [];
143
+ if (bases.length === 0) return match;
144
+ const hit = rel ? bases.find((b) => fs.existsSync(path.join(b, rel))) : null;
145
+ return (hit || bases[0]) + rel;
146
+ });
147
+ }
148
+
149
+ /** Repo-state proxy for the stall counter: porcelain status plus HEAD.
150
+ * A constant string on a non-repo cwd is fine: stalled then means "nothing
151
+ * observable changed", which is exactly the question being asked. */
152
+ function repoState(cwd) {
153
+ try {
154
+ const status = spawnSync("git", ["-C", cwd || ".", "status", "--porcelain"], { encoding: "utf8" });
155
+ const head = spawnSync("git", ["-C", cwd || ".", "log", "--oneline", "-1"], { encoding: "utf8" });
156
+ return `${status.stdout || ""}|${head.stdout || ""}`;
157
+ } catch {
158
+ return "";
159
+ }
160
+ }
161
+
162
+ /** Session-entry type backing the correction budget (see session_start). */
163
+ const CORRECTION_ENTRY = "devos-gate-correction";
164
+
165
+ /** Run a gate script. Returns {code, stderr}. Never throws: a gate that
166
+ * cannot run must allow (fail open). */
167
+ function runGate(script, args) {
168
+ try {
169
+ const r = spawnSync("bash", [path.join(GATES, script), ...args], {
170
+ encoding: "utf8",
171
+ });
172
+ if (r.error) return { code: 0, stderr: "" };
173
+ return { code: r.status ?? 0, stderr: (r.stderr || "").trim() };
174
+ } catch {
175
+ return { code: 0, stderr: "" };
176
+ }
177
+ }
178
+
179
+ /** Concatenated text of an assistant message's content parts. */
180
+ function textOf(message) {
181
+ const content = message?.content;
182
+ if (!Array.isArray(content)) return content ?? "";
183
+ return content
184
+ .filter((c) => c?.type === "text" && c.text)
185
+ .map((c) => c.text)
186
+ .join("\n");
187
+ }
188
+
189
+ // The plan gate. Prose rules hold for a model that reads all of them and
190
+ // weighs them as written. A weaker model reads part of plan.md, decides the
191
+ // approval step is ceremony, and edits code on the original ask. So the
192
+ // harness holds the phase: the spec folder this session opened decides what
193
+ // may change, derived from its files on every call.
194
+ const ACTIVE_SPEC_ENTRY = "devos-active-spec";
195
+ const IMPLEMENT_DIR = path.join(DEVOS_ROOT, "plugins/devos/skills/implement");
196
+ const SPEC_FILE_RE = /^(.*\/devos\/specs\/(?!archive\/)[^/]+)\/(?:spec-functional|spec)\.md$/;
197
+ const OPS_EVENT_RE = /ops-log\.sh\s+("[^"]+"|\S+)\s+(started|plan-approved|implemented|verified|closed)(?:\s|"|'|$)/;
198
+ const BASH_MUTATION_RE =
199
+ /\bsed\b[^|;&]*\s-(?:[a-zA-Z]*i\b|-in-place)|\bperl\b[^|;&]*\s-[a-zA-Z]*i|\bgit\s+(?:apply|commit|am)\b/;
200
+ const ROUTE_CMD_RE = /route\.sh\s+"?([FSMLRBCH])\b/;
201
+ const ASK_TOOLS = new Set(["ask_user", "AskUserQuestion"]);
202
+
203
+ const PHASES = {
204
+ spike: {
205
+ blocksCode: false,
206
+ next: "A spike is finished when findings.md holds the recommendation and the gaps. Build the recommended option next.",
207
+ },
208
+ "plan-missing": {
209
+ blocksCode: true,
210
+ next:
211
+ `Phase A. Read ${IMPLEMENT_DIR}/SKILL.md and ${IMPLEMENT_DIR}/references/plan.md whole, ` +
212
+ "write spec.md in the spec folder, present the plan, and end your turn for the user's yes.",
213
+ },
214
+ "awaiting-approval": {
215
+ blocksCode: true,
216
+ next:
217
+ "Phase A, plan written, not approved. Present the plan in a few plain lines and end your turn. " +
218
+ "After the user's unambiguous yes, log `ops-log.sh SPEC_DIR plan-approved`.",
219
+ },
220
+ "verify-pending": {
221
+ blocksCode: false,
222
+ next:
223
+ `Phase B, then C. Build the approved plan, then read ${IMPLEMENT_DIR}/references/verify-close.md ` +
224
+ "and write verifications/verification.md before any done claim.",
225
+ },
226
+ "close-pending": {
227
+ blocksCode: false,
228
+ next: `Phase C. Verified. Read ${IMPLEMENT_DIR}/references/dod.md, give the verdict, archive the folder.`,
229
+ },
230
+ missing: {
231
+ blocksCode: true,
232
+ next: "The spec folder is gone without being archived. Ask the user whether to drop it.",
233
+ },
234
+ archived: { blocksCode: false, next: "" },
235
+ };
236
+
237
+ // The route gate, one step earlier. A model that sized the task as M in its
238
+ // own words can still answer the next "go" by editing code, because no spec
239
+ // folder exists yet for the plan gate to hold. So /skill:build commits the
240
+ // size through devos_route before any project file changes, and a route that
241
+ // owes a spec keeps code blocked until the spec folder exists.
242
+ const ROUTE_ENTRY = "devos-route";
243
+ const BUILD_REFS = path.join(DEVOS_ROOT, "plugins/devos/skills/build/references");
244
+ const SPEC_ROUTE_NEXT =
245
+ "Create devos/specs/YYYY-MM-DD-<name>/spec-functional.md now, as " +
246
+ `${BUILD_REFS}/routes.md says for this size. Project files stay blocked until its plan is approved.`;
247
+ const FRAME_NEXT =
248
+ `Read ${path.join(DEVOS_ROOT, "plugins/devos/skills/frame")}/SKILL.md whole. A frame changes no production code: ` +
249
+ "it ends with devos/frames/<name>/tickets.md and one re-route per ticket.";
250
+ const ROUTES = {
251
+ F: { blocksCode: true, next: FRAME_NEXT },
252
+ S: { blocksCode: false, next: "Say the change in one plain sentence, make it, run the checks that cover it." },
253
+ M: { blocksCode: true, next: SPEC_ROUTE_NEXT },
254
+ L: { blocksCode: true, next: SPEC_ROUTE_NEXT },
255
+ C: { blocksCode: true, next: `Read ${BUILD_REFS}/refactor.md whole. ${SPEC_ROUTE_NEXT}` },
256
+ R: { blocksCode: true, next: `Read ${BUILD_REFS}/spike.md whole. A spike changes no production code.` },
257
+ B: { blocksCode: false, next: `Read ${BUILD_REFS}/defect.md whole and reproduce before any fix.` },
258
+ H: { blocksCode: false, next: `Read ${BUILD_REFS}/hard.md whole and start the ledger.` },
259
+ };
260
+ const UNROUTED_NEXT = "Size the task from the code, then call devos_route with the size before changing any file.";
261
+
262
+ /** Phase of a spec folder, from its files alone. */
263
+ export function specPhase(specDir) {
264
+ const has = (rel) => fs.existsSync(path.join(specDir, rel));
265
+ if (!fs.existsSync(specDir)) {
266
+ const archived = path.join(path.dirname(specDir), "archive", path.basename(specDir));
267
+ return fs.existsSync(archived) ? "archived" : "missing";
268
+ }
269
+ // A spike folder holds findings.md only, so it is a finished spike, not a spec without a plan.
270
+ if (!has("spec.md") && has("findings.md")) return "spike";
271
+ if (!has("spec.md")) return "plan-missing";
272
+ const ops = has("ops.jsonl") ? fs.readFileSync(path.join(specDir, "ops.jsonl"), "utf8") : "";
273
+ if (!ops.includes('"event":"plan-approved"')) return "awaiting-approval";
274
+ return has("verifications/verification.md") ? "close-pending" : "verify-pending";
275
+ }
276
+
277
+ function projectRootOf(specDir) {
278
+ return path.dirname(path.dirname(path.dirname(specDir)));
279
+ }
280
+
281
+ function isInside(file, dir) {
282
+ const rel = path.relative(dir, file);
283
+ return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
284
+ }
285
+
286
+ function routeGateReason(route, what) {
287
+ const next = route === "unrouted" ? UNROUTED_NEXT : `Route ${route}. ${ROUTES[route].next}`;
288
+ return `DevOS route gate: ${what} is blocked. ${next} Only the user lifts this gate, by running /devos-release.`;
289
+ }
290
+
291
+ function planGateReason(specDir, phase, what) {
292
+ return (
293
+ `DevOS plan gate: ${what} is blocked. ${path.relative(projectRootOf(specDir), specDir)} has no approved plan. ` +
294
+ `${PHASES[phase].next.replace("SPEC_DIR", specDir)} ` +
295
+ "Only the user lifts this gate: by approving the plan, or by running /devos-release."
296
+ );
297
+ }
298
+
299
+ function withTempPair(oldContent, newContent, fn) {
300
+ const stamp = `${process.pid}-${Math.random().toString(36).slice(2)}`;
301
+ const oldTmp = path.join(os.tmpdir(), `devos-old-${stamp}`);
302
+ const newTmp = path.join(os.tmpdir(), `devos-new-${stamp}`);
303
+ try {
304
+ fs.writeFileSync(oldTmp, oldContent);
305
+ fs.writeFileSync(newTmp, newContent);
306
+ return fn(oldTmp, newTmp);
307
+ } finally {
308
+ fs.rmSync(oldTmp, { force: true });
309
+ fs.rmSync(newTmp, { force: true });
310
+ }
311
+ }
312
+
313
+ export default function devosExtension(pi) {
314
+ // Each correction triggers a new turn, which fires turn_end again. Without
315
+ // a cap, a model that keeps repeating a malformed DONE claim would loop
316
+ // forever, spending real turns each time. Progress-aware budget: a correction
317
+ // resets its stall
318
+ // counter whenever the repo state changed since the previous one, proxied
319
+ // by `git status --porcelain` plus HEAD (fixes commit or dirty files;
320
+ // verification reports land under devos/specs/, so they show too). Stalled
321
+ // = corrections with zero state change between them: MAX_STALLED of those
322
+ // in a row, or MAX_TOTAL overall, send the gate quiet and the human reads
323
+ // the corrections already in the session. The proxy cannot see edits inside
324
+ // an already-dirty file; MAX_TOTAL bounds that ceiling.
325
+ const correctedTurns = new Set();
326
+ const MAX_STALLED = 2;
327
+ const MAX_TOTAL = 6;
328
+ let corrections = 0;
329
+ let stalled = 0;
330
+ let lastStateHash = "";
331
+ let activeSpec = null;
332
+ let route = null;
333
+ let lastHumanAt = 0;
334
+
335
+ // The budget survives /tree navigation and session reload: every correction
336
+ // is appended as a custom session entry and replayed on startup, so a
337
+ // reloaded session cannot re-spend it. Entries carry the running counters;
338
+ // pre-0.10.14 entries carry only turnIndex and replay as +1 each.
339
+ pi.on("session_start", async (_event, ctx) => {
340
+ for (const entry of ctx?.sessionManager?.getEntries() ?? []) {
341
+ if (entry.type === "custom" && entry.customType === ACTIVE_SPEC_ENTRY) {
342
+ activeSpec = entry.data?.specDir ?? null;
343
+ }
344
+ if (entry.type === "custom" && entry.customType === ROUTE_ENTRY) {
345
+ route = entry.data?.route ?? null;
346
+ }
347
+ if (entry.type === "custom" && entry.customType === CORRECTION_ENTRY) {
348
+ if (Number.isFinite(entry.data?.corrections)) {
349
+ corrections = Math.max(corrections, entry.data.corrections);
350
+ stalled = Math.max(stalled, entry.data.stalled ?? 0);
351
+ lastStateHash = entry.data.stateHash ?? lastStateHash;
352
+ } else {
353
+ corrections += 1;
354
+ }
355
+ if (Number.isFinite(entry.data?.turnIndex)) correctedTurns.add(entry.data.turnIndex);
356
+ }
357
+ }
358
+ });
359
+
360
+ function setActiveSpec(specDir) {
361
+ if (specDir && (route === "unrouted" || route === "M" || route === "L" || route === "C")) setRoute(null);
362
+ if (specDir === activeSpec) return;
363
+ activeSpec = specDir;
364
+ pi.appendEntry(ACTIVE_SPEC_ENTRY, { specDir });
365
+ }
366
+
367
+ function setRoute(next) {
368
+ if (next === route) return;
369
+ route = next;
370
+ pi.appendEntry(ROUTE_ENTRY, { route });
371
+ }
372
+
373
+ pi.registerTool({
374
+ name: "devos_route",
375
+ label: "DevOS route",
376
+ description:
377
+ "Commit the size you picked for a /skill:build task, before changing any project file. " +
378
+ "F first when the ask does not say what to change: a bare ticket title, a wish, an epic. " +
379
+ "S only for zero blast radius, sized from the code: a user calling it simple does not make it S. " +
380
+ "M, L and C must write a spec and get the plan approved before code changes. " +
381
+ "Once a larger size is set, only the user can drop back to S.",
382
+ parameters: {
383
+ type: "object",
384
+ properties: {
385
+ size: { type: "string", enum: Object.keys(ROUTES), description: "The route from build/SKILL.md" },
386
+ why: { type: "string", description: "One sentence: the evidence from the code that decided the size" },
387
+ },
388
+ required: ["size", "why"],
389
+ },
390
+ async execute(_id, params) {
391
+ return { content: [{ type: "text", text: commitRoute(params.size).text }], details: { route } };
392
+ },
393
+ });
394
+
395
+ function commitRoute(size) {
396
+ if (!ROUTES[size]) return { refused: true, text: `Unknown size ${size}. ${UNROUTED_NEXT}` };
397
+ if (size === "S" && route && route !== "unrouted" && route !== "F" && route !== "S") {
398
+ return {
399
+ refused: true,
400
+ text:
401
+ `Refused: this task is already routed ${route}, and a route never shrinks on the model's word. ` +
402
+ `${ROUTES[route].next} Ask the user if you think it is S.`,
403
+ };
404
+ }
405
+ setRoute(size);
406
+ return { refused: false, text: `Route ${size}. ${ROUTES[size].next}` };
407
+ }
408
+
409
+ pi.registerCommand("devos-release", {
410
+ description: "Drop the DevOS plan gate for this session's spec",
411
+ handler: async (_args, ctx) => {
412
+ const was = activeSpec ?? (route ? `route ${route}` : null);
413
+ setActiveSpec(null);
414
+ setRoute(null);
415
+ ctx?.ui?.notify?.(was ? `DevOS gate released for ${was}` : "No active DevOS gate", "info");
416
+ },
417
+ });
418
+
419
+ pi.on("before_agent_start", async (event) => {
420
+ const sections = event.systemPromptOptions?.sections;
421
+ if (!sections) return;
422
+ const phase = activeSpec ? specPhase(activeSpec) : "archived";
423
+ if (phase === "archived") {
424
+ if (route === "unrouted") sections["devos-state"] = `DevOS /skill:build in progress. ${UNROUTED_NEXT}`;
425
+ else if (route) sections["devos-state"] = `DevOS /skill:build route ${route}. ${ROUTES[route].next}`;
426
+ else delete sections["devos-state"];
427
+ return;
428
+ }
429
+ sections["devos-state"] =
430
+ `Active DevOS spec: ${activeSpec}\nPhase: ${phase}\nNext: ${PHASES[phase].next.replace("SPEC_DIR", activeSpec)}` +
431
+ (PHASES[phase].blocksCode ? "\nFiles outside devos/ stay unchanged until the plan is approved." : "");
432
+ });
433
+
434
+ pi.on("tool_result", async (event) => {
435
+ if (ASK_TOOLS.has(event.toolName) && !event.isError) lastHumanAt = Date.now();
436
+ });
437
+
438
+ pi.on("input", async (event) => {
439
+ if (event.source === "extension") return { action: "continue" };
440
+ lastHumanAt = Date.now();
441
+ if (/^\/skill:build(?:\s|$)/.test(event.text)) setRoute("unrouted");
442
+ const text = wrapSkillCommand(event.text);
443
+ return text ? { action: "transform", text } : { action: "continue" };
444
+ });
445
+
446
+ // One `tool_call` registration, two jobs, in order: expand the Claude Code
447
+ // path variables on whichever field that tool feeds them to, then run the
448
+ // test-integrity gate on `edit`/`write`.
449
+ pi.on("tool_call", async (event, ctx) => {
450
+ const input = event.input || {};
451
+
452
+ const varField = VAR_FIELD[event.toolName];
453
+ if (varField && input[varField]) input[varField] = resolveClaudeVars(input[varField]);
454
+
455
+ const target =
456
+ (event.toolName === "edit" || event.toolName === "write") && input.path
457
+ ? path.resolve(ctx?.cwd || ".", input.path)
458
+ : null;
459
+ const specFile = target?.match(SPEC_FILE_RE);
460
+ if (specFile) setActiveSpec(specFile[1]);
461
+
462
+ const routeCmd = event.toolName === "bash" ? input.command?.match(ROUTE_CMD_RE) : null;
463
+ if (routeCmd) {
464
+ const committed = commitRoute(routeCmd[1]);
465
+ if (committed.refused) return { block: true, reason: `DevOS route gate: ${committed.text}` };
466
+ }
467
+
468
+ const opsEvent = event.toolName === "bash" ? input.command?.match(OPS_EVENT_RE) : null;
469
+ const opsSpec = opsEvent ? path.resolve(ctx?.cwd || ".", opsEvent[1].replace(/^"|"$/g, "")) : null;
470
+ if (opsEvent?.[2] === "started") setActiveSpec(opsSpec);
471
+ if (opsEvent?.[2] === "plan-approved") {
472
+ if (!fs.existsSync(path.join(opsSpec, "spec.md"))) {
473
+ return { block: true, reason: planGateReason(opsSpec, "plan-missing", "Logging plan-approved") };
474
+ }
475
+ const planAt = fs.statSync(path.join(opsSpec, "spec.md")).mtimeMs;
476
+ if (ctx?.hasUI && lastHumanAt <= planAt) {
477
+ return {
478
+ block: true,
479
+ reason:
480
+ "DevOS plan gate: the user has not replied since spec.md was last written, so nobody approved " +
481
+ "this plan. Present it and end your turn. The original request is not the approval.",
482
+ };
483
+ }
484
+ setActiveSpec(opsSpec);
485
+ }
486
+
487
+ if (route && (route === "unrouted" || ROUTES[route].blocksCode)) {
488
+ const root = path.resolve(ctx?.cwd || ".");
489
+ if (target && isInside(target, root) && !isInside(target, path.join(root, "devos"))) {
490
+ return { block: true, reason: routeGateReason(route, `Changing ${path.relative(root, target)}`) };
491
+ }
492
+ if (event.toolName === "bash" && BASH_MUTATION_RE.test(input.command || "")) {
493
+ return { block: true, reason: routeGateReason(route, "An in-place edit or commit from bash") };
494
+ }
495
+ }
496
+
497
+ const phase = activeSpec ? specPhase(activeSpec) : "archived";
498
+ if (PHASES[phase].blocksCode) {
499
+ const root = projectRootOf(activeSpec);
500
+ if (target && isInside(target, root) && !isInside(target, path.join(root, "devos"))) {
501
+ return { block: true, reason: planGateReason(activeSpec, phase, `Changing ${path.relative(root, target)}`) };
502
+ }
503
+ if (event.toolName === "bash" && BASH_MUTATION_RE.test(input.command || "")) {
504
+ return { block: true, reason: planGateReason(activeSpec, phase, "An in-place edit or commit from bash") };
505
+ }
506
+ }
507
+
508
+ if (event.toolName === "bash" && input.command) {
509
+ // Phase-transition chokepoints carry DoD and handoff as HARD BLOCKS.
510
+ // turn_end cannot veto (header), but closing or advancing a spec routes
511
+ // through these bash invocations, so denying them denies the false
512
+ // done. Filesystem decision only: a spec with a plan may not log
513
+ // `closed` without its verification report. Unparseable commands allow,
514
+ // same fail-open posture as every other gate here.
515
+ const transition = input.command.match(
516
+ /ops-log\.sh\s+("[^"]+"|\S+)\s+(closed|verified|implemented)(?:\s|"|'|$)/,
517
+ );
518
+ if (transition) {
519
+ const specArg = transition[1].replace(/^"|"$/g, "");
520
+ const phase = transition[2];
521
+ const specDir = path.isAbsolute(specArg)
522
+ ? specArg
523
+ : path.resolve(ctx?.cwd || ".", specArg);
524
+ if (
525
+ phase === "closed" &&
526
+ fs.existsSync(path.join(specDir, "spec.md")) &&
527
+ !fs.existsSync(path.join(specDir, "verifications", "verification.md"))
528
+ ) {
529
+ return {
530
+ block: true,
531
+ reason: `DoD gate: ${specArg} has no verifications/verification.md - run Phase C before closing.`,
532
+ };
533
+ }
534
+ // Team mode records a handoff per reached phase; the same decision
535
+ // the turn-end gate corrects, enforced here at the transition itself.
536
+ const handoff = runGate("check-handoff.sh", [ctx?.cwd || "."]);
537
+ if (handoff.code === 2) {
538
+ return { block: true, reason: `handoff gate: ${handoff.stderr}` };
539
+ }
540
+ }
541
+ }
542
+
543
+ if (event.toolName !== "edit" && event.toolName !== "write") return;
544
+
545
+ const file = input.path;
546
+ if (!file) return; // unparseable -> allow, never block
547
+
548
+ // `edit` passes targeted oldText/newText snippet pairs: compare snippet
549
+ // against snippet. Comparing a snippet to the whole old file would flag
550
+ // every assertion the edit does not happen to repeat as "deleted".
551
+ // `write` passes the whole new file: compare against the old file.
552
+ let oldContent, newContent;
553
+ if (event.toolName === "edit") {
554
+ const edits = Array.isArray(input.edits) ? input.edits : [];
555
+ oldContent = edits.map((e) => e?.oldText ?? "").join("\n");
556
+ newContent = edits.map((e) => e?.newText ?? "").join("\n");
557
+ } else {
558
+ oldContent = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
559
+ newContent = input.content ?? "";
560
+ }
561
+
562
+ const result = withTempPair(oldContent, newContent, (oldTmp, newTmp) => {
563
+ const gateArgs = ["--file", file, "--old", oldTmp, "--new", newTmp];
564
+ if (event.toolName === "write") gateArgs.push("--write");
565
+ return runGate("test-integrity-rubric.sh", gateArgs);
566
+ });
567
+
568
+ if (result.code === 2) {
569
+ return {
570
+ block: true,
571
+ reason: result.stderr || "DevOS test-integrity gate: edit denied.",
572
+ };
573
+ }
574
+ });
575
+
576
+ pi.on("turn_end", async (event, ctx) => {
577
+ if (corrections >= MAX_TOTAL) return;
578
+ if (correctedTurns.has(event.turnIndex)) return;
579
+
580
+ const text = textOf(event.message);
581
+ if (!text) return;
582
+
583
+ const stamp = `${process.pid}-${event.turnIndex}`;
584
+ const tmp = path.join(os.tmpdir(), `devos-transcript-${stamp}`);
585
+ let reason = "";
586
+ try {
587
+ fs.writeFileSync(tmp, text);
588
+ const dod = runGate("check-dod-core.sh", [tmp]);
589
+ if (dod.code === 2) reason = `DoD gate: ${dod.stderr}`;
590
+ } finally {
591
+ fs.rmSync(tmp, { force: true });
592
+ }
593
+
594
+ // Handoff gate on the same surface and the same correction budget. It
595
+ // reads members.md and the active spec, so it needs no transcript. DoD
596
+ // first: a missing verification report is also what a verification-phase
597
+ // handoff would be blocked on.
598
+ if (!reason) {
599
+ const handoff = runGate("check-handoff.sh", [ctx?.cwd || "."]);
600
+ if (handoff.code === 2) reason = `handoff gate: ${handoff.stderr}`;
601
+ }
602
+
603
+ if (reason) {
604
+ const stateHash = repoState(ctx?.cwd);
605
+ if (!lastStateHash || stateHash !== lastStateHash) stalled = 0;
606
+ else stalled += 1;
607
+ lastStateHash = stateHash;
608
+ if (stalled > MAX_STALLED || corrections >= MAX_TOTAL) return;
609
+ correctedTurns.add(event.turnIndex);
610
+ corrections += 1;
611
+ pi.appendEntry(CORRECTION_ENTRY, { turnIndex: event.turnIndex, corrections, stalled, stateHash });
612
+ pi.sendUserMessage(`DevOS ${reason}`, { deliverAs: "followUp" });
613
+ }
614
+ });
615
+ }