@skathio/somi 4.0.0 → 4.1.0

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 (163) hide show
  1. package/.claude/settings.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +11 -5
  7. package/VERSION +1 -1
  8. package/agents/somi-coder.md +4 -228
  9. package/agents/somi-designer.md +4 -160
  10. package/agents/somi-discovery-analyst.md +4 -276
  11. package/agents/somi-flow.md +47 -0
  12. package/agents/somi-general.md +36 -0
  13. package/agents/somi-planner.md +4 -341
  14. package/agents/somi-reviewer.md +4 -199
  15. package/agents/somi.md +81 -253
  16. package/commands/adopt.md +6 -84
  17. package/commands/architecture-review.md +11 -86
  18. package/commands/atlas.md +10 -25
  19. package/commands/code-loop.md +10 -221
  20. package/commands/code-parallel.md +10 -151
  21. package/commands/code.md +9 -157
  22. package/commands/debug.md +9 -131
  23. package/commands/design.md +9 -160
  24. package/commands/discover.md +9 -194
  25. package/commands/impact.md +9 -25
  26. package/commands/incident.md +9 -39
  27. package/commands/plan-loop.md +9 -181
  28. package/commands/plan.md +9 -244
  29. package/commands/pr.md +10 -25
  30. package/commands/refactor-design.md +11 -89
  31. package/commands/refactor.md +11 -50
  32. package/commands/release-readiness.md +11 -70
  33. package/commands/review-panel.md +10 -141
  34. package/commands/review.md +11 -181
  35. package/commands/security-review.md +11 -75
  36. package/commands/ship-loop.md +9 -260
  37. package/commands/ship.md +9 -115
  38. package/commands/somi-config.md +12 -124
  39. package/commands/test-strategy.md +11 -75
  40. package/commands/upgrade.md +9 -72
  41. package/hooks/hooks.json +1 -1
  42. package/hooks/lib/common.mjs +15 -13
  43. package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
  44. package/hooks/pre-tool/block-secret-writes.mjs +5 -7
  45. package/hooks/pre-tool/guard-cost-lowering.mjs +26 -11
  46. package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
  47. package/hooks/session-start/ensure-default-config.mjs +34 -42
  48. package/package.json +1 -1
  49. package/scripts/lib/config-files.mjs +145 -0
  50. package/scripts/lib/cost-ceiling.mjs +29 -22
  51. package/scripts/lib/cost-defaults.mjs +2 -0
  52. package/scripts/lib/escalation-facts.mjs +146 -0
  53. package/scripts/lib/escalation.mjs +129 -0
  54. package/scripts/lib/findings-ledger.mjs +241 -0
  55. package/scripts/lib/install-text.mjs +97 -0
  56. package/scripts/lib/loop-caps.mjs +140 -0
  57. package/scripts/lib/loop-diff.mjs +12 -70
  58. package/scripts/lib/loop-engine.mjs +226 -0
  59. package/scripts/lib/loop-escalate.mjs +49 -0
  60. package/scripts/lib/loop-exit.mjs +47 -0
  61. package/scripts/lib/loop-notes-compact.mjs +72 -0
  62. package/scripts/lib/loop-notes.mjs +278 -0
  63. package/scripts/lib/loop-review.mjs +355 -12
  64. package/scripts/lib/loop-state.mjs +44 -0
  65. package/scripts/lib/loop-step-close.mjs +75 -0
  66. package/scripts/lib/loop-step-kit.mjs +179 -0
  67. package/scripts/lib/loop-step-review.mjs +140 -0
  68. package/scripts/lib/loop-step-tool.mjs +89 -0
  69. package/scripts/lib/loop-step.mjs +301 -0
  70. package/scripts/lib/mcp-project-root.mjs +18 -7
  71. package/scripts/lib/path-facts.mjs +187 -0
  72. package/scripts/lib/path-safety.mjs +171 -0
  73. package/scripts/lib/run-card.mjs +73 -0
  74. package/scripts/size-budget-overrides.json +5 -13
  75. package/scripts/somi-card.mjs +39 -0
  76. package/scripts/somi-check.mjs +4 -3
  77. package/scripts/somi-config.mjs +113 -50
  78. package/scripts/somi-findings.mjs +56 -271
  79. package/scripts/somi-loop.mjs +77 -446
  80. package/scripts/somi-mcp.mjs +27 -96
  81. package/scripts/validate.sh +92 -54
  82. package/skills/flow-adopt/SKILL.md +92 -0
  83. package/skills/flow-architecture-review/SKILL.md +94 -0
  84. package/skills/flow-atlas/SKILL.md +34 -0
  85. package/skills/flow-code/SKILL.md +167 -0
  86. package/skills/flow-code-loop/SKILL.md +263 -0
  87. package/skills/flow-code-parallel/SKILL.md +160 -0
  88. package/skills/flow-debug/SKILL.md +141 -0
  89. package/skills/flow-design/SKILL.md +170 -0
  90. package/skills/flow-discover/SKILL.md +204 -0
  91. package/skills/flow-impact/SKILL.md +35 -0
  92. package/skills/flow-incident/SKILL.md +49 -0
  93. package/skills/flow-plan/SKILL.md +254 -0
  94. package/skills/flow-plan-loop/SKILL.md +254 -0
  95. package/skills/flow-pr/SKILL.md +34 -0
  96. package/skills/flow-refactor/SKILL.md +58 -0
  97. package/skills/flow-refactor-design/SKILL.md +97 -0
  98. package/skills/flow-release-readiness/SKILL.md +82 -0
  99. package/skills/flow-review/SKILL.md +193 -0
  100. package/skills/flow-review-panel/SKILL.md +154 -0
  101. package/skills/flow-security-review/SKILL.md +83 -0
  102. package/skills/flow-ship/SKILL.md +125 -0
  103. package/skills/flow-ship-loop/SKILL.md +274 -0
  104. package/skills/flow-somi-config/SKILL.md +142 -0
  105. package/skills/flow-status/SKILL.md +43 -0
  106. package/skills/flow-test-strategy/SKILL.md +83 -0
  107. package/skills/flow-upgrade/SKILL.md +82 -0
  108. package/skills/role-coder/SKILL.md +247 -0
  109. package/skills/role-designer/SKILL.md +172 -0
  110. package/skills/role-discovery-analyst/SKILL.md +288 -0
  111. package/skills/role-planner/SKILL.md +353 -0
  112. package/skills/role-reviewer/SKILL.md +218 -0
  113. package/skills/somi-checkpoint/SKILL.md +95 -0
  114. package/skills/somi-dispatch/SKILL.md +14 -14
  115. package/skills/somi-routing/SKILL.md +6 -2
  116. package/tests/hooks/cases/block-secret-writes.json +6 -1
  117. package/tests/hooks/cases/guard-protected-paths.json +44 -2
  118. package/tests/hooks/run.sh +21 -0
  119. package/tests/scripts/checkpoint-gate.sh +2 -2
  120. package/tests/scripts/cost-defaults.sh +2 -0
  121. package/tests/scripts/cost-hardcap.sh +26 -17
  122. package/tests/scripts/dispatch-line-gate.sh +4 -4
  123. package/tests/scripts/dispatch-reference-gate.sh +14 -14
  124. package/tests/scripts/ensure-default-config.sh +4 -4
  125. package/tests/scripts/escalation.sh +409 -0
  126. package/tests/scripts/eval-runner.sh +8 -7
  127. package/tests/scripts/fact-sheet.sh +296 -0
  128. package/tests/scripts/global-config.sh +167 -0
  129. package/tests/scripts/goldens/somi-loop.json +2 -2
  130. package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
  131. package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
  132. package/tests/scripts/lib/escalation-tests.mjs +154 -0
  133. package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
  134. package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
  135. package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
  136. package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
  137. package/tests/scripts/lib/loop-notes-tests.mjs +371 -0
  138. package/tests/scripts/lib/loop-step-cli-tests.mjs +141 -0
  139. package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
  140. package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
  141. package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
  142. package/tests/scripts/lib/loop-step-tests.mjs +499 -0
  143. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
  144. package/tests/scripts/lib/path-facts-tests.mjs +198 -0
  145. package/tests/scripts/lib/path-safety-tests.mjs +201 -0
  146. package/tests/scripts/lib/run-suites.mjs +139 -0
  147. package/tests/scripts/lib/site-roadmap-gate.mjs +64 -0
  148. package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
  149. package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
  150. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
  151. package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
  152. package/tests/scripts/loop-engine.sh +22 -0
  153. package/tests/scripts/loop-flow-gate.sh +11 -0
  154. package/tests/scripts/review-panel-seats.sh +4 -4
  155. package/tests/scripts/run-card.sh +57 -0
  156. package/tests/scripts/run-suites.sh +74 -0
  157. package/tests/scripts/run.sh +11 -0
  158. package/tests/scripts/site-roadmap-gate.sh +76 -0
  159. package/tests/scripts/size-tier.sh +3 -3
  160. package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
  161. package/tests/scripts/somi-config.sh +9 -4
  162. package/tests/scripts/somi-mcp.sh +1 -0
  163. package/tests/scripts/suite-plan.json +20 -0
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env node
2
+ // The words a step response is built from (loop-exit.mjs: the gate exits and the `next` and `kind` tokens, pinned against
3
+ // docs/PLUGIN.md), the unwritten items a stored response may carry (loop-step-kit.mjs stateAt), and saveState not writing
4
+ // through a link or a hard link, and the step files emitting only members of NEXT. Run by tests/scripts/loop-engine.sh.
5
+
6
+ import { execFileSync } from 'node:child_process';
7
+ import { linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { isDeepStrictEqual } from 'node:util';
12
+ import { GATE_STOPS, KIND, KINDS, NEXT, NEXTS } from '../../../scripts/lib/loop-exit.mjs';
13
+ import { stateAt } from '../../../scripts/lib/loop-step-kit.mjs';
14
+ import { saveState } from '../../../scripts/lib/loop-state.mjs';
15
+
16
+ const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
17
+ let pass = 0; let fail = 0;
18
+ const check = (name, got, want) => {
19
+ if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
20
+ };
21
+ const tmp = mkdtempSync(path.join(tmpdir(), 'loop-words-'));
22
+ process.on('exit', () => rmSync(tmp, { recursive: true, force: true }));
23
+
24
+ const doc = readFileSync(path.join(ROOT, 'docs', 'PLUGIN.md'), 'utf8');
25
+ const listed = (word) => [...(new RegExp(`\`${word}\`(?: call)? is one of: ([^.]*)\\.`).exec(doc)?.[1] ?? '').matchAll(/`([a-z-]+)`/g)].map((m) => m[1]);
26
+ check('the gate exits, the next tokens and the kinds are frozen, and the gate exits are 2 to 5', [GATE_STOPS, [GATE_STOPS, NEXT, NEXTS, KIND, KINDS].map(Object.isFrozen)], [[2, 3, 4, 5], Array(5).fill(true)]);
27
+ check('PLUGIN.md lists exactly the next tokens and the kinds the engine owns, in order', [listed('next'), listed('kind')], [[...NEXTS], [...KINDS]]);
28
+
29
+ // The tokens a step emits are the engine's: no `next:` value is a literal in a step file, every NEXT member is used by one, and
30
+ // none names a member NEXT lacks. (A comment line is skipped; the scan reads the files as text.)
31
+ const LIB = path.join(ROOT, 'scripts', 'lib');
32
+ const src = readdirSync(LIB).filter((f) => /^loop-step.*\.mjs$/.test(f)).map((f) => [f, readFileSync(path.join(LIB, f), 'utf8').split('\n').filter((l) => !/^\s*\/\//.test(l)).join('\n')]);
33
+ const text = src.map(([, t]) => t).join('\n');
34
+ check('no step file gives next a string literal; each NEXT member is emitted by one (task-panel and task-planner included), and every NEXT.<name> they use exists', [src.filter(([, t]) => /\bnext:\s*['"`]|\bnext:[^,}\n]*[?:]\s*['"`]/.test(t)).map(([f]) => f), Object.keys(NEXT).filter((k) => !new RegExp(`\\bNEXT\\.${k}\\b`).test(text)), [...text.matchAll(/\bNEXT\.(\w+)/g)].map((m) => m[1]).filter((k) => !(k in NEXT))], [[], [], []]);
35
+
36
+ const running = (unwritten) => ({ status: 'running', loop: 'code', pass: 1, caps: { max_passes: 3, diff_cap_lines: 400 }, baseline_sha: 'a'.repeat(40), history: [], iteration_files: [], steps: { '1:open': { done: [], at: 'x', out: { wrote: [], unwritten } } } });
37
+ const item = (kind) => ({ file: 'progress.md', reason: 'r', line: 'l', ...(kind === undefined ? {} : { kind }) });
38
+ const readable = (kind) => { const f = path.join(tmp, `s${Math.random()}.json`); writeFileSync(f, JSON.stringify(running([item(kind)]))); return stateAt(f) !== null; };
39
+ check('a stored item with a kind of the set, or with none (stored before kinds existed), is readable; any other kind makes the state unreadable', [...KINDS, undefined, 'bogus', '', 7].map(readable), [...KINDS.map(() => true), true, false, false, false]);
40
+
41
+ const outside = path.join(tmp, 'outside.json'); writeFileSync(outside, 'keep');
42
+ const link = path.join(tmp, 'state.json'); symlinkSync(outside, link);
43
+ const thrown = (fn) => { try { fn(); } catch (e) { return [e.code, e.message]; } return null; };
44
+ const plainFile = path.join(tmp, 'plain.json'); writeFileSync(plainFile, 'x'.repeat(50));
45
+ check('saveState refuses a link at the state file instead of writing through it (the file it pointed to is untouched) and rewrites a plain file whole', [thrown(() => saveState(link, { a: 1 })), readFileSync(outside, 'utf8'), thrown(() => saveState(plainFile, { a: 1 })), readFileSync(plainFile, 'utf8')], [[64, 'somi-loop: the state file is a link'], 'keep', null, '{"a":1}']);
46
+
47
+ const hardState = path.join(tmp, 'hard.json'); const lonely = path.join(tmp, 'lonely.json'); writeFileSync(lonely, 'keep'); linkSync(lonely, hardState);
48
+ const dir = path.join(tmp, 'sd'); mkdirSync(dir); const copy = path.join(dir, 's.json'); linkSync(lonely, copy);
49
+ check('saveState refuses a state file that is a second name for another file, and the file outside the root is not changed', [thrown(() => saveState(hardState, { a: 1 })), thrown(() => saveState(copy, { a: 1 })), readFileSync(lonely, 'utf8')], [[64, 'somi-loop: the state file has more than one link'], [64, 'somi-loop: the state file has more than one link'], 'keep']);
50
+ const notFile = [64, 'somi-loop: the state file is not a regular file']; const fifo = path.join(tmp, 'fifo.json'); execFileSync('mkfifo', [fifo]);
51
+ check('saveState refuses a device, a directory and a FIFO as the state file: 64 with the cause, not an internal error', [thrown(() => saveState('/dev/null', { a: 1 })), thrown(() => saveState(dir, { a: 1 })), thrown(() => saveState(fifo, { a: 1 }))], [notFile, notFile, notFile]);
52
+ check('no step file compares a next value with a string literal', src.filter(([, t]) => /\.next\s*[!=]==?\s*['"`]/.test(t)).map(([f]) => f), []);
53
+
54
+ console.log(`loop step words tests: ${pass} ok, ${fail} failed`);
55
+ process.exit(fail === 0 ? 0 : 1);
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ // Tests of scripts/lib/path-facts.mjs. Risk: a committed config or a hostile path list lowering a floor (a glob
3
+ // removed, a container dropped so two modules fold into one), or a config glob costing unbounded time. Pure strings,
4
+ // no mocks. Usage: node path-facts-tests.mjs <module path>; tests/scripts/fact-sheet.sh runs it on the module and on
5
+ // scratch mutants of it, and each mutant must turn the test named there red. Hermetic: no model, no network.
6
+
7
+ import { spawnSync } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { isDeepStrictEqual } from 'node:util';
12
+ import { fileURLToPath, pathToFileURL } from 'node:url';
13
+
14
+ const modPath = path.resolve(process.argv[2]);
15
+ const M = await import(pathToFileURL(modPath).href);
16
+ const { classifyPaths, MAX_GLOBS, MAX_GLOB_CHARS, BUILTIN_CONTAINERS } = M;
17
+ const { mergeConfig } = await import(pathToFileURL(path.join(path.dirname(fileURLToPath(import.meta.url)), '../../../scripts/lib/config-files.mjs')).href);
18
+
19
+ let pass = 0; let fail = 0;
20
+ const skip = (name, why) => console.log(` skip ${name} (${why})`);
21
+ const clip = (v) => JSON.stringify(v).slice(0, 160);
22
+ const check = (name, got, want) => {
23
+ if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${clip(want)}, got ${clip(got)})`); }
24
+ };
25
+ // A throw is reported as a result, so a broken module fails the named check instead of ending the run.
26
+ const run = (paths, config) => { try { return classifyPaths(paths, config); } catch { return { threw: true }; } };
27
+ const one = (p, config) => run([p], config).files?.[0] ?? { threw: true };
28
+ const hits = (p, config) => { const f = one(p, config); return [f.sensitive, f.boundary, f.contract]; };
29
+ const modules = (paths, config) => run(paths, config).modules;
30
+ const sizing = (o) => ({ sizing: o });
31
+ const with1 = (key, list) => sizing({ [key]: list });
32
+
33
+ console.log('== path facts: glob classes ==');
34
+ check('an unconfigured repo flags .env, a migrations directory, a lockfile and a route file', [
35
+ hits('.env'), hits('db/migrations/001_init.sql'), hits('package-lock.json'), hits('src/routes/users.js'),
36
+ ], [
37
+ [['deny_list'], ['deny_list'], []],
38
+ [['migrations'], ['data'], []],
39
+ [[], [], ['lockfile']],
40
+ [[], ['routes'], []],
41
+ ]);
42
+ check('flags secrets, auth, crypto and infra as sensitive', [
43
+ hits('lib/client_secret.go')[0], hits('src/auth/login.ts')[0], hits('pkg/crypto/aes.go')[0], hits('.github/workflows/ci.yml')[0], hits('infra/main.tf')[0],
44
+ ], [['secrets'], ['auth'], ['crypto'], ['infra', 'ci'], ['infra']]);
45
+ check('flags sinks and contracts', [
46
+ hits('app/uploads/handler.py')[1], hits('x/Spawn.js')[1], hits('db/schema.sql')[1], hits('package.json')[2], hits('api/openapi.yaml')[2], hits('proto/a.proto')[2],
47
+ ], [['input'], ['process'], ['data'], ['manifest'], ['schema'], ['schema']]);
48
+ const CI_PATHS = ['.github/workflows/ci.yml', '.gitlab-ci.yml', 'x/.circleci/config.yml', '.travis.yml', 'azure-pipelines.yml', 'bitbucket-pipelines.yml', 'Jenkinsfile', 'ci/Jenkinsfile', '.gitlab/ci/build.yml', '.gitlab-ci.yaml', 'action.yml', 'sub/action.yaml', '.gitea/workflows/w.yml', '.forgejo/workflows/w.yml', 'Jenkinsfile.groovy', 'build.jenkinsfile', 'azure-pipelines-ci.yaml', '.azure-pipelines/b.yml', '.buildkite/pipeline.yml', '.drone.yml', '.woodpecker/b.yml', '.woodpecker.yaml', 'appveyor.yml', 'cloudbuild.yaml', 'buildspec.yml', '.pre-commit-config.yaml'];
49
+ check('every CI system is a ci hit in the sensitive list (a sensitive name, so it raises), and a look-alike is not', [CI_PATHS.map((p) => hits(p)[0].includes('ci')), ['docs/ci.md', 'src/jenkins.md', 'ci/run.sh', 'azure.md', 'action.md'].map((p) => hits(p)[0].includes('ci'))], [CI_PATHS.map(() => true), Array(5).fill(false)]);
50
+ check('does not flag ordinary source or a look-alike', [hits('src/util/strings.js'), hits('docs/author.md'), hits('README.md')], [[[], [], []], [[], [], []], [[], [], []]]);
51
+ check('matching is case-folded', [hits('DB/Migrations/001.SQL'), hits('SRC/Routes/X.JS')[1]], [[['migrations'], ['data'], []], ['routes']]);
52
+ check('a directory glob with a slash is anchored and also matches what is under it', [
53
+ hits('x/y.js', with1('sensitive_paths', ['x'])), hits('a/x/y.js', with1('sensitive_paths', ['x/**'])), hits('x/a/b.js', with1('sensitive_paths', ['x/**'])), hits('a/x/b.js', with1('sensitive_paths', ['**/x'])),
54
+ ].map((h) => h[0]), [['config'], [], ['config'], ['config']]);
55
+ check('a config glob is literal text except star, question mark and a ** segment', [
56
+ hits('abc', with1('sensitive_paths', ['a.c']))[0], hits('a.c', with1('sensitive_paths', ['a.c']))[0], hits('(x|y)', with1('sensitive_paths', ['(x|y)']))[0],
57
+ hits('x', with1('sensitive_paths', ['(x|y)']))[0], hits('aXc', with1('sensitive_paths', ['a?c']))[0], hits('abbc', with1('sensitive_paths', ['a*c']))[0],
58
+ ], [[], ['config'], ['config'], [], ['config'], ['config']]);
59
+
60
+ console.log('== path facts: production, test and module key ==');
61
+ check('a test file is not a production file, and a fixtures directory is not a test directory', run(['tests/a.sh', 'src/a.test.js', 'lib/b_test.go', 'x/__tests__/c.js', 'test_d.py', 'scripts/lib/e-tests.mjs', 'src/f.js', 'docs/g.md', 'app/fixtures/seed.json']).production_files, 3);
62
+ check('module key: first segment, a root file is the one module with the empty key, a deep file is its first directory', [
63
+ one('README.md').module, one('LICENSE').module, one('scripts/lib/a.mjs').module, one('a/b/c/d.js').module, one('./x\\y.js').module,
64
+ ], ['', '', 'scripts', 'a', 'x']);
65
+ check('module key under a built-in container is <container>/<segment>; a file directly in a container is the container', [
66
+ one('packages/a/x.js').module, one('src/a/b/c.js').module, one('apps/web/x').module, one('libs/core/x').module, one('src/main.js').module,
67
+ ], ['packages/a', 'src/a', 'apps/web', 'libs/core', 'src']);
68
+ check('a configured container splits its children, however its name is written', [one('services/a/x', with1('module_containers', ['services'])).module, one('Services/B/x', with1('module_containers', ['SERVICES'])).module, one('services/a/x').module,
69
+ one('services/a/x', with1('module_containers', ['services/'])).module, one('services/a/x', with1('module_containers', ['./services'])).module], ['services/a', 'Services/B', 'services', 'services/a', 'services/a']);
70
+ const LONG_PATH = 'a/'.repeat(200);
71
+ check('an unusable entry has a module key no real path can have: it never merges with a first segment like ?0', [modules([LONG_PATH, '?0/a.js']), modules([LONG_PATH, '/?0/a.js']), modules([null, '?0/a.js', '?1/a.js', LONG_PATH])], [2, 2, 4]);
72
+ check('the module key keeps the case of the path: packages/Foo and packages/foo are two modules, the container still matches folded', [modules(['packages/Foo/x', 'packages/foo/y']), one('PACKAGES/a/x').module], [2, 'PACKAGES/a']);
73
+ check('a trailing dot or space on a segment does not hide a glob hit', [hits('package.json.')[2], hits('db/migrations ./1.sql')[0]], [['manifest'], ['migrations']]);
74
+ check('the trim is an extra reading: a dots-only directory does not shift an anchored glob, and a trailing dot does not hide a wildcard', [
75
+ hits('infra/.../prod/db.yml', with1('sensitive_paths', ['infra/*/prod/**']))[0], hits('infra/prod/db.yml', with1('sensitive_paths', ['infra/*/prod/**']))[0], hits('billing./x', with1('sensitive_paths', ['billing.*']))[0],
76
+ ], [['config'], [], ['config']]);
77
+ check('a name that trims to a test directory is still production code', [one('tests./a.js').production, run(['tests./a.js', 'tests/a.js']).production_files], [true, 1]);
78
+ check('a code point that folds to a separator stays inside its segment: tests\uff0fx.js is production code, not a test directory', [one('tests\uff0fx.js').production, run(['tests\uff0fx.js', 'src/a.js']).production_files], [true, 2]);
79
+ const SEP_ANCHORED = with1('sensitive_paths', ['infra/*/prod/**']); const SEP_PLAIN = with1('sensitive_paths', ['infra/a/b/**']);
80
+ check('a code point that folds to a separator: the primary reading keeps it one segment (hits infra/*/prod/**), the re-split reading is an extra one (hits infra/a/b/**), and neither widens a plain path', [
81
+ hits('infra/a\uff0fb/prod/db.yml', SEP_ANCHORED)[0], hits('infra/a\uff0fb/x', SEP_PLAIN)[0], hits('infra/a/b/prod/db.yml', SEP_ANCHORED)[0], hits('infra/ab/x', SEP_PLAIN)[0],
82
+ ], [['config'], ['config'], [], []]);
83
+ check('a glob or a container written with a trailing dot or space is trimmed like a path segment', [
84
+ hits('services/x', with1('sensitive_paths', ['services.']))[0], hits('services./x', with1('sensitive_paths', ['services']))[0], hits('a/b', with1('sensitive_paths', ['a./b']))[0],
85
+ one('services/a/x', with1('module_containers', ['services.'])).module, one('services./a/x', with1('module_containers', ['services'])).module, one('services./a/x', with1('module_containers', ['services. '])).module,
86
+ ], [['config'], ['config'], ['config'], 'services/a', 'services./a', 'services./a']);
87
+
88
+ console.log('== path facts: the deny list floors whatever the config says ==');
89
+ const withEnv = run(['src/a.js', '.env']); const without = run(['src/a.js', 'src/b.js']);
90
+ check('a denied name reports a deny_list hit in the sensitive and boundary lists and the same list without it does not', [withEnv.sensitive, withEnv.boundary, without.sensitive.includes('deny_list'), without.boundary.includes('deny_list')], [['deny_list'], ['deny_list'], false, false]);
91
+ check('every path carries the denied fact, and a denied name hits even when the config tries to list others only', [
92
+ one('src/a.js').denied, one('config/KEY.PEM').denied, one('.git/config', with1('sensitive_paths', ['zzz'])).sensitive.includes('deny_list'), one('id_rsa', sizing({ sensitive_paths: [], module_containers: [] })).boundary,
93
+ ], [false, true, true, ['deny_list']]);
94
+ check('an unusable entry floors instead of vanishing: not a string, over the length cap, not an array, over the count cap', [
95
+ one(null).denied, one('a/'.repeat(200)).denied, run('src/a.js').sensitive, run(Array(41).fill('a.js')).boundary, one('a/'.repeat(200)).path,
96
+ ], [true, true, ['deny_list'], ['deny_list'], '']);
97
+ check('an unusable list reports the counts at the path cap', [run('src/a.js'), run(Array(41).fill('a.js'))].map((r) => [r.files.length, r.production_files, r.modules]), [[40, 40, 40], [40, 40, 40]]);
98
+
99
+ console.log('== path facts: config only adds ==');
100
+ const ALL = ['.env', 'db/migrations/1.sql', 'package-lock.json', 'src/routes/u.js', 'lib/secret.js', '.circleci/config.yml'];
101
+ const base = run(ALL);
102
+ check('config globs are added to the built-ins, not instead of them', [hits('zed/x.js', with1('sensitive_paths', ['zed']))[0], run(ALL, with1('sensitive_paths', ['zzz'])).sensitive], [['config'], base.sensitive]);
103
+ const a = { sizing: { sensitive_paths: ['a/**'] } }; const b = { sizing: { sensitive_paths: ['b/**'] } };
104
+ const merged = mergeConfig(a, b);
105
+ check('mergeConfig replaces an array between layers: global [a] plus project [b] is [b]', merged.sizing.sensitive_paths, ['b/**']);
106
+ check('the merged config adds only b, and every built-in still flags', [hits('b/x')[0], hits('a/x')[0], hits('b/x', merged)[0], hits('a/x', merged)[0], run(ALL, merged).sensitive.filter((n) => n !== 'config')], [[], [], ['config'], [], base.sensitive]);
107
+ const LAYER_MIX = [with1('sensitive_paths', ['q']), with1('sensitive_paths', []), sizing({ sensitive_paths: ['..'] }), sizing({ module_containers: ['a..b'] }), null, undefined, 'x'];
108
+ check('a later layer, valid, empty, invalid or absent, cannot remove an earlier layer\'s sensitive glob', LAYER_MIX.map((p) => hits('b/x', [with1('sensitive_paths', ['b']), p])[0]), LAYER_MIX.map(() => ['config']));
109
+ check('a later layer cannot remove an earlier layer\'s container, and an earlier layer cannot remove a later one\'s', LAYER_MIX.map((p) => [modules(['services/a/x', 'services/b/y'], [with1('module_containers', ['services']), p]), modules(['services/a/x', 'services/b/y'], [p, with1('module_containers', ['services'])])]), LAYER_MIX.map(() => [2, 2]));
110
+ check('one invalid key drops only itself: its sibling key and the other layers still apply', [
111
+ hits('good/x', sizing({ sensitive_paths: ['good'], module_containers: ['..'] }))[0], modules(['services/a/x', 'services/b/y'], sizing({ sensitive_paths: ['..'], module_containers: ['services'] })),
112
+ hits('good/x', [sizing({ sensitive_paths: ['..'] }), sizing({ sensitive_paths: ['good'] })])[0], hits('one/x', [sizing({ sensitive_paths: ['one', '..'] })])[0],
113
+ ], [['config'], 2, ['config'], []]);
114
+ check('config cannot remove a built-in glob even when it lists nothing or something else', [run(ALL, with1('sensitive_paths', [])).sensitive, run(ALL, sizing({ sensitive_paths: ['q'], module_containers: ['q'] })).files.map((f) => f.sensitive.length > 0)], [base.sensitive, [true, true, false, false, true, true]]);
115
+ check('a config cannot remove the ci class: it stays a sensitive hit with an empty list, an other list and a hostile one', [with1('sensitive_paths', []), with1('sensitive_paths', ['zzz']), with1('sensitive_paths', ['..']), null].map((c) => hits('.circleci/config.yml', c)[0].includes('ci')), [true, true, true, true]);
116
+
117
+ const WRAP = (g, p) => ({ config: with1('sensitive_paths', ['merged']), global: { path: null, present: true, config: g }, project: { path: 'p', present: true, config: p } });
118
+ check('loadConfig\'s {global, project} result is the layers [global.config, project.config]: an empty project list keeps the global glob, and the merged .config is not read', [
119
+ hits('zed/x', WRAP(with1('sensitive_paths', ['zed']), with1('sensitive_paths', [])))[0], hits('p/x', WRAP(with1('sensitive_paths', ['zed']), with1('sensitive_paths', ['p'])))[0],
120
+ hits('merged/x', WRAP({}, {}))[0], hits('zed/x', WRAP(with1('sensitive_paths', ['zed']), {}))[0], hits('zed/x', { global: {}, project: {} })[0],
121
+ ], [['config'], ['config'], [], ['config'], []]);
122
+
123
+ console.log('== path facts: caps count the folded text ==');
124
+ const FDFA = '\ufdfa'; // one character that folds to eighteen
125
+ const L = with1('sensitive_paths', ['q']);
126
+ check('a path whose fold exceeds the path cap is an unusable entry with the floor, one at the cap is usable', [one(FDFA.repeat(14)).denied, one(FDFA.repeat(14)).path, one(FDFA.repeat(13)).denied, one('a/'.repeat(119) + 'a').denied], [true, '', false, false]);
127
+ check('a glob whose fold exceeds the glob cap is refused and named, and so is one whose raw text does though its fold is short; one at the cap is accepted', [hits('q/x', with1('sensitive_paths', [FDFA.repeat(6)]))[0], run(['a.js'], with1('sensitive_paths', [FDFA.repeat(6)])).refused,
128
+ run(['a.js'], with1('sensitive_paths', ['e\u0301'.repeat(51)])).refused, run(['a.js'], with1('sensitive_paths', [FDFA.repeat(5)])).refused], [[], ['sensitive_paths'], ['sensitive_paths'], []]);
129
+ check('more layers than loadConfig supplies floor every path, and two do not', [run(['a.js'], [L, L, L]).files[0].denied, run(['a.js'], [L, L]).files[0].denied, run(['a.js'], [L, L]).files[0].path], [true, false, 'a.js']);
130
+ check('a refused key is named in refused, once, and a valid or absent one is not', [run(['a.js'], sizing({ sensitive_paths: ['*.'], module_containers: 'x' })).refused, run(['a.js'], [with1('sensitive_paths', 5), with1('sensitive_paths', 6)]).refused, run(['a.js'], sizing({ sensitive_paths: ['q'] })).refused, run(['a.js']).refused], [['module_containers', 'sensitive_paths'], ['sensitive_paths'], [], []]);
131
+
132
+ console.log('== path facts: the module override only splits ==');
133
+ const PAIR = ['packages/a/x', 'packages/b/y'];
134
+ check('an unconfigured repo counts packages/a and packages/b as two modules', modules(PAIR), 2);
135
+ const FOLDING = [undefined, {}, null, 'x', [], sizing({}), sizing(null), with1('module_containers', []), with1('module_containers', ['services']), with1('sensitive_paths', ['q']),
136
+ sizing({ module_containers: ['packages'] }), sizing({ module_containers: ['src'], sensitive_paths: [] }), sizing({ module_containers: 'packages' }), sizing({ module_containers: ['..', 'a/b'] }),
137
+ sizing({ module_containers: [], sensitive_paths: 7 }), { sizing: { module_containers: { packages: false } } }, { module_containers: [] }, sizing({ __proto__: { module_containers: [] } })];
138
+ const ROWS = ['packages/a/x', 'packages/b/y', 'src/a/y', 'services/a/x', 'services/b/y', 'README.md'];
139
+ check('still two with an empty container list, a config that omits the built-ins, and a config naming extra containers', FOLDING.map((c) => modules(PAIR, c)), FOLDING.map(() => 2));
140
+ check('no config in a finite table yields a module count below the unconfigured one', FOLDING.map((c) => modules(ROWS, c) >= modules(ROWS)), FOLDING.map(() => true));
141
+ check('extra containers raise the count and nothing else does', [modules(ROWS), modules(ROWS, with1('module_containers', ['services']))], [5, 6]);
142
+ check('one name under two containers is two modules, and two files in one module are one', [modules(['packages/a/x', 'src/a/y']), modules(['packages/a/x', 'packages/a/z']), one('src/a/y').module], [2, 1, 'src/a']);
143
+ check('the built-in containers are the stated list', BUILTIN_CONTAINERS, ['packages', 'apps', 'libs', 'src']);
144
+
145
+ console.log('== path facts: hostile config ==');
146
+ const HOSTILE = [
147
+ with1('sensitive_paths', ['x'.repeat(10000)]), with1('sensitive_paths', ['x'.repeat(MAX_GLOB_CHARS + 1)]), with1('sensitive_paths', ['..']), with1('sensitive_paths', ['a/../b']), with1('sensitive_paths', ['/etc/passwd']),
148
+ with1('sensitive_paths', ['C:\\x']), with1('sensitive_paths', ['\\x']), with1('sensitive_paths', 'abc'), with1('sensitive_paths', 5), with1('sensitive_paths', { a: 1 }), with1('sensitive_paths', [1]),
149
+ with1('sensitive_paths', ['']), with1('sensitive_paths', ['/']), with1('sensitive_paths', ['.']), with1('sensitive_paths', ['./']), with1('sensitive_paths', ['a\u0000b']), with1('sensitive_paths', ['a\u202eb']), with1('sensitive_paths', Array(MAX_GLOBS + 1).fill('q')),
150
+ with1('sensitive_paths', [' ']), with1('sensitive_paths', ['. ']), with1('sensitive_paths', ['*.']), with1('sensitive_paths', ['*/.']), with1('sensitive_paths', ['*\uff0f.']), with1('sensitive_paths', ['a/**. /b']), with1('module_containers', [' ']), with1('module_containers', ['. ']),
151
+ with1('module_containers', ['a/b']), with1('module_containers', ['..']), with1('module_containers', ['a\\b']), with1('module_containers', 'src'),
152
+ sizing({ sensitive_paths: ['good', '..'], module_containers: ['..'] }), with1('module_containers', ['*']), with1('module_containers', ['a*']), with1('module_containers', ['**']),
153
+ ];
154
+ const HOSTILE_PATHS = ['.env', 'good/x.js', 'services/a/x', 'services/b/y', 'q/z', 'src/routes/a.js', 'packages/a/x', 'packages/b/y', '../x', 'a/../b', 'etc/passwd', 'x', 'c:/x', 'a\u0000b', 'a\u202eb', 'a/b.js', 'a/c/x', 'a/d/y', 'x'.repeat(MAX_GLOB_CHARS + 1)];
155
+ const baseline = run(HOSTILE_PATHS);
156
+ check('a hostile section reads as the defaults: the same facts as no config', HOSTILE.map((c) => ({ ...run(HOSTILE_PATHS, c), refused: [] })), HOSTILE.map(() => baseline));
157
+ check('the caps are stated: a section at the limit is accepted', [hits('q', with1('sensitive_paths', Array(MAX_GLOBS).fill('q')))[0], hits('y'.repeat(MAX_GLOB_CHARS), with1('sensitive_paths', ['y'.repeat(MAX_GLOB_CHARS)]))[0]], [['config'], ['config']]);
158
+
159
+ // Pathological shapes in their own process with a clock, so a hang is a failed check and not a stuck suite.
160
+ const SHAPES = ['(a+)+$', '(a|aa)+$', 'a*a*a*a*a*a*a*a*a*a*b', '**/**/**/**/**/**/x', '*?*?*?*?*?*?*?*?c'];
161
+ const VICTIMS = [`${'a'.repeat(32)}!`, 'a/'.repeat(100), 'a'.repeat(200)];
162
+ // The real worst case under the caps (measured on the development machine): 40 paths, the cap, each of 119 segments with a trailing-dot segment and
163
+ // a U+FF0F, so all four readings differ, against two full layers (what loadConfig supplies) of 32 globs that keep every position alive (`**/a/` x19 and one
164
+ // of 31 adjacent **): about 2.5 s in-process, about 60 ms a path. The caps on the folded text are what bound it: before them a glob of `*` and 98 `?` against
165
+ // U+FDFA paths took 17 s. This check times 20 such paths, about 1.3 s, against a 2.6 s bound; the quadratic-step mutant takes about 5.4 s: a margin of about 2x each side.
166
+ // A caller with many paths bounds the total itself (escalation-facts reads the clock between chunks).
167
+ const GLOBS = Array.from({ length: MAX_GLOBS }, (_, i) => (i ? '**/a/'.repeat(19) : '**/'.repeat(31)) + 'z');
168
+ const WORST = `${'a/'.repeat(58)}a./${'a/'.repeat(30)}a/${'a/'.repeat(28)}a`;
169
+ // Adjacent ** in a glob are one step: 64 globs of 31 of them on the same paths take about 0.12 s collapsed (40 paths) and about 2.2 s without the collapse; bound 1 s.
170
+ const STARS = Array(MAX_GLOBS).fill(`${'**/'.repeat(31)}z`);
171
+ const child = `import * as M from ${JSON.stringify(pathToFileURL(modPath).href)};
172
+ const jobs = JSON.parse(process.argv[1]);
173
+ console.log(JSON.stringify(jobs.map(({ paths, layers }) => M.classifyPaths(paths, layers.map((globs) => ({ sizing: { sensitive_paths: globs } }))).sensitive)));`;
174
+ const timedJobs = (jobs, boundMs) => spawnSync(process.execPath, ['--input-type=module', '-e', child, JSON.stringify(jobs)], { encoding: 'utf8', timeout: boundMs });
175
+ const outcome = (t) => (t.status === 0 ? JSON.parse(t.stdout) : `child ended ${t.status ?? t.signal}`);
176
+ // fact-sheet.sh sets SKIP_TIMED=mutant-run for the scratch mutants that these checks do not name, so most of them need not wait for the child.
177
+ // Only that exact value skips: a stray exported SKIP_TIMED=1 never turns the cost check off, here or when this lib is run directly.
178
+ // Residual, stated: the stray-seam check there runs the real module with SKIP_TIMED=1, not a stale copy that is named like a sentinel; the guard is the exact comparison below.
179
+ const skipTimed = process.env.SKIP_TIMED === 'mutant-run';
180
+ const SHAPE_JOBS = SHAPES.map((s) => ({ paths: VICTIMS, layers: [[s]] }));
181
+ if (skipTimed) skip('nested-quantifier shapes, star runs and two layers of the largest glob list', 'SKIP_TIMED=mutant-run is set by the mutation runs that do not name this check');
182
+ else check('nested-quantifier shapes, star runs and two layers of the largest glob list on 119-segment paths with four readings finish inside the time bound and match nothing',
183
+ outcome(timedJobs([...SHAPE_JOBS, { paths: Array(20).fill(WORST), layers: [GLOBS, GLOBS] }], 2600)), [...SHAPES.map(() => []), []]);
184
+ if (skipTimed) skip('adjacent ** segments in a glob are one step', 'SKIP_TIMED=mutant-run is set by the mutation runs that do not name this check');
185
+ else check('adjacent ** segments in a glob are one step: 64 globs of 31 of them on 40 four-reading paths finish inside the time bound', outcome(timedJobs([{ paths: Array(40).fill(WORST), layers: [STARS, STARS] }], 1000)), [[]]);
186
+ check('a nested-quantifier glob is literal text: it matches only itself', [hits('(a+)+$', with1('sensitive_paths', ['(a+)+$']))[0], hits('a', with1('sensitive_paths', ['(a+)+$']))[0]], [['config'], []]);
187
+
188
+ console.log('== path facts: no content ==');
189
+ const SECRET = 'TOPSECRET-FILE-CONTENT';
190
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'path-facts-')); process.on('exit', () => fs.rmSync(dir, { recursive: true, force: true }));
191
+ fs.mkdirSync(path.join(dir, 'src')); fs.writeFileSync(path.join(dir, 'src/a.js'), SECRET); fs.writeFileSync(path.join(dir, '.env'), SECRET);
192
+ const result = run(['src/a.js', '.env', 'src/b.js']);
193
+ check('a result holds only the fixed fact fields, none of the file text', [JSON.stringify(result).includes(SECRET), Object.keys(result), Object.keys(result.files[0])], [false,
194
+ ['files', 'production_files', 'modules', 'sensitive', 'boundary', 'contract', 'refused'], ['path', 'denied', 'production', 'module', 'sensitive', 'boundary', 'contract']]);
195
+ check('the module touches no filesystem API', /node:fs|readFile|openSync|statSync/.test(fs.readFileSync(modPath, 'utf8')), false);
196
+
197
+ console.log(`SUMMARY ${pass + fail} ${fail}`);
198
+ process.exit(fail ? 1 : 0);
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env node
2
+ // Tests of scripts/lib/path-safety.mjs. Risk: a model-named path reaching the filesystem outside the project or a
3
+ // secret inside it. Real temp tree, no mocks; the only seams are the module's own (`realpath`, `constants`). Usage:
4
+ // node path-safety-tests.mjs <module path>; tests/scripts/fact-sheet.sh runs it on the module and on scratch
5
+ // mutants of it, and each mutant must turn the test named there red. Hermetic: no model, no network, no randomness.
6
+
7
+ import { spawnSync } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { isDeepStrictEqual } from 'node:util';
12
+ import { fileURLToPath, pathToFileURL } from 'node:url';
13
+
14
+ const modPath = path.resolve(process.argv[2]);
15
+ const M = await import(pathToFileURL(modPath).href);
16
+ const { inspectPath, denyListed, refuseList, REFUSAL_IDS, MAX_PATHS, MAX_PATH_CHARS, MAX_FILE_BYTES } = M;
17
+
18
+ const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'path-safety-')));
19
+ process.on('exit', () => { try { fs.chmodSync(path.join(base, 'root', 'locked'), 0o700); } catch { /* already gone */ } fs.rmSync(base, { recursive: true, force: true }); });
20
+ const root = path.join(base, 'root');
21
+ const put = (rel, body = 'x') => { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), body); };
22
+ put('a.txt', 'hello'); put('sub/b.txt'); put('..x'); put('locked/.env'); put('locked/f.txt'); put('config/secret.txt');
23
+ fs.mkdirSync(path.join(root, 'folder')); fs.mkdirSync(path.join(base, 'outside'));
24
+ fs.writeFileSync(path.join(base, 'outside', 'secret.txt'), 'outside');
25
+ fs.symlinkSync('a.txt', path.join(root, 'link.txt')); fs.symlinkSync('sub', path.join(root, 'linkdir'));
26
+ fs.symlinkSync('../outside/secret.txt', path.join(root, 'escape.txt')); fs.symlinkSync('../outside/secret.txt', path.join(root, '.env'));
27
+ fs.writeFileSync(path.join(root, 'big.bin'), Buffer.alloc(MAX_FILE_BYTES + 1)); fs.writeFileSync(path.join(root, 'max.bin'), Buffer.alloc(MAX_FILE_BYTES));
28
+ const fifo = spawnSync('mkfifo', [path.join(root, 'pipe')]).status === 0;
29
+ fs.chmodSync(path.join(root, 'locked'), 0o000);
30
+
31
+ let pass = 0; let fail = 0;
32
+ const skip = (name, why) => console.log(` skip ${name} (${why})`);
33
+ const check = (name, got, want) => {
34
+ if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
35
+ };
36
+ // A throw is reported as a result, so a broken module fails the named check instead of ending the run.
37
+ const ins = (raw, probe, seams) => { try { return inspectPath(root, raw, probe, seams); } catch { return { kind: 'threw' }; } };
38
+ const refusalOf = (raw, seams) => { const r = ins(raw, null, seams); return r.kind === 'refused' ? r.refusal : r.kind; };
39
+ const refusals = (list, seams) => list.map((p) => refusalOf(p, seams));
40
+ const same = (n, v) => Array(n).fill(v);
41
+ const DENIED = { kind: 'denied' };
42
+
43
+ // Runs fn with the filesystem entry points counted; returns the names called.
44
+ const WATCH = ['lstatSync', 'statSync', 'openSync', 'fstatSync', 'closeSync', 'readSync', 'readFileSync', 'accessSync', 'existsSync', 'readdirSync', 'readlinkSync', 'opendirSync'];
45
+ function watched(fn) {
46
+ const calls = []; const saved = {}; const realpath = fs.realpathSync; const native = realpath.native;
47
+ for (const n of WATCH) { saved[n] = fs[n]; fs[n] = (...a) => { calls.push(n); return saved[n](...a); }; }
48
+ fs.realpathSync = Object.assign((...a) => { calls.push('realpathSync'); return realpath(...a); }, { native: (...a) => { calls.push('realpathSync.native'); return native(...a); } });
49
+ try { fn(); } finally { fs.realpathSync = realpath; for (const n of WATCH) fs[n] = saved[n]; }
50
+ return calls;
51
+ }
52
+
53
+ // A call in its own process with a clock, so a hang is a failed check and not a stuck suite.
54
+ // `swap` stands in for a file replaced by another between the walk and the open: the canonical path becomes it.
55
+ function inChild(raw, swap = '') {
56
+ const seam = 'process.argv[3] ? { realpath: (p) => (p.endsWith(process.argv[2]) ? process.argv[3] : fs.realpathSync.native(p)) } : undefined';
57
+ const code = `import fs from 'node:fs'; import * as M from ${JSON.stringify(pathToFileURL(modPath).href)}; console.log(JSON.stringify(M.inspectPath(process.argv[1], process.argv[2], null, ${seam})));`;
58
+ const r = spawnSync(process.execPath, ['--input-type=module', '-e', code, root, raw, swap], { encoding: 'utf8', timeout: 5000 });
59
+ return r.status === 0 ? JSON.parse(r.stdout) : `child ended ${r.status ?? r.signal}`;
60
+ }
61
+
62
+ console.log('== path safety: refusing malformed names ==');
63
+ check('refuses an absolute path, a drive path and a UNC path', refusals(['/etc/passwd', 'C:\\x', 'c:x', '\\\\srv\\share\\x', '\\x']), same(5, 'absolute'));
64
+ check('refuses a parent segment in any position or separator', refusals(['../a.txt', 'sub/../../a.txt', 'sub\\..\\..\\a.txt', 'a/..', '.. /x', '..../x']), same(6, 'traversal'));
65
+ check('refuses NUL and control characters', refusals(['a\0.txt', 'a\n.txt', 'a\u001b[0m', 'a\u007f', 'a\u0085']), same(5, 'control'));
66
+ check('refuses bidi, zero-width and line-separator characters', refusals(['\u202eagro.txt', 'a\u2066b', 'a\u200bb', 'a\u2028b', 'a\ufeffb']), same(5, 'control'));
67
+ check('refuses lone surrogates and keeps paired ones', [refusals(['a\ud800b', '\udc00']), ins('\u{1F600}.txt').kind], [same(2, 'control'), 'contained']);
68
+ check('refuses an empty, dot-only or non-string name', refusals(['', '.', './', './/.', 5, null, undefined, {}, ['a.txt']]), same(9, 'malformed'));
69
+ const LONG = `${'.'.repeat(10000)}x`; // long enough that a quadratic trim costs seconds, short enough to keep the suite quick
70
+ const t0 = performance.now();
71
+ const longResults = [ins(LONG), refuseList(Array(MAX_PATHS + 1).fill(LONG)), refuseList([LONG]), denyListed(LONG)];
72
+ check('a huge name is refused as path_length and denied, in bounded time', [longResults, performance.now() - t0 < 500], [[{ kind: 'refused', refusal: 'path_length', denied: true }, { kind: 'refused', refusal: 'path_count', denied: true }, null, true], true]);
73
+ check('refuses a name over the length cap and accepts one at it', [refusalOf('a'.repeat(MAX_PATH_CHARS + 1)), ins('a'.repeat(MAX_PATH_CHARS))], ['path_length', { kind: 'contained', exists: false, rel: 'a'.repeat(MAX_PATH_CHARS) }]);
74
+ check('refuses a list over the count cap and accepts one at it', [refuseList(Array(MAX_PATHS + 1).fill('a.txt')), refuseList(Array(MAX_PATHS).fill('a.txt')), refuseList('a.txt')], [{ kind: 'refused', refusal: 'path_count' }, null, { kind: 'refused', refusal: 'malformed' }]);
75
+ check('a list over the cap keeps the denied fact of any name in it', refuseList([...Array(MAX_PATHS).fill('a.txt'), '.env']), { kind: 'refused', refusal: 'path_count', denied: true });
76
+ check('a list far over the cap is refused as denied without being scanned', [refuseList(same(4 * MAX_PATHS + 1, 'a.txt')), refuseList(same(4 * MAX_PATHS, 'a.txt'))], [{ kind: 'refused', refusal: 'path_count', denied: true }, { kind: 'refused', refusal: 'path_count' }]);
77
+ const marker = 'SECRETMARK\u00e9';
78
+ const hostile = [`../${marker}`, `/${marker}`, `${marker}\0`, `${marker}/nope/x`, `${marker}/a.txt`, `x${'y'.repeat(MAX_PATH_CHARS)}${marker}`];
79
+ const out = JSON.stringify(hostile.map((p) => ins(p)));
80
+ check('refusals are closed ASCII ids and never contain the input', [REFUSAL_IDS.every((id) => /^[a-z_]+$/.test(id)), Object.isFrozen(REFUSAL_IDS), out.includes('SECRETMARK'), /^[\x20-\x7e]*$/.test(out)], [true, true, false, true]);
81
+ check('every refusal the suite saw is in the closed list', [...new Set(hostile.map((p) => refusalOf(p)))].every((id) => REFUSAL_IDS.includes(id)), true);
82
+
83
+ console.log('== path safety: the deny list is name-only ==');
84
+ const SECRET_NAMES = ['.env', 'cfg/.env.local', 'id_rsa', 'k/id_rsa.pub', 'id_dsa', 'id_ecdsa', 'id_ed25519', 'a.pem', 'a.key', 'a.p12', 'a.pfx', 'a.crt', 'a.cer', 'a.der', 'a.jks', 'a.keystore', 'a.ppk', '.git/config', 'sub/.git/HEAD', '.git',
85
+ '.npmrc', 'h/.netrc', '.git-credentials', '.pypirc', '.pgpass', 'terraform.tfstate', 'a.tfvars', 'a.kdbx', '.ssh/config', 'x/.gnupg/k', '.aws/credentials',
86
+ 'prod.netrc', 'x.pgpass', 'credentials.json', 'gcp/Credentials.JSON', 'service-account.json', 'service_account.json', 'serviceAccountKey.json', 'service-account-prod.json', 'client_secret.json', 'client_secret_123.apps.json', 'terraform.tfstate.backup', 'prod.tfstate.backup',
87
+ 'key.json', 'gcp/Key.JSON', 'key.json.', 'prod.tfstate.1600000000.backup'];
88
+ check('denies .env, key and certificate file names and any .git segment', refusals(SECRET_NAMES), same(SECRET_NAMES.length, 'denied'));
89
+ const TERMINATED = ['service-account\nprod.json', 'client_secret\u2028x.json', 'client_secret\r\ny.json', 'prod.tfstate.\n.backup', 'prod.tfstate.1\u2029.backup'];
90
+ check('denies a name with a line terminator inside the matched span, and the refusal keeps the denied fact', [TERMINATED.filter((n) => !denyListed(n)), TERMINATED.map((n) => inspectPath(root, n).denied)], [[], same(TERMINATED.length, true)]);
91
+ check('credentials/ is denied as a directory, with anything under it', ['credentials/token.txt', 'a/credentials/b/c', 'credentials\\x'].map(denyListed), same(3, true));
92
+ check('does not deny look-alikes', ['.gitignore', '.github/workflows/a.yml', 'environment.md', 'src/keyboard.js', 'key.txt', 'sub/b.txt', 'a.pem.txt', 'notes~.txt', 'terraform.tf', '.aws.md', 'ssh/a'].map(denyListed), same(11, false));
93
+ check('does not deny the look-alikes of the added names', ['credentials.md', 'account.json', 'service-account.md', 'service.json', 'netrc.md', 'netrc', 'pgpass', 'client_secret.md', 'client-secret.txt', 'a.tfstate.bak', 'notes.backup', 'tfstate.backup.md', 'credentials.json.md', 'monkey.json', 'key.json.md', 'prod.tfstate.1600000000.bak'].filter(denyListed), []);
94
+ check('a bare config stays allowed on purpose, as a file and as a directory, while the secret-bearing configs are denied by their segment', [['config', 'config/app.yml', 'src/config', 'config.json'].filter(denyListed), ['.git/config', '.ssh/config', '.aws/config', '.kube/config', '.docker/config.json'].filter((n) => !denyListed(n))], [[], []]);
95
+ const HOOK_NAMES = ['gcp-key.json', 'a/b-credentials.json', 'service-account.json', 'service-account-prod.json', 'secret.yaml', 'secrets.yaml', 'secret.yml', 'config/secrets.yml', 'secret.json', 'secrets.json', 'credentials', 'x/credentials',
96
+ 'a.tfstate', '_netrc', '_pgpass', '.htpasswd', 'a.p8', '.vault-token', '.kube/config', 'x/.docker/config.json'];
97
+ check('denies the secret names the repository secret-write hook denies', HOOK_NAMES.filter((n) => !denyListed(n)), []);
98
+ check('does not deny look-alikes of those names', ['credentials.md', 'terraform.tf', 'service-account.md', 'secrets.md', 'secret.txt', 'secretsanta.json', 'monkey.json', 'key.json.md', 'a.mp8', 'htpasswd', 'vault-token', 'netrc', 'a.tfstates', '.dockerignore', '.kubernetes', 'docs/kube/a'].filter(denyListed), []);
99
+ // Parity with the secret-write hook (hooks/pre-tool/block-secret-writes.mjs, the file hooks.json runs; common.mjs holds only
100
+ // the matching helpers). Each SECRET_PATTERNS literal is read from the hook's source with its flags, built with
101
+ // new RegExp, and must match the basename of its own representative: the widest name it matches (an unanchored
102
+ // suffix gets `a.<suffix>`, so the overlap with a prefix or exact rule cannot hide a gap). Every representative must be
103
+ // denied here. The hook runs on import and exports nothing, so its text is the only way to read the list.
104
+ // `^config$` is the one pattern whose basename is allowed here (see NAME_EXACT): its representative is denied through
105
+ // the `.aws` segment, and a bare `config` is pinned as allowed above.
106
+ const HOOK_TABLE = [
107
+ [String.raw`/^\.env$/`, '.env'], [String.raw`/^\.env\.local$/`, '.env.local'], [String.raw`/^\.env\.production$/`, '.env.production'], [String.raw`/^\.env\.prod$/`, '.env.prod'],
108
+ [String.raw`/^\.env\.staging$/`, '.env.staging'], [String.raw`/^\.env\.secret$/`, '.env.secret'], [String.raw`/\.pem$/`, 'a.pem'], [String.raw`/\.key$/`, 'a.key'], [String.raw`/\.p12$/`, 'a.p12'],
109
+ [String.raw`/\.pfx$/`, 'a.pfx'], [String.raw`/\.jks$/`, 'a.jks'], [String.raw`/^id_rsa$/`, 'id_rsa'], [String.raw`/^id_ed25519$/`, 'id_ed25519'], [String.raw`/^id_ecdsa$/`, 'id_ecdsa'],
110
+ [String.raw`/^id_dsa$/`, 'id_dsa'], [String.raw`/^credentials$/`, 'credentials'], [String.raw`/^config$/`, '.aws/config'], [String.raw`/-key\.json$/`, 'gcp-key.json'],
111
+ [String.raw`/-credentials\.json$/`, 'gcp-credentials.json'], [String.raw`/service-account.*\.json$/`, 'my-service-account-prod.json'], [String.raw`/\.netrc$/`, 'prod.netrc'],
112
+ [String.raw`/\.pgpass$/`, 'prod.pgpass'], [String.raw`/\.kdbx$/`, 'a.kdbx'], [String.raw`/secrets?\.ya?ml$/`, 'my-secrets.yml'], [String.raw`/secrets?\.json$/`, 'my-secrets.json'],
113
+ ];
114
+ // SECRET_HOOK_SOURCE is a seam for fact-sheet.sh's hook mutants only: it is read when it names a file called hook-mutant.mjs, so a
115
+ // stray exported value (a stale copy, /dev/null) can never repoint the parity check, here or when this lib is run directly.
116
+ const hookSeam = path.basename(process.env.SECRET_HOOK_SOURCE ?? '') === 'hook-mutant.mjs' ? process.env.SECRET_HOOK_SOURCE : undefined;
117
+ const hookFile = hookSeam ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../hooks/pre-tool/block-secret-writes.mjs');
118
+ // The block runs from its opening line to the first line that is just `];`, so a character class inside a pattern cannot end it early.
119
+ const hookLiterals = (() => {
120
+ try {
121
+ if (fs.statSync(hookFile).size > 65536) return null;
122
+ const block = /const SECRET_PATTERNS = \[\n([\s\S]*?)\n\];/.exec(fs.readFileSync(hookFile, 'utf8'));
123
+ if (!block) return null;
124
+ const lines = block[1].split('\n').filter((l) => l.trim() !== '' && !l.trim().startsWith('//'));
125
+ const found = lines.map((l) => /^\s*(\/(.+)\/([a-z]*)),\s*(?:\/\/.*)?$/.exec(l));
126
+ return { patterns: found.filter(Boolean).map((m) => ({ literal: m[1], source: m[2], flags: m[3] })), unparsed: found.filter((m) => !m).length };
127
+ } catch { return null; }
128
+ })();
129
+ const parsed = hookLiterals?.patterns ?? [];
130
+ const repOf = new Map(HOOK_TABLE);
131
+ // A pattern whose flags changed has no row of its own; it is still tried against the representative of its body.
132
+ const repOfBody = new Map(HOOK_TABLE.map(([literal, rep]) => [literal.slice(1, literal.lastIndexOf('/')), rep]));
133
+ const hookBase = (rep) => rep.replace(/\\/g, '/').split('/').pop();
134
+ check('the hook secret-name patterns and the representative table list the same literals, flags included, and every line parses', [hookLiterals !== null, hookLiterals?.unparsed, parsed.filter((p) => !repOf.has(p.literal)).map((p) => p.literal), HOOK_TABLE.map(([l]) => l).filter((l) => !parsed.some((p) => p.literal === l))], [true, 0, [], []]);
135
+ check('each hook pattern, built with its own flags, matches the basename of its representative', parsed.filter((p) => { const rep = repOf.get(p.literal) ?? repOfBody.get(p.source); return rep !== undefined && !new RegExp(p.source, p.flags).test(hookBase(rep)); }).map((p) => p.literal), []);
136
+ check('every representative of a hook pattern is denied here', HOOK_TABLE.filter(([, rep]) => !denyListed(rep)).map(([l]) => l), []);
137
+ const WIN = ['ENV~1', 'ENV~1.LOC', 'GIT~1/config', 'key.pem::$DATA', 'a/b:c'];
138
+ check('denies Windows short names and stream suffixes', refusals(WIN), same(WIN.length, 'denied'));
139
+ const CASED = ['.ENV', '.Env.local', 'ID_RSA', 'Key.PEM', '.Git/config', '.GIT/hooks/x', 'CERT.Crt'];
140
+ check('floors drive-letter paths and ~<digit> names as denied, on purpose', ['C:\\x', 'c:x', 'file~1.txt', 'notes~2'].map(denyListed), same(4, true));
141
+ check('denies case variants exactly as the lower-case forms', refusals(CASED), same(CASED.length, 'denied'));
142
+ check('denies a name that only full case folding reads as denied', refusals(['.pgpa\u00df', '.\u00dfh']), same(2, 'denied'));
143
+ check('denies a name written with another separator, a trailing dot or space, or compatibility characters', refusals(['sub\\.env', '.git\\config', '.env.', 'Key.pem ', '\uff0eenv', '.\uff45\uff4e\uff56', '\uff49\uff44_rsa']), same(7, 'denied'));
144
+ const FOLDED_SEP = ['x\uff0f.env', 'service-account\uff0fprod.json', 'client_secret\uff0fx.json', 'a\uff3c.git', 'service-account\ufe68prod.json', 'client_secret\u2100x.json', 'client_secret\u2105x.json'];
145
+ check('denies a name whose compatibility fold writes a separator: the segment whole and its pieces both count', refusals(FOLDED_SEP), same(FOLDED_SEP.length, 'denied'));
146
+ check('a fold-to-separator code point does not deny a plain name', ['a\uff0fb.txt', 'a\ufe68b', 'src\u2100main.js'].map(denyListed), same(3, false));
147
+ check('a deny-listed name is decided without any filesystem call, for a root that does not exist too', [watched(() => { inspectPath(root, '.env'); inspectPath(root, 'sub/.GIT/x'); inspectPath('/nonexistent-root', 'a.pem', null, { realpath: () => { throw new Error('called'); } }); })], [[]]);
148
+ check('denied names make no call to the injected realpath', (() => { let n = 0; ins('.env', null, { realpath: (p) => { n++; return p; } }); return n; })(), 0);
149
+ check('a missing, a symlinked and an unreadable-directory .env give the same result', [ins('nothing/.env'), ins('.env'), ins('locked/.env'), ins('.env.missing')], same(4, DENIED));
150
+ check('a deny-listed name with a missing parent or in a non-directory is still denied', [ins('a.txt/.env'), ins('nope/deeper/key.pem')], same(2, DENIED));
151
+ check('a malformed deny-listed name returns the refusal id and denied: true', [ins('../../.env'), ins('/x/id_rsa'), ins('a\0/.env'), ins('.git/../x'), ins('x'.repeat(MAX_PATH_CHARS + 1) + '/.env')], [['traversal'], ['absolute'], ['control'], ['traversal'], ['path_length']].map(([refusal]) => ({ kind: 'refused', refusal, denied: true })));
152
+ check('a malformed name that is not deny-listed carries no denied fact', [ins('../x'), ins('/etc/passwd')], [{ kind: 'refused', refusal: 'traversal' }, { kind: 'refused', refusal: 'absolute' }]);
153
+ const canon = (to) => (p) => (p.endsWith(`${path.sep}secret.txt`) ? p.replace('secret.txt', to) : fs.realpathSync.native(p));
154
+ check('a path whose canonical on-disk spelling is a denied name is denied with no open', [ins('config/secret.txt', null, { realpath: canon('KEY.PEM') }), watched(() => ins('config/secret.txt', null, { realpath: canon('KEY.PEM') })).filter((c) => c === 'openSync')], [DENIED, []]);
155
+ check('the canonical re-check also covers a .git directory spelled differently', ins('config/secret.txt', null, { realpath: (p) => (p.endsWith('secret.txt') ? path.join(root, '.GIT', 'secret.txt') : fs.realpathSync.native(p)) }), DENIED);
156
+ check('the canonical path from the injected realpath is the one reported', ins('config/secret.txt', null, { realpath: (p) => (p.endsWith('secret.txt') ? path.join(root, 'sub', 'b.txt') : fs.realpathSync.native(p)) }).rel, 'sub/b.txt');
157
+
158
+ console.log('== path safety: containment and plain files ==');
159
+ check('refuses a symlinked file, a file under a symlinked directory and a symlink that leaves the root', refusals(['link.txt', 'linkdir/b.txt', 'linkdir', 'escape.txt']), same(4, 'symlink'));
160
+ check('refuses a path whose canonical form leaves the root, is the root, or is its parent', refusals(['a.txt'], { realpath: (p) => (p.endsWith('a.txt') ? path.join(base, 'outside', 'secret.txt') : fs.realpathSync.native(p)) }).concat(refusals(['a.txt', 'sub/b.txt'], { realpath: (p) => (p.endsWith('b.txt') ? base : p.endsWith('a.txt') ? root : fs.realpathSync.native(p)) })), same(3, 'escape'));
161
+ check('a file whose name begins with two dots is inside the root', ins('..x', null).kind, 'contained');
162
+ check('refuses a link swapped in after the check, because the open does not follow it', refusalOf('a.txt', { realpath: (p) => (p.endsWith('a.txt') ? path.join(root, 'link.txt') : fs.realpathSync.native(p)) }), 'symlink');
163
+ const swapTo = (rel) => ({ realpath: (p) => (p.endsWith('a.txt') ? path.join(root, rel) : fs.realpathSync.native(p)) });
164
+ check('refuses a directory, a path through a file, a path under a missing directory, and a directory swapped in', [refusalOf('folder'), refusalOf('a.txt/x'), refusalOf('nope/new.txt'), refusalOf('a.txt', swapTo('folder'))], ['not_file', 'not_file', 'no_parent', 'not_file']);
165
+ check('a FIFO is refused and the call returns, also when swapped in after the check', fifo ? [inChild('pipe'), inChild('a.txt', path.join(root, 'pipe'))] : 'no mkfifo', same(2, { kind: 'refused', refusal: 'not_file' }));
166
+ check('a device is refused', fs.existsSync('/dev/null') ? inspectPath('/dev', 'null') : 'no /dev/null', { kind: 'refused', refusal: 'not_file' });
167
+ check('refuses a file over the size cap and accepts one at it', [refusalOf('big.bin'), ins('max.bin').size], ['file_size', MAX_FILE_BYTES]);
168
+ // Linux only: NAME_MAX counts bytes there (255), so 128 two-byte characters are over it; APFS counts characters and accepts them.
169
+ const longName = '\u00e9'.repeat(128);
170
+ if (process.platform !== 'linux') skip('a name the filesystem cannot look up is refused as unreadable', 'not Linux: the name limit counts bytes only there');
171
+ else check('a name the filesystem cannot look up is refused as unreadable, for any user', refusalOf(longName), 'unreadable');
172
+ if (process.getuid?.() === 0) skip('a file in an unreadable directory is refused as unreadable', 'running as root, which reads it');
173
+ else check('a file in an unreadable directory is refused as unreadable', refusalOf('locked/f.txt'), 'unreadable');
174
+ check('an unreadable root is refused, not read through', inspectPath(path.join(base, 'no-root'), 'a.txt'), { kind: 'refused', refusal: 'unreadable' });
175
+ check('a new path in the root or in an existing directory is contained', [ins('new.txt'), ins('sub\\new.txt')], [{ kind: 'contained', exists: false, rel: 'new.txt' }, { kind: 'contained', exists: false, rel: 'sub/new.txt' }]);
176
+ check('a Windows-style separator reaches the same file', ins('sub\\b.txt'), { kind: 'contained', exists: true, rel: 'sub/b.txt', size: 1 });
177
+ check('a plain file is contained with its size and no content', ins('a.txt'), { kind: 'contained', exists: true, rel: 'a.txt', size: 5 });
178
+ check('result keys per kind are fixed: nothing carries file content', [ins('a.txt', () => true), ins('new.txt'), ins('.env'), ins('../x'), ins('..x', () => false)].map((r) => Object.keys(r).sort().join()), ['answer,exists,kind,rel,size', 'exists,kind,rel', 'kind', 'kind,refusal', 'answer,exists,kind,rel,size']);
179
+
180
+ console.log('== path safety: the descriptor ==');
181
+ check('the probe gets an open descriptor and the size and its answer is a boolean', [ins('a.txt', (fd, size) => size === 5 && fs.readSync(fd, Buffer.alloc(5), 0, 5, 0) === 5).answer, ins('a.txt', () => 'hello').answer, ins('a.txt', () => 1).answer], [true, false, false]);
182
+ const openClose = (fn) => { const c = watched(fn); return [c.filter((n) => n === 'openSync').length, c.filter((n) => n === 'closeSync').length]; };
183
+ check('the descriptor is closed after a probe, after a refusal and after a probe that throws', [openClose(() => ins('a.txt', () => true)), openClose(() => ins('a.txt', null, swapTo('folder'))), openClose(() => ins('big.bin')), openClose(() => { try { inspectPath(root, 'a.txt', () => { throw new Error('probe'); }); } catch { /* only reached by a module that rethrows */ } })], same(4, [1, 1]));
184
+ const failingClose = (probe) => { const real = fs.closeSync; fs.closeSync = (fd) => { real(fd); throw new Error('EIO'); }; try { return ins('a.txt', probe); } finally { fs.closeSync = real; } };
185
+ check('a close that fails is unreadable with no probe, and the probe refusal with one', [failingClose(null), failingClose(() => true)], [{ kind: 'refused', refusal: 'unreadable' }, { kind: 'refused', refusal: 'probe' }]);
186
+ check('a probe that closes the descriptor is a refusal, not a throw', ins('a.txt', (fd) => { fs.closeSync(fd); return true; }), { kind: 'refused', refusal: 'probe' });
187
+ check('an error from the probe is a refusal and its message does not leave', ins('a.txt', () => { throw new Error('PROBEMSG'); }), { kind: 'refused', refusal: 'probe' });
188
+ check('a path that does not exist, a directory or a FIFO opens nothing', openClose(() => { ins('new.txt'); ins('folder'); ins('pipe'); }), [0, 0]);
189
+ const openFlags = () => { const real = fs.openSync; const seen = []; fs.openSync = (p, f, ...r) => { seen.push(f); return real(p, f, ...r); }; try { ins('a.txt'); } finally { fs.openSync = real; } return seen; };
190
+ check('the open follows no link, cannot block, and never takes a controlling terminal', openFlags().map((f) => [fs.constants.O_NOFOLLOW, fs.constants.O_NONBLOCK, fs.constants.O_NOCTTY ?? 0].every((b) => (f & b) === b)), [true]);
191
+ const spied = watched(() => ins('a.txt'));
192
+ check('the filesystem spy sees the calls a contained path makes', [spied.includes('lstatSync'), spied.includes('realpathSync.native')], [true, true]);
193
+
194
+ console.log('== path safety: a platform without O_NOFOLLOW ==');
195
+ const noFollow = { ...fs.constants, O_NOFOLLOW: undefined }; const noBlock = { ...fs.constants, O_NONBLOCK: undefined };
196
+ check('fails closed with `platform` for every reading call', [refusalOf('a.txt', { constants: noFollow }), refusalOf('new.txt', { constants: noFollow }), refusalOf('a.txt', { constants: noBlock }), refusalOf('a.txt', { constants: {} })], same(4, 'platform'));
197
+ check('still decides names without the flag: denied stays denied and malformed keeps its id', [ins('.env', null, { constants: noFollow }), ins('../.env', null, { constants: noFollow }), ins('../x', null, { constants: noFollow })], [DENIED, { kind: 'refused', refusal: 'traversal', denied: true }, { kind: 'refused', refusal: 'traversal' }]);
198
+ check('never opens without the flag', watched(() => ins('a.txt', null, { constants: noFollow })).filter((c) => c === 'openSync'), []);
199
+
200
+ console.log(`SUMMARY ${pass + fail} ${fail}`);
201
+ process.exit(fail ? 1 : 0);