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
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Check: the canonical skill store against the installed package
3
+ * (`skills:store-version:store`).
4
+ *
5
+ * THE HOLE THIS CLOSES. `skill-reference-parity` compares the canonical store
6
+ * against the IDE trees — and on a normal install the IDE entry is a LINK INTO
7
+ * the store, so the two sides are the SAME tree and the comparison is always in
8
+ * parity. A store frozen at an old release is perfectly self-consistent, and
9
+ * therefore invisible to that check. The comparison this one makes is the other
10
+ * axis: STORE against PACKAGE. The store's sidecar records the version that
11
+ * produced each copy; the package's `package.json#version` is the version that
12
+ * SHOULD have produced it. A gap between them is staleness nothing else can see.
13
+ *
14
+ * THE PATTERN. It is the `dist-source-version` shape applied to the store: a
15
+ * missing input is INFORMATIONAL, never a red — a machine with no store at all
16
+ * has nothing stale, and saying so is not a finding. A store that cannot be
17
+ * read is a different case: it looks exactly like "no drift", so it is
18
+ * reported.
19
+ *
20
+ * IT ALWAYS EMITS A ROW. A check that stays silent when it finds nothing
21
+ * cannot be told apart from a check that never ran; this one says "clean" out
22
+ * loud, with the version it compared against.
23
+ *
24
+ * READ-ONLY. It lists the store and reads sidecars. It never writes, repairs
25
+ * or deletes; the remedy it names (`peaks skill sync`) is the repair.
26
+ */
27
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
28
+ import { join } from 'node:path';
29
+ import { CLI_VERSION } from 'peaks-loop-shared/version';
30
+ import { z } from 'zod';
31
+ import { isExpectedFsMiss } from '../../../../shared/fs-utils.js';
32
+ import { tryParseJson } from '../../../../shared/json-parse.js';
33
+ import { compareReleaseVersions } from '../../../artifacts/prerequisite-checks.js';
34
+ import { peaksHome } from '../../../sop/sop-paths.js';
35
+ /** The sidecar shape the store writes. A marker in any other shape is legacy. */
36
+ const markerSchema = z.object({
37
+ format: z.literal('peaks-managed-v2'),
38
+ path: z.string().optional(),
39
+ version: z.string().optional()
40
+ });
41
+ /** The version a sidecar records, or null when it records none. */
42
+ export function readMarkerVersion(markerPath) {
43
+ let content;
44
+ try {
45
+ content = readFileSync(markerPath, 'utf8');
46
+ }
47
+ catch (err) {
48
+ // A sidecar that raced away is "no version"; anything else is a real fault
49
+ // and is not swallowed here.
50
+ if (!isExpectedFsMiss(err))
51
+ throw err;
52
+ return null;
53
+ }
54
+ const parsed = tryParseJson(content, markerSchema);
55
+ if (!parsed.ok)
56
+ return null;
57
+ const version = parsed.value.version;
58
+ return typeof version === 'string' && version.length > 0 ? version : null;
59
+ }
60
+ /**
61
+ * Is the recorded version behind the installed one? An UNKNOWN version is
62
+ * behind: a copy that cannot say how old it is cannot be shown to be current,
63
+ * and the installed package is the authority on what should be there.
64
+ */
65
+ function isBehind(recorded, installed) {
66
+ return compareReleaseVersions(recorded ?? '0.0.0', installed) < 0;
67
+ }
68
+ /**
69
+ * The managed entries of one canonical skills store, and the ones behind.
70
+ *
71
+ * `storeRoot` is the canonical SKILLS directory (`<PEAKS_HOME or ~/.peaks>/skills`).
72
+ * An entry the user authored carries no sidecar and is not ours, so it is not
73
+ * counted and never reported.
74
+ */
75
+ export function inspectCanonicalStoreVersions(storeRoot, installedVersion) {
76
+ if (!existsSync(storeRoot)) {
77
+ return {
78
+ storeRoot,
79
+ storePresent: false,
80
+ readable: true,
81
+ managed: 0,
82
+ entries: [],
83
+ stale: [],
84
+ installedVersion
85
+ };
86
+ }
87
+ let names;
88
+ try {
89
+ names = readdirSync(storeRoot).sort();
90
+ }
91
+ catch (err) {
92
+ // A store root that exists but cannot be listed is not "no drift" — it is
93
+ // a store nobody can check, and it is reported rather than passed over.
94
+ if (!isExpectedFsMiss(err))
95
+ throw err;
96
+ return {
97
+ storeRoot,
98
+ storePresent: true,
99
+ readable: false,
100
+ managed: 0,
101
+ entries: [],
102
+ stale: [],
103
+ installedVersion
104
+ };
105
+ }
106
+ const entries = [];
107
+ for (const name of names) {
108
+ if (name.endsWith('.peaks-managed') || name.startsWith('.peaks-tmp-'))
109
+ continue;
110
+ const markerPath = join(storeRoot, `${name}.peaks-managed`);
111
+ if (!existsSync(markerPath))
112
+ continue;
113
+ entries.push({ name, version: readMarkerVersion(markerPath) });
114
+ }
115
+ const stale = entries.filter((entry) => isBehind(entry.version, installedVersion));
116
+ return {
117
+ storeRoot,
118
+ storePresent: true,
119
+ readable: true,
120
+ managed: entries.length,
121
+ entries,
122
+ stale,
123
+ installedVersion
124
+ };
125
+ }
126
+ /** The canonical skills store, exactly where the store writes it. */
127
+ function canonicalSkillsStore() {
128
+ return join(peaksHome(), 'skills');
129
+ }
130
+ /** How an entry's recorded version reads in a message. */
131
+ function describeEntry(entry) {
132
+ return entry.version === null
133
+ ? `${entry.name} (no version recorded)`
134
+ : `${entry.name} (${entry.version})`;
135
+ }
136
+ function toCheck(inspection) {
137
+ const id = 'skills:store-version:store';
138
+ if (!inspection.storePresent) {
139
+ return {
140
+ id,
141
+ ok: true,
142
+ message: `No canonical skill store at ${inspection.storeRoot}; nothing to compare ` +
143
+ '(run `peaks skill sync` to create one)'
144
+ };
145
+ }
146
+ if (!inspection.readable) {
147
+ return {
148
+ id,
149
+ ok: false,
150
+ severity: 'warning',
151
+ message: `The canonical skill store at ${inspection.storeRoot} cannot be read; ` +
152
+ 'it was not compared with the installed package'
153
+ };
154
+ }
155
+ if (inspection.managed === 0) {
156
+ return {
157
+ id,
158
+ ok: true,
159
+ message: `The canonical skill store at ${inspection.storeRoot} holds no peaks-managed entries; ` +
160
+ 'nothing to compare'
161
+ };
162
+ }
163
+ if (inspection.stale.length === 0) {
164
+ return {
165
+ id,
166
+ ok: true,
167
+ message: `The canonical skill store at ${inspection.storeRoot} is current for all ` +
168
+ `${inspection.managed} managed entries against peaks-loop ${inspection.installedVersion}`
169
+ };
170
+ }
171
+ return {
172
+ id,
173
+ ok: false,
174
+ message: `The canonical skill store at ${inspection.storeRoot} is behind the installed ` +
175
+ `peaks-loop ${inspection.installedVersion}: ${inspection.stale.length} of ` +
176
+ `${inspection.managed} managed entries record an older version ` +
177
+ `(${inspection.stale.map(describeEntry).join(', ')}). ` +
178
+ 'Run `peaks skill sync` to refresh the store.'
179
+ };
180
+ }
181
+ function run({ options }) {
182
+ const injected = options.canonicalStoreVersion;
183
+ const storeRoot = injected?.storeRoot ?? canonicalSkillsStore();
184
+ const installedVersion = injected?.installedVersion ?? CLI_VERSION;
185
+ return [toCheck(inspectCanonicalStoreVersions(storeRoot, installedVersion))];
186
+ }
187
+ export const check = {
188
+ name: 'canonical-store-version',
189
+ run
190
+ };
@@ -35,6 +35,7 @@ import { check as skillParse } from './checks/skill-parse.js';
35
35
  import { check as skillRunbook } from './checks/skill-runbook.js';
