@orion-qa/orion 3.1.0 → 3.3.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 (113) hide show
  1. package/.claude/agents/automation-strategist.md +1 -0
  2. package/.claude/agents/change-agent.md +1 -0
  3. package/.claude/agents/codebase-analyst.md +2 -1
  4. package/.claude/agents/environment-discovery.md +1 -0
  5. package/.claude/agents/evidence-validator.md +1 -0
  6. package/.claude/agents/executor.md +1 -0
  7. package/.claude/agents/failure-analyst.md +2 -1
  8. package/.claude/agents/implementer.md +2 -1
  9. package/.claude/agents/requirement-analyst.md +1 -0
  10. package/.claude/agents/reviewer.md +1 -0
  11. package/.claude/agents/test-reporter.md +1 -0
  12. package/.claude/settings.json +17 -0
  13. package/.claude/skills/architecture-analysis/SKILL.md +1 -1
  14. package/.claude/skills/automation-implementation/SKILL.md +7 -5
  15. package/.claude/skills/automation-review/references/assertion-guard.md +1 -1
  16. package/.claude/skills/code-review/SKILL.md +2 -0
  17. package/.claude/skills/documentation/SKILL.md +1 -1
  18. package/.claude/skills/execution/SKILL.md +5 -4
  19. package/.claude/skills/orion/SKILL.md +12 -7
  20. package/.claude/skills/orion/references/assess-fix.md +5 -4
  21. package/.claude/skills/orion/references/batch.md +64 -0
  22. package/.claude/skills/orion/references/blockers.md +1 -1
  23. package/.claude/skills/orion/references/conversation.md +56 -25
  24. package/.claude/skills/orion/references/delivery-formats.md +23 -35
  25. package/.claude/skills/orion/references/doctor.md +1 -1
  26. package/.claude/skills/orion/references/greeting.md +23 -0
  27. package/.claude/skills/orion/references/hosts.md +3 -2
  28. package/.claude/skills/orion/references/modes.md +4 -2
  29. package/.claude/skills/orion/references/plain-language.md +57 -0
  30. package/.claude/skills/orion/references/project-context-files.md +2 -1
  31. package/.claude/skills/orion/references/recovery-loop.md +8 -0
  32. package/.claude/skills/orion/references/setup-card.md +18 -3
  33. package/.claude/skills/orion/references/status-lines.md +10 -4
  34. package/.claude/skills/orion/scripts/batch_detect.mjs +98 -0
  35. package/.claude/skills/orion/scripts/batch_state.mjs +179 -0
  36. package/.claude/skills/orion/scripts/browser_setup.mjs +12 -7
  37. package/.claude/skills/orion/scripts/cases_export.py +724 -0
  38. package/.claude/skills/orion/scripts/codemap.mjs +116 -0
  39. package/.claude/skills/orion/scripts/done_check.mjs +200 -0
  40. package/.claude/skills/orion/scripts/fix_plan.mjs +21 -0
  41. package/.claude/skills/orion/scripts/hooks/lean_guard.mjs +162 -0
  42. package/.claude/skills/orion/scripts/lib/table.mjs +116 -0
  43. package/.claude/skills/orion/scripts/quiet.mjs +160 -0
  44. package/.claude/skills/orion/scripts/report_check.mjs +6 -3
  45. package/.claude/skills/orion/scripts/report_make.mjs +186 -0
  46. package/.claude/skills/orion/scripts/results_parse.mjs +16 -3
  47. package/.claude/skills/orion/scripts/rules.mjs +92 -0
  48. package/.claude/skills/orion/scripts/run_state.mjs +67 -0
  49. package/.claude/skills/orion/scripts/suite_check.mjs +41 -2
  50. package/.claude/skills/orion/templates/project-context/assessment.md +2 -2
  51. package/.claude/skills/orion/templates/project-context/retry-policy.md +6 -0
  52. package/.claude/skills/orion/templates/project-context/test-design.md +6 -0
  53. package/.claude/skills/playwright/templates/dotnet/PageObjects/BasePage.cs +4 -0
  54. package/.claude/skills/playwright/templates/javascript/fixtures/index.js +4 -2
  55. package/.claude/skills/playwright/templates/javascript/fixtures/session.js +9 -6
  56. package/.claude/skills/playwright/templates/javascript/jsconfig.json +3 -2
  57. package/.claude/skills/playwright/templates/javascript/pageObjects/basePage.js +4 -0
  58. package/.claude/skills/playwright/templates/javascript/playwright.config.js +3 -0
  59. package/.claude/skills/playwright/templates/javascript/reporters/summaryReporter.js +15 -1
  60. package/.claude/skills/playwright/templates/javascript/src/config/env.js +29 -1
  61. package/.claude/skills/playwright/templates/project/fixtures/index.ts +4 -2
  62. package/.claude/skills/playwright/templates/project/fixtures/session.ts +7 -5
  63. package/.claude/skills/playwright/templates/project/pageObjects/basePage.ts +4 -0
  64. package/.claude/skills/playwright/templates/project/playwright.config.ts +3 -0
  65. package/.claude/skills/playwright/templates/project/reporters/summaryReporter.ts +15 -0
  66. package/.claude/skills/playwright/templates/project/src/config/env.ts +29 -1
  67. package/.claude/skills/playwright/templates/python/page_objects/base_page.py +3 -0
  68. package/.claude/skills/playwright/templates/python/src/config/env.py +34 -2
  69. package/.claude/skills/selenium/templates/csharp-nunit/PageObjects/BasePage.cs +4 -0
  70. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/pageObjects/BasePage.java +3 -0
  71. package/.claude/skills/selenium/templates/python-pytest/page_objects/base_page.py +3 -0
  72. package/.claude/skills/self-healing/SKILL.md +1 -1
  73. package/.claude/skills/test-reporting/references/tool-mapping.md +13 -9
  74. package/.claude/skills/ui-observation/SKILL.md +1 -0
  75. package/.claude-plugin/plugin.json +15 -2
  76. package/.codex/agents/automation-strategist.toml +1 -0
  77. package/.codex/agents/change-agent.toml +1 -0
  78. package/.codex/agents/codebase-analyst.toml +1 -0
  79. package/.codex/agents/environment-discovery.toml +1 -0
  80. package/.codex/agents/evidence-validator.toml +1 -0
  81. package/.codex/agents/executor.toml +1 -0
  82. package/.codex/agents/failure-analyst.toml +1 -0
  83. package/.codex/agents/implementer.toml +2 -1
  84. package/.codex/agents/requirement-analyst.toml +1 -0
  85. package/.codex/agents/reviewer.toml +1 -0
  86. package/.codex/agents/test-reporter.toml +1 -0
  87. package/.codex/hooks.json +15 -0
  88. package/.cursor/commands/orion.md +1 -1
  89. package/.cursor/hooks.json +10 -0
  90. package/.devin/hooks.v1.json +13 -0
  91. package/.gemini/agents/automation-strategist.md +1 -0
  92. package/.gemini/agents/change-agent.md +1 -0
  93. package/.gemini/agents/codebase-analyst.md +1 -0
  94. package/.gemini/agents/environment-discovery.md +1 -0
  95. package/.gemini/agents/evidence-validator.md +1 -0
  96. package/.gemini/agents/executor.md +1 -0
  97. package/.gemini/agents/failure-analyst.md +1 -0
  98. package/.gemini/agents/implementer.md +2 -1
  99. package/.gemini/agents/requirement-analyst.md +1 -0
  100. package/.gemini/agents/reviewer.md +1 -0
  101. package/.gemini/agents/test-reporter.md +1 -0
  102. package/.gemini/commands/orion.toml +2 -2
  103. package/.github/hooks/orion-lean.json +13 -0
  104. package/.github/prompts/orion.prompt.md +2 -2
  105. package/.windsurf/workflows/orion.md +2 -2
  106. package/AGENTS.md +7 -7
  107. package/README.md +55 -160
  108. package/assets/run-flow.svg +1 -1
  109. package/bin/orion.mjs +7 -7
  110. package/hosts/gemini-extension/gemini-extension.json +1 -1
  111. package/hosts/gemini-extension/hooks/hooks.json +16 -0
  112. package/hosts/gemini-extension/policies/platform.toml +5 -0
  113. package/package.json +5 -1
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Code map: one compact line per file with its classes, functions, methods, page-object fields and test titles, each
4
+ * with its line number, so an agent learns what a suite has without reading its files whole. In measured runs, dumping
5
+ * the suite's own files in a loop was 16 KB of one turn's output, re-read on every later turn
6
+ * (evals/workflows/runs/2026-11-18-cost-breakdown.md). Orion's own version of the "code knowledge graph" idea: no
7
+ * install, no model call. Open a file only to change it, at the line the map gives.
8
+ *
9
+ * Usage (from the workspace root):
10
+ * node .claude/skills/orion/scripts/codemap.mjs <suite folder> [--find <name>] [--max-bytes 6000] [--out <file>]
11
+ * --find only the lines whose file, class, function or test title holds <name> (case-insensitive)
12
+ * --out also write the full map to that file (e.g. project-context/graph/codemap.md); without it nothing is written,
13
+ * so read-only agents can run it
14
+ * Languages: JavaScript, TypeScript, Python, Java, C#, Kotlin; Gherkin feature and scenario names. Regular
15
+ * expressions, not a parser: it lists what a line declares, and the source stays the truth.
16
+ * Exit code: 0 printed · 1 nothing found · 2 wrong arguments.
17
+ */
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { pathToFileURL } from 'node:url';
21
+
22
+ const SKIP = new Set(['node_modules', '.git', 'auth', 'playwright-report', 'test-results', 'allure-results', 'blob-report', 'bin',
23
+ 'obj', 'target', 'reports', 'TestResults', '.venv', 'venv', '__pycache__', '.pytest_cache', 'test-output', 'dist', 'build',
24
+ '.gradle', '.idea', '.vscode', 'coverage', 'screenshots', 'videos', 'downloads', 'test-summary']);
25
+ const SKIP_TOP = new Set(['.claude', 'registry', '.cursor', '.cursor-plugin', '.gemini', '.codex', '.windsurf', 'project-context', '.ui-map']);
26
+ const EXT = /\.(m?[jt]sx?|cjs|py|java|kt|cs|feature)$/;
27
+ const KW = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'function', 'new', 'else', 'using', 'lock', 'foreach', 'await',
28
+ 'throw', 'typeof', 'super', 'this', 'synchronized', 'try', 'do', 'base', 'get', 'set', 'static', 'async', 'expect', 'test',
29
+ 'describe', 'it', 'require', 'import', 'export', 'const', 'let', 'var', 'and', 'or', 'not', 'in', 'is', 'print', 'assert']);
30
+
31
+ function files(root) {
32
+ const out = [];
33
+ const walk = (d) => {
34
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
35
+ const p = path.join(d, e.name);
36
+ if (e.isDirectory()) { if (!SKIP.has(e.name) && !(d === root && SKIP_TOP.has(e.name)) && !e.name.startsWith('.')) walk(p); }
37
+ else if (EXT.test(e.name) && !/\.(d\.ts|min\.js)$/.test(e.name) && fs.statSync(p).size < 400 * 1024) out.push(p);
38
+ }
39
+ };
40
+ walk(root);
41
+ return out.sort();
42
+ }
43
+
44
+ /** What one file declares, as short items with line numbers. */
45
+ export function declarations(text, file) {
46
+ const items = [];
47
+ const lines = text.split('\n');
48
+ const js = /\.(m?[jt]sx?|cjs)$/.test(file), py = /\.py$/.test(file), jv = /\.(java|kt|cs)$/.test(file), gh = /\.feature$/.test(file);
49
+ lines.forEach((l, i) => {
50
+ const n = i + 1;
51
+ let m;
52
+ if (js) {
53
+ if ((m = l.match(/^\s*(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?/))) items.push(`class ${m[1]}${m[2] ? `<${m[2]}` : ''} :${n}`);
54
+ else if ((m = l.match(/^\s*(?:export\s+)?(?:async\s+)?function\s*\*?\s*(\w+)\s*\(([^)]*)\)/))) items.push(`${m[1]}(${m[2].replace(/\s+/g, ' ').slice(0, 40)}) :${n}`);
55
+ else if ((m = l.match(/^\s*(?:export\s+)?const\s+(\w+)\s*=\s*(?:async\s*)?(?:\(([^)]*)\)|(\w+))\s*=>/))) items.push(`${m[1]}(${(m[2] ?? m[3] ?? '').replace(/\s+/g, ' ').slice(0, 40)}) :${n}`);
56
+ else if ((m = l.match(/^\s{2,}(?:public\s+|private\s+|protected\s+|static\s+|readonly\s+)*(?:async\s+)?(\w+)\s*\(([^)]*)\)\s*(?::\s*[^{]+)?\{\s*$/)) && !KW.has(m[1])) items.push(`${m[1]}(${m[2].replace(/\s+/g, ' ').slice(0, 40)}) :${n}`);
57
+ else if ((m = l.match(/^\s+this\.(\w+)\s*=\s*(?:this\.)?page\.(\w+)/))) items.push(`.${m[1]}=${m[2]} :${n}`);
58
+ else if ((m = l.match(/^\s*(?:readonly\s+)?(\w+)\s*=\s*(?:this\.)?page\.(locator|getBy\w+)/))) items.push(`.${m[1]}=${m[2]} :${n}`);
59
+ else if ((m = l.match(/\b(test\.describe|describe)(?:\.\w+)?\(\s*(['"`])(.+?)\2/))) items.push(`describe "${m[3].slice(0, 60)}" :${n}`);
60
+ else if ((m = l.match(/\b(test|it)(?:\.(?:only|skip|fixme|fail|slow))?\(\s*(['"`])(.+?)\2/))) items.push(`test "${m[3].slice(0, 70)}" :${n}`);
61
+ else if ((m = l.match(/\btest\(\s*titleOf\((\w+)\)/))) items.push(`test <${m[1]}> :${n}`);
62
+ } else if (py) {
63
+ if ((m = l.match(/^\s*class\s+(\w+)(?:\(([^)]*)\))?/))) items.push(`class ${m[1]}${m[2] ? `<${m[2]}` : ''} :${n}`);
64
+ else if ((m = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)/))) items.push(`${m[1] ? '' : ''}${m[2]}(${m[3].replace(/\s+/g, ' ').replace(/^self,?\s*/, '').slice(0, 40)}) :${n}`);
65
+ else if ((m = l.match(/^@pytest\.fixture/))) items.push(`@fixture :${n}`);
66
+ } else if (jv) {
67
+ if ((m = l.match(/^\s*(?:public\s+|internal\s+|abstract\s+|sealed\s+|partial\s+|static\s+)*(?:class|interface|record)\s+(\w+)/))) items.push(`class ${m[1]} :${n}`);
68
+ else if ((m = l.match(/^\s*(?:@Test|\[Test\]|\[Fact\]|\[TestMethod\])/))) items.push(`@test :${n}`);
69
+ else if ((m = l.match(/^\s*(?:public|protected|internal)\s+(?:static\s+|async\s+|override\s+|virtual\s+|final\s+)*[\w<>,\[\]? ]+?\s+(\w+)\s*\(([^)]*)\)/)) && !KW.has(m[1])) items.push(`${m[1]}(${m[2].replace(/\s+/g, ' ').slice(0, 40)}) :${n}`);
70
+ } else if (gh) {
71
+ if ((m = l.match(/^\s*(Feature|Scenario(?: Outline)?):\s*(.+)/))) items.push(`${m[1]} "${m[2].trim().slice(0, 70)}" :${n}`);
72
+ }
73
+ });
74
+ return items;
75
+ }
76
+
77
+ function main() {
78
+ const argv = process.argv.slice(2);
79
+ const o = { maxBytes: 6000 };
80
+ for (let i = 0; i < argv.length; i++) {
81
+ if (argv[i] === '--find') o.find = argv[++i];
82
+ else if (argv[i] === '--max-bytes') { o.maxBytes = Number(argv[++i]); if (!(o.maxBytes > 0)) { console.log('codemap: --max-bytes needs a number of bytes'); process.exit(2); } }
83
+ else if (argv[i] === '--out') o.out = argv[++i];
84
+ else if (!o.root) o.root = argv[i];
85
+ else { console.log(`codemap: unknown argument ${argv[i]}`); process.exit(2); }
86
+ }
87
+ if (!o.root || !fs.existsSync(o.root)) { console.log('usage: node .claude/skills/orion/scripts/codemap.mjs <suite folder> [--find <name>] [--max-bytes 6000]'); process.exit(2); }
88
+ const root = path.resolve(o.root);
89
+ const rows = [];
90
+ for (const f of files(root)) {
91
+ const rel = path.relative(root, f).split(path.sep).join('/');
92
+ const items = declarations(fs.readFileSync(f, 'utf8'), f);
93
+ if (items.length) rows.push(`${rel}: ${items.join(' · ')}`);
94
+ }
95
+ const full = `# Code map of ${path.relative(process.cwd(), root) || '.'} (${rows.length} files; line numbers after ":")\n${rows.join('\n')}\n`;
96
+ let outFile = o.out || null;
97
+ if (outFile && !o.find) {
98
+ try { fs.mkdirSync(path.dirname(outFile), { recursive: true }); fs.writeFileSync(outFile, full); } catch { console.log(`codemap: could not write ${outFile}; printing only`); outFile = null; }
99
+ }
100
+ let shown = rows;
101
+ if (o.find) {
102
+ const q = o.find.toLowerCase();
103
+ shown = rows.map((r) => {
104
+ const [file, rest] = [r.slice(0, r.indexOf(': ')), r.slice(r.indexOf(': ') + 2)];
105
+ if (file.toLowerCase().includes(q)) return r;
106
+ const hits = rest.split(' · ').filter((x) => x.toLowerCase().includes(q));
107
+ return hits.length ? `${file}: ${hits.join(' · ')}` : null;
108
+ }).filter(Boolean);
109
+ }
110
+ if (!shown.length) { console.log(o.find ? `codemap: nothing named like "${o.find}"` : 'codemap: no source files found'); process.exit(1); }
111
+ let text = shown.join('\n');
112
+ if (Buffer.byteLength(text) > o.maxBytes) text = `${text.slice(0, o.maxBytes)}\n… cut at ${o.maxBytes} bytes: use --find <name>${outFile && !o.find ? ` or read ${outFile}` : ''}`;
113
+ console.log(`${shown.length} file(s)${outFile && !o.find ? ` · full map: ${outFile}` : ''}\n${text}`);
114
+ }
115
+
116
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The run's definition of done, checked by machine. The orchestrator's loop ("until COMPLETE") ends only when this
4
+ * exits 0; each FAIL row names the next action, which becomes the loop's next step. Gate claims were the agent's own
5
+ * word before this: in four rehearsals on a real site (2026-11-18), a run delivered a `npm test` that stopped at once,
6
+ * no run recorded its per-run results, a graph gap went unmentioned, and results ran 172–477 words against a 120 limit,
7
+ * while each run reported itself done.
8
+ *
9
+ * Usage (from the workspace root):
10
+ * node .claude/skills/orion/scripts/done_check.mjs --project <test project> --story <KEY> --run <run id>
11
+ * [--existing] [--base <git sha>] [--command "npm test"] [--no-run] [--results project-context/results] [--report <report.md>]
12
+ * [--result-text <file with the result message>] [--known-failures TS-4,TS-6] [--json]
13
+ * Checks (each PASS, FAIL with the next action, or SKIP with why):
14
+ * project suite_check.mjs reports 0 findings (placeholders, layers, scripts that name missing projects, …); for an
15
+ * existing suite (--existing, or when suite_check says most layers are missing) only the findings that
16
+ * hold for any suite count: placeholders left and scripts that name a missing project
17
+ * command the command the result gives the user exits 0; a failing test is allowed only when it is in
18
+ * --known-failures (an app defect the result reports)
19
+ * runs 3 or more results files for this run (results_parse.mjs output, `<run id>*.json`), and in each, every
20
+ * test of the story passed on its first attempt (retries off), except --known-failures
21
+ * coverage graph.mjs check --story finds no gap (an AC with no case, a case with no test, a test with no case)
22
+ * report report_check.mjs finds nothing in the report
23
+ * result the result message: no table, at most 120 words before "Accept?", no line over 30 words
24
+ * reuse reuse_check.mjs on what changed since the run's base (--base, else the `base <sha>` on the run file's
25
+ * code line): no copied function body and no method that only calls another (the reuse ladder); the
26
+ * other kinds (a shared locator, repeated steps, unused, same name) are listed, not failed
27
+ * Exit code: 0 all PASS or SKIP · 1 a FAIL (not done: act on its next action and run this again) · 2 wrong arguments.
28
+ */
29
+ import fs from 'node:fs';
30
+ import path from 'node:path';
31
+ import { spawnSync } from 'node:child_process';
32
+ import { fileURLToPath, pathToFileURL } from 'node:url';
33
+
34
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
35
+
36
+ function args(argv) {
37
+ const o = { results: 'project-context/results', known: [] };
38
+ for (let i = 0; i < argv.length; i++) {
39
+ const a = argv[i];
40
+ const v = () => argv[++i];
41
+ if (a === '--project') o.project = v();
42
+ else if (a === '--story') o.story = v();
43
+ else if (a === '--run') o.run = v();
44
+ else if (a === '--command') o.command = v();
45
+ else if (a === '--no-run') o.noRun = true;
46
+ else if (a === '--results') o.results = v();
47
+ else if (a === '--report') o.report = v();
48
+ else if (a === '--result-text') o.resultText = v();
49
+ else if (a === '--known-failures') o.known = v().split(',').map((s) => s.trim()).filter(Boolean);
50
+ else if (a === '--json') o.json = true;
51
+ else if (a === '--existing') o.existing = true;
52
+ else if (a === '--base') o.base = v();
53
+ else { console.log(`done_check: unknown argument ${a}`); process.exit(2); }
54
+ }
55
+ if (!o.project || !o.story || !o.run) {
56
+ console.log('usage: node .claude/skills/orion/scripts/done_check.mjs --project <test project> --story <KEY> --run <run id> [--command "npm test"] [--report <file>] [--result-text <file>] [--known-failures TS-4]');
57
+ process.exit(2);
58
+ }
59
+ return o;
60
+ }
61
+
62
+ const node = (script, a, cwd) => spawnSync(process.execPath, [path.join(HERE, script), ...a], { cwd, encoding: 'utf8' });
63
+
64
+ /** The command a person would run in this project, when none was given. */
65
+ function defaultCommand(project) {
66
+ if (fs.existsSync(path.join(project, 'package.json'))) {
67
+ try { if (JSON.parse(fs.readFileSync(path.join(project, 'package.json'), 'utf8')).scripts?.test) return 'npm test'; } catch { /* reported by the project check */ }
68
+ }
69
+ if (['pytest.ini', 'conftest.py', 'pyproject.toml'].some((f) => fs.existsSync(path.join(project, f)))) return 'pytest';
70
+ if (fs.existsSync(path.join(project, 'pom.xml'))) return 'mvn -q test';
71
+ if (fs.readdirSync(project).some((f) => /\.(csproj|sln)$/.test(f))) return 'dotnet test';
72
+ return null;
73
+ }
74
+
75
+ /** Words in a line, a code span counting as one. */
76
+ const words = (s) => s.replace(/`[^`]*`/g, 'x').split(/\s+/).filter(Boolean).length;
77
+
78
+ export function checkResultText(text) {
79
+ const top = text.split(/Accept\?/)[0].trim();
80
+ const lines = top.split('\n').filter((l) => l.trim());
81
+ const problems = [];
82
+ if (!/Accept\?/.test(text)) problems.push('no "Accept? (yes / changes)"');
83
+ if (lines.some((l) => /^\s*\|/.test(l))) problems.push('a table (coverage is one line)');
84
+ const n = words(top);
85
+ if (n > 120) problems.push(`${n} words before "Accept?" (at most 120)`);
86
+ const long = lines.filter((l) => words(l) > 30);
87
+ if (long.length) problems.push(`${long.length} line(s) over 30 words, e.g. "${long[0].slice(0, 60)}…"`);
88
+ if (lines.length > 7) problems.push(`${lines.length} lines before "Accept?" (the 5 lines of conversation.md, at most 2 of them ⚠️)`);
89
+ if (lines.length && !/^\*\*(✅|⚠️|❌)/.test(lines[0].trim())) problems.push('the first line is not the bold verdict (**✅ Ready to accept**, **⚠️ Ready, with notes** or **❌ Not ready**)');
90
+ // Chat windows render Markdown: lines with no blank line between them run together into one paragraph (seen in Cursor).
91
+ if (lines.length >= 3 && !/\n[ \t]*\n/.test(top)) problems.push('the lines run together in Markdown: leave a blank line between them');
92
+ const setup = lines.find((l) => /\b(reload|restart) (Cursor|VS Code|Claude Code|Gemini|Codex|your (AI )?tool)|\bMCP\b|browser_run_code_unsafe|Cursor Settings|report_check|done_check|suite_check|type[- ]?check/i.test(l));
93
+ if (setup) problems.push(`a note about the tools' own setup or Orion's checks: "${setup.trim().slice(0, 60)}…" (it goes in the report, not the result)`);
94
+ return problems;
95
+ }
96
+
97
+ function main() {
98
+ const o = args(process.argv.slice(2));
99
+ const root = process.cwd();
100
+ const project = path.resolve(root, o.project);
101
+ const rows = [];
102
+ const add = (check, status, detail, next = '') => rows.push({ check, status, detail, next });
103
+
104
+ // project
105
+ const sc = node('suite_check.mjs', [project], root);
106
+ const existing = o.existing || /suite Orion didn't generate/.test(sc.stdout || '');
107
+ let found = (sc.stdout || '').split('\n').filter((l) => l.includes(project) && !/: \w+ suite,/.test(l));
108
+ if (existing) found = found.filter((l) => /unfilled starter placeholder|package\.json: script/.test(l));
109
+ const m = /suite check: (\d+) finding/.exec(sc.stdout || '');
110
+ if (!m && !existing) add('project', 'FAIL', `suite_check exit ${sc.status}`, 'run suite_check on the project and fix what it names');
111
+ else if (!found.length) add('project', 'PASS', existing ? 'existing suite: no placeholders left, every script names a real project' : 'suite_check: 0 findings');
112
+ else add('project', 'FAIL', found.slice(0, 3).join(' | '), 'fix what suite_check names, then run it again');
113
+
114
+ // command
115
+ const command = o.command || defaultCommand(project);
116
+ if (o.noRun) add('command', 'SKIP', `not run (--no-run)${command ? `: ${command}` : ''}`);
117
+ else if (!command) add('command', 'FAIL', 'no command a person could run (no test script)', 'give the project a test command and name it in the result');
118
+ else {
119
+ const r = spawnSync(command, { cwd: project, shell: true, encoding: 'utf8', timeout: 20 * 60 * 1000, env: { ...process.env, CI: '1' } });
120
+ const out = `${r.stdout || ''}${r.stderr || ''}`;
121
+ const failing = [...new Set((out.match(/^.*(✘|\bfailed\b|FAILED|\[fail\]).*$/gim) || []).flatMap((l) => l.match(/\bTS-\d+\b/g) || []))];
122
+ const unknown = failing.filter((t) => !o.known.includes(t));
123
+ if (r.status === 0) add('command', 'PASS', `${command}: exit 0`);
124
+ else if (failing.length && !unknown.length) add('command', 'PASS', `${command}: exit ${r.status}, failing only known app defects ${failing.join(', ')}`);
125
+ else add('command', 'FAIL', `${command}: exit ${r.status}${unknown.length ? `, failing ${unknown.join(', ')}` : ''} · ${out.trim().split('\n').slice(-2).join(' | ').slice(0, 160)}`,
126
+ unknown.length ? 'classify the failures (recovery loop) and heal or report them' : 'make the command run as given (a missing project, a setup step, a download)');
127
+ }
128
+
129
+ // runs
130
+ const dir = path.resolve(root, o.results);
131
+ const files = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.startsWith(o.run) && f.endsWith('.json') && !/\.(pw|raw|report)\.json$/.test(f)).sort() : [];
132
+ if (files.length < 3) add('runs', 'FAIL', `${files.length} results file(s) for ${o.run} in ${o.results}`, 'after each counted run: results_parse.mjs <project>/test-summary/results.json (or the run\'s JSON or JUnit report) --run <run id>-<n> --out project-context/results/<run id>-<n>.json');
133
+ else {
134
+ const bad = [];
135
+ for (const f of files) {
136
+ let d;
137
+ try { d = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); } catch { bad.push(`${f}: not JSON`); continue; }
138
+ const tests = (d.tests || []).filter((t) => t.test_id && (!t.story || t.story === o.story || String(t.test_id).startsWith(`${o.story}:`)));
139
+ if (!tests.length) bad.push(`${f}: no ${o.story} tests`);
140
+ for (const t of tests) {
141
+ const id = String(t.test_id).replace(/^.*:/, '');
142
+ if (o.known.includes(id)) continue;
143
+ if (t.status !== 'passed' || (t.attempts || 1) > 1) bad.push(`${f}: ${id} ${t.status}${t.attempts > 1 ? ` after ${t.attempts} attempts` : ''}`);
144
+ }
145
+ }
146
+ if (bad.length) add('runs', 'FAIL', bad.slice(0, 4).join(' | '), 'a new test passes 3 of 3 with retries off: recovery loop for each test named');
147
+ else add('runs', 'PASS', `${files.length} recorded runs, every ${o.story} test passed first time`);
148
+ }
149
+
150
+ // coverage
151
+ const gc = node('graph.mjs', ['check', '--story', o.story], root);
152
+ const g = /graph check [^:]*: (\d+) gap/.exec(gc.stdout || '');
153
+ if (!g && /no graph|not built|ENOENT/i.test(`${gc.stdout}${gc.stderr}`)) add('coverage', 'FAIL', 'no graph', 'graph.mjs build, then run this again');
154
+ else if (g && g[1] !== '0') add('coverage', 'FAIL', (gc.stdout || '').split('\n').filter((l) => l.startsWith(`${o.story}:`)).slice(0, 3).join(' | '), 'write the missing test or case, or name the gap in the result as an open item (--known-failures does not cover gaps)');
155
+ else if (g) add('coverage', 'PASS', 'graph check: 0 gaps');
156
+ else add('coverage', 'SKIP', `graph check gave no count (exit ${gc.status})`);
157
+
158
+ // reuse ladder: new code must not copy or wrap what already exists
159
+ let base = o.base;
160
+ if (!base) {
161
+ const rf = path.join(root, 'project-context', 'runs', `${o.run}.md`);
162
+ if (fs.existsSync(rf)) base = (fs.readFileSync(rf, 'utf8').match(/^code: .*\bbase ([0-9a-f]{7,40})\b/m) || [])[1];
163
+ }
164
+ if (!base) add('reuse', 'SKIP', 'no git base for this run (--base or the run file\'s code line)');
165
+ else {
166
+ const rc = node('reuse_check.mjs', [project, '--changed', base, '--json'], root);
167
+ let found = null;
168
+ try { found = JSON.parse(rc.stdout).findings || []; } catch { found = null; }
169
+ if (!found) add('reuse', 'SKIP', `reuse_check gave no result (exit ${rc.status})`);
170
+ else {
171
+ const hard = found.filter((f) => ['duplicate', 'pass-through'].includes(f.kind));
172
+ const soft = found.length - hard.length;
173
+ if (hard.length) add('reuse', 'FAIL', hard.slice(0, 3).map((f) => `${f.file}:${f.line} ${f.kind}: ${f.what}`.slice(0, 150)).join(' | '), 'reuse or extend the existing code (the reuse ladder in automation-implementation), then run this again');
174
+ else add('reuse', 'PASS', `no copied or pass-through code in the change${soft ? ` (${soft} note(s) for the report: shared locators, repeated steps)` : ''}`);
175
+ }
176
+ }
177
+
178
+ // report and result
179
+ if (o.report) {
180
+ const rc = node('report_check.mjs', [o.report], root);
181
+ const n = /report check: (\d+) finding/.exec(rc.stdout || '');
182
+ if (n && n[1] === '0') add('report', 'PASS', 'report_check: 0 findings');
183
+ else add('report', 'FAIL', (rc.stdout || '').split('\n')[0].slice(0, 160), 'fix the report as report_check says');
184
+ } else add('report', 'SKIP', 'no --report');
185
+ if (o.resultText) {
186
+ const p = checkResultText(fs.readFileSync(path.resolve(root, o.resultText), 'utf8'));
187
+ if (p.length) add('result', 'FAIL', p.join('; '), 'rewrite the result as conversation.md\'s 5 lines');
188
+ else add('result', 'PASS', 'short: 5 lines, within 120 words');
189
+ } else add('result', 'SKIP', 'no --result-text');
190
+
191
+ const failed = rows.filter((r) => r.status === 'FAIL');
192
+ if (o.json) console.log(JSON.stringify({ story: o.story, run: o.run, done: !failed.length, rows }, null, 1));
193
+ else {
194
+ for (const r of rows) console.log(`${r.status.padEnd(4)} ${r.check.padEnd(8)} ${r.detail}${r.next ? `\n next: ${r.next}` : ''}`);
195
+ console.log(failed.length ? `not done: ${failed.length} check(s) failed (${failed.map((r) => r.check).join(', ')}); act on the first, then run done_check again` : 'done: every check passed');
196
+ }
197
+ process.exit(failed.length ? 1 : 0);
198
+ }
199
+
200
+ if (import.meta.url === pathToFileURL(process.argv[1]).href) main();
@@ -14,6 +14,10 @@
14
14
  * node .claude/skills/orion/scripts/fix_plan.mjs set <fix-plan.md> <batch n> <state> ["<note>"]
15
15
  * state: pending · applied · verified · reverted · skipped
16
16
  * node .claude/skills/orion/scripts/fix_plan.mjs summary <fix-plan.md>
17
+ * node .claude/skills/orion/scripts/fix_plan.mjs scope <fix-plan.md> <batch n> --since <batch start sha> [--until <sha>] [--repo <work copy>]
18
+ * the files the batch changed (git diff from its start, plus new files) against its ticked items' `changes:`
19
+ * lists: exit 1 naming each file outside them. Run before the review; a file outside stops the batch, and the
20
+ * user is asked (H14) to add it to the item, never edited silently.
17
21
  * Each item says whether it needs the user's H8 (it changes what a test asserts or expects: U6, U8, U12, P15, or a
18
22
  * proposed fix that names an assertion or expected value) and whether it needs a secret's variable name (U2).
19
23
  * Each item lists the files its fix may change (`changes:`): the assessment's "Changes" column when it has one (e.g. a
@@ -23,6 +27,7 @@
23
27
  */
24
28
  import fs from 'node:fs';
25
29
  import path from 'node:path';
30
+ import { execFileSync } from 'node:child_process';
26
31
  import { insideWorkspace } from './lib/inside.mjs';
27
32
 
28
33
  const SEV = { critical: 0, blocking: 1, major: 2, minor: 3 };
@@ -138,6 +143,22 @@ function main() {
138
143
  if (!b) die(1, 'no batch left: every ticked item is verified, reverted or skipped');
139
144
  return console.log(JSON.stringify({ batch: b.n, state: b.state, items: b.items.filter((i) => i.ticked).map((i) => ({ id: i.id, text: i.text })) }, null, 2));
140
145
  }
146
+ if (cmd === 'scope') {
147
+ const [n, ...opts] = rest;
148
+ const opt = (k) => { const i = opts.indexOf(k); return i >= 0 ? opts[i + 1] : undefined; };
149
+ const since = opt('--since');
150
+ const repo = opt('--repo') || '.';
151
+ const until = opt('--until');
152
+ const b = batches.find((x) => x.n === Number(n));
153
+ if (!b || !since || ![since, until || since].every((s) => /^[0-9a-f]{7,40}$/i.test(s))) die(2, 'scope <batch n> --since <commit sha> [--until <commit sha>] [--repo <work copy>]');
154
+ const git = (...a) => { try { return execFileSync('git', ['-C', repo, ...a], { encoding: 'utf8' }); } catch (e) { die(2, `git failed in ${repo}: ${e.message.split('\n')[0]}`); } return ''; };
155
+ const changed = [...new Set([...git('diff', '--name-only', since, ...(until ? [until] : []), '--').split('\n'), ...(until ? [] : git('ls-files', '--others', '--exclude-standard').split('\n'))]
156
+ .map((f) => f.trim()).filter((f) => f && !f.startsWith('project-context/') && !f.startsWith('.ui-map/')))];
157
+ const allowed = new Set(b.items.filter((i) => i.ticked).flatMap((i) => (i.text.match(/·\s*changes:\s*([^·]+)/)?.[1] || '').split(',').map((s) => s.trim()).filter(Boolean)));
158
+ const outside = changed.filter((f) => !allowed.has(f));
159
+ if (outside.length) die(1, `batch ${b.n} changed files outside its items' changes lists: ${outside.join(', ')} (allowed: ${[...allowed].join(', ') || 'none'})`);
160
+ return console.log(`batch ${b.n}: ${changed.length} changed file(s), all in its items' changes lists`);
161
+ }
141
162
  if (cmd === 'summary') {
142
163
  const t = batches.flatMap((b) => b.items).filter((i) => i.ticked).length;
143
164
  for (const b of batches) console.log(`batch ${b.n}: ${b.state} · ticked ${b.items.filter((i) => i.ticked).length}/${b.items.length}${b.note ? ` · ${b.note}` : ''}`);
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Lean guard (Claude Code PreToolUse hook for Bash and Read): during an Orion run, blocks the three habits that filled
4
+ * an agent's context most in measured runs (evals/workflows/runs/2026-11-18-cost-breakdown.md) and names the lean
5
+ * command instead. It never rewrites a command and never approves one: a blocked call is re-issued by the agent as the
6
+ * lean command, which then goes through the same approval rules as before.
7
+ * 1. a test, build or install command run raw → `node .claude/skills/orion/scripts/quiet.mjs <same command>`
8
+ * 2. a skill reference file over 8 KB read whole (a SKILL.md itself is exempt) → `node .claude/skills/orion/scripts/rules.mjs <file> --list`, then
9
+ * the section needed (or `--all` when the whole file really is needed)
10
+ * 3. three or more of the suite's source files dumped in one command → `node .claude/skills/orion/scripts/codemap.mjs
11
+ * <suite>`, then only the files to change
12
+ * Active only while a run is open: a run file under project-context/runs/ changed in the last 12 hours that is not
13
+ * finished (every gate ✓ or n/a, or COMPLETE in its log). Outside a run, and with ORION_LEAN=off in the environment, it does nothing. It fails open: any error here
14
+ * exits 0 and the call proceeds. Reads only the hook's JSON on stdin and file sizes; never a file's contents.
15
+ * Hosts: one script for every host with hooks. It reads the JSON each host sends (Claude Code, Codex, Gemini CLI,
16
+ * GitHub Copilot and Devin/Windsurf: tool_name + tool_input; Grok Build and Copilot's camelCase form: toolName +
17
+ * toolInput/toolArgs; Cursor's beforeShellExecution: command + cwd) and maps each host's shell and read tools
18
+ * (Bash, run_shell_command, bash, powershell, exec, exec_command · Read, read_file, view). The host files that call it
19
+ * are generated by scripts/build_hosts.py; which host checks what: .claude/skills/orion/references/hosts.md.
20
+ * Exit code: 0 allow (nothing printed) · 2 block (the reason on stderr, shown to the agent). With `--host cursor` it
21
+ * always exits 0 and prints Cursor's JSON instead ({"permission":"allow"} or "deny" with the reason), because Cursor
22
+ * reads a decision from stdout; "allow" only means no objection (Cursor's own approval rules still apply).
23
+ */
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import { fileURLToPath, pathToFileURL } from 'node:url';
27
+
28
+ const RUNNER = /^(npm (test|t|run test\S*|ci|install|i)\b|npx (--no-install )?playwright test\b|pytest\b|python3? -m pytest\b|py -m pytest\b|mvn\b|\.\/mvnw\b|gradle\b|\.\/gradlew\b|dotnet (test|build|restore)\b|pip3? install\b|python3? -m pip install\b|yarn (test|install)\b|pnpm (test|install|i)\b)/;
29
+ const BIG = 8 * 1024;
30
+
31
+ /** A run is finished when gate 8 is ✓, every gate row is ✓ or n/a (a mode's unused gates), or its log records COMPLETE. */
32
+ export function finished(text) {
33
+ const states = [...text.matchAll(/^\| [1-8] \| (\S+)/gm)].map((m) => m[1]);
34
+ if (/^\| 8 \| ✓ \|/m.test(text)) return true;
35
+ if (states.length === 8 && states.every((s) => s === '✓' || /^n\/a/i.test(s))) return true;
36
+ return /^\|[^|\n]*\|[^|\n]*\|[^|\n]*\| *COMPLETE *\|/m.test(text);
37
+ }
38
+
39
+ function openRun(cwd) {
40
+ let d = path.resolve(cwd);
41
+ for (let k = 0; k < 12; k++) {
42
+ const runs = path.join(d, 'project-context', 'runs');
43
+ if (fs.existsSync(runs)) {
44
+ const now = Date.now();
45
+ for (const f of fs.readdirSync(runs)) {
46
+ if (!/^R-.*\.md$/.test(f) || /\.(report|result)\.md$/.test(f)) continue;
47
+ const p = path.join(runs, f);
48
+ if (now - fs.statSync(p).mtimeMs > 12 * 3600 * 1000) continue;
49
+ if (!finished(fs.readFileSync(p, 'utf8'))) return d;
50
+ }
51
+ return null;
52
+ }
53
+ const up = path.dirname(d);
54
+ if (up === d) return null;
55
+ d = up;
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /** Strip a leading `cd x &&` and environment assignments, so the command's own first word is checked. */
61
+ const core = (c) => c.trim().replace(/^(bash|sh|zsh)\s+-l?c\s+(['"])([\s\S]*)\2$/, '$3').trim()
62
+ .replace(/^(cd\s+\S+\s*(&&|;)\s*)+/, '').replace(/^([A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/, '');
63
+
64
+ function bigRuleFile(p, root) {
65
+ try {
66
+ const abs = path.resolve(root, p);
67
+ // A skill's own SKILL.md is meant to be read whole when the skill starts; only references and other notes are held to sections.
68
+ return /[\\/]\.claude[\\/]skills[\\/].+\.md$/.test(abs) && !/[\\/]SKILL\.md$/.test(abs) && fs.statSync(abs).size > BIG ? abs : null;
69
+ } catch { return null; }
70
+ }
71
+
72
+ const SHELL = /^(Bash|bash|powershell|shell|run_shell_command|exec|exec_command|run_terminal_cmd|run_in_terminal)$/;
73
+ const READ = /^(Read|read_file|readFile|view)$/;
74
+
75
+ /** One shape for every host's hook input: { tool: 'Bash' | 'Read' | other, ti: { command } | { file_path, partial } }. */
76
+ export function normalize(input) {
77
+ if (!input || typeof input !== 'object') return { tool: null, ti: {} };
78
+ if (typeof input.command === 'string' && !input.tool_name && !input.toolName) return { tool: 'Bash', ti: { command: input.command } };
79
+ const name = input.tool_name ?? input.toolName ?? '';
80
+ let ti = input.tool_input ?? input.toolInput ?? input.toolArgs ?? {};
81
+ if (typeof ti === 'string') { try { ti = JSON.parse(ti); } catch { ti = { command: ti }; } }
82
+ if (!ti || typeof ti !== 'object') ti = {};
83
+ if (SHELL.test(name)) {
84
+ let c = ti.command ?? ti.cmd ?? ti.script;
85
+ // Codex sends ["bash", "-lc", "<command>"]: the command is the last element.
86
+ if (Array.isArray(c)) c = /^(ba|z|)sh$|[\\/](ba|z|)sh$|^pwsh$|^powershell/.test(c[0] || '') && c.length >= 3 ? c[c.length - 1] : c.join(' ');
87
+ return { tool: 'Bash', ti: { command: c } };
88
+ }
89
+ if (READ.test(name)) {
90
+ const partial = Boolean(ti.limit || ti.offset || ti.start_line || ti.end_line || ti.view_range || ti.line_range || ti.lines);
91
+ return { tool: 'Read', ti: { file_path: ti.file_path ?? ti.path ?? ti.absolute_path ?? ti.filePath, partial } };
92
+ }
93
+ return { tool: name, ti };
94
+ }
95
+
96
+ /** The quiet runner's path as the agent should type it: relative when the workspace holds it (the usual install),
97
+ * else this script's own sibling as an absolute path (a plugin install keeps the skills outside the workspace). */
98
+ const quietPath = (root) => {
99
+ const own = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'quiet.mjs');
100
+ const rel = path.relative(root, own);
101
+ return !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : own;
102
+ };
103
+
104
+ export function verdict(input, root) {
105
+ const { tool, ti } = normalize(input);
106
+ if (tool === 'Read') {
107
+ const f = ti.file_path && bigRuleFile(ti.file_path, root);
108
+ if (f && !ti.partial) return `Read the section you need instead of the whole ${path.basename(f)} (${Math.round(fs.statSync(f).size / 1024)} KB): node .claude/skills/orion/scripts/rules.mjs ${path.relative(root, f)} --list, then rules.mjs <file> <words from the section title>. Whole file only when you need all of it: rules.mjs <file> --all. Without a shell: Grep -n the section's heading, then Read with offset and limit.`;
109
+ return null;
110
+ }
111
+ if (tool !== 'Bash' || typeof ti.command !== 'string') return null;
112
+ const cmd = ti.command;
113
+ if (/\bquiet\.mjs\b|\brules\.mjs\b|\bcodemap\.mjs\b/.test(cmd)) return null;
114
+ for (const part of cmd.split(/&&|;|\n/)) {
115
+ const c = core(part);
116
+ if (RUNNER.test(c)) {
117
+ const whole = cmd.trim().replace(/^(bash|sh|zsh)\s+-l?c\s+(['"])([\s\S]*)\2$/, '$3').trim();
118
+ const form = whole === c && !/[<>|]/.test(c) ? c : `"${whole.replace(/"/g, '\\"')}"`;
119
+ return `Run it through the quiet runner (same command, same folder, same approval; the full log is saved): node ${quietPath(root)} ${form.slice(0, 200)}`;
120
+ }
121
+ }
122
+ if (/\b(cat|head|tail|sed|less|more|awk|grep)\b/.test(cmd)) {
123
+ const paths = cmd.match(/[\w./~-]+\.md\b/g) || [];
124
+ for (const p of paths) {
125
+ const f = bigRuleFile(p, root);
126
+ if (f && !/grep\s+-(n|c|l)\w*\s+["'][^"']+["']/.test(cmd) && !/sed -n ['"]?\d+,\d{1,2}p/.test(cmd)) {
127
+ return `Read the section you need instead of the whole ${path.basename(f)} (${Math.round(fs.statSync(f).size / 1024)} KB): node .claude/skills/orion/scripts/rules.mjs ${path.relative(root, f)} --list, then rules.mjs <file> <words from the section title>.`;
128
+ }
129
+ }
130
+ const code = (cmd.match(/[\w./*-]+\.(m?[jt]sx?|cjs|py|java|kt|cs|feature)\b/g) || []).filter((p) => !/node_modules|\.claude\//.test(p));
131
+ const globs = code.filter((p) => p.includes('*')).length;
132
+ if (/\b(cat|head|sed -n)\b/.test(cmd) && (code.length >= 3 || globs >= 1 || /for \w+ in [^;]*\.(m?[jt]sx?|py|java|cs)/.test(cmd))) {
133
+ return 'Get the map first instead of reading the files whole: node .claude/skills/orion/scripts/codemap.mjs <suite folder> [--find <name>]; then open only the files you change, at the lines it gives.';
134
+ }
135
+ }
136
+ return null;
137
+ }
138
+
139
+ function decide() {
140
+ if (process.env.ORION_LEAN === 'off') return null;
141
+ let raw = '';
142
+ try { raw = fs.readFileSync(0, 'utf8'); } catch { return null; }
143
+ try {
144
+ const input = JSON.parse(raw.replace(/^\uFEFF/, ''));
145
+ const cwd = input.cwd || input.workspaceRoot || (Array.isArray(input.workspace_roots) && input.workspace_roots[0]) || process.cwd();
146
+ const root = openRun(cwd);
147
+ return root ? verdict(input, root) : null;
148
+ } catch { return null; }
149
+ }
150
+
151
+ function main() {
152
+ const cursor = process.argv.includes('--host') && process.argv[process.argv.indexOf('--host') + 1] === 'cursor';
153
+ const why = decide();
154
+ if (cursor) {
155
+ process.stdout.write(JSON.stringify(why ? { permission: 'deny', user_message: `Orion lean rule: ${why}`, agent_message: `Orion lean rule: ${why}` } : { permission: 'allow' }));
156
+ process.exit(0);
157
+ }
158
+ if (why) { process.stderr.write(`Orion lean rule: ${why}\n`); process.exit(2); }
159
+ process.exit(0);
160
+ }
161
+
162
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Rows of a CSV or Excel (.xlsx) file as arrays of strings, with Node alone (an .xlsx is a zip of XML parts; zlib
3
+ * inflates it). The same reading rules as `requirement-analysis/scripts/tm.py xlsx-to-csv`: the first sheet unless one
4
+ * is named, shared and inline strings, booleans as TRUE/FALSE, numbers as written; empty trailing rows dropped.
5
+ * Used by batch_detect.mjs and batch_state.mjs (a batch from a stories file) and checked by check_batch.py.
6
+ */
7
+ import fs from 'node:fs';
8
+ import zlib from 'node:zlib';
9
+
10
+ /** Entries of a zip file: Map name → Buffer (stored or deflated entries; encrypted ones are refused). */
11
+ export function unzip(buf) {
12
+ let eocd = -1;
13
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
14
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
15
+ }
16
+ if (eocd < 0) throw new Error('not a zip file (no end of central directory)');
17
+ const count = buf.readUInt16LE(eocd + 10);
18
+ let p = buf.readUInt32LE(eocd + 16);
19
+ const out = new Map();
20
+ for (let n = 0; n < count; n++) {
21
+ if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error('broken zip central directory');
22
+ const flags = buf.readUInt16LE(p + 8);
23
+ const method = buf.readUInt16LE(p + 10);
24
+ const size = buf.readUInt32LE(p + 20);
25
+ const nameLen = buf.readUInt16LE(p + 28);
26
+ const extraLen = buf.readUInt16LE(p + 30);
27
+ const commentLen = buf.readUInt16LE(p + 32);
28
+ const local = buf.readUInt32LE(p + 42);
29
+ const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
30
+ if (flags & 1) throw new Error(`${name} is encrypted`);
31
+ const lNameLen = buf.readUInt16LE(local + 26);
32
+ const lExtraLen = buf.readUInt16LE(local + 28);
33
+ const start = local + 30 + lNameLen + lExtraLen;
34
+ const data = buf.subarray(start, start + size);
35
+ if (method === 0) out.set(name, data);
36
+ else if (method === 8) out.set(name, zlib.inflateRawSync(data));
37
+ else throw new Error(`${name}: unsupported compression ${method}`);
38
+ p += 46 + nameLen + extraLen + commentLen;
39
+ }
40
+ return out;
41
+ }
42
+
43
+ const decode = (s) => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'")
44
+ .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
45
+ .replace(/&amp;/g, '&');
46
+ /** The text of a string item: every <t> run joined (rich text included), phonetic runs (<rPh>) left out. */
47
+ const textOf = (xml) => decode([...xml.replace(/<rPh\b[\s\S]*?<\/rPh>/g, '').matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((m) => m[1]).join(''));
48
+ const colIndex = (ref) => [...ref.replace(/\d+/g, '')].reduce((n, c) => n * 26 + (c.charCodeAt(0) - 64), 0) - 1;
49
+
50
+ /** Rows of one sheet of an .xlsx file (the first unless `sheet` names one). */
51
+ export function xlsxRows(file, sheet = null) {
52
+ const z = unzip(fs.readFileSync(file));
53
+ const read = (n) => (z.has(n) ? z.get(n).toString('utf8') : '');
54
+ const shared = [...read('xl/sharedStrings.xml').matchAll(/<si>([\s\S]*?)<\/si>/g)].map((m) => textOf(m[1]));
55
+ const wb = read('xl/workbook.xml');
56
+ const rels = read('xl/_rels/workbook.xml.rels');
57
+ const sheets = [...wb.matchAll(/<sheet\b([^>]*)\/?>/g)].map((m) => ({
58
+ name: decode(m[1].match(/\bname="([^"]*)"/)?.[1] || ''),
59
+ rid: m[1].match(/\br:id="([^"]*)"/)?.[1] || m[1].match(/\bid="([^"]*)"/)?.[1],
60
+ }));
61
+ if (!sheets.length) throw new Error('no sheets in the workbook');
62
+ const pick = sheet ? sheets.find((s) => s.name === sheet) : sheets[0];
63
+ if (!pick) throw new Error(`no sheet named "${sheet}" (sheets: ${sheets.map((s) => s.name).join(', ')})`);
64
+ const target = [...rels.matchAll(/<Relationship\b([^>]*)\/?>/g)].map((m) => m[1])
65
+ .find((r) => r.includes(`Id="${pick.rid}"`))?.match(/Target="([^"]*)"/)?.[1] || 'worksheets/sheet1.xml';
66
+ const xml = read(target.startsWith('/') ? target.slice(1) : `xl/${target.replace(/^\.\//, '')}`);
67
+ const rows = [];
68
+ for (const rm of xml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>|<row\b[^>]*\/>/g)) {
69
+ const row = [];
70
+ for (const cm of (rm[1] || '').matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
71
+ const attrs = cm[1];
72
+ const ref = attrs.match(/\br="([A-Z]+\d+)"/)?.[1];
73
+ const t = attrs.match(/\bt="(\w+)"/)?.[1];
74
+ const inner = cm[2] || '';
75
+ const v = inner.match(/<v>([\s\S]*?)<\/v>/)?.[1];
76
+ let val = '';
77
+ if (t === 's') val = shared[Number(v)] ?? '';
78
+ else if (t === 'inlineStr') val = textOf(inner);
79
+ else if (t === 'b') val = v === '1' ? 'TRUE' : 'FALSE';
80
+ else if (v !== undefined) val = decode(v);
81
+ const at = ref ? colIndex(ref) : row.length;
82
+ while (row.length < at) row.push('');
83
+ row[at] = val;
84
+ }
85
+ rows.push(row);
86
+ }
87
+ while (rows.length && rows[rows.length - 1].every((c) => !String(c).trim())) rows.pop();
88
+ return rows;
89
+ }
90
+
91
+ /** Rows of a CSV text (RFC 4180: quoted fields, doubled quotes, newlines inside quotes; a leading BOM dropped). */
92
+ export function csvRows(text) {
93
+ const rows = [];
94
+ let row = [], field = '', quoted = false;
95
+ const s = text.replace(/^/, '');
96
+ for (let i = 0; i < s.length; i++) {
97
+ const c = s[i];
98
+ if (quoted) {
99
+ if (c === '"' && s[i + 1] === '"') { field += '"'; i++; } else if (c === '"') quoted = false; else field += c;
100
+ } else if (c === '"') quoted = true;
101
+ else if (c === ',') { row.push(field); field = ''; } else if (c === '\n' || c === '\r') {
102
+ if (c === '\r' && s[i + 1] === '\n') i++;
103
+ row.push(field); rows.push(row); row = []; field = '';
104
+ } else field += c;
105
+ }
106
+ if (field || row.length) { row.push(field); rows.push(row); }
107
+ while (rows.length && rows[rows.length - 1].every((c) => !c.trim())) rows.pop();
108
+ return rows;
109
+ }
110
+
111
+ /** Rows of a .csv or .xlsx file. */
112
+ export function readRows(file, sheet = null) {
113
+ if (/\.xlsx$/i.test(file)) return xlsxRows(file, sheet);
114
+ if (/\.csv$/i.test(file)) return csvRows(fs.readFileSync(file, 'utf8'));
115
+ throw new Error('only .csv and .xlsx files are read (save other formats as one of these)');
116
+ }