peaks-loop 4.1.16 → 4.1.18

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 (48) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +193 -0
  3. package/dist/cli/commands/code-auto-compact-command.js +46 -23
  4. package/dist/cli/commands/code-auto-compact-deferral.d.ts +34 -0
  5. package/dist/cli/commands/code-auto-compact-deferral.js +59 -0
  6. package/dist/cli/commands/code-gate-command.d.ts +4 -4
  7. package/dist/cli/commands/code-gate-command.js +4 -4
  8. package/dist/cli/commands/core/skill-registry-commands.js +32 -0
  9. package/dist/cli/commands/core/skill-store-report.d.ts +8 -0
  10. package/dist/cli/commands/core/skill-store-report.js +79 -0
  11. package/dist/cli/commands/dispatch-prompt-composition.js +7 -2
  12. package/dist/cli/commands/dispatch-scratch-path-block.d.ts +73 -0
  13. package/dist/cli/commands/dispatch-scratch-path-block.js +131 -0
  14. package/dist/cli/commands/hooks-commands.js +36 -7
  15. package/dist/cli/commands/hooks-uninstall-command.js +5 -5
  16. package/dist/services/code/auto-compact-orchestrator.js +7 -5
  17. package/dist/services/code/auto-compact-run-types.d.ts +8 -4
  18. package/dist/services/dispatch/dispatch-ledger-reader.d.ts +13 -0
  19. package/dist/services/dispatch/dispatch-ledger-reader.js +164 -0
  20. package/dist/services/doctor/doctor-service/checks/canonical-store-version.d.ts +57 -0
  21. package/dist/services/doctor/doctor-service/checks/canonical-store-version.js +190 -0
  22. package/dist/services/doctor/doctor-service/plugin-registry.js +2 -0
  23. package/dist/services/doctor/doctor-service/types.d.ts +12 -0
  24. package/dist/services/hooks/gate-path-normalize.d.ts +37 -0
  25. package/dist/services/hooks/gate-path-normalize.js +74 -4
  26. package/dist/services/hooks/hook-payload-cwd.js +25 -9
  27. package/dist/services/hooks/pre-tool-code-gate.d.ts +24 -4
  28. package/dist/services/hooks/pre-tool-code-gate.js +72 -22
  29. package/dist/services/session/getSessionDir.d.ts +13 -0
  30. package/dist/services/session/getSessionDir.js +7 -1
  31. package/dist/services/skills/hooks-settings-types.d.ts +17 -21
  32. package/dist/services/skills/sync-service-support.d.ts +27 -0
  33. package/dist/services/skills/sync-service.js +1 -0
  34. package/dist/services/workflow/workflow-inflight-probe.d.ts +68 -31
  35. package/dist/services/workflow/workflow-inflight-probe.js +163 -75
  36. package/package.json +7 -5
  37. package/scripts/canonical-store-fs.mjs +112 -0
  38. package/scripts/canonical-store-link.mjs +13 -22
  39. package/scripts/canonical-store-marker.mjs +241 -0
  40. package/scripts/canonical-store.mjs +119 -141
  41. package/scripts/install-skills-bundles.mjs +56 -13
  42. package/scripts/install-skills-fs.mjs +73 -0
  43. package/scripts/install-skills-output-styles.mjs +8 -2
  44. package/scripts/install-skills-report.mjs +19 -0
  45. package/scripts/install-skills.mjs +9 -0
  46. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +20 -1
  47. package/skills/peaks-code/SKILL.md +1 -1
  48. package/skills/peaks-race-code/SKILL.md +6 -3