36
36
  import { check as skillApplyNote } from './checks/skill-apply-note.js';
37
37
  import { check as skillReferenceParity } from './checks/skill-reference-parity.js';
38
+ import { check as canonicalStoreVersion } from './checks/canonical-store-version.js';
38
39
  import { check as schemaValidity } from './checks/schema-validity.js';
39
40
  import { check as userConfig } from './checks/user-config.js';
40
41
  import { check as skillPresence } from './checks/skill-presence.js';
@@ -66,6 +67,7 @@ export const PLUGINS = [
66
67
  skillRunbook, // id prefix "skill-runbook:"
67
68
  skillApplyNote, // id prefix "skill-apply-note:"
68
69
  skillReferenceParity, // ids "skills:reference-parity:<ide>:<skill>" + "skills:reference-parity:store"
70
+ canonicalStoreVersion, // id "skills:store-version:store" — the store against the installed package
69
71
  schemaValidity, // id prefix "schema:"
70
72
  userConfig, // id "config:user"
71
73
  skillPresence, // ids "skill-presence:current" + "skill-presence:freshness"
@@ -120,6 +120,18 @@ export type DoctorOptions = {
120
120
  skillsDir: string;
121
121
  }>;
122
122
  };
123
+ /**
124
+ * Injected roots/versions for the `skills:store-version` check. When omitted
125
+ * the check binds `$PEAKS_HOME`/`~/.peaks` and the installed release. Tests
126
+ * pass a temp store and a temp version here, so no test reads the real home
127
+ * directory or the real release.
128
+ */
129
+ canonicalStoreVersion?: {
130
+ /** The canonical SKILLS directory (`<root>/skills`). */
131
+ readonly storeRoot: string;
132
+ /** The version to compare the store against. */
133
+ readonly installedVersion: string;
134
+ };
123
135
  /**
124
136
  * root for the L3:l3-memory-health check (defaults to
125
137
  * `findProjectRoot(process.cwd())`). Tests use this to point the
@@ -14,6 +14,12 @@
14
14
  * subdirectory. The file it lands in is then judged by where it sits inside
15
15
  * the project, so the families still name this project's directories.
16
16
  *
17
+ * Two readings of one file are offered: the LEXICAL one (`normalizeGatePath`)
18
+ * and the CANONICAL one (`canonicalGatePath`). One directory can be named
19
+ * two ways, and the caller takes the STRICTEST of the two — a wrongly
20
+ * allowed edit is a hole in the gate, a wrongly refused one is only an
21
+ * inconvenience.
22
+ *
17
23
  * The arithmetic lives apart from the decision on purpose: the decision is
18
24
  * the gate's rule, and this is the path arithmetic it rests on. The file the
19
25
  * decision sits in was at its size cap, and the arithmetic needs room.
@@ -48,7 +54,38 @@ export type GateRoots = string | null | GateRootPair;
48
54
  * project. A path that lands OUTSIDE the project keeps the older reading,
49
55
  * the spelling read against the project root, which never widens the gate:
50
56
  * it refuses a spelled family the file itself never reached.
57
+ *
58
+ * "Inside" and "outside" are asked LEXICALLY first and CANONICALLY second
59
+ * (see `relativizeInsideRoot`), so two spellings of one directory reach one
60
+ * verdict.
61
+ *
62
+ * This is the LEXICAL reading. The CANONICAL reading — the file named by the
63
+ * directory it really sits in — is a separate question, asked by
64
+ * `canonicalGatePath`.
51
65
  */
