peaks-loop 4.1.18 → 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 (168) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +126 -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 +26 -18
  14. package/dist/cli/commands/core/skill-generated-config-notice.d.ts +5 -0
  15. package/dist/cli/commands/core/skill-generated-config-notice.js +42 -8
  16. package/dist/cli/commands/core/skill-presence-commands.js +42 -74
  17. package/dist/cli/commands/core/skill-presence-set-command.d.ts +11 -0
  18. package/dist/cli/commands/core/skill-presence-set-command.js +175 -0
  19. package/dist/cli/commands/core/standards-init-command.js +44 -8
  20. package/dist/cli/commands/core/standards-migrate-command.js +5 -4
  21. package/dist/cli/commands/dispatch-dag-runners.d.ts +1 -0
  22. package/dist/cli/commands/dispatch-dag-runners.js +11 -1
  23. package/dist/cli/commands/dispatch-detached-branch.js +19 -1
  24. package/dist/cli/commands/mut-commands-helpers.d.ts +72 -5
  25. package/dist/cli/commands/mut-commands-helpers.js +197 -4
  26. package/dist/cli/commands/mut-commands.d.ts +9 -1
  27. package/dist/cli/commands/mut-commands.js +82 -154
  28. package/dist/cli/commands/preferences-commands.js +27 -2
  29. package/dist/cli/commands/scan-scope-helpers.js +2 -2
  30. package/dist/services/24h-mode/auto-engage.d.ts +11 -3
  31. package/dist/services/24h-mode/auto-engage.js +14 -6
  32. package/dist/services/artifacts/artifact-templates.js +10 -0
  33. package/dist/services/artifacts/backcompat-acceptance.d.ts +8 -1
  34. package/dist/services/artifacts/backcompat-acceptance.js +8 -7
  35. package/dist/services/artifacts/rd-transition-gates.d.ts +32 -5
  36. package/dist/services/artifacts/rd-transition-gates.js +96 -19
  37. package/dist/services/artifacts/request-artifact-service.js +6 -6
  38. package/dist/services/audit/enforcers/lint-output-style.js +14 -2
  39. package/dist/services/audit/enforcers/root-scratch-artifacts.d.ts +46 -0
  40. package/dist/services/audit/enforcers/root-scratch-artifacts.js +97 -0
  41. package/dist/services/audit/static-service.js +4 -4
  42. package/dist/services/code/auto-compact-history.d.ts +6 -1
  43. package/dist/services/code/auto-compact-history.js +6 -1
  44. package/dist/services/code/auto-compact-modes.d.ts +60 -14
  45. package/dist/services/code/auto-compact-modes.js +75 -20
  46. package/dist/services/code/auto-compact-profile.d.ts +23 -0
  47. package/dist/services/code/auto-compact-profile.js +51 -0
  48. package/dist/services/compact-history/compact-history-service.d.ts +6 -1
  49. package/dist/services/compact-history/compact-history-service.js +5 -1
  50. package/dist/services/context/auto-compact-types.d.ts +7 -5
  51. package/dist/services/doctor/doctor-service/checks/l3-runtime-root-census.d.ts +37 -0
  52. package/dist/services/doctor/doctor-service/checks/l3-runtime-root-census.js +100 -0
  53. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.d.ts +11 -3
  54. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.js +48 -29
  55. package/dist/services/doctor/doctor-service/plugin-registry.js +2 -0
  56. package/dist/services/hooks/hook-payload-cwd.d.ts +11 -4
  57. package/dist/services/hooks/hook-payload-cwd.js +11 -4
  58. package/dist/services/hooks/presence-marker-detector.d.ts +3 -0
  59. package/dist/services/hooks/presence-marker-detector.js +21 -19
  60. package/dist/services/ide/adapters/claude-code-adapter.js +6 -8
  61. package/dist/services/ide/adapters/codex-adapter.js +23 -7
  62. package/dist/services/ide/adapters/cursor-adapter.js +23 -7
  63. package/dist/services/mode/mode-status-service.d.ts +26 -27
  64. package/dist/services/mode/mode-status-service.js +36 -60
  65. package/dist/services/preferences/preferences-types.d.ts +30 -0
  66. package/dist/services/preferences/preferences-types.js +13 -0
  67. package/dist/services/scan/acceptance-coverage-service.d.ts +14 -11
  68. package/dist/services/scan/acceptance-coverage-service.js +157 -52
  69. package/dist/services/scan/rid-change-claims.d.ts +15 -0
  70. package/dist/services/scan/rid-change-claims.js +116 -0
  71. package/dist/services/skills/presence-caller-id.d.ts +51 -0
  72. package/dist/services/skills/presence-caller-id.js +43 -0
  73. package/dist/services/skills/presence-gate.d.ts +65 -0
  74. package/dist/services/skills/presence-gate.js +113 -0
  75. package/dist/services/skills/presence-lease-resolver.d.ts +63 -0
  76. package/dist/services/skills/presence-lease-resolver.js +114 -0
  77. package/dist/services/skills/presence-lease-selection.d.ts +91 -0
  78. package/dist/services/skills/presence-lease-selection.js +135 -0
  79. package/dist/services/skills/presence-lease-service.d.ts +3 -11
  80. package/dist/services/skills/presence-lease-service.js +34 -87
  81. package/dist/services/skills/presence-lease-store.d.ts +33 -0
  82. package/dist/services/skills/presence-lease-store.js +94 -0
  83. package/dist/services/skills/presence-lease-types.d.ts +31 -0
  84. package/dist/services/skills/presence-lease-types.js +27 -0
  85. package/dist/services/skills/presence-role.d.ts +35 -0
  86. package/dist/services/skills/presence-role.js +72 -0
  87. package/dist/services/skills/skill-presence-service.d.ts +39 -9
  88. package/dist/services/skills/skill-presence-service.js +143 -174
  89. package/dist/services/skills/skill-presence-write.d.ts +60 -0
  90. package/dist/services/skills/skill-presence-write.js +74 -0
  91. package/dist/services/skills/skill-statusline-service.js +7 -7
  92. package/dist/services/standards/ide-aware-standards-service.d.ts +35 -23
  93. package/dist/services/standards/ide-aware-standards-service.js +45 -20
  94. package/dist/services/standards/migrate-claude-rules-service.d.ts +6 -0
  95. package/dist/services/standards/migrate-claude-rules-service.js +18 -0
  96. package/dist/services/standards/migrate-service.d.ts +1 -1
  97. package/dist/services/standards/migrate-service.js +27 -7
  98. package/dist/services/standards/project-scripts.d.ts +25 -0
  99. package/dist/services/standards/project-scripts.js +116 -0
  100. package/dist/services/standards/project-standards-service.d.ts +23 -15
  101. package/dist/services/standards/project-standards-service.js +176 -243
  102. package/dist/services/standards/standards-constitution.d.ts +89 -0
  103. package/dist/services/standards/standards-constitution.js +199 -0
  104. package/dist/services/standards/standards-files.d.ts +37 -0
  105. package/dist/services/standards/standards-files.js +138 -0
  106. package/dist/services/standards/standards-pointer.d.ts +73 -0
  107. package/dist/services/standards/standards-pointer.js +98 -0
  108. package/dist/services/standards/standards-render-agents.d.ts +34 -0
  109. package/dist/services/standards/standards-render-agents.js +149 -0
  110. package/dist/services/standards/standards-render-common.d.ts +38 -1
  111. package/dist/services/standards/standards-render-common.js +44 -7
  112. package/dist/services/standards/standards-render.d.ts +1 -3
  113. package/dist/services/standards/standards-render.js +6 -87
  114. package/dist/services/workflow/workflow-graph-ensure.d.ts +77 -0
  115. package/dist/services/workflow/workflow-graph-ensure.js +97 -0
  116. package/dist/services/workflow/workflow-presence-lifecycle.js +21 -6
  117. package/dist/services/workspace/generated-artifacts-content.d.ts +46 -0
  118. package/dist/services/workspace/generated-artifacts-content.js +167 -0
  119. package/dist/services/workspace/generated-artifacts-stamp.d.ts +36 -13
  120. package/dist/services/workspace/generated-artifacts-stamp.js +37 -15
  121. package/dist/services/workspace/runtime-layout.d.ts +64 -0
  122. package/dist/services/workspace/runtime-layout.js +62 -0
  123. package/output-styles/peaks-skill-swarm.md +18 -2
  124. package/package.json +8 -9
  125. package/schemas/doctor-report.schema.json +1 -1
  126. package/skills/bee/peaks-perf-audit/SKILL.md +3 -1
  127. package/skills/bee/peaks-prd/SKILL.md +5 -3
  128. package/skills/bee/peaks-qa/SKILL.md +4 -2
  129. package/skills/bee/peaks-qa/references/qa-skill-presence.md +1 -1
  130. package/skills/bee/peaks-qa/references/qa-standards-preflight.md +3 -1
  131. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  132. package/skills/bee/peaks-rd/SKILL.md +4 -2
  133. package/skills/bee/peaks-rd/references/artifact-and-standards-output.md +1 -1
  134. package/skills/bee/peaks-rd/references/rd-runbook.md +11 -2
  135. package/skills/bee/peaks-rd/references/rd-standards-preflight.md +3 -1
  136. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +4 -4
  137. package/skills/bee/peaks-rd/references/rd-transition-gates.md +49 -5
  138. package/skills/bee/peaks-rd/references/skill-presence-and-title.md +1 -1
  139. package/skills/bee/peaks-reviewer/SKILL.md +3 -1
  140. package/skills/bee/peaks-sc/SKILL.md +4 -2
  141. package/skills/bee/peaks-security-audit/SKILL.md +3 -1
  142. package/skills/bee/peaks-txt/SKILL.md +5 -3
  143. package/skills/bee/peaks-ui/SKILL.md +6 -4
  144. package/skills/peaks-audit/SKILL.md +3 -1
  145. package/skills/peaks-code/SKILL.md +3 -1
  146. package/skills/peaks-code/references/a2a-artifact-mapping.md +3 -3
  147. package/skills/peaks-code/references/completion-handoff.md +1 -1
  148. package/skills/peaks-code/references/local-artifact-workspace.md +10 -11
  149. package/skills/peaks-code/references/micro-cycle.md +2 -2
  150. package/skills/peaks-code/references/mode-selection-with-stale-presence.md +3 -3
  151. package/skills/peaks-code/references/runbook.md +4 -4
  152. package/skills/peaks-code/references/skill-presence-and-title.md +4 -2
  153. package/skills/peaks-code/references/standards-preflight.md +7 -6
  154. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  155. package/skills/peaks-code/references/swarm-dispatch-contract.md +5 -5
  156. package/skills/peaks-code/references/workflow-gates-and-types.md +37 -11
  157. package/skills/peaks-content/SKILL.md +3 -1
  158. package/skills/peaks-doctor/SKILL.md +3 -1
  159. package/skills/peaks-final-review/SKILL.md +3 -1
  160. package/skills/peaks-ide/SKILL.md +3 -1
  161. package/skills/peaks-issue-fix-orchestrator/SKILL.md +5 -3
  162. package/skills/peaks-race-code/SKILL.md +3 -1
  163. package/skills/peaks-resume/SKILL.md +3 -1
  164. package/skills/peaks-slice-decompose/SKILL.md +3 -1
  165. package/skills/peaks-solo/SKILL.md +3 -1
  166. package/skills/peaks-sop/SKILL.md +4 -2
  167. package/skills/peaks-status/SKILL.md +3 -1
  168. package/skills/peaks-test/SKILL.md +3 -1
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Deterministic presence-lease selection — pure rules, no filesystem I/O.
3
+ *
4
+ * WHY THIS MODULE EXISTS. The canonical presence read used to look at ONE
5
+ * session tree — the tree the caller is bound to — and answered "inactive"
6
+ * whenever that tree had no in-flight lease. A peaks run whose lease landed
7
+ * in a different tree (a sibling session, a rotated session, a session the
8
+ * caller-id resolution could not reach) was therefore invisible:
9
+ * `peaks skill presence --json` reported `{"active": false}` while a live
10
+ * lease sat on disk. The rules live here, free of I/O, so they can be
11
+ * unit-tested directly against fixture lease sets.
12
+ *
13
+ * THE RULES (in order):
14
+ *
15
+ * 1. ELIGIBLE = not terminal AND not stale.
16
+ *
17
+ * - terminal: `terminalAt` is set, or `status` is outside
18
+ * {`running`, `preparing`} — a lease that already reached its end
19
+ * state is never reported as driving the work.
20
+ * - stale: `now - lastHeartbeat` is past the lease's OWN window
21
+ * (`staleThresholdMs`). Nothing refreshes a lease heartbeat on a
22
+ * cadence, so a lease left behind by a finished session would
23
+ * otherwise keep reporting "active" forever.
24
+ *
25
+ * 2. SCOPE. When the BOUND tree (the tree the caller is bound to) holds
26
+ * at least one eligible lease, only bound-tree leases are selectable:
27
+ * the bound tree is the caller's own state and keeps its precedence.
28
+ * Only when the bound tree has NO eligible lease do the other trees'
29
+ * leases become selectable — that is the cross-session fallback.
30
+ *
31
+ * 3. ORDER. Freshest heartbeat first, then freshest start, then
32
+ * sessionId, callerId, workflowId. The tail is a total order, so the
33
+ * same lease set always names the same winner — no `readdirSync`
34
+ * order leaks into the answer.
35
+ */
36
+ import { comparePresenceLeases } from './presence-lease-order.js';
37
+ import { STALE_HEARTBEAT_MS, STALE_STARTED_AFTER_MS } from './presence-lease-types.js';
38
+ /**
39
+ * The stale window that applies to THIS lease.
40
+ *
41
+ * `24h` leases get the 24h run's own window (`STALE_STARTED_AFTER_MS`,
42
+ * 24h30m — the canonical lease-GC start predicate); every other lease
43
+ * gets the canonical heartbeat window (`STALE_HEARTBEAT_MS`, 1h). A 24h
44
+ * run must not lose its presence after one hour just because nothing
45
+ * refreshes the lease heartbeat while the run is in flight.
46
+ */
47
+ export function staleThresholdMs(lease) {
48
+ return lease.mode === '24h' ? STALE_STARTED_AFTER_MS : STALE_HEARTBEAT_MS;
49
+ }
50
+ /** A lease that reached its end state — never reported as active. */
51
+ export function isTerminalPresenceLease(lease) {
52
+ if (typeof lease.terminalAt === 'string' && lease.terminalAt.length > 0)
53
+ return true;
54
+ return lease.status !== 'running' && lease.status !== 'preparing';
55
+ }
56
+ /** A lease whose heartbeat is older than its window — never reported as active. */
57
+ export function isStalePresenceLease(lease, nowMs) {
58
+ const heartbeatMs = Date.parse(lease.lastHeartbeat);
59
+ // An unparseable heartbeat carries no liveness signal — treat it as
60
+ // stale (fail closed) rather than reporting a lease we cannot date.
61
+ if (!Number.isFinite(heartbeatMs))
62
+ return true;
63
+ return nowMs - heartbeatMs > staleThresholdMs(lease);
64
+ }
65
+ /** A lease that may be reported as the active presence. */
66
+ export function isEligiblePresenceLease(lease, nowMs) {
67
+ return !isTerminalPresenceLease(lease) && !isStalePresenceLease(lease, nowMs);
68
+ }
69
+ /**
70
+ * Total order over candidates: freshest heartbeat, then freshest start,
71
+ * then sessionId, callerId, workflowId.
72
+ */
73
+ function compareCandidates(a, b) {
74
+ const byLease = comparePresenceLeases(a.lease, b.lease);
75
+ if (byLease !== 0)
76
+ return byLease;
77
+ const bySession = a.sessionId.localeCompare(b.sessionId);
78
+ if (bySession !== 0)
79
+ return bySession;
80
+ const byCaller = a.lease.callerId.localeCompare(b.lease.callerId);
81
+ if (byCaller !== 0)
82
+ return byCaller;
83
+ return a.lease.workflowId.localeCompare(b.lease.workflowId);
84
+ }
85
+ /**
86
+ * Pick the lease that represents "who is driving peaks right now".
87
+ *
88
+ * Returns `null` when no candidate is eligible — the caller answers
89
+ * "inactive" (never an optimistic default).
90
+ */
91
+ export function selectActivePresenceLease(candidates, nowMs) {
92
+ const eligible = candidates.filter((c) => isEligiblePresenceLease(c.lease, nowMs));
93
+ if (eligible.length === 0)
94
+ return null;
95
+ const bound = eligible.filter((c) => c.scope === 'bound');
96
+ const pool = bound.length > 0 ? bound : eligible;
97
+ const sorted = pool.slice().sort(compareCandidates);
98
+ return sorted[0] ?? null;
99
+ }
100
+ /**
101
+ * Explain why the read found nothing active.
102
+ *
103
+ * Precondition: called only when `selectActivePresenceLease` returned
104
+ * `null` (so `eligibleCount` is 0). The `eligible-present` reason is a
105
+ * defensive branch for a caller that violates that precondition.
106
+ */
107
+ export function explainInactivePresence(candidates, nowMs) {
108
+ let terminalCount = 0;
109
+ let staleCount = 0;
110
+ let eligibleCount = 0;
111
+ for (const candidate of candidates) {
112
+ if (isTerminalPresenceLease(candidate.lease)) {
113
+ terminalCount += 1;
114
+ continue;
115
+ }
116
+ if (isStalePresenceLease(candidate.lease, nowMs)) {
117
+ staleCount += 1;
118
+ continue;
119
+ }
120
+ eligibleCount += 1;
121
+ }
122
+ const leaseCount = candidates.length;
123
+ let reason;
124
+ if (leaseCount === 0)
125
+ reason = 'no-leases';
126
+ else if (eligibleCount > 0)
127
+ reason = 'eligible-present';
128
+ else if (terminalCount === leaseCount)
129
+ reason = 'all-terminal';
130
+ else if (staleCount === leaseCount)
131
+ reason = 'all-stale';
132
+ else
133
+ reason = 'terminal-and-stale';
134
+ return { reason, leaseCount, terminalCount, staleCount, eligibleCount };
135
+ }
@@ -10,17 +10,9 @@
10
10
  */