@@ -17,28 +17,24 @@ export type HookInstallOptions = {
17
17
  */
18
18
  readonly ide?: IdeId;
19
19
  /**
20
- * Slice #013 (bugfix — peaks hooks install --no-progress): when `true`,
21
- * skip emitting the progress-start PreToolUse hook entry while still
22
- * installing the gate-enforce entry. The progress-start hook auto-spawns
23
- * a new terminal running `peaks progress watch`; with dispatch +
24
- * heartbeat (slice #009 + #010) that auto-spawn is dead weight. Default
25
- * `false` preserves the pre-slice install shape (both entries). The
26
- * sentinel-based install is idempotent: re-running with `skipProgress:
27
- * true` over a settings.json that previously had the progress entry
28
- * installed will remove that entry. `uninstall` honors the same flag
29
- * so it can find and remove both entries when both are present and
30
- * only the gate-enforce entry when only the gate-enforce is present.
20
+ * Slice #013 (bugfix — peaks hooks install --no-progress): the published
21
+ * flag that skipped the progress-start PreToolUse hook entry. That hook
22
+ * auto-spawns a new terminal running a progress watcher; with dispatch +
23
+ * heartbeat (slice #009 + #010) the auto-spawn is dead weight.
31
24
  *
32
- * Slice #014 (refactor — full removal of legacy progress-start surface):
33
- * the field is preserved for API stability, but the underlying
34
- * install only ever emits the gate-enforce entry. The progress-start
35
- * entry is no longer installed regardless of this flag's value. The
36
- * legacy `peaks progress start|watch|close` CLI surface is gone
37
- * (replaced by `peaks sub-agent dispatch|heartbeat|share`); the hook
38
- * entry would have been pointing at a `peaks progress start` that no
39
- * longer exists. The sentinel `peaks progress start` constant is still
40
- * exported (some tests + back-compat reads rely on it) but no new
41
- * hook entries use it.
25
+ * The field is retained for API stability and NO LONGER CHANGES WHAT IS
26
+ * INSTALLED: it defaults to unset and the entry resolver ignores it, so an
27
+ * install always writes the adapter's whole peaks-managed entry set — for
28
+ * Claude Code: `peaks gate enforce` (Bash and MCP tool calls),
29
+ * `peaks code-gate` (Edit|Write|MultiEdit), `peaks outer-cache write`,
30
+ * `peaks session primer`, `peaks session reinject`, `peaks compact settle`
31
+ * — plus the Layer-3 `permissions.deny` entries (worktree governance);
32
+ * the other adapters install their own single hook entry. No code path
33
+ * writes the legacy progress-start entry any more.
34
+ *
35
+ * `uninstall` ignores this field as well: it strips entries by a sentinel
36
+ * scan over the peaks-managed sentinel set, which covers every entry an
37
+ * install writes plus the legacy progress-start one.
42
38
  */
43
39
  readonly skipProgress?: boolean;
44
40
  };
@@ -5,6 +5,29 @@ import type { IdeId } from '../ide/ide-types.js';
5
5
  * single source of truth for the sync fan-out.
6
6
  */
7
7
  export declare const SYNC_PLATFORMS: readonly IdeId[];