52
66
  export declare function normalizeGatePath(filePath: string, projectRoot?: string | null, toolCwd?: string | null): string;
53
67
  /** The roots, whichever of the two spellings the caller used. */
54
68
  export declare function rootPair(roots: GateRoots | undefined): GateRootPair;
69
+ /**
70
+ * The CANONICAL project-relative form of a target path: the file the call
71
+ * really touches, named by the directory it REALLY sits in.
72
+ *
73
+ * The lexical form says how the path is WRITTEN; this one says where the
74
+ * file IS. The two differ whenever a directory is named two ways — a
75
+ * symlink, a junction, macOS's `/var` → `/private/var` — and the difference
76
+ * is what a symlinked BASE inside the project looks like: the call runs in
77
+ * `link/`, the file is in `src/`, and the lexical form says `link/x.ts`
78
+ * (no family) while this one says `src/x.ts` (a family).
79
+ *
80
+ * The two sides are compared as they are CANONICALLY spelled, so the answer
81
+ * is the directory the file is in and not the spelling the caller used to
82
+ * reach it. The LEXICAL-first-then-canonical retry belongs to the other
83
+ * reading (`relativizeInsideRoot`), which needs it because a lexical answer
84
+ * can be a statement about the SPELLING rather than about the directory.
85
+ *
86
+ * `null` when the file is outside the project: the project has no name for
87
+ * it, and the spelling-anchored reading the caller already holds is the one
88
+ * that applies. `null` also when there is no project root at all, for the
89
+ * same reason — a path cannot be made relative to nothing.
90
+ */
91
+ export declare function canonicalGatePath(filePath: string, projectRoot?: string | null, toolCwd?: string | null): string | null;
@@ -14,12 +14,18 @@
14
14
  * subdirectory. The file it lands in is then judged by where it sits inside
