peaks-loop 4.1.17 → 4.1.19

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 (205) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +269 -0
  3. package/README-en.md +6 -0
  4. package/README.md +5 -0
  5. package/contracts/test-style-contract.md +14 -5
  6. package/dist/cli/commands/audit-red-lines-runners.js +6 -1
  7. package/dist/cli/commands/best-practice-scan-collision.d.ts +42 -0
  8. package/dist/cli/commands/best-practice-scan-collision.js +115 -0
  9. package/dist/cli/commands/best-practice-scan-command.d.ts +5 -0
  10. package/dist/cli/commands/best-practice-scan-command.js +9 -18
  11. package/dist/cli/commands/best-practice-scan-helpers.d.ts +12 -6
  12. package/dist/cli/commands/best-practice-scan-helpers.js +37 -17
  13. package/dist/cli/commands/code-auto-compact-command.js +71 -40
  14. package/dist/cli/commands/code-auto-compact-deferral.d.ts +34 -0
  15. package/dist/cli/commands/code-auto-compact-deferral.js +59 -0
  16. package/dist/cli/commands/code-gate-command.d.ts +4 -4
  17. package/dist/cli/commands/code-gate-command.js +4 -4
  18. package/dist/cli/commands/core/skill-generated-config-notice.d.ts +5 -0
  19. package/dist/cli/commands/core/skill-generated-config-notice.js +42 -8
  20. package/dist/cli/commands/core/skill-presence-commands.js +42 -74
  21. package/dist/cli/commands/core/skill-presence-set-command.d.ts +11 -0
  22. package/dist/cli/commands/core/skill-presence-set-command.js +175 -0
  23. package/dist/cli/commands/core/skill-registry-commands.js +32 -0
  24. package/dist/cli/commands/core/skill-store-report.d.ts +8 -0
  25. package/dist/cli/commands/core/skill-store-report.js +79 -0
  26. package/dist/cli/commands/core/standards-init-command.js +44 -8
  27. package/dist/cli/commands/core/standards-migrate-command.js +5 -4
  28. package/dist/cli/commands/dispatch-dag-runners.d.ts +1 -0
  29. package/dist/cli/commands/dispatch-dag-runners.js +11 -1
  30. package/dist/cli/commands/dispatch-detached-branch.js +19 -1
  31. package/dist/cli/commands/dispatch-prompt-composition.js +7 -2
  32. package/dist/cli/commands/dispatch-scratch-path-block.d.ts +73 -0
  33. package/dist/cli/commands/dispatch-scratch-path-block.js +131 -0
  34. package/dist/cli/commands/hooks-commands.js +36 -7
  35. package/dist/cli/commands/hooks-uninstall-command.js +5 -5
  36. package/dist/cli/commands/mut-commands-helpers.d.ts +72 -5
  37. package/dist/cli/commands/mut-commands-helpers.js +197 -4
  38. package/dist/cli/commands/mut-commands.d.ts +9 -1
  39. package/dist/cli/commands/mut-commands.js +82 -154
  40. package/dist/cli/commands/preferences-commands.js +27 -2
  41. package/dist/cli/commands/scan-scope-helpers.js +2 -2
  42. package/dist/services/24h-mode/auto-engage.d.ts +11 -3
  43. package/dist/services/24h-mode/auto-engage.js +14 -6
  44. package/dist/services/artifacts/artifact-templates.js +10 -0
  45. package/dist/services/artifacts/backcompat-acceptance.d.ts +8 -1
  46. package/dist/services/artifacts/backcompat-acceptance.js +8 -7
  47. package/dist/services/artifacts/rd-transition-gates.d.ts +32 -5
  48. package/dist/services/artifacts/rd-transition-gates.js +96 -19
  49. package/dist/services/artifacts/request-artifact-service.js +6 -6
  50. package/dist/services/audit/enforcers/lint-output-style.js +14 -2
  51. package/dist/services/audit/enforcers/root-scratch-artifacts.d.ts +46 -0
  52. package/dist/services/audit/enforcers/root-scratch-artifacts.js +97 -0
  53. package/dist/services/audit/static-service.js +4 -4
  54. package/dist/services/code/auto-compact-history.d.ts +6 -1
  55. package/dist/services/code/auto-compact-history.js +6 -1
  56. package/dist/services/code/auto-compact-modes.d.ts +60 -14
  57. package/dist/services/code/auto-compact-modes.js +75 -20
  58. package/dist/services/code/auto-compact-orchestrator.js +7 -5
  59. package/dist/services/code/auto-compact-profile.d.ts +23 -0
  60. package/dist/services/code/auto-compact-profile.js +51 -0
  61. package/dist/services/code/auto-compact-run-types.d.ts +8 -4
  62. package/dist/services/compact-history/compact-history-service.d.ts +6 -1
  63. package/dist/services/compact-history/compact-history-service.js +5 -1
  64. package/dist/services/context/auto-compact-types.d.ts +7 -5
  65. package/dist/services/dispatch/dispatch-ledger-reader.d.ts +13 -0
  66. package/dist/services/dispatch/dispatch-ledger-reader.js +164 -0
  67. package/dist/services/doctor/doctor-service/checks/canonical-store-version.d.ts +57 -0
  68. package/dist/services/doctor/doctor-service/checks/canonical-store-version.js +190 -0
  69. package/dist/services/doctor/doctor-service/checks/l3-runtime-root-census.d.ts +37 -0
  70. package/dist/services/doctor/doctor-service/checks/l3-runtime-root-census.js +100 -0
  71. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.d.ts +11 -3
  72. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.js +48 -29
  73. package/dist/services/doctor/doctor-service/plugin-registry.js +4 -0
  74. package/dist/services/doctor/doctor-service/types.d.ts +12 -0
  75. package/dist/services/hooks/hook-payload-cwd.d.ts +11 -4
  76. package/dist/services/hooks/hook-payload-cwd.js +11 -4
  77. package/dist/services/hooks/pre-tool-code-gate.d.ts +4 -4
  78. package/dist/services/hooks/pre-tool-code-gate.js +4 -4
  79. package/dist/services/hooks/presence-marker-detector.d.ts +3 -0
  80. package/dist/services/hooks/presence-marker-detector.js +21 -19
  81. package/dist/services/ide/adapters/claude-code-adapter.js +6 -8
  82. package/dist/services/ide/adapters/codex-adapter.js +23 -7
  83. package/dist/services/ide/adapters/cursor-adapter.js +23 -7
  84. package/dist/services/mode/mode-status-service.d.ts +26 -27
  85. package/dist/services/mode/mode-status-service.js +36 -60
  86. package/dist/services/preferences/preferences-types.d.ts +30 -0
  87. package/dist/services/preferences/preferences-types.js +13 -0
  88. package/dist/services/scan/acceptance-coverage-service.d.ts +14 -11
  89. package/dist/services/scan/acceptance-coverage-service.js +157 -52
  90. package/dist/services/scan/rid-change-claims.d.ts +15 -0
  91. package/dist/services/scan/rid-change-claims.js +116 -0
  92. package/dist/services/session/getSessionDir.d.ts +13 -0
  93. package/dist/services/session/getSessionDir.js +7 -1
  94. package/dist/services/skills/hooks-settings-types.d.ts +17 -21
  95. package/dist/services/skills/presence-caller-id.d.ts +51 -0
  96. package/dist/services/skills/presence-caller-id.js +43 -0
  97. package/dist/services/skills/presence-gate.d.ts +65 -0
  98. package/dist/services/skills/presence-gate.js +113 -0
  99. package/dist/services/skills/presence-lease-resolver.d.ts +63 -0
  100. package/dist/services/skills/presence-lease-resolver.js +114 -0
  101. package/dist/services/skills/presence-lease-selection.d.ts +91 -0
  102. package/dist/services/skills/presence-lease-selection.js +135 -0
  103. package/dist/services/skills/presence-lease-service.d.ts +3 -11
  104. package/dist/services/skills/presence-lease-service.js +34 -87
  105. package/dist/services/skills/presence-lease-store.d.ts +33 -0
  106. package/dist/services/skills/presence-lease-store.js +94 -0
  107. package/dist/services/skills/presence-lease-types.d.ts +31 -0
  108. package/dist/services/skills/presence-lease-types.js +27 -0
  109. package/dist/services/skills/presence-role.d.ts +35 -0
  110. package/dist/services/skills/presence-role.js +72 -0
  111. package/dist/services/skills/skill-presence-service.d.ts +39 -9
  112. package/dist/services/skills/skill-presence-service.js +143 -174
  113. package/dist/services/skills/skill-presence-write.d.ts +60 -0
  114. package/dist/services/skills/skill-presence-write.js +74 -0
  115. package/dist/services/skills/skill-statusline-service.js +7 -7
  116. package/dist/services/skills/sync-service-support.d.ts +27 -0
  117. package/dist/services/skills/sync-service.js +1 -0
  118. package/dist/services/standards/ide-aware-standards-service.d.ts +35 -23
  119. package/dist/services/standards/ide-aware-standards-service.js +45 -20
  120. package/dist/services/standards/migrate-claude-rules-service.d.ts +6 -0
  121. package/dist/services/standards/migrate-claude-rules-service.js +18 -0
  122. package/dist/services/standards/migrate-service.d.ts +1 -1
  123. package/dist/services/standards/migrate-service.js +27 -7
  124. package/dist/services/standards/project-scripts.d.ts +25 -0
  125. package/dist/services/standards/project-scripts.js +116 -0
  126. package/dist/services/standards/project-standards-service.d.ts +23 -15
  127. package/dist/services/standards/project-standards-service.js +176 -243
  128. package/dist/services/standards/standards-constitution.d.ts +89 -0
  129. package/dist/services/standards/standards-constitution.js +199 -0
  130. package/dist/services/standards/standards-files.d.ts +37 -0
  131. package/dist/services/standards/standards-files.js +138 -0
  132. package/dist/services/standards/standards-pointer.d.ts +73 -0
  133. package/dist/services/standards/standards-pointer.js +98 -0
  134. package/dist/services/standards/standards-render-agents.d.ts +34 -0
  135. package/dist/services/standards/standards-render-agents.js +149 -0
  136. package/dist/services/standards/standards-render-common.d.ts +38 -1
  137. package/dist/services/standards/standards-render-common.js +44 -7
  138. package/dist/services/standards/standards-render.d.ts +1 -3
  139. package/dist/services/standards/standards-render.js +6 -87
  140. package/dist/services/workflow/workflow-graph-ensure.d.ts +77 -0
  141. package/dist/services/workflow/workflow-graph-ensure.js +97 -0
  142. package/dist/services/workflow/workflow-inflight-probe.d.ts +68 -31
  143. package/dist/services/workflow/workflow-inflight-probe.js +163 -75
  144. package/dist/services/workflow/workflow-presence-lifecycle.js +21 -6
  145. package/dist/services/workspace/generated-artifacts-content.d.ts +46 -0
  146. package/dist/services/workspace/generated-artifacts-content.js +167 -0
  147. package/dist/services/workspace/generated-artifacts-stamp.d.ts +36 -13
  148. package/dist/services/workspace/generated-artifacts-stamp.js +37 -15
  149. package/dist/services/workspace/runtime-layout.d.ts +64 -0
  150. package/dist/services/workspace/runtime-layout.js +62 -0
  151. package/output-styles/peaks-skill-swarm.md +18 -2
  152. package/package.json +10 -9
  153. package/schemas/doctor-report.schema.json +1 -1
  154. package/scripts/canonical-store-fs.mjs +112 -0
  155. package/scripts/canonical-store-link.mjs +13 -22
  156. package/scripts/canonical-store-marker.mjs +241 -0
  157. package/scripts/canonical-store.mjs +119 -141
  158. package/scripts/install-skills-bundles.mjs +56 -13
  159. package/scripts/install-skills-fs.mjs +73 -0
  160. package/scripts/install-skills-output-styles.mjs +8 -2
  161. package/scripts/install-skills-report.mjs +19 -0
  162. package/scripts/install-skills.mjs +9 -0
  163. package/skills/bee/peaks-perf-audit/SKILL.md +3 -1
  164. package/skills/bee/peaks-prd/SKILL.md +5 -3
  165. package/skills/bee/peaks-qa/SKILL.md +4 -2
  166. package/skills/bee/peaks-qa/references/qa-skill-presence.md +1 -1
  167. package/skills/bee/peaks-qa/references/qa-standards-preflight.md +3 -1
  168. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  169. package/skills/bee/peaks-rd/SKILL.md +4 -2
  170. package/skills/bee/peaks-rd/references/artifact-and-standards-output.md +1 -1
  171. package/skills/bee/peaks-rd/references/rd-runbook.md +11 -2
  172. package/skills/bee/peaks-rd/references/rd-standards-preflight.md +3 -1
  173. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +24 -5
  174. package/skills/bee/peaks-rd/references/rd-transition-gates.md +49 -5
  175. package/skills/bee/peaks-rd/references/skill-presence-and-title.md +1 -1
  176. package/skills/bee/peaks-reviewer/SKILL.md +3 -1
  177. package/skills/bee/peaks-sc/SKILL.md +4 -2
  178. package/skills/bee/peaks-security-audit/SKILL.md +3 -1
  179. package/skills/bee/peaks-txt/SKILL.md +5 -3
  180. package/skills/bee/peaks-ui/SKILL.md +6 -4
  181. package/skills/peaks-audit/SKILL.md +3 -1
  182. package/skills/peaks-code/SKILL.md +4 -2
  183. package/skills/peaks-code/references/a2a-artifact-mapping.md +3 -3
  184. package/skills/peaks-code/references/completion-handoff.md +1 -1
  185. package/skills/peaks-code/references/local-artifact-workspace.md +10 -11
  186. package/skills/peaks-code/references/micro-cycle.md +2 -2
  187. package/skills/peaks-code/references/mode-selection-with-stale-presence.md +3 -3
  188. package/skills/peaks-code/references/runbook.md +4 -4
  189. package/skills/peaks-code/references/skill-presence-and-title.md +4 -2
  190. package/skills/peaks-code/references/standards-preflight.md +7 -6
  191. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  192. package/skills/peaks-code/references/swarm-dispatch-contract.md +5 -5
  193. package/skills/peaks-code/references/workflow-gates-and-types.md +37 -11
  194. package/skills/peaks-content/SKILL.md +3 -1
  195. package/skills/peaks-doctor/SKILL.md +3 -1
  196. package/skills/peaks-final-review/SKILL.md +3 -1
  197. package/skills/peaks-ide/SKILL.md +3 -1
  198. package/skills/peaks-issue-fix-orchestrator/SKILL.md +5 -3
  199. package/skills/peaks-race-code/SKILL.md +9 -4
  200. package/skills/peaks-resume/SKILL.md +3 -1
  201. package/skills/peaks-slice-decompose/SKILL.md +3 -1
  202. package/skills/peaks-solo/SKILL.md +3 -1
  203. package/skills/peaks-sop/SKILL.md +4 -2
  204. package/skills/peaks-status/SKILL.md +3 -1
  205. package/skills/peaks-test/SKILL.md +3 -1
