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,116 @@
1
+ /**
2
+ * The per-rid "changed paths" claim table.
3
+ *
4
+ * A request artifact declares the paths its own slice touched, in a
5
+ * machine-readable section:
6
+ *
7
+ * ```markdown
8
+ * ## Changed paths
9
+ * changedPath: src/services/skills/presence-role.ts
10
+ * ```
11
+ *
12
+ * The format is line-based `key: value` because `prd/handoff-*.md` already uses
13
+ * that shape for its own markers (`schemaVersion: 2`, `sha256:`); a
14
+ * comma-separated list would break on a comma inside a file name.
15
+ *
16
+ * TWO STATES, NOT ONE. An artifact that carries the `## Changed paths` heading
17
+ * HAS declared — an empty list is a declaration ("this slice touched nothing").
18
+ * An artifact WITHOUT it has not, and the caller falls back to the whole
19
+ * working tree, which is STRICTER, not looser. The heading is the switch.
20
+ * The rid is read with the repository's own naming rule
21
+ * (`requestIdFromFileName`), so the writer and this reader cannot drift apart.
22
+ */
23
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
24
+ import { join } from 'node:path';
25
+ import { requestIdFromFileName } from '../../shared/incrementing-number.js';
26
+ import { isUnsafePathInput } from '../../shared/path-safety.js';
27
+ import { guardRuntimeSegment, runtimeRoot } from '../../shared/runtime-root.js';
28
+ /** The heading that marks an artifact as HAVING a declaration. */
29
+ const CHANGED_PATHS_HEADING_RE = /^#{1,6}\s+changed\s+paths\s*$/i;
30
+ /** One declared path per line: `changedPath: <path>`, at the start of the line. */
31
+ const CHANGED_PATH_LINE_RE = /^changedPath:\s*(\S.*?)\s*$/;
32
+ /** True when the artifact carries the `## Changed paths` heading. */
33
+ export function hasChangedPathsSection(body) {
34
+ return body.split(/\r?\n/).some((line) => CHANGED_PATHS_HEADING_RE.test(line.trim()));
35
+ }
36
+ /** Every `changedPath:` line of the body, in the order they were written. */
37
+ export function parseChangedPathLines(body) {
38
+ const paths = [];
39
+ for (const line of body.split(/\r?\n/)) {
40
+ const declared = CHANGED_PATH_LINE_RE.exec(line)?.[1];
41
+ if (declared !== undefined)
42
+ paths.push(declared);
43
+ }
44
+ return paths;
45
+ }
46
+ /** The session's RD request-artifact directory, or null when the id is unusable. */
47
+ function rdRequestsDir(projectRoot, sessionId) {
48
+ const session = guardedSegmentOrNull(sessionId, 'session id');
49
+ if (session === null)
50
+ return null;
51
+ return runtimeRoot(projectRoot).join(session, guardRuntimeSegment('rd', 'role'), guardRuntimeSegment('requests', 'leaf'));
52
+ }
53
+ /**
54
+ * The id as a guarded segment, or `null` when it is not one: the guard THROWS
55
+ * on an unusable id, so the predicate it applies (`isUnsafePathInput`) is asked
56
+ * first and "unusable" is a VALUE here instead of an exception.
57
+ */
58
+ function guardedSegmentOrNull(value, label) {
59
+ return isUnsafePathInput(value) ? null : guardRuntimeSegment(value, label);
60
+ }
61
+ /** The artifact file names in that directory; an unreadable directory throws. */
62
+ function rdArtifactFileNames(dir) {
63
+ if (!existsSync(dir))
64
+ return [];
65
+ try {
66
+ return readdirSync(dir).filter((name) => requestIdFromFileName(name) !== null);
67
+ }
68
+ catch (error) {
69
+ throw new Error(`cannot read the RD artifact directory ${dir}: ${String(error)}`);
70
+ }
71
+ }
72
+ /** Every rid that HAS an RD artifact in the session — declared or not. The
73
+ * caller compares this list against the claim table to learn whether the table
74
+ * is COMPLETE, which is what decides whether the anti-lie fallback may run.
75
+ */
76
+ export function listSessionRdArtifactIds(projectRoot, sessionId) {
77
+ const dir = rdRequestsDir(projectRoot, sessionId);
78
+ if (dir === null)
79
+ return [];
80
+ const ids = [];
81
+ for (const name of rdArtifactFileNames(dir)) {
82
+ const rid = requestIdFromFileName(name);
83
+ if (rid !== null && rid.length > 0)
84
+ ids.push(rid);
85
+ }
86
+ return ids;
87
+ }
88
+ /**
89
+ * rid -> the paths it declared. ONLY artifacts carrying the `## Changed paths`
90
+ * heading are in the table; a rid without it is NOT, and the caller reads that
91
+ * absence as "this rid declared nothing" and falls back to the whole tree.
92
+ */
93
+ export function readRidChangeClaims(projectRoot, sessionId) {
94
+ const dir = rdRequestsDir(projectRoot, sessionId);
95
+ const claims = new Map();
96
+ if (dir === null)
97
+ return claims;
98
+ for (const name of rdArtifactFileNames(dir)) {
99
+ const rid = requestIdFromFileName(name);
100
+ if (rid === null || rid.length === 0 || claims.has(rid))
101
+ continue;
102
+ let body;
103
+ try {
104
+ body = readFileSync(join(dir, name), 'utf8');
105
+ }
106
+ catch {
107
+ // An unreadable artifact cannot prove a declaration: leave the rid out of
108
+ // the table, which makes the table incomplete and the fallback stand down.
109
+ continue;
110
+ }
111
+ if (!hasChangedPathsSection(body))
112
+ continue;
113
+ claims.set(rid, parseChangedPathLines(body));
114
+ }
115
+ return claims;
116
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The presence write side's caller-id gate.
3
+ *
4
+ * Outside Claude Code the IDE adapter cannot resolve a callerId, so
5
+ * `presence:set` was fail-closed with no way out and the lease could never be
6
+ * built. This module adds the vendor-neutral escape hatch the rest of the
7
+ * CLI already has (`peaks request init`): an explicit `--caller-id` flag and
8
+ * the `PEAKS_CALLER_ID` environment variable, both short-circuiting BEFORE
9
+ * the adapter.
10
+ *
11
+ * The priority chain lives in `resolve-caller-id.ts` and is NOT restated
12
+ * here: flag > `PEAKS_CALLER_ID` env > active IDE adapter. This module only
13
+ * turns the resolver's typed failures into a discriminated result the CLI
14
+ * can render without knowing the resolver's error taxonomy.
15
+ *
16
+ * Pure: no filesystem access, no state. The caller decides what to do with
17
+ * the resolved id.
18
+ */
19
+ import { type CallerProjectionSource } from '../session/resolve-caller-id.js';
20
+ export type PresenceCallerIdResult = {
21
+ readonly ok: true;
22
+ readonly callerId: string;
23
+ readonly source: CallerProjectionSource;
24
+ } | {
25
+ readonly ok: false;
26
+ /**
27
+ * `CALLER_ID_INVALID` — a value WAS supplied but it does not match
28
+ * the D1 regex (`^[a-zA-Z0-9._-]{1,200}$`).
29
+ * `PEAKS_CALLER_NOT_RESOLVED` — nothing could be resolved at all.
30
+ */
31
+ readonly code: 'CALLER_ID_INVALID' | 'PEAKS_CALLER_NOT_RESOLVED';
32
+ readonly message: string;
33
+ };
34
+ export interface ResolvePresenceCallerIdOptions {
35
+ /** The project root the caller id is resolved against. */
36
+ readonly projectRoot: string;
37
+ /**
38
+ * The `--caller-id <id>` flag value. Priority level 1 — it wins over the
39
+ * env var and short-circuits the adapter, so a host that is not Claude
40
+ * Code can still build a lease.
41
+ */
42
+ readonly flagValue?: string | undefined;
43
+ }
44
+ /**
45
+ * Resolve the caller id for a presence write.
46
+ *
47
+ * Never throws: a shape mismatch (`CALLER_ID_INVALID`) and an unresolvable
48
+ * caller (`PEAKS_CALLER_NOT_RESOLVED`) both come back as a refusal so the
49
+ * CLI can print one readable envelope for each.
50
+ */
51
+ export declare function resolvePresenceCallerId(opts: ResolvePresenceCallerIdOptions): PresenceCallerIdResult;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The presence write side's caller-id gate.
3
+ *
4
+ * Outside Claude Code the IDE adapter cannot resolve a callerId, so
5
+ * `presence:set` was fail-closed with no way out and the lease could never be
6
+ * built. This module adds the vendor-neutral escape hatch the rest of the
7
+ * CLI already has (`peaks request init`): an explicit `--caller-id` flag and
8
+ * the `PEAKS_CALLER_ID` environment variable, both short-circuiting BEFORE
9
+ * the adapter.
10
+ *
11
+ * The priority chain lives in `resolve-caller-id.ts` and is NOT restated
12
+ * here: flag > `PEAKS_CALLER_ID` env > active IDE adapter. This module only
13
+ * turns the resolver's typed failures into a discriminated result the CLI
14
+ * can render without knowing the resolver's error taxonomy.
15
+ *
16
+ * Pure: no filesystem access, no state. The caller decides what to do with
17
+ * the resolved id.
18
+ */
19
+ import { CallerIdError, resolveCallerProjection } from '../session/resolve-caller-id.js';
20
+ /**
21
+ * Resolve the caller id for a presence write.
22
+ *
23
+ * Never throws: a shape mismatch (`CALLER_ID_INVALID`) and an unresolvable
24
+ * caller (`PEAKS_CALLER_NOT_RESOLVED`) both come back as a refusal so the
25
+ * CLI can print one readable envelope for each.
26
+ */
27
+ export function resolvePresenceCallerId(opts) {
28
+ try {
29
+ const projection = resolveCallerProjection({
30
+ projectRoot: opts.projectRoot,
31
+ ...(opts.flagValue !== undefined ? { flagValue: opts.flagValue } : {})
32
+ });
33
+ return { ok: true, callerId: projection.callerId, source: projection.source };
34
+ }
35
+ catch (err) {
36
+ const invalid = err instanceof CallerIdError && err.code === 'EX_DATAERR';
37
+ return {
38
+ ok: false,
39
+ code: invalid ? 'CALLER_ID_INVALID' : 'PEAKS_CALLER_NOT_RESOLVED',
40
+ message: err instanceof Error ? err.message : String(err)
41
+ };
42
+ }
43
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The `gate` field of a presence lease — write-side contract.
3
+ *
4
+ * WHAT THE GATE IS. The status header the LLM is told to display —
5
+ * `Peaks-Loop Skill: <skill> | Peaks-Loop Gate: <gate> | Next: <action>` —
6
+ * has three cells. The middle one was, until this slice, MODEL-INVENTED
7
+ * prose: `SetPresenceLeaseInput.gate` existed, but the lease constructor
8
+ * never expanded it, so the lease carried no gate and the read side had
9
+ * nothing to project. The gate is now persisted and projected, so the
10
+ * middle cell is a machine fact.
11
+ *
12
+ * ENUM OR FREE STRING? Free string with a shape check. The gate values
13
+ * this repository actually uses are enumerated in `KNOWN_PRESENCE_GATES`
14
+ * below, but they are NOT an allow-list:
15
+ *
16
+ * - `repair-cycle-<N>` is a TEMPLATE — the runtime value carries a
17
+ * counter (`repair-cycle-1`), so it cannot be closed over a static
18
+ * enumeration.
19
+ * - `peaks sop check --gate <gate-id>` addresses a gate id defined at
20
+ * runtime by an SOP, so SOP-scoped gates are not knowable at build
21
+ * time either.
22
+ * - third-party skills are free to pass their own gate token.
23
+ *
24
+ * A closed enumeration would reject those, and the CLI already accepts any
25
+ * `--gate <value>` string today; rejecting unknown values would break
26
+ * working callers for no gain. What IS rejected is a malformed value: a
27
+ * control character (it lands verbatim in the status header) or a value
28
+ * longer than `MAX_PRESENCE_GATE_LENGTH`. An empty / whitespace-only value
29
+ * is DROPPED, not rejected — that is the pre-existing behaviour of the
30
+ * `...(gate ? { gate } : {})` spread and it is kept.
31
+ */
32
+ /** Error code for a gate value that cannot be persisted. */
33
+ export declare const PEAKS_GATE_INVALID = "PEAKS_GATE_INVALID";
34
+ /** Longest gate value that may be persisted. */
35
+ export declare const MAX_PRESENCE_GATE_LENGTH = 200;
36
+ /** A presence error carrying a typed `code`. */
37
+ export type PresenceGateError = Error & {
38
+ readonly code: string;
39
+ };
40
+ /**
41
+ * The gate vocabulary this repository uses today (enumerated 2026-10-24
42
+ * from `skills/**` and `src/**`).
43
+ *
44
+ * NOT an allow-list — see the module header. The list exists so the
45
+ * regression test can assert that every gate value the repository uses is
46
+ * accepted by `normalizePresenceGate`, and so a reader can see the
47
+ * vocabulary without grepping.
48
+ */
49
+ export declare const KNOWN_PRESENCE_GATES: readonly string[];
50
+ /**
51
+ * Normalize a gate value for persistence.
52
+ *
53
+ * Returns `undefined` when there is no gate to persist (absent, or empty
54
+ * after trimming). Throws a `PEAKS_GATE_INVALID` error for a value that
55
+ * must not be written (control characters, over-length).
56
+ */
57
+ export declare function normalizePresenceGate(value: string | undefined | null): string | undefined;
58
+ /**
59
+ * Project a gate value that was READ back from disk.
60
+ *
61
+ * Tolerant by design: a hand-edited lease file, or a lease written by an
62
+ * older release, must never make the read throw. Anything that is not a
63
+ * non-empty string is reported as "no gate".
64
+ */
65
+ export declare function readPresenceGate(value: unknown): string | undefined;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The `gate` field of a presence lease — write-side contract.
3
+ *
4
+ * WHAT THE GATE IS. The status header the LLM is told to display —
5
+ * `Peaks-Loop Skill: <skill> | Peaks-Loop Gate: <gate> | Next: <action>` —
6
+ * has three cells. The middle one was, until this slice, MODEL-INVENTED
7
+ * prose: `SetPresenceLeaseInput.gate` existed, but the lease constructor
8
+ * never expanded it, so the lease carried no gate and the read side had
9
+ * nothing to project. The gate is now persisted and projected, so the
10
+ * middle cell is a machine fact.
11
+ *
12
+ * ENUM OR FREE STRING? Free string with a shape check. The gate values
13
+ * this repository actually uses are enumerated in `KNOWN_PRESENCE_GATES`
14
+ * below, but they are NOT an allow-list:
15
+ *
16
+ * - `repair-cycle-<N>` is a TEMPLATE — the runtime value carries a
17
+ * counter (`repair-cycle-1`), so it cannot be closed over a static
18
+ * enumeration.
19
+ * - `peaks sop check --gate <gate-id>` addresses a gate id defined at
20
+ * runtime by an SOP, so SOP-scoped gates are not knowable at build
21
+ * time either.
22
+ * - third-party skills are free to pass their own gate token.
23
+ *
24
+ * A closed enumeration would reject those, and the CLI already accepts any
25
+ * `--gate <value>` string today; rejecting unknown values would break
26
+ * working callers for no gain. What IS rejected is a malformed value: a
27
+ * control character (it lands verbatim in the status header) or a value
28
+ * longer than `MAX_PRESENCE_GATE_LENGTH`. An empty / whitespace-only value
29
+ * is DROPPED, not rejected — that is the pre-existing behaviour of the
30
+ * `...(gate ? { gate } : {})` spread and it is kept.
31
+ */
32
+ /** Error code for a gate value that cannot be persisted. */
33
+ export const PEAKS_GATE_INVALID = 'PEAKS_GATE_INVALID';
34
+ /** Longest gate value that may be persisted. */
35
+ export const MAX_PRESENCE_GATE_LENGTH = 200;
36
+ /**
37
+ * The gate vocabulary this repository uses today (enumerated 2026-10-24
38
+ * from `skills/**` and `src/**`).
39
+ *
40
+ * NOT an allow-list — see the module header. The list exists so the
41
+ * regression test can assert that every gate value the repository uses is
42
+ * accepted by `normalizePresenceGate`, and so a reader can see the
43
+ * vocabulary without grepping.
44
+ */
45
+ export const KNOWN_PRESENCE_GATES = [
46
+ 'startup',
47
+ 'qa-validation',
48
+ 'swarm-fan-out',
49
+ 'swarm-converged',
50
+ 'repair-cycle-<N>',
51
+ 'review-fan-out-converged'
52
+ ];
53
+ function gateError(message) {
54
+ const err = new Error(message);
55
+ err.name = 'PresenceError';
56
+ err.code = PEAKS_GATE_INVALID;
57
+ return err;
58
+ }
59
+ /**
60
+ * The control-character boundaries `hasControlCharacter` tests against.
61
+ *
62
+ * C0 controls occupy code points 0x00-0x1F; DEL (0x7F) is the one control
63
+ * character above them. Named constants so the `no-magic-numbers` rule has
64
+ * nothing left to flag in the comparison.
65
+ */
66
+ const C0_CONTROL_MAX = 0x20;
67
+ const DEL_CONTROL_CODE = 0x7f;
68
+ /** True when the value carries a C0 / DEL control character. */
69
+ function hasControlCharacter(value) {
70
+ for (const ch of value) {
71
+ const code = ch.codePointAt(0) ?? 0;
72
+ if (code < C0_CONTROL_MAX || code === DEL_CONTROL_CODE)
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+ /**
78
+ * Normalize a gate value for persistence.
79
+ *
80
+ * Returns `undefined` when there is no gate to persist (absent, or empty
81
+ * after trimming). Throws a `PEAKS_GATE_INVALID` error for a value that
82
+ * must not be written (control characters, over-length).
83
+ */
84
+ export function normalizePresenceGate(value) {
85
+ if (value === undefined || value === null)
86
+ return undefined;
87
+ if (typeof value !== 'string') {
88
+ throw gateError('gate must be a string');
89
+ }
90
+ const trimmed = value.trim();
91
+ if (trimmed.length === 0)
92
+ return undefined;
93
+ if (trimmed.length > MAX_PRESENCE_GATE_LENGTH) {
94
+ throw gateError(`gate is ${trimmed.length} characters long (max ${MAX_PRESENCE_GATE_LENGTH})`);
95
+ }
96
+ if (hasControlCharacter(trimmed)) {
97
+ throw gateError('gate must not contain control characters');
98
+ }
99
+ return trimmed;
100
+ }
101
+ /**
102
+ * Project a gate value that was READ back from disk.
103
+ *
104
+ * Tolerant by design: a hand-edited lease file, or a lease written by an
105
+ * older release, must never make the read throw. Anything that is not a
106
+ * non-empty string is reported as "no gate".
107
+ */
108
+ export function readPresenceGate(value) {
109
+ if (typeof value !== 'string')
110
+ return undefined;
111
+ const trimmed = value.trim();
112
+ return trimmed.length === 0 ? undefined : trimmed;
113
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The cross-session presence read.
3
+ *
4
+ * WHAT IT SOLVES. The canonical presence read used to look at ONE session
5
+ * 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
7
+ * landed in a different tree was therefore invisible: `peaks skill
8
+ * presence --json` reported `{"active": false}` while a live lease sat on
9
+ * disk. The caller-id resolution failing (an IDE adapter that claims a
10
+ * harness the host runtime is not) made that the NORMAL case, not the
11
+ * corner case.
12
+ *
13
+ * WHAT IT DOES. It enumerates every session tree of the project, marks
14
+ * the bound tree against the others, and hands the candidate set to the
15
+ * pure selection rules in `presence-lease-selection.ts`.
16
+ *
17
+ * WHY IT IS ITS OWN MODULE. `skill-presence-service.ts` was already over
18
+ * the repository's 300-raw-line cap, and that cap is a ratchet: a file
19
+ * over it may be touched, but never grown. The read half moved here.
20
+ */
21
+ import { type PresenceInactiveDiagnostic, type PresenceLeaseCandidate, type PresenceLeaseSelection } from './presence-lease-selection.js';
22
+ /**
23
+ * The project root the presence read runs against: the caller's override
24
+ * when it gave one, otherwise the project the cwd belongs to.
25
+ */
26
+ export declare function resolveProjectRoot(override?: string): string;
27
+ /**
28
+ * The session tree this caller is bound to, or `null` when nothing is
29
+ * bound. Never throws: an unresolvable caller id must not blind the
30
+ * presence read.
31
+ */
32
+ export declare function resolveBoundSessionId(projectRoot: string): string | null;
33
+ /**
34
+ * Every presence lease of the project, from every session tree.
35
+ *
36
+ * The session trees are enumerated from the RUNTIME ROOT, not through
37
+ * `listSessions`: that helper only recognises the dated-hex session id
38
+ * shape (`2026-10-23-session-5e40e0`), so a tree whose id has any other
39
+ * shape would be invisible to the presence read. What actually matters
40
+ * here is "a directory under `.peaks/_runtime/` that holds a `leases/`
41
+ * directory" — the directories without one (`callers`, `change`,
42
+ * `_audit`) contribute nothing.
43
+ *
44
+ * The `scope` marks the tree the caller is bound to (`bound`) against
45
+ * every other tree (`other`) — the bound tree keeps its precedence when
46
+ * it holds an eligible lease.
47
+ */
48
+ export declare function collectPresenceLeaseCandidates(projectRoot: string, boundSessionId: string | null): PresenceLeaseCandidate[];
49
+ /**
50
+ * The lease that represents "who is driving peaks right now", across
51
+ * EVERY session tree of the project.
52
+ *
53
+ * The bound tree keeps its precedence: when it holds an eligible lease,
54
+ * only its own leases are considered. When it holds none — the caller id
55
+ * could not be resolved, the binding points at a tree without leases,
56
+ * the session rotated — the other trees' leases are considered instead.
57
+ */
58
+ export declare function resolvePresenceLease(projectRoot: string): PresenceLeaseSelection | null;
59
+ /**
60
+ * Why the read found nothing active — the diagnostic behind
61
+ * `peaks skill presence --json --check-stale` on the inactive path.
62
+ */
63
+ export declare function diagnosePresence(projectRoot: string): PresenceInactiveDiagnostic;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The cross-session presence read.
3
+ *
4
+ * WHAT IT SOLVES. The canonical presence read used to look at ONE session
5
+ * 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
7
+ * landed in a different tree was therefore invisible: `peaks skill
8
+ * presence --json` reported `{"active": false}` while a live lease sat on
9
+ * disk. The caller-id resolution failing (an IDE adapter that claims a
10
+ * harness the host runtime is not) made that the NORMAL case, not the
11
+ * corner case.
12
+ *
13
+ * WHAT IT DOES. It enumerates every session tree of the project, marks
14
+ * the bound tree against the others, and hands the candidate set to the
15
+ * pure selection rules in `presence-lease-selection.ts`.
16
+ *
17
+ * WHY IT IS ITS OWN MODULE. `skill-presence-service.ts` was already over
18
+ * the repository's 300-raw-line cap, and that cap is a ratchet: a file
19
+ * over it may be touched, but never grown. The read half moved here.
20
+ */
21
+ import { readdirSync } from 'node:fs';
22
+ import { join, resolve } from 'node:path';
23
+ import { findProjectRoot } from '../config/config-safety.js';
24
+ import { getSessionId } from '../session/session-manager.js';
25
+ import { listPresenceLeases } from './presence-lease-service.js';
26
+ import { explainInactivePresence, selectActivePresenceLease } from './presence-lease-selection.js';
27
+ /**
28
+ * The project root the presence read runs against: the caller's override
29
+ * when it gave one, otherwise the project the cwd belongs to.
30
+ */
31
+ export function resolveProjectRoot(override) {
32
+ if (override)
33
+ return resolve(override);
34
+ return findProjectRoot(process.cwd()) ?? process.cwd();
35
+ }
36
+ /**
37
+ * The session tree this caller is bound to, or `null` when nothing is
38
+ * bound. Never throws: an unresolvable caller id must not blind the
39
+ * presence read.
40
+ */
41
+ export function resolveBoundSessionId(projectRoot) {
42
+ let sessionId = null;
43
+ try {
44
+ sessionId = getSessionId(projectRoot);
45
+ }
46
+ catch {
47
+ // The caller id could not be resolved. That must NOT blind the
48
+ // presence read: the cross-session fallback works without a bound
49
+ // tree, so the read continues with no bound tree.
50
+ sessionId = null;
51
+ }
52
+ return sessionId;
53
+ }
54
+ /**
55
+ * Every presence lease of the project, from every session tree.
56
+ *
57
+ * The session trees are enumerated from the RUNTIME ROOT, not through
58
+ * `listSessions`: that helper only recognises the dated-hex session id
59
+ * shape (`2026-10-23-session-5e40e0`), so a tree whose id has any other
60
+ * shape would be invisible to the presence read. What actually matters
61
+ * here is "a directory under `.peaks/_runtime/` that holds a `leases/`
62
+ * directory" — the directories without one (`callers`, `change`,
63
+ * `_audit`) contribute nothing.
64
+ *
65
+ * The `scope` marks the tree the caller is bound to (`bound`) against
66
+ * every other tree (`other`) — the bound tree keeps its precedence when
67
+ * it holds an eligible lease.
68
+ */
69
+ export function collectPresenceLeaseCandidates(projectRoot, boundSessionId) {
70
+ const candidates = [];
71
+ const runtimeRoot = join(projectRoot, '.peaks', '_runtime');
72
+ let entries = [];
73
+ try {
74
+ entries = readdirSync(runtimeRoot, { withFileTypes: true })
75
+ .filter((entry) => entry.isDirectory())
76
+ .map((entry) => entry.name);
77
+ }
78
+ catch {
79
+ // A project with no runtime root has no session trees, and one that
80
+ // cannot be read has none this read can see. Either way the honest
81
+ // answer is "no leases", not an exception.
82
+ entries = [];
83
+ }
84
+ for (const sessionId of entries) {
85
+ const scope = sessionId === boundSessionId ? 'bound' : 'other';
86
+ for (const lease of listPresenceLeases(projectRoot, sessionId)) {
87
+ candidates.push({ lease, sessionId, scope });
88
+ }
89
+ }
90
+ return candidates;
91
+ }
92
+ /**
93
+ * The lease that represents "who is driving peaks right now", across
94
+ * EVERY session tree of the project.
95
+ *
96
+ * The bound tree keeps its precedence: when it holds an eligible lease,
97
+ * only its own leases are considered. When it holds none — the caller id
98
+ * could not be resolved, the binding points at a tree without leases,
99
+ * the session rotated — the other trees' leases are considered instead.
100
+ */
101
+ export function resolvePresenceLease(projectRoot) {
102
+ const boundSessionId = resolveBoundSessionId(projectRoot);
103
+ const candidates = collectPresenceLeaseCandidates(projectRoot, boundSessionId);
104
+ return selectActivePresenceLease(candidates, Date.now());
105
+ }
106
+ /**
107
+ * Why the read found nothing active — the diagnostic behind
108
+ * `peaks skill presence --json --check-stale` on the inactive path.
109
+ */
110
+ export function diagnosePresence(projectRoot) {
111
+ const boundSessionId = resolveBoundSessionId(projectRoot);
112
+ const candidates = collectPresenceLeaseCandidates(projectRoot, boundSessionId);
113
+ return explainInactivePresence(candidates, Date.now());
114
+ }
@@ -0,0 +1,91 @@
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 { type SkillPresenceLease } from './presence-lease-types.js';
37
+ /** Which tree a candidate lease was read from. */
38
+ export type PresenceLeaseScope = 'bound' | 'other';
39
+ export type PresenceLeaseCandidate = {
40
+ readonly lease: SkillPresenceLease;
41
+ /** The session tree the lease was read from. */
42
+ readonly sessionId: string;
43
+ readonly scope: PresenceLeaseScope;
44
+ };
45
+ export type PresenceLeaseSelection = {
46
+ readonly lease: SkillPresenceLease;
47
+ readonly sessionId: string;
48
+ readonly scope: PresenceLeaseScope;
49
+ };
50
+ /** Why the read found no active lease. */
51
+ export type PresenceInactiveReason = 'no-leases' | 'all-terminal' | 'all-stale' | 'terminal-and-stale'
52
+ /** Defensive: the caller passed a candidate set that DOES hold an eligible lease. */
53
+ | 'eligible-present';
54
+ export type PresenceInactiveDiagnostic = {
55
+ readonly reason: PresenceInactiveReason;
56
+ readonly leaseCount: number;
57
+ readonly terminalCount: number;
58
+ readonly staleCount: number;
59
+ readonly eligibleCount: number;
60
+ };
61
+ /**
62
+ * The stale window that applies to THIS lease.
63
+ *
64
+ * `24h` leases get the 24h run's own window (`STALE_STARTED_AFTER_MS`,
65
+ * 24h30m — the canonical lease-GC start predicate); every other lease
66
+ * gets the canonical heartbeat window (`STALE_HEARTBEAT_MS`, 1h). A 24h
67
+ * run must not lose its presence after one hour just because nothing
68
+ * refreshes the lease heartbeat while the run is in flight.
69
+ */
70
+ export declare function staleThresholdMs(lease: SkillPresenceLease): number;
71
+ /** A lease that reached its end state — never reported as active. */
72
+ export declare function isTerminalPresenceLease(lease: SkillPresenceLease): boolean;
73
+ /** A lease whose heartbeat is older than its window — never reported as active. */
74
+ export declare function isStalePresenceLease(lease: SkillPresenceLease, nowMs: number): boolean;
75
+ /** A lease that may be reported as the active presence. */
76
+ export declare function isEligiblePresenceLease(lease: SkillPresenceLease, nowMs: number): boolean;
77
+ /**
78
+ * Pick the lease that represents "who is driving peaks right now".
79
+ *
80
+ * Returns `null` when no candidate is eligible — the caller answers
81
+ * "inactive" (never an optimistic default).
82
+ */
83
+ export declare function selectActivePresenceLease(candidates: readonly PresenceLeaseCandidate[], nowMs: number): PresenceLeaseSelection | null;
84
+ /**
85
+ * Explain why the read found nothing active.
86
+ *
87
+ * Precondition: called only when `selectActivePresenceLease` returned
88
+ * `null` (so `eligibleCount` is 0). The `eligible-present` reason is a
89
+ * defensive branch for a caller that violates that precondition.
90
+ */
91
+ export declare function explainInactivePresence(candidates: readonly PresenceLeaseCandidate[], nowMs: number): PresenceInactiveDiagnostic;