15
15
  * the project, so the families still name this project's directories.
16
16
  *
17
+ * Two readings of one file are offered: the LEXICAL one (`normalizeGatePath`)
18
+ * and the CANONICAL one (`canonicalGatePath`). One directory can be named
19
+ * two ways, and the caller takes the STRICTEST of the two — a wrongly
20
+ * allowed edit is a hole in the gate, a wrongly refused one is only an
21
+ * inconvenience.
22
+ *
17
23
  * The arithmetic lives apart from the decision on purpose: the decision is
18
24
  * the gate's rule, and this is the path arithmetic it rests on. The file the
19
25
  * decision sits in was at its size cap, and the arithmetic needs room.
20
26
  */
21
27
  import { isAbsolute, relative, resolve } from 'node:path';
22
- import { normalizePath } from '../../shared/path-utils.js';
28
+ import { normalizePath, stablePath } from '../../shared/path-utils.js';
23
29
  /** The directory a path is resolved against, or `null` when there is none. */
24
30
  function resolvedDirectory(value) {
25
31
  return typeof value === 'string' && value.length > 0 ? resolve(value) : null;
@@ -57,10 +63,10 @@ function collapseRelativeDotSegments(path) {
57
63
  return out.join('/');
58
64
  }
59
65
  /**
60
- * The path of `target` relative to `root`, when `target` is INSIDE `root`;
61
- * `null` when it is not — the target is outside the root, or it is the root.
66
+ * The path of `target` relative to `root`, compared LEXICALLY: `null` when
67
+ * `target` is not inside `root` — it is outside the root, or it is the root.
62
68
  */
63
- function relativizeInsideRoot(target, root) {
69
+ function relativizeLexically(target, root) {
64
70
  const relativePath = normalizePath(relative(root, target));
65
71
  if (relativePath.length === 0)
66
72
  return null;
@@ -68,6 +74,29 @@ function relativizeInsideRoot(target, root) {
68
74
  return null;
69
75
  return stripLeadingDotSegments(relativePath);
70
76
  }
77
+ /**
78
+ * The path of `target` relative to `root`, when `target` is INSIDE `root`;
79
+ * `null` when it is not — the target is outside the root, or it is the root.
80
+ *
81
+ * The answer is LEXICAL first: the two sides are compared as they are
82
+ * written, so the common case costs no syscall. When the lexical answer is
83
+ * "outside", the question is asked again with the CANONICAL spelling of both
84
+ * sides, because one directory can be named two ways — a symlink, a junction,
85
+ * macOS's `/var` → `/private/var` — and then the lexical answer is a
86
+ * statement about the SPELLING, not about the directory the file is in. The
87
+ * retry can only turn "outside" into "inside", so it can only tighten the
88
+ * gate; whenever the lexical answer says "inside", that answer stands.
89
+ *
90
+ * The canonical answer is relativized against the CANONICAL root, because
91
+ * the project-relative spelling it produces is what the deny families are
92
+ * matched against.
93
+ */
94
+ function relativizeInsideRoot(target, root) {
95
+ const lexical = relativizeLexically(target, root);
96
+ if (lexical !== null)
97
+ return lexical;
98
+ return relativizeLexically(stablePath(target), stablePath(root));
99
+ }
71
100
  /**
72
101
  * The one form of a target path the families are written in.
73
102
  *
@@ -87,6 +116,14 @@ function relativizeInsideRoot(target, root) {
87
116
  * project. A path that lands OUTSIDE the project keeps the older reading,
88
117
  * the spelling read against the project root, which never widens the gate:
89
118
  * it refuses a spelled family the file itself never reached.
119
+ *
120
+ * "Inside" and "outside" are asked LEXICALLY first and CANONICALLY second
121
+ * (see `relativizeInsideRoot`), so two spellings of one directory reach one
122
+ * verdict.
123
+ *
124
+ * This is the LEXICAL reading. The CANONICAL reading — the file named by the
125
+ * directory it really sits in — is a separate question, asked by
126
+ * `canonicalGatePath`.
90
127
  */
91
128
  export function normalizeGatePath(filePath, projectRoot, toolCwd) {
92
129
  if (filePath.length === 0)
@@ -119,3 +156,36 @@ export function rootPair(roots) {
119
156
  return { projectRoot: roots };
120
157
  return roots;
121
158
  }
159
+ /**
160
+ * The CANONICAL project-relative form of a target path: the file the call
161
+ * really touches, named by the directory it REALLY sits in.
162
+ *
163
+ * The lexical form says how the path is WRITTEN; this one says where the
164
+ * file IS. The two differ whenever a directory is named two ways — a
165
+ * symlink, a junction, macOS's `/var` → `/private/var` — and the difference
166
+ * is what a symlinked BASE inside the project looks like: the call runs in
167
+ * `link/`, the file is in `src/`, and the lexical form says `link/x.ts`
168
+ * (no family) while this one says `src/x.ts` (a family).
169
+ *
170
+ * The two sides are compared as they are CANONICALLY spelled, so the answer
171
+ * is the directory the file is in and not the spelling the caller used to
172
+ * reach it. The LEXICAL-first-then-canonical retry belongs to the other
173
+ * reading (`relativizeInsideRoot`), which needs it because a lexical answer
174
+ * can be a statement about the SPELLING rather than about the directory.
175
+ *
176
+ * `null` when the file is outside the project: the project has no name for
177
+ * it, and the spelling-anchored reading the caller already holds is the one
178
+ * that applies. `null` also when there is no project root at all, for the
179
+ * same reason — a path cannot be made relative to nothing.
180
+ */
181
+ export function canonicalGatePath(filePath, projectRoot, toolCwd) {
182
+ if (filePath.length === 0)
183
+ return null;
184
+ const slashed = normalizePath(filePath);
185
+ const root = resolvedDirectory(projectRoot);
186
+ if (root === null)
187
+ return null;
188
+ const base = resolvedDirectory(toolCwd) ?? root;
189
+ const target = isAbsolute(slashed) ? resolve(slashed) : resolve(base, slashed);
190
+ return relativizeLexically(stablePath(target), stablePath(root));
191
+ }
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import { statSync } from 'node:fs';
19
19
  import { isAbsolute, relative, resolve } from 'node:path';
20
- import { normalizePath } from '../../shared/path-utils.js';
20
+ import { normalizePath, stablePath } from '../../shared/path-utils.js';
21
21
  export function readToolCallCwd(payload) {
22
22
  const cwd = payload['cwd'];
23
23
  if (typeof cwd !== 'string')
@@ -42,15 +42,10 @@ function isExistingDirectory(dir) {
42
42
  }
43
43
  }
44
44
  /**
45
- * Is `dir` the project root itself, or a directory inside it?
46
- *
47
- * The check is LEXICAL, like the path arithmetic it feeds: a symlink inside
48
- * the project that points outside it passes here. A base outside the project
49
- * resolves the path against a tree the families do not name, so the file it
50
- * lands in cannot be judged by where it sits in the project — which is the
51
- * invariant the gate is built on.
45
+ * Is `dir` the project root itself, or a directory inside it? Compared
46
+ * LEXICALLY: the two are compared as they are written.
52
47
  */
53
- function isInsideProject(root, dir) {
48
+ function isInsideLexically(root, dir) {
54
49
  const rel = normalizePath(relative(resolve(root), resolve(dir)));
55
50
  if (rel.length === 0)
56
51
  return true;
@@ -58,6 +53,27 @@ function isInsideProject(root, dir) {
58
53
  return false;
59
54
  return !isAbsolute(rel);
60
55
  }
56
+ /**
57
+ * Is `dir` the project root itself, or a directory inside it?
58
+ *
59
+ * The check is LEXICAL first, like the path arithmetic it feeds: a symlink
60
+ * inside the project that points outside it passes here. A base outside the
61
+ * project resolves the path against a tree the families do not name, so the
62
+ * file it lands in cannot be judged by where it sits in the project — which
63
+ * is the invariant the gate is built on.
64
+ *
65
+ * When the lexical answer says "outside", the question is asked again with the
66
+ * CANONICAL spelling of both sides, because one directory can be named two
67
+ * ways — a symlink, a junction, macOS's `/var` → `/private/var` — and then
68
+ * the lexical answer is a statement about the SPELLING, not about the
69
+ * directory. The retry can only turn "outside" into "inside", so the base it
70
+ * accepts is one that really is inside the project.
71
+ */
72
+ function isInsideProject(root, dir) {
73
+ if (isInsideLexically(root, dir))
74
+ return true;
75
+ return isInsideLexically(stablePath(root), stablePath(dir));
76
+ }
61
77
  /**
62
78
  * The directory a relative target path is read against.
63
79
  *
@@ -13,10 +13,10 @@
13
13
  * (.peaks/**, .peaks/_runtime/**, skills/**, docs/**, *.md)
14
14
  * → allow (silent exit 0).
15
15
  *
16
- * Pure function. The shell-script sibling
17
- * (`pre-tool-code-gate.sh`) is the canonical source for the same
18
- * logic, usable from any non-Node harness. Both share the same
19
- * hard-blocked + allow-listed path families.
16
+ * Pure function. This module is the ONE implementation of the rule: the
17
+ * shell-script sibling (`pre-tool-code-gate.sh`) is a thin wrapper that
18
+ * execs the CLI built on it, and its own no-CLI fallback carries a
19
+ * narrower copy of the same families.
20
20
  */
21
21
  import { normalizeGatePath, type GateRoots } from './gate-path-normalize.js';
22
22
  export { normalizeGatePath };
@@ -70,5 +70,25 @@ export declare function extractFilePath(input: Readonly<Record<string, unknown>>
70
70
  * file a call writes is the one that directory names. It does not move the
71
71
  * families - those stay relative to the project root - it only says which
72
72
  * file the payload points at.
73
+ *
74
+ * THE VERDICT IS THE STRICTEST OF THE TWO READINGS. The path is read
75
+ * LEXICALLY - how it is written - and, when that reading has not already
76
+ * denied the file, CANONICALLY - where the file really is. A directory can
77
+ * be named two ways, and the difference is what a symlinked base looks like:
78
+ * a call that runs in `link/` and writes `deep/x.ts` lands in `src/deep/x.ts`
79
+ * when `link` points at `src`, and the lexical reading says `link/deep/x.ts`
80
+ * - no family at all. §18.1 rules that the verdict depends on WHICH
81
+ * DIRECTORY the file is in, not on how the path is written.
82
+ *
83
+ * Strictest, and not "canonical wins": making the canonical reading
84
+ * authoritative would WIDEN the gate in a layout this repository supports.
85
+ * When `src` is a symlink to `shared/src`, the lexical reading is
86
+ * `src/x.ts` (a family) and the canonical one is `shared/src/x.ts` (not
87
+ * one), and the file the gate denies today must stay denied. The tie-breaker
88
+ * is the repository's own: a wrongly ALLOWED edit is a hole, a wrongly
89
+ * REFUSED one is only an inconvenience. So a file reached through a
90
+ * directory NAMED `src` stays refused even when it really sits in `docs/` -
91
+ * the spelling is what the path says in this project's terms, and the gate
92
+ * refuses it rather than resolve it.
73
93
  */
74
94
  export declare function decideGateAction(tool: GateToolName, input: Readonly<Record<string, unknown>>, driver?: string | null, roots?: GateRoots): GateVerdict;
@@ -13,12 +13,12 @@
13
13
  * (.peaks/**, .peaks/_runtime/**, skills/**, docs/**, *.md)
14
14
  * → allow (silent exit 0).
15
15
  *
16
- * Pure function. The shell-script sibling
17
- * (`pre-tool-code-gate.sh`) is the canonical source for the same
18
- * logic, usable from any non-Node harness. Both share the same
19
- * hard-blocked + allow-listed path families.
16
+ * Pure function. This module is the ONE implementation of the rule: the
17
+ * shell-script sibling (`pre-tool-code-gate.sh`) is a thin wrapper that
18
+ * execs the CLI built on it, and its own no-CLI fallback carries a
19
+ * narrower copy of the same families.
20
20
  */
21
- import { normalizeGatePath, rootPair } from './gate-path-normalize.js';
21
+ import { canonicalGatePath, normalizeGatePath, rootPair } from './gate-path-normalize.js';
22
22
  export { normalizeGatePath };
23
23
  /** Hard-blocked path families — orchestrator MUST NOT Edit/Write these. */
24
24
  export const HARD_BLOCKED_PATH_FAMILIES = [
@@ -91,6 +91,40 @@ function matchesAny(path, families) {
91
91
  }
92
92
  return null;
93
93
  }
94
+ /**
95
+ * The hard-blocked family a reading of the path names, or `null` when it
96
+ * names none.
97
+ *
98
+ * The ALLOW-LIST is read FIRST, for each reading on its own: a path the
99
+ * project allows is allowed, and a reading that names an allow-listed
100
+ * directory does not become a deny because ANOTHER reading names a family.
101
+ * That is what keeps `src/x.md` allowed, exactly as it was before.
102
+ *
103
+ * The family comparison folds CASE, because every family name is written in
104
+ * lower case and the filesystem holding the file may not be.
105
+ */
106
+ function hardBlockedFamilyOf(reading) {
107
+ if (matchesAny(reading, ALLOW_LISTED_PATH_PATTERNS) !== null)
108
+ return null;
109
+ return matchesAny(reading, HARD_BLOCKED_PATH_FAMILIES);
110
+ }
111
+ /**
112
+ * The verdict for a file that one reading of the path placed in a
113
+ * hard-blocked family.
114
+ *
115
+ * A driver that is not the fast lane falls through to the same deny a
116
+ * two-argument call produces, so an unresolvable identity can never become a
117
+ * silent pass.
118
+ */
119
+ function denyVerdict(family, requestedPath, driver) {
120
+ if (driver === FAST_LANE_DRIVER) {
121
+ return { action: 'allow' };
122
+ }
123
+ const reason = `${family} (orchestrator's hard-blocked path family)`;
124
+ const message = `PEAKS_CODE_PROHIBITED_DIRECT_EDIT: ${requestedPath} matches hard-blocked path family ${reason}; ` +
125
+ `orchestrator MUST NOT Edit/Write these directly. Use: peaks sub-agent dispatch rd --prompt '<your task>' --request-id <rid> --project . --batch-id <uuid>`;
126
+ return { action: 'deny', filePath: requestedPath, reason, message };
127
+ }
94
128
  /**
95
129
  * Pure decision function. Given the tool name + input object, return
96
130
  * the gate verdict. Tolerates malformed payloads (allow).
@@ -116,6 +150,26 @@ function matchesAny(path, families) {
116
150
  * file a call writes is the one that directory names. It does not move the
117
151
  * families - those stay relative to the project root - it only says which
118
152
  * file the payload points at.
153
+ *
154
+ * THE VERDICT IS THE STRICTEST OF THE TWO READINGS. The path is read
155
+ * LEXICALLY - how it is written - and, when that reading has not already
156
+ * denied the file, CANONICALLY - where the file really is. A directory can
157
+ * be named two ways, and the difference is what a symlinked base looks like:
158
+ * a call that runs in `link/` and writes `deep/x.ts` lands in `src/deep/x.ts`
159
+ * when `link` points at `src`, and the lexical reading says `link/deep/x.ts`
160
+ * - no family at all. §18.1 rules that the verdict depends on WHICH
161
+ * DIRECTORY the file is in, not on how the path is written.
162
+ *
163
+ * Strictest, and not "canonical wins": making the canonical reading
164
+ * authoritative would WIDEN the gate in a layout this repository supports.
165
+ * When `src` is a symlink to `shared/src`, the lexical reading is
166
+ * `src/x.ts` (a family) and the canonical one is `shared/src/x.ts` (not
167
+ * one), and the file the gate denies today must stay denied. The tie-breaker
168
+ * is the repository's own: a wrongly ALLOWED edit is a hole, a wrongly
169
+ * REFUSED one is only an inconvenience. So a file reached through a
170
+ * directory NAMED `src` stays refused even when it really sits in `docs/` -
171
+ * the spelling is what the path says in this project's terms, and the gate
172
+ * refuses it rather than resolve it.
119
173
  */
120
174
  export function decideGateAction(tool, input, driver, roots) {
121
175
  // Only gate Edit / Write / MultiEdit.
@@ -135,25 +189,21 @@ export function decideGateAction(tool, input, driver, roots) {
135
189
  // echoes the path the tool actually asked for.
136
190
  const pair = rootPair(roots);
137
191
  const filePath = normalizeGatePath(requestedPath, pair.projectRoot, pair.toolCwd);
138
- // Allow-list check first — short-circuits any deny, for every driver.
139
- const allowMatch = matchesAny(filePath, ALLOW_LISTED_PATH_PATTERNS);
140
- if (allowMatch !== null) {
141
- return { action: 'allow' };
142
- }
143
- // Hard-blocked family check — case-insensitively, because every family name
144
- // is lower-case and the filesystem holding the file may not be.
145
- const denyMatch = matchesAny(filePath, HARD_BLOCKED_PATH_FAMILIES);
192
+ // The LEXICAL reading: the allow-list first — it short-circuits any deny,
193
+ // for every driver — and then the hard-blocked families.
194
+ const denyMatch = hardBlockedFamilyOf(filePath);
146
195
  if (denyMatch !== null) {
147
- // A driver that is not the fast lane falls through to the same deny a
148
- // two-argument call produces, so an unresolvable identity can never
149
- // become a silent pass.
150
- if (driver === FAST_LANE_DRIVER) {
151
- return { action: 'allow' };
196
+ return denyVerdict(denyMatch, requestedPath, driver ?? null);
197
+ }
198
+ // The CANONICAL reading, asked only when the lexical one has not already
199
+ // denied the file: it costs two filesystem lookups, and the file it names
200
+ // is the one the lexical reading could not place.
201
+ const canonical = canonicalGatePath(requestedPath, pair.projectRoot, pair.toolCwd);
202
+ if (canonical !== null) {
203
+ const canonicalMatch = hardBlockedFamilyOf(canonical);
204
+ if (canonicalMatch !== null) {
205
+ return denyVerdict(canonicalMatch, requestedPath, driver ?? null);
152
206
  }
153
- const reason = `${denyMatch} (orchestrator's hard-blocked path family)`;
154
- const message = `PEAKS_CODE_PROHIBITED_DIRECT_EDIT: ${requestedPath} matches hard-blocked path family ${reason}; ` +
155
- `orchestrator MUST NOT Edit/Write these directly. Use: peaks sub-agent dispatch rd --prompt '<your task>' --request-id <rid> --project . --batch-id <uuid>`;
156
- return { action: 'deny', filePath: requestedPath, reason, message };
157
207
  }
158
208
  // Anything not in the deny list → allow (e.g. CHANGELOG, README, top-level files).
159
209
  return { action: 'allow' };
@@ -1,3 +1,16 @@
1
+ /**
2
+ * The documented contract: one path segment. `isUnsafePathInput` is a
3
+ * traversal guard only and ADMITS `a/b`, so the separator axes are
4
+ * checked here as well. The session dir is ONE directory name under
5
+ * `_runtime/`.
6
+ *
7
+ * EXPORTED because the session id is the last caller-supplied segment of
8
+ * more than one session-scoped path: the runtime dir here, and the dispatch
9
+ * ledger's dir under `.peaks/_sub_agents/` (read by
10
+ * `src/services/dispatch/dispatch-ledger-reader.ts`). One predicate, two
11
+ * users, so the two cannot drift apart.
12
+ */
13
+ export declare function isSinglePathSegment(sessionId: string): boolean;
1
14
  export declare function getSessionDir(projectRoot: string, sessionId: string): string;
2
15
  /**
3
16
  * The TOTAL entry to the same axis. Same predicate, same path; the only
@@ -49,8 +49,14 @@ import { isUnsafePathInput } from '../../shared/path-safety.js';
49
49
  * traversal guard only and ADMITS `a/b`, so the separator axes are
50
50
  * checked here as well. The session dir is ONE directory name under
51
51
  * `_runtime/`.
52
+ *
53
+ * EXPORTED because the session id is the last caller-supplied segment of
54
+ * more than one session-scoped path: the runtime dir here, and the dispatch
55
+ * ledger's dir under `.peaks/_sub_agents/` (read by
56
+ * `src/services/dispatch/dispatch-ledger-reader.ts`). One predicate, two
57
+ * users, so the two cannot drift apart.
52
58
  */
53
- function isSinglePathSegment(sessionId) {
59
+ export function isSinglePathSegment(sessionId) {
54
60
  return !isUnsafePathInput(sessionId) && !sessionId.includes('/') && !sessionId.includes('\\');
55
61
  }
56
62
  export function getSessionDir(projectRoot, sessionId) {