8
+ /**
9
+ * What the canonical store holds for one skill, as the installer found it.
10
+ *
11
+ * `current` — the store holds this entry and it is not behind the installed
12
+ * release. `stale` — it is behind, or its bytes differ from the package's.
13
+ * `unmanaged` — the store holds an entry peaks-loop does not own (no
14
+ * sidecar); it is never overwritten, and it is reported so the skip is not
15
+ * silent. `retired` — the store holds an entry peaks-loop owns that this
16
+ * release does not ship any more. `absent` — the store does not hold this
17
+ * entry at all: there is nothing there to compare, so it is neither current
18
+ * nor stale.
19
+ */
20
+ export type StoreEntryState = 'current' | 'stale' | 'unmanaged' | 'retired' | 'absent';
21
+ export interface StoreEntryReport {
22
+ readonly name: string;
23
+ readonly state: StoreEntryState;
24
+ /** What the installer did: `installed`, `unchanged`, `planned`, `unmanaged`. */
25
+ readonly action: string;
26
+ /** The version the copy was made from, or null when the marker records none. */
27
+ readonly version: string | null;
28
+ /** Why a stale entry was stale: `version` or `content`; null otherwise. */
29
+ readonly reason: string | null;
30
+ }
8
31
  export interface PlatformSyncResult {
9
32
  /** The platform that was attempted. */
10
33
  readonly platform: IdeId;
@@ -14,6 +37,8 @@ export interface PlatformSyncResult {
14
37
  readonly installed: readonly string[];
15
38
  /** Skills whose target was not a managed symlink (third-party owned). */
16
39
  readonly skipped: readonly string[];
40
+ /** What the canonical store holds per skill, as found. */
41
+ readonly entries?: readonly StoreEntryReport[];
17
42
  /** Error message; present when ok=false. */
18
43
  readonly error?: string;
19
44
  /** Wall-clock duration in ms. */
@@ -47,6 +72,8 @@ export interface InstallBundledSkillsOptions {
47
72
  export interface InstallResult {
48
73
  readonly installed: readonly string[];
49
74
  readonly skipped: readonly string[];
75
+ /** What the canonical store holds per skill, when the installer reports it. */
76
+ readonly entries?: readonly StoreEntryReport[];
50
77
  }
51
78
  export type InstallerFn = (opts: InstallBundledSkillsOptions) => InstallResult;
52
79
  /**
@@ -191,6 +191,7 @@ export async function runSkillSync(input) {
191
191
  ok: true,
192
192
  installed: result.installed,
193
193
  skipped: result.skipped,
194
+ ...(result.entries !== undefined ? { entries: result.entries } : {}),
194
195
  durationMs: Date.now() - start
195
196
  });
196
197
  syncedCount += 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 {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peaks-loop",
3
- "version": "4.1.16",
3
+ "version": "4.1.18",
4
4
  "description": "Loop Engineering CLI — workflow primitive / loop guards / evaluators / slice orchestration",
5
5
  "author": "SquabbyZ",
6
6
  "keywords": [
@@ -83,6 +83,8 @@
83
83
  "scripts/install-skills-output-styles.mjs",
84
84
  "scripts/install-skills-output-style-default.mjs",
85
85
  "scripts/canonical-store.mjs",
86
+ "scripts/canonical-store-fs.mjs",
87
+ "scripts/canonical-store-marker.mjs",
86
88
  "scripts/canonical-store-link.mjs",
87
89
  "scripts/canonical-store-prune.mjs",
88
90
  "scripts/watch.mjs",
@@ -129,10 +131,10 @@
129
131
  "picomatch": "4.0.7",
130
132
  "yaml": "^2.9.1",
131
133
  "zod": "^4.6.7",
132
- "peaks-loop-mut": "0.1.70",
133
- "peaks-loop-shared": "0.0.105",
134
- "peaks-loop-shared-channel": "0.0.73",
135
- "peaks-loop-internal-runtime": "0.0.56"
134
+ "peaks-loop-internal-runtime": "0.0.58",
135
+ "peaks-loop-mut": "0.1.72",
136
+ "peaks-loop-shared": "0.0.107",
137
+ "peaks-loop-shared-channel": "0.0.75"
136
138
  },
137
139
  "devDependencies": {
138
140
  "@changesets/cli": "2.31.1",
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // The canonical store's FILESYSTEM vocabulary: how a path is identified, and how
4
+ // two trees are compared.
5
+ //
6
+ // Split out of `scripts/canonical-store.mjs` (the b1 file-size campaign): the
7
+ // store's own file was one line under the 300-line cap, and the version-aware
8
+ // staleness decision did not fit beside it. Every line below was moved
9
+ // VERBATIM; only this header and the import block are new.
10
+ //
11
+ // TWO CONCERNS, ONE FILE. They are here together because they are the two
12
+ // questions the store asks about the disk, and both of them are about IDENTITY
13
+ // rather than about policy:
14
+ //
15
+ // 1. IDENTITY — `linkResolvesTo` decides whether two paths are the same
16
+ // directory. It goes through `realpath`, strips the `\\?\` long-path
17
+ // prefix and folds case on Windows, so a trailing separator, a case
18
+ // difference or a long-path spelling cannot make one directory look like
19
+ // two. A path that does not resolve claims nothing.
20
+ //
21
+ // 2. EQUALITY — `contentMatches` is the byte-for-byte comparison of a source
22
+ // and the store's copy. It is what makes the copy idempotent, and it is
23
+ // the SECOND half of the staleness decision: the first half is the
24
+ // version the copy was made from, which lives with the marker.
25
+
26
+ import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
27
+ import { join } from 'node:path';
28
+
29
+ export function getPathStats(path) {
30
+ try {
31
+ return lstatSync(path);
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ /** `\\?\C:\x` and `\\?\UNC\srv\share` are spellings of a path, not other paths. */
38
+ export function stripLongPathPrefix(value) {
39
+ const uncPrefix = '\\\\?\\UNC\\';
40
+ if (value.startsWith(uncPrefix)) return `\\\\${value.slice(uncPrefix.length)}`;
41
+ const prefix = '\\\\?\\';
42
+ return value.startsWith(prefix) ? value.slice(prefix.length) : value;
43
+ }
44
+
45
+ /**
46
+ * The real, resolved, case-folded identity of a path, or null when it does not
47
+ * resolve (a dangling junction included).
48
+ */
49
+ export function resolveIdentity(path) {
50
+ let resolved;
51
+ try {
52
+ resolved = realpathSync(path);
53
+ } catch {
54
+ return null;
55
+ }
56
+ const normalized = stripLongPathPrefix(resolved);
57
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
58
+ }
59
+
60
+ /**
61
+ * Whether `linkPath` resolves to the same directory as `expectedPath`. Both sides
62
+ * go through `realpath`, so a `\\?\` prefix, a `.` segment or a case difference
63
+ * cannot make one directory look like two.
64
+ */
65
+ export function linkResolvesTo(linkPath, expectedPath) {
66
+ const actual = resolveIdentity(linkPath);
67
+ const expected = resolveIdentity(expectedPath);
68
+ return actual !== null && expected !== null && actual === expected;
69
+ }
70
+
71
+ /** Every file and directory under `rootPath`, as sorted `/`-joined relative paths. */
72
+ function listTreeEntries(rootPath) {
73
+ const entries = [];
74
+ const walk = (dir, prefix) => {
75
+ for (const name of readdirSync(dir).sort()) {
76
+ const relativePath = prefix === '' ? name : `${prefix}/${name}`;
77
+ const stats = lstatSync(join(dir, name));
78
+ if (stats.isDirectory()) {
79
+ entries.push(`${relativePath}/`);
80
+ walk(join(dir, name), relativePath);
81
+ } else if (stats.isFile()) {
82
+ entries.push(relativePath);
83
+ } else {
84
+ throw new Error(
85
+ `Peaks canonical store cannot read ${join(dir, name)}: not a file or directory`
86
+ );
87
+ }
88
+ }
89
+ };
90
+ walk(rootPath, '');
91
+ return entries;
92
+ }
93
+
94
+ /** True when `targetPath` already holds exactly the bytes `sourcePath` holds. */
95
+ export function contentMatches(sourcePath, targetPath) {
96
+ const targetStats = getPathStats(targetPath);
97
+ if (!targetStats || targetStats.isSymbolicLink()) return false;
98
+ if (!targetStats.isDirectory()) {
99
+ return targetStats.isFile() && readFileSync(sourcePath).equals(readFileSync(targetPath));
100
+ }
101
+ const sourceEntries = listTreeEntries(sourcePath);
102
+ const targetEntries = listTreeEntries(targetPath);
103
+ if (sourceEntries.length !== targetEntries.length) return false;
104
+ for (let index = 0; index < sourceEntries.length; index += 1) {
105
+ if (sourceEntries[index] !== targetEntries[index]) return false;
106
+ if (sourceEntries[index].endsWith('/')) continue;
107
+ const from = join(sourcePath, sourceEntries[index]);
108
+ const to = join(targetPath, targetEntries[index]);
109
+ if (!readFileSync(from).equals(readFileSync(to))) return false;
110
+ }
111
+ return true;
112
+ }