@@ -1,52 +1,89 @@
1
1
  /**
2
- * Workflow in-flight probe (RD §4 D4d — slice 4.0.8).
2
+ * The in-flight probe: is a dispatch in flight right now?
3
3
  *
4
- * The single source of truth for `inFlightBatch` in 24h mode is the
5
- * set of `status=running && age(lastHeartbeat)<30min` nodes across
6
- * all valid graphs for the bound session. No CLI boolean or lease-age
7
- * heuristic may override graph facts in production. This probe is the
8
- * production replacement for the previous lease-age `inFlightBatch`
9
- * computation in `auto-compact-orchestrator.ts`.
4
+ * THE DISPATCH LEDGER IS THE SOURCE OF TRUTH. The session's ledger — the
5
+ * `active-dispatches.json` index plus the dispatch record each row names — is
6
+ * the artifact that records what the auto-compact deferral is about: a
7
+ * sub-agent that is running right now. The workflow graphs never carried that
8
+ * fact. A dispatch node sits at `prepared` and no writer stamps a heartbeat
9
+ * onto it, so a graph-backed probe could only ever answer "no"; the deferral
10
+ * was unreachable in production for that reason alone.
11
+ *
12
+ * WHERE THE BOUNDARY SITS. This module is the pure half: it opens no file,
13
+ * reads no clock of its own, and decides from the facts the reader hands it.
14
+ * The reader lives in `../dispatch/dispatch-ledger-reader.js` and produces
15
+ * plain data for the types below. That split is what keeps the decision
16
+ * testable without a filesystem, and it is the reason the reader and the probe
17
+ * are two modules rather than one.
18
+ *
19
+ * THE DIRECTION OF THE ANSWER. A wrongly deferred compaction is an
20
+ * inconvenience; a compaction that lands in the middle of a batch is a lost
21
+ * batch. So every unknown — a ledger that cannot be enumerated, a record that
22
+ * cannot be read, a status this probe does not recognise, a freshness signal
23
+ * that cannot be parsed — answers "in flight" and defers the compaction.
24
+ */
25
+ /**
26
+ * The freshness bound, shared with the deferral that uses it. A dispatch whose
27
+ * freshness signal is older than this is not in flight any more.
10
28
  */