11
11
  import { type SkillPresenceLease, type PresenceIndex, type PresenceProjection, type GcResult } from './presence-lease-types.js';
12
12
  import { type TerminalReason } from '../workflow/workflow-graph-types.js';
13
- export interface PresenceError extends Error {
14
- readonly code: string;
15
- }
16
- export declare const STALE_HEARTBEAT_MS: number;
17
- export declare const STALE_STARTED_AFTER_MS: number;
18
- /** Resolve the lease directory. */
19
- export declare function leaseDir(projectRoot: string, sessionId: string): string;
20
- /** Resolve the caller index directory. */
21
- export declare function presenceIndexDir(projectRoot: string, sessionId: string): string;
22
- /** Resolve the migrations directory. */
23
- export declare function migrationsDir(projectRoot: string, sessionId: string): string;
13
+ export { leaseDir, presenceIndexDir, migrationsDir } from './presence-lease-store.js';
14
+ export type { PresenceError } from './presence-lease-store.js';
15
+ export { STALE_HEARTBEAT_MS, STALE_STARTED_AFTER_MS } from './presence-lease-types.js';
24
16
  export interface SetPresenceLeaseInput {
25
17
  readonly projectRoot: string;
26
18
  readonly sessionId?: string | null;
@@ -8,18 +8,20 @@
8
8
  * responsibility, and the resolved callerId is passed in as a typed
9
9
  * argument. Same-project GC lives here (RD §3 D3).
10
10
  */
11
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
12
- import { dirname, join, resolve, sep } from 'node:path';
11
+ import { existsSync, readdirSync, writeFileSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { STALE_HEARTBEAT_MS, STALE_STARTED_AFTER_MS } from './presence-lease-types.js';
14
+ import { normalizePresenceGate, readPresenceGate } from './presence-gate.js';
15
+ import { callerIndexPath, leaseDir, leaseFilePath, presenceError, readJsonStrict, sessionRuntimeRoot, writeAtomic } from './presence-lease-store.js';
13
16
  import { WORKFLOW_ID_REGEX } from '../workflow/workflow-graph-types.js';
14
17
  import { PEAKS_SESSION_NOT_BOUND, PEAKS_CALLER_NOT_RESOLVED, PEAKS_GRAPH_REF_BROKEN } from '../workflow/workflow-graph-store.js';
15
- function presenceError(code, message) {
16
- const err = new Error(message);
17
- err.name = 'PresenceError';
18
- err.code = code;
19
- return err;
20
- }
21
- export const STALE_HEARTBEAT_MS = 60 * 60 * 1000; // 1h
22
- export const STALE_STARTED_AFTER_MS = 24 * 60 * 60 * 1000 + 30 * 60 * 1000; // 24h30m (RD §3 calls for >24h; the +30m buffer disambiguates leases that started in the 24-25h window so only leases older than 24h30m are GC'd)
18
+ import { ensureGraphExists } from '../workflow/workflow-graph-ensure.js';
19
+ // The path helpers and the atomic IO primitives live in
20
+ // `presence-lease-store.ts` (this file was already over the repository's
21
+ // 300-line cap, which may only go down). The public surface is unchanged:
22
+ // the same names are still exported from here.
23
+ export { leaseDir, presenceIndexDir, migrationsDir } from './presence-lease-store.js';
24
+ export { STALE_HEARTBEAT_MS, STALE_STARTED_AFTER_MS } from './presence-lease-types.js';
23
25
  /** Validate `callerId` shape. Returns trimmed value or throws. */
24
26
  function validateCallerId(callerId) {
25
27
  if (typeof callerId !== 'string') {
@@ -52,72 +54,6 @@ function validateWorkflowId(workflowId) {
52
54
  }
53
55
  return workflowId;
54
56
  }
55
- /** Resolve the session runtime root. */
56
- function sessionRuntimeRoot(projectRoot, sessionId) {
57
- const root = resolve(projectRoot);
58
- return join(root, '.peaks', '_runtime', sessionId);
59
- }
60
- /** Resolve the lease directory. */
61
- export function leaseDir(projectRoot, sessionId) {
62
- return join(sessionRuntimeRoot(projectRoot, sessionId), 'leases');
63
- }
64
- /** Resolve the caller index directory. */
65
- export function presenceIndexDir(projectRoot, sessionId) {
66
- return join(sessionRuntimeRoot(projectRoot, sessionId), 'presence-index');
67
- }
68
- /** Resolve the migrations directory. */
69
- export function migrationsDir(projectRoot, sessionId) {
70
- return join(sessionRuntimeRoot(projectRoot, sessionId), 'migrations');
71
- }
72
- /** Resolve the lease file path for a (callerId, workflowId) pair. */
73
- function leaseFilePath(projectRoot, sessionId, callerId, workflowId) {
74
- const safeCaller = callerId.replace(/[^a-zA-Z0-9._-]/g, '_');
75
- const safeWorkflow = workflowId.replace(/[^a-zA-Z0-9._-]/g, '_');
76
- const path = join(leaseDir(projectRoot, sessionId), `presence-${safeCaller}-${safeWorkflow}.json`);
77
- const root = sessionRuntimeRoot(projectRoot, sessionId);
78
- if (!path.startsWith(root + sep) && path !== root) {
79
- throw presenceError(PEAKS_GRAPH_REF_BROKEN, `lease path escapes session root: ${path}`);
80
- }
81
- return path;
82
- }
83
- /** Caller index path. */
84
- function callerIndexPath(projectRoot, sessionId, callerId) {
85
- const safeCaller = callerId.replace(/[^a-zA-Z0-9._-]/g, '_');
86
- const path = join(presenceIndexDir(projectRoot, sessionId), `${safeCaller}.json`);
87
- const root = sessionRuntimeRoot(projectRoot, sessionId);
88
- if (!path.startsWith(root + sep) && path !== root) {
89
- throw presenceError(PEAKS_GRAPH_REF_BROKEN, `index path escapes session root: ${path}`);
90
- }
91
- return path;
92
- }
93
- /** Atomic write — tmp + rename. */
94
- function writeAtomic(path, body) {
95
- const dir = dirname(path);
96
- if (!existsSync(dir))
97
- mkdirSync(dir, { recursive: true });
98
- const tmp = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
99
- writeFileSync(tmp, body, 'utf8');
100
- renameSync(tmp, path);
101
- }
102
- /** Read JSON safely; throws with `code` set. */
103
- function readJsonStrict(path, codeOnError) {
104
- if (!existsSync(path)) {
105
- throw presenceError('PEAKS_LEASE_NOT_FOUND', `file not found: ${path}`);
106
- }
107
- let raw;
108
- try {
109
- raw = readFileSync(path, 'utf8');
110
- }
111
- catch (err) {
112
- throw presenceError(codeOnError, `read failed: ${err.message}`);
113
- }
114
- try {
115
- return JSON.parse(raw);
116
- }
117
- catch (err) {
118
- throw presenceError(codeOnError, `JSON malformed: ${err.message}`);
119
- }
120
- }
121
57
  /* ---------- Set / read / mark-lost ---------- */
122
58
  export function setPresenceLease(input) {
123
59
  const sessionId = validateSessionId(input.sessionId ?? null);
@@ -136,6 +72,11 @@ export function setPresenceLease(input) {
136
72
  leases: input.staleLeases ?? [],
137
73
  trigger: 'presence-set'
138
74
  });
75
+ // The gate is persisted so the status header's middle cell
76
+ // (`Peaks-Loop Gate: <gate>`) is a machine fact. A malformed gate is
77
+ // rejected BEFORE any filesystem write (same fail-closed contract as
78
+ // the caller-id / session-id checks above).
79
+ const gate = normalizePresenceGate(input.gate);
139
80
  const lease = {
140
81
  callerId,
141
82
  workflowId,
@@ -143,6 +84,7 @@ export function setPresenceLease(input) {
143
84
  skill: input.skill,
144
85
  ...(input.parentWorkflowId ? { parentWorkflowId: input.parentWorkflowId } : {}),
145
86
  ...(input.mode ? { mode: input.mode } : {}),
87
+ ...(gate !== undefined ? { gate } : {}),
146
88
  depth: input.depth ?? 0,
147
89
  startedAt: now,
148
90
  lastHeartbeat: now,
@@ -150,6 +92,9 @@ export function setPresenceLease(input) {
150
92
  schemaVersion: 1
151
93
  };
152
94
  const leasePath = leaseFilePath(input.projectRoot, sessionId, callerId, workflowId);
95
+ // The lease names a graph the terminalize path requires, so the graph is
96
+ // written before the lease: no lease is left pointing at a missing graph.
97
+ ensureGraphExists({ projectRoot: input.projectRoot, sessionId, workflowId, skill: input.skill });
153
98
  writeAtomic(leasePath, JSON.stringify(lease, null, 2));
154
99
  const index = {
155
100
  callerId,
@@ -162,12 +107,9 @@ export function setPresenceLease(input) {
162
107
  };
163
108
  const indexPath = callerIndexPath(input.projectRoot, sessionId, callerId);
164
109
  writeAtomic(indexPath, JSON.stringify(index, null, 2));
165
- // Return shape: tests read both `result.lease.status` AND top-level
166
- // `lease.workflowId`. We spread the inner lease fields at the top
167
- // level so destructuring like `const lease = await api.setPresenceLease(...)`
168
- // yields a record with `.workflowId`, `.status`, etc. (test seam),
169
- // while `result.lease` and `result.index` and `result.gc` remain intact
170
- // for the production consumers.
110
+ // Return shape: the inner lease fields are spread at the top level so a
111
+ // test seam destructuring `const lease = await api.setPresenceLease(...)`
112
+ // gets `.workflowId` / `.status`; `result.lease` / `index` / `gc` stay intact.
171
113
  return {
172
114
  ...lease,
173
115
  lease,
@@ -216,11 +158,10 @@ export function readPresenceLease(input) {
216
158
  }
217
159
  // Graph file existence is OPTIONAL on the read path: the lease is the
218
160
  // source of truth for the lease lifecycle, and the graph store separately
219
- // validates its own corruption. Forcing a strict graph-existence check
220
- // here would break test seams that materialize leases without writing a
221
- // graph (e.g. the TC-SM-07 multi-caller fixture). The graph-backed
222
- // 24h probe and the inFlightBatch contract still consult the graph
223
- // explicitly; the read-side projection here stays a thin lookup.
161
+ // validates its own corruption. The write path creates the graph before
162
+ // the lease, but a read must not fail on a lease whose graph was not
163
+ // materialized: the graph-backed 24h probe and the inFlightBatch contract
164
+ // consult the graph explicitly, and this projection stays a thin lookup.
224
165
  const graphPath = join(sessionRuntimeRoot(input.projectRoot, sessionId), input.graphRef);
225
166
  const graphExists = existsSync(graphPath);
226
167
  void graphExists;
@@ -238,6 +179,11 @@ export function readPresenceLease(input) {
238
179
  // remains the typed `preparing|running|terminalized|lost` value; the
239
180
  // top-level spread status is the legacy projection.
240
181
  const projectedStatus = lease.status === 'preparing' ? 'running' : lease.status;
182
+ // The gate is projected so the caller can render
183
+ // `Peaks-Loop Gate: <gate>` from machine state. A lease written before
184
+ // the gate was persisted has no `gate` field — it loads, and the gate
185
+ // is simply absent.
186
+ const gate = readPresenceGate(lease.gate);
241
187
  // Spread lease fields at the top level so the test seam
242
188
  // `const other = await api.readPresenceLease(...)` yields a record with
243
189
  // `.status`, `.workflowId`, etc., matching the legacy SkillPresence
@@ -253,6 +199,7 @@ export function readPresenceLease(input) {
253
199
  callerId,
254
200
  sessionId,
255
201
  skill: lease.skill,
202
+ ...(gate !== undefined ? { gate } : {}),
256
203
  setAt: lease.startedAt,
257
204
  lastHeartbeat: lease.lastHeartbeat
258
205
  };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Canonical presence-lease paths + atomic file IO.
3
+ *
4
+ * Lives on its own because `presence-lease-service.ts` was already over the
5
+ * repository's 300-raw-line cap, and that cap is a RATCHET: a file that is
6
+ * over it may be touched, but never grown. The path helpers and the atomic
7
+ * write/read primitives moved here so the service could take the `gate`
8
+ * field without growing.
9
+ *
10
+ * Every function here is a MOVE, not a rewrite: the paths, the escape
11
+ * check, the tmp+rename write and the typed read failure are the same
12
+ * decisions the service made before, in the same place in the flow.
13
+ */
14
+ export interface PresenceError extends Error {
15
+ readonly code: string;
16
+ }
17
+ export declare function presenceError(code: string, message: string): PresenceError;
18
+ /** Resolve the session runtime root. */
19
+ export declare function sessionRuntimeRoot(projectRoot: string, sessionId: string): string;
20
+ /** Resolve the lease directory. */
21
+ export declare function leaseDir(projectRoot: string, sessionId: string): string;
22
+ /** Resolve the caller index directory. */
23
+ export declare function presenceIndexDir(projectRoot: string, sessionId: string): string;
24
+ /** Resolve the migrations directory. */
25
+ export declare function migrationsDir(projectRoot: string, sessionId: string): string;
26
+ /** Resolve the lease file path for a (callerId, workflowId) pair. */
27
+ export declare function leaseFilePath(projectRoot: string, sessionId: string, callerId: string, workflowId: string): string;
28
+ /** Caller index path. */
29
+ export declare function callerIndexPath(projectRoot: string, sessionId: string, callerId: string): string;
30
+ /** Atomic write — tmp + rename. */
31
+ export declare function writeAtomic(path: string, body: string): void;
32
+ /** Read JSON safely; throws with `code` set. */
33
+ export declare function readJsonStrict<T>(path: string, codeOnError: string): T;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Canonical presence-lease paths + atomic file IO.
3
+ *
4
+ * Lives on its own because `presence-lease-service.ts` was already over the
5
+ * repository's 300-raw-line cap, and that cap is a RATCHET: a file that is
6
+ * over it may be touched, but never grown. The path helpers and the atomic
7
+ * write/read primitives moved here so the service could take the `gate`
8
+ * field without growing.
9
+ *
10
+ * Every function here is a MOVE, not a rewrite: the paths, the escape
11
+ * check, the tmp+rename write and the typed read failure are the same
12
+ * decisions the service made before, in the same place in the flow.
13
+ */
14
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
15
+ import { dirname, join, resolve, sep } from 'node:path';
16
+ export function presenceError(code, message) {
17
+ const err = new Error(message);
18
+ err.name = 'PresenceError';
19
+ err.code = code;
20
+ return err;
21
+ }
22
+ /** Resolve the session runtime root. */
23
+ export function sessionRuntimeRoot(projectRoot, sessionId) {
24
+ const root = resolve(projectRoot);
25
+ return join(root, '.peaks', '_runtime', sessionId);
26
+ }
27
+ /** Resolve the lease directory. */
28
+ export function leaseDir(projectRoot, sessionId) {
29
+ return join(sessionRuntimeRoot(projectRoot, sessionId), 'leases');
30
+ }
31
+ /** Resolve the caller index directory. */
32
+ export function presenceIndexDir(projectRoot, sessionId) {
33
+ return join(sessionRuntimeRoot(projectRoot, sessionId), 'presence-index');
34
+ }
35
+ /** Resolve the migrations directory. */
36
+ export function migrationsDir(projectRoot, sessionId) {
37
+ return join(sessionRuntimeRoot(projectRoot, sessionId), 'migrations');
38
+ }
39
+ /** Resolve the lease file path for a (callerId, workflowId) pair. */
40
+ export function leaseFilePath(projectRoot, sessionId, callerId, workflowId) {
41
+ const safeCaller = callerId.replace(/[^a-zA-Z0-9._-]/g, '_');
42
+ const safeWorkflow = workflowId.replace(/[^a-zA-Z0-9._-]/g, '_');
43
+ const path = join(leaseDir(projectRoot, sessionId), `presence-${safeCaller}-${safeWorkflow}.json`);
44
+ const root = sessionRuntimeRoot(projectRoot, sessionId);
45
+ if (!path.startsWith(root + sep) && path !== root) {
46
+ throw presenceError('PEAKS_GRAPH_REF_BROKEN', `lease path escapes session root: ${path}`);
47
+ }
48
+ return path;
49
+ }
50
+ /** Caller index path. */
51
+ export function callerIndexPath(projectRoot, sessionId, callerId) {
52
+ const safeCaller = callerId.replace(/[^a-zA-Z0-9._-]/g, '_');
53
+ const path = join(presenceIndexDir(projectRoot, sessionId), `${safeCaller}.json`);
54
+ const root = sessionRuntimeRoot(projectRoot, sessionId);
55
+ if (!path.startsWith(root + sep) && path !== root) {
56
+ throw presenceError('PEAKS_GRAPH_REF_BROKEN', `index path escapes session root: ${path}`);
57
+ }
58
+ return path;
59
+ }
60
+ /**
61
+ * The tmp-file suffix primitives: the base-36 radix the random token is
62
+ * rendered in, and how many characters of it are kept. Named constants so
63
+ * the `no-magic-numbers` rule has nothing left to flag in the write.
64
+ */
65
+ const RANDOM_SUFFIX_RADIX = 36;
66
+ const RANDOM_SUFFIX_LENGTH = 8;
67
+ /** Atomic write — tmp + rename. */
68
+ export function writeAtomic(path, body) {
69
+ const dir = dirname(path);
70
+ if (!existsSync(dir))
71
+ mkdirSync(dir, { recursive: true });
72
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(RANDOM_SUFFIX_RADIX).slice(2, RANDOM_SUFFIX_LENGTH)}`;
73
+ writeFileSync(tmp, body, 'utf8');
74
+ renameSync(tmp, path);
75
+ }
76
+ /** Read JSON safely; throws with `code` set. */
77
+ export function readJsonStrict(path, codeOnError) {
78
+ if (!existsSync(path)) {
79
+ throw presenceError('PEAKS_LEASE_NOT_FOUND', `file not found: ${path}`);
80
+ }
81
+ let raw;
82
+ try {
83
+ raw = readFileSync(path, 'utf8');
84
+ }
85
+ catch (err) {
86
+ throw presenceError(codeOnError, `read failed: ${err.message}`);
87
+ }
88
+ try {
89
+ return JSON.parse(raw);
90
+ }
91
+ catch (err) {
92
+ throw presenceError(codeOnError, `JSON malformed: ${err.message}`);
93
+ }
94
+ }
@@ -7,12 +7,43 @@
7
7
  * lookups; no filesystem I/O.
8
8
  */
9
9
  import type { LeaseStatus, TerminalReason } from '../workflow/workflow-graph-types.js';
10
+ /**
11
+ * The lease heartbeat-stale window (1h) — the canonical lease-GC
12
+ * heartbeat predicate. Also the window the presence READ uses to decide
13
+ * that a lease is no longer driving the work.
14
+ */
15
+ export declare const STALE_HEARTBEAT_MS: number;
16
+ /**
17
+ * The lease start-stale window (24h30m) — the canonical lease-GC start
18
+ * predicate. RD §3 calls for >24h; the +30m buffer disambiguates leases
19
+ * that started in the 24-25h window so only leases older than 24h30m are
20
+ * GC'd. It is also the window a `mode: '24h'` lease is held to: a 24h
21
+ * run must not lose its presence after one hour just because nothing
22
+ * refreshes the lease heartbeat while the run is in flight.
23
+ */
24
+ export declare const STALE_STARTED_AFTER_MS: number;
10
25
  export interface SkillPresenceLease {
11
26
  readonly callerId: string;
12
27
  readonly workflowId: string;
13
28
  readonly graphRef: string;
14
29
  readonly skill: string;
15
30
  readonly parentWorkflowId?: string;
31
+ /**
32
+ * Execution mode recorded on the lease (`full-auto` | `assisted` |
33
+ * `strict` | `24h`). Optional: leases written before the mode was
34
+ * stamped carry no `mode` field.
35
+ */
36
+ readonly mode?: string;
37
+ /**
38
+ * The gate the presence is parked on (`startup`, `swarm-fan-out`, …).
39
+ *
40
+ * Optional and additive: a lease written by an older release carries
41
+ * no `gate` field and still loads. The field is what makes the middle
42
+ * cell of the status header
43
+ * (`Peaks-Loop Skill: <skill> | Peaks-Loop Gate: <gate> | Next: …`)
44
+ * a machine fact instead of model-invented prose.
45
+ */
46
+ readonly gate?: string;
16
47
  readonly depth: number;
17
48
  readonly startedAt: string;
18
49
  readonly lastHeartbeat: string;
@@ -6,6 +6,33 @@
6
6
  * `.peaks/_runtime/<sid>/presence-index/...` writes. No vendor env
7
7
  * lookups; no filesystem I/O.
8
8
  */
9
+ /**
10
+ * The time primitives the two stale windows are built from.
11
+ *
12
+ * The repo's existing lease-TTL idiom (`container-lease.ts`,
13
+ * `worktree-lease.ts`, `dispatch-record-types.ts`): the minute/hour math
14
+ * lives in named constants, so the `no-magic-numbers` rule has nothing left
15
+ * to flag in the windows themselves.
16
+ */
17
+ const MINUTES_PER_HOUR = 60;
18
+ const MS_PER_MINUTE = MINUTES_PER_HOUR * 1_000;
19
+ const HOURS_PER_DAY = 24;
20
+ const STALE_STARTED_BUFFER_MINUTES = 30;
21
+ /**
22
+ * The lease heartbeat-stale window (1h) — the canonical lease-GC
23
+ * heartbeat predicate. Also the window the presence READ uses to decide
24
+ * that a lease is no longer driving the work.
25
+ */
26
+ export const STALE_HEARTBEAT_MS = MINUTES_PER_HOUR * MS_PER_MINUTE;
27
+ /**
28
+ * The lease start-stale window (24h30m) — the canonical lease-GC start
29
+ * predicate. RD §3 calls for >24h; the +30m buffer disambiguates leases
30
+ * that started in the 24-25h window so only leases older than 24h30m are
31
+ * GC'd. It is also the window a `mode: '24h'` lease is held to: a 24h
32
+ * run must not lose its presence after one hour just because nothing
33
+ * refreshes the lease heartbeat while the run is in flight.
34
+ */
35
+ export const STALE_STARTED_AFTER_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * MS_PER_MINUTE + STALE_STARTED_BUFFER_MINUTES * MS_PER_MINUTE;
9
36
  // Re-export the 4.0.8 typed error union + projection shape from
10
37
  // caller-id-types so lease consumers can branch on the canonical code
11
38
  // without importing the session service directly. The error code
@@ -0,0 +1,35 @@
1
+ /**
2
+ * `src/services/skills/presence-role.ts`
3
+ *
4
+ * The role tier of a Peaks-Loop skill: `orchestrator` — a user-facing
5
+ * workflow that owns the gate transitions — or `bee` — a 1-level sub-role
6
+ * dispatched by an orchestrator and owning one stage.
7
+ *
8
+ * THE LIST IS THE OUTPUT-STYLE DOCUMENT'S. The response contract in
9
+ * `.claude/output-styles/peaks-skill-swarm.md` names both tiers and the
10
+ * skills in each; this module is that list in code, so the status header's
11
+ * `Role` cell is a machine fact read from the presence projection rather
12
+ * than a tier the model decides for itself.
13
+ *
14
+ * THE LIST IS COMPLETE OVER THE SHIPPED SKILLS. Every skill under `skills/`
15
+ * is in exactly one tier, so the Role cell is never empty for a shipped skill;
16
+ * one outside the shipped set yields `null`. The guard
17
+ * `tests/unit/skills/presence-role-coverage.test.ts` holds the two copies together.
18
+ *
19
+ * AN UNKNOWN SKILL HAS NO TIER. A skill in neither list yields `null`; the
20
+ * caller renders `null` rather than falling back to a tier that may be wrong.
21
+ */
22
+ /** The two tiers the Peaks-Loop skill family is built from. */
23
+ export type PresenceRoleTier = 'orchestrator' | 'bee';
24
+ /** The 1-level skills that own the gate transitions. */
25
+ export declare const ORCHESTRATOR_ROLE_SKILLS: readonly string[];
26
+ /** The 1-level sub-roles an orchestrator dispatches. */
27
+ export declare const BEE_ROLE_SKILLS: readonly string[];
28
+ /**
29
+ * The tier of `skill`, or `null` when the skill is in neither list.
30
+ *
31
+ * Never throws and never guesses: a skill the family does not name has no
32
+ * tier, and the status header renders that as "no tier" instead of inventing
33
+ * one.
34
+ */
35
+ export declare function presenceRoleTier(skill: string): PresenceRoleTier | null;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * `src/services/skills/presence-role.ts`
3
+ *
4
+ * The role tier of a Peaks-Loop skill: `orchestrator` — a user-facing
5
+ * workflow that owns the gate transitions — or `bee` — a 1-level sub-role
6
+ * dispatched by an orchestrator and owning one stage.
7
+ *
8
+ * THE LIST IS THE OUTPUT-STYLE DOCUMENT'S. The response contract in
9
+ * `.claude/output-styles/peaks-skill-swarm.md` names both tiers and the
10
+ * skills in each; this module is that list in code, so the status header's
11
+ * `Role` cell is a machine fact read from the presence projection rather
12
+ * than a tier the model decides for itself.
13
+ *
14
+ * THE LIST IS COMPLETE OVER THE SHIPPED SKILLS. Every skill under `skills/`
15
+ * is in exactly one tier, so the Role cell is never empty for a shipped skill;
16
+ * one outside the shipped set yields `null`. The guard
17
+ * `tests/unit/skills/presence-role-coverage.test.ts` holds the two copies together.
18
+ *
19
+ * AN UNKNOWN SKILL HAS NO TIER. A skill in neither list yields `null`; the
20
+ * caller renders `null` rather than falling back to a tier that may be wrong.
21
+ */
22
+ /** The 1-level skills that own the gate transitions. */
23
+ export const ORCHESTRATOR_ROLE_SKILLS = [
24
+ 'peaks-code',
25
+ 'peaks-content',
26
+ 'peaks-doctor',
27
+ 'peaks-issue-fix-orchestrator',
28
+ 'peaks-solo',
29
+ 'peaks-ide',
30
+ 'peaks-sop',
31
+ // The entry point of every peaks-* workflow: the goal is audited and
32
+ // accepted here, before any PRD or RD skill may run. Nothing dispatches it.
33
+ 'peaks-audit',
34
+ // The fast lane — a user-facing entry the user picks instead of the full workflow.
35
+ 'peaks-race-code'
36
+ ];
37
+ /** The 1-level sub-roles an orchestrator dispatches. */
38
+ export const BEE_ROLE_SKILLS = [
39
+ 'peaks-prd',
40
+ 'peaks-rd',
41
+ 'peaks-qa',
42
+ 'peaks-ui',
43
+ 'peaks-sc',
44
+ 'peaks-txt',
45
+ 'peaks-final-review',
46
+ 'peaks-resume',
47
+ 'peaks-status',
48
+ 'peaks-test',
49
+ 'peaks-reviewer',
50
+ // One stage of a larger flow: it reads what the caller produced and
51
+ // emits one artifact back to that caller.
52
+ 'peaks-slice-decompose',
53
+ // One dimension audited, decoupled from the RD fan-out: one envelope,
54
+ // written for the caller that asked for the audit.
55
+ 'peaks-perf-audit',
56
+ 'peaks-security-audit'
57
+ ];
58
+ /** The two lists as ONE lookup, so a skill's tier is decided in one place. */
59
+ const ROLE_TIERS = new Map([
60
+ ...ORCHESTRATOR_ROLE_SKILLS.map((skill) => [skill, 'orchestrator']),
61
+ ...BEE_ROLE_SKILLS.map((skill) => [skill, 'bee'])
62
+ ]);
63
+ /**
64
+ * The tier of `skill`, or `null` when the skill is in neither list.
65
+ *
66
+ * Never throws and never guesses: a skill the family does not name has no
67
+ * tier, and the status header renders that as "no tier" instead of inventing
68
+ * one.
69
+ */
70
+ export function presenceRoleTier(skill) {
71
+ return ROLE_TIERS.get(skill) ?? null;
72
+ }