@pugi/cli 0.1.0-beta.5 → 0.1.0-beta.51

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 (264) hide show
  1. package/THIRD_PARTY_NOTICES.md +40 -0
  2. package/assets/pugi-mascot.ansi +15 -25
  3. package/assets/pugi-prozr2-mascot.ansi +9 -0
  4. package/bin/run.js +33 -1
  5. package/dist/commands/jobs-watch.js +201 -0
  6. package/dist/commands/jobs.js +15 -0
  7. package/dist/commands/smoke.js +133 -0
  8. package/dist/core/agent-progress/cleanup.js +134 -0
  9. package/dist/core/agent-progress/schema.js +144 -0
  10. package/dist/core/agent-progress/writer.js +101 -0
  11. package/dist/core/artifact-chain/dispatcher.js +148 -0
  12. package/dist/core/artifact-chain/exporter.js +164 -0
  13. package/dist/core/artifact-chain/state.js +243 -0
  14. package/dist/core/artifact-chain/steps.js +169 -0
  15. package/dist/core/auth/ensure-authenticated.js +129 -0
  16. package/dist/core/auth/env-provider.js +238 -0
  17. package/dist/core/auto-update/channels.js +122 -0
  18. package/dist/core/auto-update/checker.js +241 -0
  19. package/dist/core/auto-update/state.js +235 -0
  20. package/dist/core/bare-mode/index.js +107 -0
  21. package/dist/core/bash-classifier.js +400 -4
  22. package/dist/core/checkpoint/resumer.js +149 -0
  23. package/dist/core/checkpoint/rewinder.js +291 -0
  24. package/dist/core/codegraph/decision-store.js +248 -0
  25. package/dist/core/codegraph/detect-repo.js +459 -0
  26. package/dist/core/codegraph/install.js +134 -0
  27. package/dist/core/codegraph/offer-hook.js +220 -0
  28. package/dist/core/compact/auto-trigger.js +96 -0
  29. package/dist/core/compact/buffer-rewriter.js +115 -0
  30. package/dist/core/compact/summarizer.js +208 -0
  31. package/dist/core/compact/token-counter.js +108 -0
  32. package/dist/core/consensus/diff-capture.js +112 -3
  33. package/dist/core/context/index.js +7 -0
  34. package/dist/core/context/markdown-traverse.js +255 -0
  35. package/dist/core/cost/rate-card.js +129 -0
  36. package/dist/core/cost/tracker.js +221 -0
  37. package/dist/core/denial-tracking/index.js +8 -0
  38. package/dist/core/denial-tracking/state.js +264 -0
  39. package/dist/core/diagnostics/probe-runner.js +93 -0
  40. package/dist/core/diagnostics/probes/api.js +46 -0
  41. package/dist/core/diagnostics/probes/auth.js +86 -0
  42. package/dist/core/diagnostics/probes/bare-mode.js +42 -0
  43. package/dist/core/diagnostics/probes/cli-version.js +127 -0
  44. package/dist/core/diagnostics/probes/config.js +72 -0
  45. package/dist/core/diagnostics/probes/denial-tracking.js +57 -0
  46. package/dist/core/diagnostics/probes/disk.js +81 -0
  47. package/dist/core/diagnostics/probes/git.js +65 -0
  48. package/dist/core/diagnostics/probes/hooks.js +118 -0
  49. package/dist/core/diagnostics/probes/mcp.js +75 -0
  50. package/dist/core/diagnostics/probes/node.js +59 -0
  51. package/dist/core/diagnostics/probes/pnpm.js +36 -0
  52. package/dist/core/diagnostics/probes/pugi-md.js +89 -0
  53. package/dist/core/diagnostics/probes/sandbox.js +40 -0
  54. package/dist/core/diagnostics/probes/session.js +74 -0
  55. package/dist/core/diagnostics/probes/status-snapshot.js +488 -0
  56. package/dist/core/diagnostics/probes/workspace.js +63 -0
  57. package/dist/core/diagnostics/types.js +70 -0
  58. package/dist/core/dispatch/cache-cleanup.js +197 -0
  59. package/dist/core/dispatch/cache-handoff.js +295 -0
  60. package/dist/core/edits/dispatch.js +218 -2
  61. package/dist/core/edits/journal.js +199 -0
  62. package/dist/core/edits/layer-d-ast.js +557 -14
  63. package/dist/core/edits/verify-hook.js +273 -0
  64. package/dist/core/edits/worktree.js +322 -0
  65. package/dist/core/engine/anvil-client.js +115 -5
  66. package/dist/core/engine/auto-compact.js +179 -0
  67. package/dist/core/engine/budgets.js +155 -0
  68. package/dist/core/engine/context-prefix.js +155 -0
  69. package/dist/core/engine/intent.js +260 -0
  70. package/dist/core/engine/native-pugi.js +897 -211
  71. package/dist/core/engine/prompts.js +88 -2
  72. package/dist/core/engine/strip-internal-fields.js +124 -0
  73. package/dist/core/engine/tool-bridge.js +1045 -36
  74. package/dist/core/feedback/queue.js +177 -0
  75. package/dist/core/feedback/submitter.js +145 -0
  76. package/dist/core/file-cache.js +113 -1
  77. package/dist/core/hooks/events.js +44 -0
  78. package/dist/core/hooks/index.js +15 -0
  79. package/dist/core/hooks/registry.js +213 -0
  80. package/dist/core/hooks/runner.js +236 -0
  81. package/dist/core/hooks/v2/event-emitter.js +115 -0
  82. package/dist/core/hooks/v2/executor.js +282 -0
  83. package/dist/core/hooks/v2/index.js +25 -0
  84. package/dist/core/hooks/v2/lifecycle.js +104 -0
  85. package/dist/core/hooks/v2/loader.js +216 -0
  86. package/dist/core/hooks/v2/matcher.js +125 -0
  87. package/dist/core/hooks/v2/trust.js +143 -0
  88. package/dist/core/hooks/v2/types.js +86 -0
  89. package/dist/core/lsp/cache.js +105 -0
  90. package/dist/core/lsp/client.js +776 -0
  91. package/dist/core/lsp/language-detect.js +66 -0
  92. package/dist/core/lsp/post-edit-diagnostics.js +171 -0
  93. package/dist/core/mcp/client.js +75 -6
  94. package/dist/core/mcp/http-server.js +553 -0
  95. package/dist/core/mcp/orchestrator-tools.js +662 -0
  96. package/dist/core/mcp/permission.js +190 -0
  97. package/dist/core/mcp/registry.js +24 -2
  98. package/dist/core/mcp/server-tools.js +219 -0
  99. package/dist/core/mcp/server.js +397 -0
  100. package/dist/core/memory/dual-write.js +416 -0
  101. package/dist/core/memory/phase1-kinds.js +20 -0
  102. package/dist/core/memory-sync/queue.js +158 -0
  103. package/dist/core/onboarding/ensure-initialized.js +133 -0
  104. package/dist/core/onboarding/marker.js +111 -0
  105. package/dist/core/onboarding/telemetry-state.js +108 -0
  106. package/dist/core/output-style/presets.js +176 -0
  107. package/dist/core/output-style/state.js +185 -0
  108. package/dist/core/path-security.js +284 -2
  109. package/dist/core/permissions/auto-classifier.js +124 -0
  110. package/dist/core/permissions/circuit-breaker.js +83 -0
  111. package/dist/core/permissions/gate.js +278 -0
  112. package/dist/core/permissions/index.js +20 -0
  113. package/dist/core/permissions/mode.js +174 -0
  114. package/dist/core/permissions/state.js +241 -0
  115. package/dist/core/permissions/tool-class.js +93 -0
  116. package/dist/core/prd-check/parser.js +215 -0
  117. package/dist/core/prd-check/reporter.js +127 -0
  118. package/dist/core/prd-check/session-review.js +557 -0
  119. package/dist/core/prd-check/verifiers.js +223 -0
  120. package/dist/core/pugi-md/context-injector.js +76 -0
  121. package/dist/core/pugi-md/walk-up.js +207 -0
  122. package/dist/core/release-notes/parser.js +241 -0
  123. package/dist/core/release-notes/state.js +116 -0
  124. package/dist/core/repl/history.js +11 -1
  125. package/dist/core/repl/model-pricing.js +135 -0
  126. package/dist/core/repl/session.js +1897 -37
  127. package/dist/core/repl/slash-commands.js +430 -15
  128. package/dist/core/repl/store/session-store.js +31 -2
  129. package/dist/core/repl/workspace-context.js +22 -0
  130. package/dist/core/repo-map/build.js +125 -0
  131. package/dist/core/repo-map/cache.js +185 -0
  132. package/dist/core/repo-map/extractor.js +254 -0
  133. package/dist/core/repo-map/formatter.js +145 -0
  134. package/dist/core/repo-map/scanner.js +211 -0
  135. package/dist/core/retry-budget/budget.js +284 -0
  136. package/dist/core/retry-budget/index.js +5 -0
  137. package/dist/core/session.js +92 -0
  138. package/dist/core/settings.js +80 -0
  139. package/dist/core/share/formatter.js +271 -0
  140. package/dist/core/share/redactor.js +221 -0
  141. package/dist/core/share/uploader.js +267 -0
  142. package/dist/core/skills/defaults.js +457 -0
  143. package/dist/core/smoke/headless-driver.js +174 -0
  144. package/dist/core/smoke/orchestrator.js +194 -0
  145. package/dist/core/smoke/runner.js +238 -0
  146. package/dist/core/smoke/scenario-parser.js +316 -0
  147. package/dist/core/subagents/dispatcher-real.js +600 -0
  148. package/dist/core/subagents/dispatcher.js +113 -24
  149. package/dist/core/subagents/index.js +18 -5
  150. package/dist/core/subagents/isolation-matrix.js +213 -0
  151. package/dist/core/subagents/spawn.js +19 -4
  152. package/dist/core/telemetry/emitter.js +229 -0
  153. package/dist/core/telemetry/queue.js +251 -0
  154. package/dist/core/theme/context.js +91 -0
  155. package/dist/core/theme/presets.js +228 -0
  156. package/dist/core/theme/state.js +181 -0
  157. package/dist/core/todos/invariant.js +10 -0
  158. package/dist/core/todos/state.js +177 -0
  159. package/dist/core/transport/version-interceptor.js +166 -0
  160. package/dist/core/vim/keymap.js +288 -0
  161. package/dist/core/vim/state.js +92 -0
  162. package/dist/core/worktree-manager/cleanup.js +123 -0
  163. package/dist/core/worktree-manager/manager.js +303 -0
  164. package/dist/index.js +28 -0
  165. package/dist/runtime/bootstrap.js +190 -0
  166. package/dist/runtime/cli.js +3241 -343
  167. package/dist/runtime/commands/cancel.js +231 -0
  168. package/dist/runtime/commands/chain.js +489 -0
  169. package/dist/runtime/commands/codegraph-status.js +227 -0
  170. package/dist/runtime/commands/compact.js +297 -0
  171. package/dist/runtime/commands/cost.js +199 -0
  172. package/dist/runtime/commands/delegate.js +242 -11
  173. package/dist/runtime/commands/dispatch.js +126 -0
  174. package/dist/runtime/commands/doctor.js +412 -0
  175. package/dist/runtime/commands/feedback.js +184 -0
  176. package/dist/runtime/commands/hooks.js +184 -0
  177. package/dist/runtime/commands/lsp.js +368 -0
  178. package/dist/runtime/commands/mcp.js +879 -0
  179. package/dist/runtime/commands/memory.js +508 -0
  180. package/dist/runtime/commands/model.js +237 -0
  181. package/dist/runtime/commands/onboarding.js +275 -0
  182. package/dist/runtime/commands/patch.js +128 -0
  183. package/dist/runtime/commands/permissions.js +112 -0
  184. package/dist/runtime/commands/plan.js +143 -0
  185. package/dist/runtime/commands/prd-check.js +285 -0
  186. package/dist/runtime/commands/redo-blob-store.js +92 -0
  187. package/dist/runtime/commands/redo.js +361 -0
  188. package/dist/runtime/commands/release-notes.js +229 -0
  189. package/dist/runtime/commands/repo-map.js +95 -0
  190. package/dist/runtime/commands/report.js +299 -0
  191. package/dist/runtime/commands/resume.js +118 -0
  192. package/dist/runtime/commands/review-consensus.js +17 -2
  193. package/dist/runtime/commands/rewind.js +333 -0
  194. package/dist/runtime/commands/sessions.js +163 -0
  195. package/dist/runtime/commands/share.js +316 -0
  196. package/dist/runtime/commands/status.js +186 -0
  197. package/dist/runtime/commands/stickers.js +82 -0
  198. package/dist/runtime/commands/style.js +194 -0
  199. package/dist/runtime/commands/theme.js +196 -0
  200. package/dist/runtime/commands/undo.js +32 -0
  201. package/dist/runtime/commands/update.js +289 -0
  202. package/dist/runtime/commands/vim.js +140 -0
  203. package/dist/runtime/commands/worktree.js +177 -0
  204. package/dist/runtime/commands/worktrees.js +155 -0
  205. package/dist/runtime/headless-repl.js +195 -0
  206. package/dist/runtime/headless.js +543 -0
  207. package/dist/runtime/load-hooks-or-exit.js +71 -0
  208. package/dist/runtime/plan-decompose.js +531 -0
  209. package/dist/runtime/version.js +65 -0
  210. package/dist/tools/agent-tool.js +229 -0
  211. package/dist/tools/apply-patch.js +556 -0
  212. package/dist/tools/ask-user-question.js +213 -0
  213. package/dist/tools/ask-user.js +115 -0
  214. package/dist/tools/bash.js +203 -4
  215. package/dist/tools/file-tools.js +85 -14
  216. package/dist/tools/lsp-tools.js +189 -0
  217. package/dist/tools/mcp-tool.js +260 -0
  218. package/dist/tools/multi-edit.js +361 -0
  219. package/dist/tools/powershell.js +268 -0
  220. package/dist/tools/registry.js +51 -0
  221. package/dist/tools/skill-tool.js +96 -0
  222. package/dist/tools/tasks.js +208 -0
  223. package/dist/tools/todo-write.js +184 -0
  224. package/dist/tools/web-fetch.js +147 -2
  225. package/dist/tools/web-search.js +458 -0
  226. package/dist/tui/agent-progress-card.js +111 -0
  227. package/dist/tui/agent-tree.js +10 -0
  228. package/dist/tui/ask-modal.js +2 -2
  229. package/dist/tui/ask-user-question-prompt.js +192 -0
  230. package/dist/tui/compact-banner.js +81 -0
  231. package/dist/tui/conversation-pane.js +82 -8
  232. package/dist/tui/cost-table.js +111 -0
  233. package/dist/tui/doctor-table.js +46 -0
  234. package/dist/tui/feedback-prompt.js +156 -0
  235. package/dist/tui/input-box.js +218 -3
  236. package/dist/tui/markdown-render.js +4 -4
  237. package/dist/tui/onboarding-wizard.js +240 -0
  238. package/dist/tui/permissions-picker.js +86 -0
  239. package/dist/tui/render.js +35 -0
  240. package/dist/tui/repl-render.js +313 -35
  241. package/dist/tui/repl-splash-art.js +1 -1
  242. package/dist/tui/repl-splash-mascot.js +32 -8
  243. package/dist/tui/repl-splash.js +2 -2
  244. package/dist/tui/repl.js +85 -5
  245. package/dist/tui/splash.js +1 -1
  246. package/dist/tui/status-bar.js +94 -16
  247. package/dist/tui/status-table.js +7 -0
  248. package/dist/tui/stickers-art.js +136 -0
  249. package/dist/tui/style-table.js +28 -0
  250. package/dist/tui/theme-table.js +29 -0
  251. package/dist/tui/thinking-spinner.js +123 -0
  252. package/dist/tui/tool-stream-pane.js +52 -3
  253. package/dist/tui/update-banner.js +27 -2
  254. package/dist/tui/vim-input.js +267 -0
  255. package/dist/tui/welcome-banner.js +107 -0
  256. package/dist/tui/welcome-data.js +293 -0
  257. package/docs/examples/codegraph.mcp.json +10 -0
  258. package/package.json +13 -7
  259. package/test/scenarios/codegen-create-file.scenario.txt +13 -0
  260. package/test/scenarios/compact-force.scenario.txt +11 -0
  261. package/test/scenarios/identity.scenario.txt +11 -0
  262. package/test/scenarios/persona-handoff.scenario.txt +11 -0
  263. package/test/scenarios/walkback.scenario.txt +12 -0
  264. package/dist/core/engine/compaction-hook.js +0 -154
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Agent progress JSON schema — α7 live-progress sprint (2026-05-27).
3
+ *
4
+ * Long-running agents (spawned externally OR via `pugi /agent`) emit a
5
+ * single JSON document per agent to `~/.pugi/agent-progress/<id>.json`.
6
+ * `pugi jobs --watch` tails the directory via chokidar and re-renders
7
+ * an Ink TUI that mirrors the Claude Code `/compact` visual pattern
8
+ * (header with elapsed + token counter, unicode progress bar, milestone
9
+ * list with done/active/pending status icons).
10
+ *
11
+ * Schema is intentionally optimistic — every numeric field is clamped
12
+ * by the writer/reader so a malformed document degrades to a partial
13
+ * card instead of crashing the watcher. The `pendingCount` /
14
+ * `completedCount` fields are pre-computed by the agent for the
15
+ * "… +N pending, M completed" footer; the renderer never re-counts
16
+ * (the agent may have collapsed milestone history to save bytes).
17
+ */
18
+ /**
19
+ * Validate an unknown payload as an `AgentProgress` document. Returns
20
+ * the typed value on success and a string error otherwise. We deliberately
21
+ * keep this hand-rolled (no zod) — every field is checked exactly once,
22
+ * the error message is human-readable, and zero runtime deps.
23
+ */
24
+ export function validateAgentProgress(value) {
25
+ if (typeof value !== 'object' || value === null) {
26
+ return { ok: false, error: 'progress payload must be a JSON object' };
27
+ }
28
+ const raw = value;
29
+ const requiredString = (field) => {
30
+ const v = raw[field];
31
+ return typeof v === 'string' && v.length > 0 ? v : null;
32
+ };
33
+ const agentId = requiredString('agentId');
34
+ if (!agentId)
35
+ return { ok: false, error: 'agentId required (non-empty string)' };
36
+ if (!/^[a-zA-Z0-9_-]+$/.test(agentId)) {
37
+ return { ok: false, error: 'agentId must match [a-zA-Z0-9_-]+ (filename-safe)' };
38
+ }
39
+ const agentType = requiredString('agentType');
40
+ if (!agentType)
41
+ return { ok: false, error: 'agentType required (non-empty string)' };
42
+ const task = requiredString('task');
43
+ if (!task)
44
+ return { ok: false, error: 'task required (non-empty string)' };
45
+ const startedAt = requiredString('startedAt');
46
+ if (!startedAt)
47
+ return { ok: false, error: 'startedAt required (ISO string)' };
48
+ if (Number.isNaN(Date.parse(startedAt))) {
49
+ return { ok: false, error: 'startedAt must be a parseable ISO timestamp' };
50
+ }
51
+ const lastUpdate = requiredString('lastUpdate');
52
+ if (!lastUpdate)
53
+ return { ok: false, error: 'lastUpdate required (ISO string)' };
54
+ if (Number.isNaN(Date.parse(lastUpdate))) {
55
+ return { ok: false, error: 'lastUpdate must be a parseable ISO timestamp' };
56
+ }
57
+ const elapsedMs = raw.elapsedMs;
58
+ if (typeof elapsedMs !== 'number' || !Number.isFinite(elapsedMs) || elapsedMs < 0) {
59
+ return { ok: false, error: 'elapsedMs required (non-negative number)' };
60
+ }
61
+ const percentComplete = raw.percentComplete;
62
+ if (typeof percentComplete !== 'number' ||
63
+ !Number.isFinite(percentComplete)) {
64
+ return { ok: false, error: 'percentComplete required (number 0..100)' };
65
+ }
66
+ const clampedPercent = Math.max(0, Math.min(100, percentComplete));
67
+ const status = raw.status;
68
+ if (status !== 'running' && status !== 'completed' && status !== 'failed') {
69
+ return { ok: false, error: 'status must be running | completed | failed' };
70
+ }
71
+ const currentStep = raw.currentStep;
72
+ if (typeof currentStep !== 'number' || currentStep < 0) {
73
+ return { ok: false, error: 'currentStep required (non-negative number)' };
74
+ }
75
+ const totalSteps = raw.totalSteps;
76
+ if (typeof totalSteps !== 'number' || totalSteps < 0) {
77
+ return { ok: false, error: 'totalSteps required (non-negative number)' };
78
+ }
79
+ const stepDescription = typeof raw.stepDescription === 'string'
80
+ ? raw.stepDescription
81
+ : '';
82
+ const milestonesRaw = raw.milestones;
83
+ if (!Array.isArray(milestonesRaw)) {
84
+ return { ok: false, error: 'milestones required (array, may be empty)' };
85
+ }
86
+ const milestones = [];
87
+ for (let i = 0; i < milestonesRaw.length; i += 1) {
88
+ const m = milestonesRaw[i];
89
+ if (typeof m !== 'object' || m === null) {
90
+ return { ok: false, error: `milestones[${i}] must be an object` };
91
+ }
92
+ const mr = m;
93
+ const label = typeof mr.label === 'string' ? mr.label : '';
94
+ if (!label) {
95
+ return { ok: false, error: `milestones[${i}].label required` };
96
+ }
97
+ const mStatus = mr.status;
98
+ if (mStatus !== 'done' && mStatus !== 'active' && mStatus !== 'pending') {
99
+ return {
100
+ ok: false,
101
+ error: `milestones[${i}].status must be done | active | pending`,
102
+ };
103
+ }
104
+ const ts = typeof mr.ts === 'string' ? mr.ts : undefined;
105
+ milestones.push({ label, status: mStatus, ts });
106
+ }
107
+ const tokensUsed = typeof raw.tokensUsed === 'number' && Number.isFinite(raw.tokensUsed)
108
+ ? Math.max(0, raw.tokensUsed)
109
+ : undefined;
110
+ const pendingCount = typeof raw.pendingCount === 'number' && Number.isFinite(raw.pendingCount)
111
+ ? Math.max(0, Math.floor(raw.pendingCount))
112
+ : undefined;
113
+ const completedCount = typeof raw.completedCount === 'number' && Number.isFinite(raw.completedCount)
114
+ ? Math.max(0, Math.floor(raw.completedCount))
115
+ : undefined;
116
+ return {
117
+ ok: true,
118
+ value: {
119
+ agentId,
120
+ agentType,
121
+ task,
122
+ startedAt,
123
+ lastUpdate,
124
+ elapsedMs,
125
+ tokensUsed,
126
+ percentComplete: clampedPercent,
127
+ status,
128
+ currentStep,
129
+ totalSteps,
130
+ stepDescription,
131
+ milestones,
132
+ pendingCount,
133
+ completedCount,
134
+ },
135
+ };
136
+ }
137
+ /**
138
+ * Default directory the writer and watcher share. Lives under the
139
+ * project workspace by convention so worktree-isolated agents can emit
140
+ * progress without crossing tenant boundaries. Operators can override
141
+ * via `PUGI_AGENT_PROGRESS_DIR` env var.
142
+ */
143
+ export const DEFAULT_AGENT_PROGRESS_DIRNAME = '.pugi/agent-progress';
144
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Agent progress writer — atomic file ops so the chokidar watcher
3
+ * never reads a half-written JSON document.
4
+ *
5
+ * Pattern (POSIX-portable):
6
+ * 1. Build the canonical JSON body.
7
+ * 2. Write to `<dir>/<agentId>.json.tmp-<pid>-<seq>`.
8
+ * 3. Rename (atomic on the same filesystem) to `<dir>/<agentId>.json`.
9
+ * 4. Cleanup is a no-op on success; on failure the caller bubbles the
10
+ * error and the .tmp file is removed best-effort.
11
+ *
12
+ * The auto-cleanup of completed entries lives in `cleanup.ts` (commit 4);
13
+ * the writer here is the minimal surface the agent prompt boilerplate
14
+ * needs to copy + paste.
15
+ */
16
+ import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { dirname, join, resolve } from 'node:path';
19
+ import { DEFAULT_AGENT_PROGRESS_DIRNAME, validateAgentProgress, } from './schema.js';
20
+ let writeSequence = 0;
21
+ /**
22
+ * Resolve the effective progress directory. Public so the watcher can
23
+ * share the same resolution rules without duplicating env-var logic.
24
+ */
25
+ export function resolveProgressDir(override) {
26
+ const candidate = override
27
+ ?? process.env.PUGI_AGENT_PROGRESS_DIR
28
+ ?? join(process.cwd(), DEFAULT_AGENT_PROGRESS_DIRNAME);
29
+ if (candidate.startsWith('~/')) {
30
+ return join(homedir(), candidate.slice(2));
31
+ }
32
+ return resolve(candidate);
33
+ }
34
+ /**
35
+ * Write a progress document atomically.
36
+ *
37
+ * Throws on validation failure so the caller is loud about a schema
38
+ * regression. File-system errors propagate untouched.
39
+ */
40
+ export function writeProgress(progress, options = {}) {
41
+ const validation = validateAgentProgress(progress);
42
+ if (!validation.ok) {
43
+ throw new Error(`invalid agent-progress payload: ${validation.error}`);
44
+ }
45
+ const dir = resolveProgressDir(options.dir);
46
+ if (!existsSync(dir)) {
47
+ mkdirSync(dir, { recursive: true });
48
+ }
49
+ const finalPath = join(dir, `${progress.agentId}.json`);
50
+ writeSequence += 1;
51
+ const tmpPath = `${finalPath}.tmp-${process.pid}-${writeSequence}`;
52
+ const body = `${JSON.stringify(progress, null, 2)}\n`;
53
+ try {
54
+ // mkdirSync above may have created `dir`, but a parallel agent could
55
+ // delete it between the existsSync and writeFile — ensure the parent
56
+ // of the tmp file exists right before the write.
57
+ const parent = dirname(tmpPath);
58
+ if (!existsSync(parent)) {
59
+ mkdirSync(parent, { recursive: true });
60
+ }
61
+ writeFileSync(tmpPath, body, 'utf8');
62
+ renameSync(tmpPath, finalPath);
63
+ }
64
+ catch (err) {
65
+ try {
66
+ rmSync(tmpPath, { force: true });
67
+ }
68
+ catch {
69
+ // best-effort cleanup; surface the original error
70
+ }
71
+ throw err;
72
+ }
73
+ return { path: finalPath };
74
+ }
75
+ /**
76
+ * Build a fresh progress document with sensible defaults. Mostly a
77
+ * convenience for tests + the agent prompt boilerplate — the writer
78
+ * does NOT call this implicitly because agents have richer context
79
+ * about their own milestone state.
80
+ */
81
+ export function makeInitialProgress(input) {
82
+ const now = input.now ?? Date.now;
83
+ const iso = new Date(now()).toISOString();
84
+ return {
85
+ agentId: input.agentId,
86
+ agentType: input.agentType,
87
+ task: input.task,
88
+ startedAt: iso,
89
+ lastUpdate: iso,
90
+ elapsedMs: 0,
91
+ percentComplete: 0,
92
+ status: 'running',
93
+ currentStep: 0,
94
+ totalSteps: Math.max(0, Math.floor(input.totalSteps)),
95
+ stepDescription: '',
96
+ milestones: input.milestones ?? [],
97
+ pendingCount: input.milestones?.filter((m) => m.status === 'pending').length,
98
+ completedCount: input.milestones?.filter((m) => m.status === 'done').length,
99
+ };
100
+ }
101
+ //# sourceMappingURL=writer.js.map
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Artifact chain dispatcher — Pugi α7 Wave 6 (2026-05-27).
3
+ *
4
+ * Bridges the chain state machine (`state.ts`) to the existing
5
+ * `pugi delegate` surface. Each step renders a brief from the
6
+ * step's template + chain context, dispatches the brief to the
7
+ * step's persona, and writes the persona's response verbatim to the
8
+ * artifact file on disk.
9
+ *
10
+ * Mock-friendly by contract — the dispatcher accepts an injected
11
+ * `dispatch` function so specs can drive every branch without
12
+ * standing up a real runtime + Anvil round-trip. The real wire-up
13
+ * binds `dispatch` to the existing `submitDelegate` SDK helper +
14
+ * the SSE waiter; that wiring lives in `runtime/commands/chain.ts`
15
+ * so this module stays pure with respect to the network.
16
+ *
17
+ * Module contract:
18
+ *
19
+ * - `dispatchStep` is the ONLY entry point. It reads the chain,
20
+ * renders the brief, calls the injected dispatcher, persists the
21
+ * artifact, and flips the step state. Callers do not touch the
22
+ * state machine directly — that surface is intentionally narrow.
23
+ *
24
+ * - The dispatcher never auto-advances. After a step lands the
25
+ * cursor stays on the same step until the operator runs
26
+ * `pugi chain next` again (or until `markComplete` is invoked
27
+ * by the CLI handler after operator approval).
28
+ */
29
+ import { mkdirSync, writeFileSync } from 'node:fs';
30
+ import { join } from 'node:path';
31
+ import { chainDir, markComplete, markDispatched, markError, readChain, } from './state.js';
32
+ import { findStep, renderBrief, } from './steps.js';
33
+ /**
34
+ * Dispatch one step in the chain. The function is non-throwing — every
35
+ * failure mode returns a structured result so the CLI handler can map
36
+ * to an exit code without a try/catch wrapper.
37
+ */
38
+ export async function dispatchStep(options) {
39
+ const now = options.now ?? (() => new Date());
40
+ const state = readChain(options.workspaceCwd, options.chainId);
41
+ if (!state) {
42
+ // Gemini P1 fix (PR #608): the docblock above promises a non-
43
+ // throwing surface, but the historical implementation threw here.
44
+ // Return a structured result keyed on `reason: 'chain_not_found'`
45
+ // so callers can switch on the failure family deterministically.
46
+ return {
47
+ ok: false,
48
+ stepId: 'prd',
49
+ error: `chain ${options.chainId} not found`,
50
+ reason: 'chain_not_found',
51
+ state: null,
52
+ };
53
+ }
54
+ const targetStepId = options.stepId ?? state.nextStep;
55
+ if (!targetStepId) {
56
+ return {
57
+ ok: false,
58
+ stepId: 'code',
59
+ error: 'chain is finalised — every step is already complete',
60
+ state,
61
+ };
62
+ }
63
+ const step = findStep(targetStepId);
64
+ if (!step) {
65
+ return {
66
+ ok: false,
67
+ stepId: targetStepId,
68
+ error: `unknown step id '${targetStepId}'`,
69
+ state,
70
+ };
71
+ }
72
+ const stepRecord = state.steps.find((s) => s.id === targetStepId);
73
+ if (stepRecord?.status === 'complete') {
74
+ return {
75
+ ok: false,
76
+ stepId: targetStepId,
77
+ error: `step '${targetStepId}' is already complete`,
78
+ state,
79
+ };
80
+ }
81
+ const brief = renderBrief(step.briefTemplate, {
82
+ chainId: state.id,
83
+ intent: state.intent,
84
+ });
85
+ let outcome;
86
+ try {
87
+ outcome = await options.dispatch({ chainId: state.id, step, brief });
88
+ }
89
+ catch (err) {
90
+ const message = err instanceof Error ? err.message : String(err);
91
+ const errorState = markError(options.workspaceCwd, options.chainId, targetStepId, message, { now });
92
+ return {
93
+ ok: false,
94
+ stepId: targetStepId,
95
+ error: message,
96
+ state: errorState,
97
+ };
98
+ }
99
+ if (outcome.kind === 'failed') {
100
+ const errorState = markError(options.workspaceCwd, options.chainId, targetStepId, outcome.error, { now });
101
+ return {
102
+ ok: false,
103
+ stepId: targetStepId,
104
+ error: outcome.error,
105
+ state: errorState,
106
+ };
107
+ }
108
+ // Success path: persist the artifact, flip the step to dispatched
109
+ // (or complete when autoApprove is set).
110
+ const dir = chainDir(options.workspaceCwd, state.id);
111
+ mkdirSync(dir, { recursive: true });
112
+ const artifactPath = join(dir, step.artifactFilename);
113
+ writeFileSync(artifactPath, ensureTrailingNewline(outcome.artifact), 'utf8');
114
+ let finalState = markDispatched(options.workspaceCwd, options.chainId, targetStepId, outcome.dispatchId, { now });
115
+ if (options.autoApprove) {
116
+ finalState = markComplete(options.workspaceCwd, options.chainId, targetStepId, { now });
117
+ }
118
+ return {
119
+ ok: true,
120
+ stepId: targetStepId,
121
+ dispatchId: outcome.dispatchId,
122
+ artifactPath,
123
+ state: finalState,
124
+ };
125
+ }
126
+ /**
127
+ * Synthesize a dispatcher that captures every call for inspection.
128
+ * Test-only — the real wire-up never uses this.
129
+ */
130
+ export function createRecordingDispatcher(outcomes) {
131
+ const calls = [];
132
+ let index = 0;
133
+ const fn = async ({ chainId, step, brief }) => {
134
+ calls.push({ chainId, stepId: step.id, brief });
135
+ const outcome = outcomes[index];
136
+ index += 1;
137
+ if (!outcome) {
138
+ throw new Error(`recording dispatcher exhausted at call #${calls.length}`);
139
+ }
140
+ return outcome;
141
+ };
142
+ fn.calls = calls;
143
+ return fn;
144
+ }
145
+ function ensureTrailingNewline(text) {
146
+ return text.endsWith('\n') ? text : `${text}\n`;
147
+ }
148
+ //# sourceMappingURL=dispatcher.js.map
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Artifact chain exporter — Pugi α7 Wave 6 (2026-05-27).
3
+ *
4
+ * Bundles the seven step artifacts under `.pugi/chains/<id>/` into a
5
+ * single markdown report (default) or a deterministic JSON envelope
6
+ * the operator can feed into a future zip bundler. The exporter is
7
+ * read-only — it never mutates state.
8
+ *
9
+ * Why markdown instead of an actual `.zip`: the CLI ships zero binary
10
+ * dependencies (HARD rule for `@pugi/cli` install footprint — the
11
+ * 4.4MB bundled-zip toolchains would land the install at ~20MB).
12
+ * Operators that want a true zip pipe `pugi chain export` through
13
+ * `zip -j chain.zip` or similar; the markdown form covers 95% of the
14
+ * "share with my CTO" workflow without the dep.
15
+ *
16
+ * Module contract:
17
+ *
18
+ * - `renderMarkdownReport` is pure. Pass it a snapshot + a map of
19
+ * filename → contents and it returns the rendered report. The
20
+ * CLI handler does the disk read; the spec drives the renderer
21
+ * with synthetic content so it never touches the filesystem.
22
+ *
23
+ * - `exportChain` does the disk dance — reads every artifact that
24
+ * exists, skips missing ones (a partially-finished chain still
25
+ * exports cleanly), and returns the report + the list of
26
+ * skipped steps so the renderer can warn the operator.
27
+ */
28
+ import { existsSync, readFileSync } from 'node:fs';
29
+ import { join } from 'node:path';
30
+ import { chainDir, readChain } from './state.js';
31
+ import { CHAIN_STEPS } from './steps.js';
32
+ /**
33
+ * Render the markdown report. The format is intentionally stable so
34
+ * downstream tools can grep it; do NOT reformat without bumping the
35
+ * report version comment in the header.
36
+ *
37
+ * Report layout:
38
+ *
39
+ * # Pugi artifact chain: <chain id>
40
+ *
41
+ * - **Intent**: ...
42
+ * - **Created**: ...
43
+ * - **Finalised**: ... (or "in progress")
44
+ *
45
+ * ## 1. PRD — Olivia (PM)
46
+ * <contents>
47
+ *
48
+ * ## 2. ADR — Marcus (CTO)
49
+ * <contents>
50
+ *
51
+ * ... (one section per step)
52
+ */
53
+ export function renderMarkdownReport(envelope) {
54
+ const lines = [];
55
+ lines.push(`# Pugi artifact chain: ${envelope.chainId}`);
56
+ lines.push('');
57
+ lines.push(`- **Intent**: ${envelope.intent}`);
58
+ lines.push(`- **Created**: ${envelope.createdAt}`);
59
+ lines.push(`- **Finalised**: ${envelope.finalisedAt ?? 'in progress'}`);
60
+ if (envelope.missingSteps.length > 0) {
61
+ lines.push(`- **Missing steps**: ${envelope.missingSteps.join(', ')}`);
62
+ }
63
+ lines.push('');
64
+ for (const entry of envelope.artifacts) {
65
+ lines.push(`## ${entry.step.ordinal}. ${entry.step.id.toUpperCase()} — ${entry.step.personaLabel}`);
66
+ lines.push('');
67
+ if (entry.contents === null) {
68
+ lines.push(`_artifact not yet produced (${entry.step.artifactFilename})_`);
69
+ }
70
+ else {
71
+ const trimmed = entry.contents.trimEnd();
72
+ lines.push(trimmed.length === 0 ? '_empty artifact_' : trimmed);
73
+ }
74
+ lines.push('');
75
+ }
76
+ return lines.join('\n');
77
+ }
78
+ /**
79
+ * Render a deterministic JSON envelope. Same shape as
80
+ * `ChainExportEnvelope` minus the descriptor object (we serialise the
81
+ * step id + ordinal + persona so the consumer does not need access to
82
+ * the in-process descriptor table).
83
+ */
84
+ export function renderJsonReport(envelope) {
85
+ const serialisable = {
86
+ chainId: envelope.chainId,
87
+ intent: envelope.intent,
88
+ createdAt: envelope.createdAt,
89
+ finalisedAt: envelope.finalisedAt,
90
+ missingSteps: envelope.missingSteps,
91
+ artifacts: envelope.artifacts.map((entry) => ({
92
+ stepId: entry.step.id,
93
+ ordinal: entry.step.ordinal,
94
+ persona: entry.step.persona,
95
+ personaLabel: entry.step.personaLabel,
96
+ filename: entry.step.artifactFilename,
97
+ bytes: entry.bytes,
98
+ contents: entry.contents,
99
+ })),
100
+ };
101
+ return `${JSON.stringify(serialisable, null, 2)}\n`;
102
+ }
103
+ /**
104
+ * Read the chain + every artifact on disk, build the envelope, and
105
+ * render either markdown OR JSON. Returns BOTH the envelope and the
106
+ * rendered string so callers can route to stdout, a file, or both.
107
+ *
108
+ * Non-throwing per the artifact-chain module contract — every failure
109
+ * mode (chain not found, malformed state) returns a structured
110
+ * `ok: false` result so callers can map to an exit code without a
111
+ * try/catch wrapper.
112
+ */
113
+ export function exportChain(options) {
114
+ const state = readChain(options.workspaceCwd, options.chainId);
115
+ if (!state) {
116
+ return {
117
+ ok: false,
118
+ error: `chain ${options.chainId} not found`,
119
+ reason: 'chain_not_found',
120
+ };
121
+ }
122
+ const envelope = buildEnvelope(state, options.workspaceCwd);
123
+ const format = options.format ?? 'markdown';
124
+ const rendered = format === 'json' ? renderJsonReport(envelope) : renderMarkdownReport(envelope);
125
+ return { ok: true, envelope, rendered };
126
+ }
127
+ /**
128
+ * Build the export envelope from a chain snapshot + the workspace
129
+ * directory. Exported so the spec can drive the renderer against a
130
+ * fixture state without an explicit disk read.
131
+ */
132
+ export function buildEnvelope(state, workspaceCwd, options = {}) {
133
+ const dir = chainDir(workspaceCwd, state.id);
134
+ const readArtifact = options.readArtifact ?? defaultReadArtifact;
135
+ const artifacts = [];
136
+ const missing = [];
137
+ for (const step of CHAIN_STEPS) {
138
+ const path = join(dir, step.artifactFilename);
139
+ const contents = readArtifact(path);
140
+ if (contents === null) {
141
+ missing.push(step.id);
142
+ }
143
+ artifacts.push({
144
+ step,
145
+ contents,
146
+ bytes: contents === null ? 0 : Buffer.byteLength(contents, 'utf8'),
147
+ });
148
+ }
149
+ const finalisedAt = state.nextStep === null ? state.updatedAt : null;
150
+ return {
151
+ chainId: state.id,
152
+ intent: state.intent,
153
+ createdAt: state.createdAt,
154
+ finalisedAt,
155
+ artifacts,
156
+ missingSteps: missing,
157
+ };
158
+ }
159
+ function defaultReadArtifact(path) {
160
+ if (!existsSync(path))
161
+ return null;
162
+ return readFileSync(path, 'utf8');
163
+ }
164
+ //# sourceMappingURL=exporter.js.map