11
- import { type GraphNodeStatus, type WorkflowId } from './workflow-graph-types.js';
12
29
  export declare const FRESH_RUNNING_THRESHOLD_MS: number;
30
+ /** The dispatch record carried no freshness signal this probe could read. */
13
31
  export declare const PEAKS_HEARTBEAT_MISSING = "PEAKS_HEARTBEAT_MISSING";
14
- export declare const PEAKS_GRAPH_REF_BROKEN = "PEAKS_GRAPH_REF_BROKEN";
15
- export declare const PEAKS_GRAPH_CORRUPTED = "PEAKS_GRAPH_CORRUPTED";
16
- export interface ProbeGraph {
17
- readonly workflowId?: WorkflowId;
18
- readonly rootSkill?: string;
19
- readonly nodes?: ReadonlyArray<{
20
- readonly id?: string;
21
- readonly kind?: string;
22
- readonly status?: GraphNodeStatus;
23
- readonly lastHeartbeat?: string;
24
- }>;
25
- readonly edges?: ReadonlyArray<unknown>;
26
- readonly schemaVersion?: number;
27
- /** Sentinel for corrupt graphs the test seam wants to surface as broken. */
28
- readonly corrupt?: boolean;
29
- readonly graphRef?: string;
32
+ /** The ledger, or one of the records it names, could not be read. */
33
+ export declare const PEAKS_DISPATCH_LEDGER_UNREADABLE = "PEAKS_DISPATCH_LEDGER_UNREADABLE";
34
+ /** The record's status is not one this probe recognises. */
35
+ export declare const PEAKS_DISPATCH_STATUS_UNKNOWN = "PEAKS_DISPATCH_STATUS_UNKNOWN";
36
+ /**
37
+ * One dispatch's ledger facts, as the reader found them.
38
+ *
39
+ * `absent` means the record file is gone, so no dispatch is running behind it —
40
+ * the record IS the artifact that proves liveness, and without it there is
41
+ * nothing running. `unreadable` means the record is there but cannot be
42
+ * believed, which is an unknown, not an absence.
43
+ */
44
+ export type LedgerDispatchFact = {
45
+ readonly kind: 'absent';
46
+ readonly recordPath: string;
47
+ } | {
48
+ readonly kind: 'unreadable';
49
+ readonly recordPath: string;
50
+ } | {
51
+ readonly kind: 'record';
52
+ readonly recordPath: string;
53
+ readonly status: string;
54
+ readonly outcome: string;
55
+ readonly lastBeatAt: string | null;
56
+ readonly createdAt: string;
57
+ readonly disposed: boolean;
58
+ };
59
+ /** What the reader found in one session's dispatch ledger. */
60
+ export interface LedgerFacts {
61
+ /** `absent` = the session has no ledger; `unreadable` = the ledger cannot be enumerated. */
62
+ readonly ledgerState: 'absent' | 'unreadable' | 'readable';
63
+ readonly dispatches: readonly LedgerDispatchFact[];
30
64
  }
31
65
  export interface ProbeInput {
32
66
  readonly now: string;
33
- readonly graphs: ReadonlyArray<ProbeGraph>;
34
- readonly leases?: ReadonlyArray<unknown>;
67
+ readonly ledger: LedgerFacts;
35
68
  readonly redLine?: boolean;
36
- readonly autoCompact?: boolean;
37
69
  }
38
70
  export interface ProbeWarning {
39
71
  readonly code: string;
40
72
  readonly message: string;
41
- readonly graphRef?: string;
42
- readonly nodeId?: string;
73
+ readonly recordPath?: string;
43
74
  }
44
75
  export interface ProbeResult {
45
76
  readonly inFlightBatch: boolean;
46
77
  readonly shouldCompact: boolean;
47
78
  readonly deferPreCompact: boolean;
48
- readonly warnings: ReadonlyArray<ProbeWarning>;
49
- readonly errors: ReadonlyArray<ProbeWarning>;
79
+ readonly warnings: readonly ProbeWarning[];
80
+ readonly errors: readonly ProbeWarning[];
50
81
  readonly reason: string;
51
82
  }
83
+ /**
84
+ * The decision. Pure: the ledger's facts go in, the answer comes out.
85
+ *
86
+ * Red-line compaction overrides the in-flight deferral, so a session at the
87
+ * red line still asks the harness to compact.
88
+ */
52
89
  export declare function probeInFlightBatch(input: ProbeInput): ProbeResult;
@@ -1,93 +1,181 @@
1
1
  /**
2
- * Workflow in-flight probe (RD §4 D4d — slice 4.0.8).
2
+ * The in-flight probe: is a dispatch in flight right now?
3
3
  *
4
- * The single source of truth for `inFlightBatch` in 24h mode is the
5
- * set of `status=running && age(lastHeartbeat)<30min` nodes across
6
- * all valid graphs for the bound session. No CLI boolean or lease-age
7
- * heuristic may override graph facts in production. This probe is the
8
- * production replacement for the previous lease-age `inFlightBatch`
9
- * computation in `auto-compact-orchestrator.ts`.
4
+ * THE DISPATCH LEDGER IS THE SOURCE OF TRUTH. The session's ledger — the
5
+ * `active-dispatches.json` index plus the dispatch record each row names — is
6
+ * the artifact that records what the auto-compact deferral is about: a
7
+ * sub-agent that is running right now. The workflow graphs never carried that
8
+ * fact. A dispatch node sits at `prepared` and no writer stamps a heartbeat
9
+ * onto it, so a graph-backed probe could only ever answer "no"; the deferral
10
+ * was unreachable in production for that reason alone.
11
+ *
12
+ * WHERE THE BOUNDARY SITS. This module is the pure half: it opens no file,
13
+ * reads no clock of its own, and decides from the facts the reader hands it.
14
+ * The reader lives in `../dispatch/dispatch-ledger-reader.js` and produces
15
+ * plain data for the types below. That split is what keeps the decision
16
+ * testable without a filesystem, and it is the reason the reader and the probe
17
+ * are two modules rather than one.
18
+ *
19
+ * THE DIRECTION OF THE ANSWER. A wrongly deferred compaction is an
20
+ * inconvenience; a compaction that lands in the middle of a batch is a lost
21
+ * batch. So every unknown — a ledger that cannot be enumerated, a record that
22
+ * cannot be read, a status this probe does not recognise, a freshness signal
23
+ * that cannot be parsed — answers "in flight" and defers the compaction.
10
24
  */
11
- import { isArray } from '../../shared/array-guards.js';
12
- export const FRESH_RUNNING_THRESHOLD_MS = 30 * 60 * 1000; // 30 minutes
25
+ /** One minute, in milliseconds. */
26
+ const MS_PER_MINUTE = 60_000;
27
+ /** How long a dispatch's freshness signal stays fresh. */
28
+ const FRESH_RUNNING_MINUTES = 30;
29
+ /**
30
+ * The freshness bound, shared with the deferral that uses it. A dispatch whose
31
+ * freshness signal is older than this is not in flight any more.
32
+ */
33
+ export const FRESH_RUNNING_THRESHOLD_MS = FRESH_RUNNING_MINUTES * MS_PER_MINUTE;
34
+ /** The dispatch record carried no freshness signal this probe could read. */
13
35
  export const PEAKS_HEARTBEAT_MISSING = 'PEAKS_HEARTBEAT_MISSING';
14
- export const PEAKS_GRAPH_REF_BROKEN = 'PEAKS_GRAPH_REF_BROKEN';
15
- export const PEAKS_GRAPH_CORRUPTED = 'PEAKS_GRAPH_CORRUPTED';
16
- const NON_RUNNING = new Set([
17
- 'prepared',
18
- 'dispatched',
19
- 'envelope-received',
20
- 'consumed-by-parent',
21
- 'terminalized',
22
- 'lost'
36
+ /** The ledger, or one of the records it names, could not be read. */
37
+ export const PEAKS_DISPATCH_LEDGER_UNREADABLE = 'PEAKS_DISPATCH_LEDGER_UNREADABLE';
38
+ /** The record's status is not one this probe recognises. */
39
+ export const PEAKS_DISPATCH_STATUS_UNKNOWN = 'PEAKS_DISPATCH_STATUS_UNKNOWN';
40
+ /**
41
+ * The statuses that mean the dispatch is over. `no-execution` and
42
+ * `never-started` are here because the dispatch never ran; `unreadable` is
43
+ * NOT here, because a record that cannot be believed is an unknown rather
44
+ * than a finished dispatch — it is answered by the status-unknown branch.
45
+ */
46
+ const TERMINAL_STATUSES = new Set([
47
+ 'done',
48
+ 'failed',
49
+ 'cancelled',
50
+ 'no-execution',
51
+ 'never-started'
52
+ ]);
53
+ /**
54
+ * The statuses that mean the dispatch may still be running. `stale` is here
55
+ * because a stale dispatch is quiet, not finished — its freshness signal is
56
+ * what decides it.
57
+ */
58
+ const LIVE_STATUSES = new Set(['queued', 'running', 'finalizing', 'stale']);
59
+ /**
60
+ * The outcomes that mean the dispatch is over. `no-execution` is absent: it is
61
+ * the value a record carries BEFORE it runs, so on its own it says nothing
62
+ * about liveness.
63
+ */
64
+ const TERMINAL_OUTCOMES = new Set([
65
+ 'success',
66
+ 'failed',
67
+ 'timeout',
68
+ 'cancelled'
23
69
  ]);
70
+ const NOT_IN_FLIGHT = {
71
+ inFlight: false,
72
+ unknown: false,
73
+ warning: null,
74
+ error: null
75
+ };
76
+ function unreadableVerdict(recordPath, message) {
77
+ return {
78
+ inFlight: true,
79
+ unknown: true,
80
+ warning: null,
81
+ error: { code: PEAKS_DISPATCH_LEDGER_UNREADABLE, message, recordPath }
82
+ };
83
+ }
84
+ function unknownStatusVerdict(recordPath, status) {
85
+ return {
86
+ inFlight: true,
87
+ unknown: true,
88
+ warning: {
89
+ code: PEAKS_DISPATCH_STATUS_UNKNOWN,
90
+ message: `dispatch record status '${status}' is not one this probe recognises`,
91
+ recordPath
92
+ },
93
+ error: null
94
+ };
95
+ }
96
+ function missingHeartbeatVerdict(recordPath, message) {
97
+ return {
98
+ inFlight: true,
99
+ unknown: true,
100
+ warning: { code: PEAKS_HEARTBEAT_MISSING, message, recordPath },
101
+ error: null
102
+ };
103
+ }
104
+ /** Is this record's own state terminal — finished, failed, disposed, or never executed? */
105
+ function isTerminal(fact) {
106
+ return fact.disposed || TERMINAL_STATUSES.has(fact.status) || TERMINAL_OUTCOMES.has(fact.outcome);
107
+ }
108
+ /**
109
+ * The freshness of one live dispatch.
110
+ *
111
+ * The anchor is `lastBeatAt` when the dispatch has beaten, and `createdAt`
112
+ * when it has not. The floor is bounded by the SAME threshold as a beat, so a
113
+ * dispatch that never beats can defer a compaction for at most thirty
114
+ * minutes after it was issued — a dead dispatch cannot defer forever, and a
115
+ * dispatch that was just issued is still a live member of its batch.
116
+ *
117
+ * The heartbeat ARRAY is not consulted: `lastBeatAt` is written in the same
118
+ * atomic write as the array's last entry, so the two cannot disagree, and the
119
+ * array keeps only its last hundred entries, so it is not a history.
120
+ */
121
+ function judgeFreshness(fact, nowMs) {
122
+ const anchor = fact.lastBeatAt ?? fact.createdAt;
123
+ const anchorMs = new Date(anchor).getTime();
124
+ if (!Number.isFinite(anchorMs)) {
125
+ return missingHeartbeatVerdict(fact.recordPath, 'dispatch record carries no freshness signal this probe could read');
126
+ }
127
+ if (nowMs - anchorMs < FRESH_RUNNING_THRESHOLD_MS) {
128
+ return { inFlight: true, unknown: false, warning: null, error: null };
129
+ }
130
+ return NOT_IN_FLIGHT;
131
+ }
132
+ /** What one dispatch's facts add up to. */
133
+ function judgeDispatch(fact, nowMs) {
134
+ if (fact.kind === 'absent')
135
+ return NOT_IN_FLIGHT;
136
+ if (fact.kind === 'unreadable') {
137
+ return unreadableVerdict(fact.recordPath, 'dispatch record could not be read');
138
+ }
139
+ if (isTerminal(fact))
140
+ return NOT_IN_FLIGHT;
141
+ if (!LIVE_STATUSES.has(fact.status)) {
142
+ return unknownStatusVerdict(fact.recordPath, fact.status);
143
+ }
144
+ return judgeFreshness(fact, nowMs);
145
+ }
146
+ /**
147
+ * The decision. Pure: the ledger's facts go in, the answer comes out.
148
+ *
149
+ * Red-line compaction overrides the in-flight deferral, so a session at the
150
+ * red line still asks the harness to compact.
151
+ */
24
152
  export function probeInFlightBatch(input) {
25
153
  const nowMs = new Date(input.now).getTime();
26
154
  const warnings = [];
27
155
  const errors = [];
28
- let inFlight = false;
29
- for (const graph of input.graphs) {
30
- if (graph.corrupt === true || graph.schemaVersion !== 1) {
31
- errors.push({
32
- code: PEAKS_GRAPH_REF_BROKEN,
33
- message: 'corrupt or missing graph',
34
- ...(graph.graphRef ? { graphRef: graph.graphRef } : {})
35
- });
36
- continue;
37
- }
38
- // `isArray` (not `Array.isArray`, typed `arg is any[]`), so `graph.nodes`
39
- // keeps its declared `ReadonlyArray<{...}>` and the loop below reads typed
40
- // `node` fields. The `!graph.nodes` half already covers undefined. See
41
- // `src/shared/array-guards.ts`.
42
- if (!graph.nodes || !isArray(graph.nodes)) {
43
- errors.push({
44
- code: PEAKS_GRAPH_CORRUPTED,
45
- message: 'graph.nodes missing',
46
- ...(graph.graphRef ? { graphRef: graph.graphRef } : {})
47
- });
48
- continue;
49
- }
50
- for (const node of graph.nodes) {
51
- if (node.status !== 'running')
52
- continue;
53
- if (!node.lastHeartbeat || typeof node.lastHeartbeat !== 'string') {
54
- warnings.push({
55
- code: PEAKS_HEARTBEAT_MISSING,
56
- message: 'running node missing lastHeartbeat',
57
- ...(node.id ? { nodeId: node.id } : {})
58
- });
59
- continue;
60
- }
61
- const hbMs = new Date(node.lastHeartbeat).getTime();
62
- if (!Number.isFinite(hbMs)) {
63
- warnings.push({
64
- code: PEAKS_HEARTBEAT_MISSING,
65
- message: 'heartbeat unparseable',
66
- ...(node.id ? { nodeId: node.id } : {})
67
- });
68
- continue;
69
- }
70
- const age = nowMs - hbMs;
71
- if (age < FRESH_RUNNING_THRESHOLD_MS) {
72
- inFlight = true;
73
- }
74
- }
156
+ const ledgerUnreadable = input.ledger.ledgerState === 'unreadable';
157
+ if (ledgerUnreadable) {
158
+ errors.push({
159
+ code: PEAKS_DISPATCH_LEDGER_UNREADABLE,
160
+ message: 'the dispatch ledger could not be enumerated'
161
+ });
162
+ }
163
+ const verdicts = input.ledger.dispatches.map((fact) => judgeDispatch(fact, nowMs));
164
+ for (const verdict of verdicts) {
165
+ if (verdict.warning !== null)
166
+ warnings.push(verdict.warning);
167
+ if (verdict.error !== null)
168
+ errors.push(verdict.error);
75
169
  }
76
- // Red-line compaction overrides in-flight deferral (RD §8 TC-IF-09).
170
+ const inFlight = ledgerUnreadable || verdicts.some((verdict) => verdict.inFlight);
171
+ const unknown = ledgerUnreadable || verdicts.some((verdict) => verdict.unknown);
77
172
  const shouldCompact = input.redLine === true ? true : !inFlight;
78
- const deferPreCompact = inFlight;
79
173
  return {
80
174
  inFlightBatch: inFlight,
81
175
  shouldCompact,
82
- deferPreCompact,
176
+ deferPreCompact: inFlight,
83
177
  warnings,
84
178
  errors,
85
- reason: inFlight
86
- ? 'fresh-running-node'
87
- : errors.length > 0
88
- ? 'corrupt-graphs'
89
- : 'no-fresh-running-node'
179
+ reason: unknown ? 'unknown-ledger-state' : inFlight ? 'fresh-dispatch' : 'no-fresh-dispatch'
90
180
  };
91
181
  }
92
- void NON_RUNNING;
93
- void {};
@@ -12,7 +12,8 @@
12
12
  import { existsSync, readFileSync } from 'node:fs';
13
13
  import { join } from 'node:path';
14
14
  import { TERMINAL_REASONS } from './workflow-graph-types.js';
15
- import { emptyGraph, readGraph, writeGraph, validateGraph, graphPathFor, PEAKS_GRAPH_NOT_FOUND, PEAKS_GRAPH_CORRUPTED, PEAKS_TERMINALIZE_ATOMICITY_FAILED, PEAKS_TERMINAL_REASON_INVALID } from './workflow-graph-store.js';
15
+ import { writeGraph, validateGraph, graphPathFor, PEAKS_GRAPH_NOT_FOUND, PEAKS_GRAPH_CORRUPTED, PEAKS_TERMINALIZE_ATOMICITY_FAILED, PEAKS_TERMINAL_REASON_INVALID } from './workflow-graph-store.js';
16
+ import { newWorkflowGraph, readGraphOrRepair } from './workflow-graph-ensure.js';
16
17
  import { setPresenceLease, readPresenceLease, markPresenceLost } from '../skills/presence-lease-service.js';
17
18
  function lifeError(code, message, extra = {}) {
18
19
  const err = new Error(message);
@@ -28,12 +29,11 @@ export async function initWorkflow(input) {
28
29
  if (graphRef !== `graphs/${workflowId}.json`) {
29
30
  throw lifeError(PEAKS_GRAPH_NOT_FOUND, `graphRef must normalize to graphs/${workflowId}.json; got ${graphRef}`);
30
31
  }
31
- const graph = emptyGraph({
32
+ const graph = newWorkflowGraph({
32
33
  workflowId,
33
34
  rootSkill: input.skill,
34
35
  ...(input.parentWorkflowId ? { parentWorkflowId: input.parentWorkflowId } : {})
35
36
  });
36
- validateGraph(graph);
37
37
  // Phase 1: write graph first.
38
38
  writeGraph({
39
39
  projectRoot: input.projectRoot,
@@ -83,12 +83,27 @@ export async function terminalizeWorkflow(input) {
83
83
  const events = [];
84
84
  let successEventCount = 0;
85
85
  try {
86
- // Phase 1: read graph (fail closed if missing/corrupt).
87
- const graph = readGraph({
86
+ // Phase 0: the lease IS the workflow's identity. It is read before the
87
+ // graph so a terminalize aimed at a workflow this lease does not carry
88
+ // is refused before anything is written, and so the repair below can
89
+ // take the lease's own skill as the graph's rootSkill.
90
+ const currentLease = readPresenceLease({
88
91
  projectRoot: input.projectRoot,
89
92
  sessionId: input.sessionId,
93
+ callerId: input.callerId,
94
+ workflowId: input.workflowId,
95
+ graphRef: input.graphRef
96
+ });
97
+ // Phase 1: read the graph. A graph that was never written is repaired —
98
+ // the same graph the write path creates — while a graph that is on disk
99
+ // but CORRUPT keeps failing closed (PEAKS_GRAPH_CORRUPTED is rethrown
100
+ // untouched).
101
+ const graph = readGraphOrRepair({
102
+ projectRoot: input.projectRoot,
103
+ sessionId: input.sessionId,
104
+ workflowId: input.workflowId,
90
105
  graphRef: input.graphRef,
91
- workflowId: input.workflowId
106
+ skill: currentLease.skill
92
107
  });
93
108
  // Phase 2: check unconsumed envelopes (RD §4 terminalize contract).
94
109
  if (input.requireConsumed === true) {
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Content comparison for the artifacts `peaks workspace init` generates into a
3
+ * consumer project.
4
+ *
5
+ * WHY A SEPARATE MODULE. `generated-artifacts-stamp.ts` owns the stamp and the
6
+ * staleness verdict; this module owns ONE question — "do the bytes on disk still
7
+ * match what the current release renders?" — plus the per-artifact detail that
8
+ * answers it. Splitting them keeps both files inside the 300-line size cap.
9
+ *
10
+ * WHAT IS COMPARED. The rendered template (`buildClaudeSettingsLocalJson()`)
11
+ * against the content of each generated artifact. The predicate is
12
+ * `templateContentMatches` — the one the materializer uses to decide
13
+ * `already-current` — so the detector and the writer cannot disagree.
14
+ *
15
+ * WHY CONTAINMENT AND NOT BYTE EQUALITY. `templateContentMatches` asks whether
16
+ * every entry the template declares is PRESENT and ignores extra on-disk
17
+ * entries. `.claude/settings.local.json` has a second writer (the auto-compact
18
+ * installer appends a `Bash|Task` entry) and carries the user's own keys; a
19
+ * byte-equality rule would call every such project stale on every turn.
20
+ *
21
+ * A MISSING ARTIFACT IS NOT DRIFT. There is nothing on disk to compare, and the
22
+ * generator recreates it on the next init; the stamp's reason codes cover the
23
+ * "never initialized" and "not readable" cases.
24
+ */
25
+ /** One generated artifact that no longer matches the rendered template. */
26
+ export type GeneratedArtifactDrift = {
27
+ /**
28
+ * Project-root-relative path of the artifact, POSIX-separated so the warning
29
+ * names the same file on every platform.
30
+ */
31
+ readonly artifact: string;
32
+ /** What differs, in one clause a reader can act on. */
33
+ readonly detail: string;
34
+ };
35
+ /** The verdict, plus the detail behind it. */
36
+ export type GeneratedArtifactContentStatus = {
37
+ readonly drifted: boolean;
38
+ readonly drifts: ReadonlyArray<GeneratedArtifactDrift>;
39
+ };
40
+ /**
41
+ * Compare every generated artifact on disk against the current template.
42
+ *
43
+ * The verdict is `templateContentMatches` — the writer's own predicate — and
44
+ * the per-artifact detail is a best-effort localisation of WHAT differs.
45
+ */
46
+ export declare function compareGeneratedArtifactContent(projectRoot: string, artifactPaths: ReadonlyArray<string>): GeneratedArtifactContentStatus;
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Content comparison for the artifacts `peaks workspace init` generates into a
3
+ * consumer project.
4
+ *
5
+ * WHY A SEPARATE MODULE. `generated-artifacts-stamp.ts` owns the stamp and the
6
+ * staleness verdict; this module owns ONE question — "do the bytes on disk still
7
+ * match what the current release renders?" — plus the per-artifact detail that
8
+ * answers it. Splitting them keeps both files inside the 300-line size cap.
9
+ *
10
+ * WHAT IS COMPARED. The rendered template (`buildClaudeSettingsLocalJson()`)
11
+ * against the content of each generated artifact. The predicate is
12
+ * `templateContentMatches` — the one the materializer uses to decide
13
+ * `already-current` — so the detector and the writer cannot disagree.
14
+ *
15
+ * WHY CONTAINMENT AND NOT BYTE EQUALITY. `templateContentMatches` asks whether
16
+ * every entry the template declares is PRESENT and ignores extra on-disk
17
+ * entries. `.claude/settings.local.json` has a second writer (the auto-compact
18
+ * installer appends a `Bash|Task` entry) and carries the user's own keys; a
19
+ * byte-equality rule would call every such project stale on every turn.
20
+ *
21
+ * A MISSING ARTIFACT IS NOT DRIFT. There is nothing on disk to compare, and the
22
+ * generator recreates it on the next init; the stamp's reason codes cover the
23
+ * "never initialized" and "not readable" cases.
24
+ */
25
+ import { existsSync, readFileSync } from 'node:fs';
26
+ import { join } from 'node:path';
27
+ import { normalizePath } from '../../shared/path-utils.js';
28
+ import { EXTERNAL_GATE_EXEMPT_ENV } from '../skills/hooks-codegate-superpowers.js';
29
+ import { buildClaudeSettingsLocalJson, templateContentMatches } from './claude-settings-template.js';
30
+ import { isPreToolUseEntry, isRetiredTemplateEntry } from './claude-settings-retirements.js';
31
+ /**
32
+ * Compare every generated artifact on disk against the current template.
33
+ *
34
+ * The verdict is `templateContentMatches` — the writer's own predicate — and
35
+ * the per-artifact detail is a best-effort localisation of WHAT differs.
36
+ */
37
+ export function compareGeneratedArtifactContent(projectRoot, artifactPaths) {
38
+ const template = buildClaudeSettingsLocalJson();
39
+ const rendered = JSON.stringify(template);
40
+ const drifts = [];
41
+ for (const artifact of artifactPaths) {
42
+ for (const detail of artifactDriftDetails(projectRoot, artifact, template, rendered)) {
43
+ drifts.push({ artifact: normalizePath(artifact), detail });
44
+ }
45
+ }
46
+ return { drifted: drifts.length > 0, drifts };
47
+ }
48
+ /** The details for ONE artifact. Empty when it matches or is absent. */
49
+ function artifactDriftDetails(projectRoot, artifact, template, rendered) {
50
+ const path = join(projectRoot, artifact);
51
+ if (!existsSync(path))
52
+ return [];
53
+ let content;
54
+ try {
55
+ content = readFileSync(path, 'utf8');
56
+ }
57
+ catch {
58
+ return ['the file could not be read'];
59
+ }
60
+ if (templateContentMatches(rendered, content))
61
+ return [];
62
+ return contentDiffDetails(template, content);
63
+ }
64
+ /** Name what differs between the rendered template and the on-disk content. */
65
+ function contentDiffDetails(template, content) {
66
+ const parsed = parseJsonObject(content);
67
+ if (!parsed.ok)
68
+ return [parsed.reason];
69
+ const details = [
70
+ ...missingEntryDetails(template.hooks.PreToolUse, parsed.value.hooks),
71
+ ...retiredEntryDetails(parsed.value.hooks),
72
+ ...missingExemptionDetails(parsed.value.env)
73
+ ];
74
+ return details.length > 0 ? details : ['the content differs from the current template'];
75
+ }
76
+ /**
77
+ * The parsed top-level object of a settings file, or the reason there is none —
78
+ * DISCRIMINATED: "not JSON" and "JSON but not an object" are different facts.
79
+ */
80
+ function parseJsonObject(content) {
81
+ try {
82
+ const parsed = JSON.parse(content);
83
+ if (!isPlainRecord(parsed))
84
+ return { ok: false, reason: 'the file is not a JSON object' };
85
+ return { ok: true, value: parsed };
86
+ }
87
+ catch {
88
+ return { ok: false, reason: 'the file is not valid JSON' };
89
+ }
90
+ }
91
+ /**
92
+ * The template entries the on-disk file does not carry. Matching is
93
+ * multiset-aware: the template declares TWO `Bash` entries and each needs its
94
+ * own counterpart, so a file holding one copy is still drift.
95
+ */
96
+ function missingEntryDetails(templateEntries, onDiskHooks) {
97
+ const onDiskEntries = preToolUseEntries(onDiskHooks);
98
+ if (onDiskEntries === undefined) {
99
+ return [
100
+ `hooks.PreToolUse is missing (the template declares ${templateEntries.length} entries)`
101
+ ];
102
+ }
103
+ const unmatched = [...onDiskEntries];
104
+ const details = [];
105
+ templateEntries.forEach((required, index) => {
106
+ const at = unmatched.findIndex((candidate) => sameEntry(required, candidate));
107
+ if (at === -1) {
108
+ details.push(`hooks.PreToolUse entry #${index + 1} (matcher "${required.matcher}") is missing or differs`);
109
+ return;
110
+ }
111
+ unmatched.splice(at, 1);
112
+ });
113
+ return details;
114
+ }
115
+ /** The on-disk `hooks.PreToolUse` entries, or `undefined` when there are none. */
116
+ function preToolUseEntries(hooks) {
117
+ if (typeof hooks !== 'object' || hooks === null || Array.isArray(hooks))
118
+ return undefined;
119
+ const entries = hooks.PreToolUse;
120
+ if (!Array.isArray(entries))
121
+ return undefined;
122
+ return entries.filter(isPreToolUseEntry);
123
+ }
124
+ /** Structural equality of two `PreToolUse` entries. */
125
+ function sameEntry(required, candidate) {
126
+ if (required.matcher !== candidate.matcher)
127
+ return false;
128
+ if (required.hooks.length !== candidate.hooks.length)
129
+ return false;
130
+ return required.hooks.every((handler, index) => {
131
+ const other = candidate.hooks[index];
132
+ if (other === undefined)
133
+ return false;
134
+ return (handler.type === other.type &&
135
+ handler.command === other.command &&
136
+ handler.shell === other.shell);
137
+ });
138
+ }
139
+ /** The retired entries the on-disk file still carries, if any. */
140
+ function retiredEntryDetails(onDiskHooks) {
141
+ const entries = preToolUseEntries(onDiskHooks);
142
+ if (entries === undefined)
143
+ return [];
144
+ const retired = entries.filter((entry) => isRetiredTemplateEntry(entry));
145
+ return retired.length === 0 ? [] : ['hooks.PreToolUse carries an entry this release retired'];
146
+ }
147
+ /** The gate exemptions the on-disk file does not declare. */
148
+ function missingExemptionDetails(onDiskEnv) {
149
+ const env = isPlainRecord(onDiskEnv) ? onDiskEnv : {};
150
+ const details = [];
151
+ for (const [key, glob] of Object.entries(EXTERNAL_GATE_EXEMPT_ENV)) {
152
+ const current = env[key];
153
+ const declared = typeof current === 'string' &&
154
+ current
155
+ .split(',')
156
+ .map((part) => part.trim())
157
+ .includes(glob);
158
+ if (!declared) {
159
+ details.push(`env.${key} does not declare "${glob}"`);
160
+ }
161
+ }
162
+ return details;
163
+ }
164
+ /** A JSON object, as opposed to a null / array / primitive. */
165
+ function isPlainRecord(value) {
166
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
167
+ }