@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,160 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Quiet runner: runs a test, build or install command and prints only what an agent needs (the outcome, every failure
4
+ * with its context, warnings and the runner's summary), saving the full output to a log file it can grep. Command
5
+ * output was the largest part of an agent's context in a measured run (101 KB of tool output in one story, re-read on
6
+ * every later turn: evals/workflows/runs/2026-11-18-cost-breakdown.md), so this is Orion's own version of the
7
+ * "token killer" idea, with nothing to install.
8
+ *
9
+ * Usage (from anywhere inside the workspace):
10
+ * node .claude/skills/orion/scripts/quiet.mjs <command and its arguments>
11
+ * e.g. node .claude/skills/orion/scripts/quiet.mjs npm test --silent -- tests/ui/x.spec.js --retries=0
12
+ * Prints: the command, exit code and duration; the kept lines (failures with up to 8 lines of context each, errors,
13
+ * warnings, the runner's counts and summary, the last lines); `full log: <path>`. Exits with the command's own exit
14
+ * code, so nothing that checks it changes. A redirect or a leading `cd <dir> &&` works as in the shell when the whole
15
+ * command is one quoted argument: `quiet.mjs "cd sut/app && npm test -- x > out.json"`.
16
+ * Allowing quiet.mjs for good allows the commands it runs, so it runs only test, build and install commands (npm test,
17
+ * npm run test/build/lint/e2e/verify…, npm ci/install, npx playwright, pytest, python -m pytest, mvn,
18
+ * gradle/gradlew, dotnet test/build/restore, k6, newman, pip install, node run.js / test*.js / *.spec.js, yarn, pnpm),
19
+ * one command at a time, redirects only inside the workspace; anything else exits 2,
20
+ * so it can't become a way round the host's approval rules. Never prints a secret: values of variables whose names
21
+ * look secret (PASSWORD, TOKEN, SECRET, KEY, AUTH, COOKIE) and Bearer / JWT strings are masked as ***.
22
+ * Logs go to <workspace>/project-context/logs/ (the folder with project-context/ or .claude/ above the current one),
23
+ * never into the suite, with a .gitignore of their own so they are never committed. `ORION_QUIET_LINES=<n>` changes the cap on kept lines (default 60).
24
+ * Exit code: the command's own · 2 a command it doesn't run, or no command.
25
+ */
26
+ import fs from 'node:fs';
27
+ import path from 'node:path';
28
+ import { spawnSync } from 'node:child_process';
29
+ import { pathToFileURL } from 'node:url';
30
+
31
+ const ALLOWED = /^(npm (test|t|ci|install|i)\b|npm run (test|build|lint|typecheck|check|e2e|verify|smoke|compile)[\w:.-]*|npx (--no-install )?playwright (test|install|show-report|--version)\b|pytest\b|python3? -m pytest\b|py -m pytest\b|mvn\b|\.\/mvnw\b|gradle\b|\.\/gradlew\b|dotnet (test|build|restore)\b|k6 (run|version)\b|newman run\b|npx newman run\b|pip3? install\b|python3? -m pip install\b|node (?!-e\b|--eval\b)(?:[\w.-]+\/)*(?:run|test[\w-]*|[\w-]+\.(?:spec|test))\.(?:m?js|cjs)\b|yarn(\s*$| (test|install)\b| run (test|build|lint|typecheck|check|e2e|verify|smoke|compile)[\w:.-]*)|pnpm (test|install|i|run (test|build|lint|typecheck|check|e2e|verify|smoke|compile)[\w:.-]*)\b)/;
32
+ const KEEP = /(\b(error|errors|failed|failing|failure|fail|exception|traceback|assert(ion)?error|timed? ?out|warning|warn|deprecated|npm err|err!|build (success|failure)|tests? run:|passed|skipped|flaky|did not run|interrupted|expected|received|not found|cannot find|unable to)\b|✘|✗|×|^\s*\d+\) |^\s*at .*\.(spec|test)\.|^={3,}|^-{3,} |^\s*\d+ (passed|failed|skipped|flaky))/i;
33
+ const NOISE = /^\s*at .*(node_modules|internal\/|node:)|^\s*$|^\s*(✓|✔|ok \d+|\[\d+\/\d+\].*(✓|passed))/;
34
+ const SECRET_NAME = /(PASSWORD|PASSWD|TOKEN|SECRET|API[_-]?KEY|AUTH|COOKIE)/i;
35
+
36
+ function mask(text) {
37
+ let t = text;
38
+ for (const [k, v] of Object.entries(process.env)) {
39
+ if (SECRET_NAME.test(k) && v && v.length >= 4) t = t.split(v).join('***');
40
+ }
41
+ return t.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/g, 'Bearer ***').replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '***')
42
+ .replace(/((?:password|passwd|token|secret)\s*[=:]\s*)\S+/gi, '$1***');
43
+ }
44
+
45
+ /** The workspace root: the nearest folder at or above `from` holding project-context/ or .claude/. */
46
+ function workspaceRoot(from) {
47
+ let d = path.resolve(from);
48
+ for (;;) {
49
+ if (fs.existsSync(path.join(d, 'project-context')) || fs.existsSync(path.join(d, '.claude'))) return d;
50
+ const up = path.dirname(d);
51
+ if (up === d) return path.resolve(from);
52
+ d = up;
53
+ }
54
+ }
55
+
56
+ /** The lines worth keeping from a run's output: failures with context, warnings, counts and the tail. */
57
+ export function summarize(raw, cap = 60) {
58
+ const lines = raw.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r(?!\n)/g, '\n').split('\n');
59
+ const keep = new Set();
60
+ lines.forEach((l, i) => {
61
+ if (!KEEP.test(l) || NOISE.test(l)) return;
62
+ keep.add(i);
63
+ if (/\b(error|failed|failure|exception|traceback|✘|✗|×)\b|^\s*\d+\) /i.test(l)) {
64
+ for (let j = i + 1; j <= Math.min(lines.length - 1, i + 8); j++) if (!NOISE.test(lines[j])) keep.add(j);
65
+ }
66
+ });
67
+ const tail = lines.map((l, i) => [l, i]).filter(([l]) => l.trim() && !NOISE.test(l)).slice(-8).map(([, i]) => i);
68
+ tail.forEach((i) => keep.add(i));
69
+ const seen = new Set(); const out = [];
70
+ for (const i of [...keep].sort((a, b) => a - b)) {
71
+ const l = lines[i].replace(/\s+$/, '');
72
+ const k = l.trim();
73
+ if (!k || seen.has(k)) continue;
74
+ seen.add(k); out.push(l.length > 300 ? `${l.slice(0, 300)} …` : l);
75
+ }
76
+ if (out.length > cap) return [...out.slice(0, cap - 10), `… ${out.length - cap} more kept lines in the full log …`, ...out.slice(-9)];
77
+ return out;
78
+ }
79
+
80
+ /** Leading `cd <dir> &&` steps and VAR=value assignments, which the shell keeps; the check looks past them. */
81
+ const PREFIX = /^\s*((cd\s+("[^"]*"|'[^']*'|\S+)\s*&&\s*)|([A-Za-z_][A-Za-z0-9_]*=("[^"]*"|'[^']*'|\S*)\s+))*/;
82
+
83
+ /** Several arguments are joined back into one command, each quoted again when it holds a space or a quote, so
84
+ * `quiet.mjs npx playwright test --grep "log in"` runs with "log in" as one argument. One argument is used as given
85
+ * (the form for a redirect or a `cd … &&`: `quiet.mjs "npm test -- x > out.json"`). */
86
+ export function commandOf(argv, win = process.platform === 'win32') {
87
+ if (argv.length === 1) return argv[0].trim();
88
+ const q = (a) => (!/[\s"'$`\\]/.test(a) || /^[<>|&;]+$/.test(a) ? a
89
+ : win ? `"${a.replace(/"/g, '\\"')}"` : `'${a.replace(/'/g, `'\\''`)}'`);
90
+ return argv.map(q).join(' ').trim();
91
+ }
92
+
93
+ /** Why a command is refused, or null. One test, build or install command only: after the leading `cd`/VAR= steps, no
94
+ * second command (`;`, `&&`, `||`, a pipe, `&`, backticks, `$(…)`, a new line), and a redirect only into the workspace
95
+ * (the folder holding project-context/ or .claude/). Once a person allows quiet.mjs, it must not become a way to run
96
+ * anything else. */
97
+ export function refusal(cmd, from = process.cwd()) {
98
+ const rest = cmd.replace(PREFIX, '');
99
+ // Where the command runs: the folder after its leading `cd` steps; a redirect is resolved from there.
100
+ let at = path.resolve(from);
101
+ for (const m of (cmd.match(PREFIX)?.[0] || '').matchAll(/cd\s+("[^"]*"|'[^']*'|\S+)/g)) at = path.resolve(at, m[1].replace(/^["']|["']$/g, ''));
102
+ const root = workspaceRoot(from);
103
+ if (!ALLOWED.test(rest)) return 'runs only test, build and install commands';
104
+ if (/\$\(|`/.test(rest.replace(/'[^']*'/g, "''"))) return 'runs one command only (no $(…) or backticks)';
105
+ const bare = rest.replace(/'[^']*'|"[^"]*"/g, '""');
106
+ if (/[;|`\n\r]|&&|\$\(|<\(|(^|[^>0-9])&(?!>)|&\s/.test(bare.replace(/\d?>&\d/g, ''))) return 'runs one command only (no ;, &&, ||, pipes, & or $(…) after it)';
107
+ for (const m of bare.matchAll(/\d?>>?\s*([^\s&]+)/g)) {
108
+ if (/^&\d$/.test(m[1])) continue;
109
+ const target = path.resolve(at, m[1]);
110
+ if (/^~/.test(m[1]) || (target !== root && !target.startsWith(root + path.sep))) return `writes output only inside the workspace (not ${m[1]})`;
111
+ }
112
+ return null;
113
+ }
114
+
115
+ /** The folders a command's redirects write into (inside the workspace, checked by refusal), so a first run doesn't
116
+ * fail with "Directory nonexistent" before project-context/results/ exists. */
117
+ export function redirectDirs(cmd, from = process.cwd()) {
118
+ let at = path.resolve(from);
119
+ for (const m of (cmd.match(PREFIX)?.[0] || '').matchAll(/cd\s+("[^"]*"|'[^']*'|\S+)/g)) at = path.resolve(at, m[1].replace(/^["']|["']$/g, ''));
120
+ const bare = cmd.replace(PREFIX, '').replace(/'[^']*'|"[^"]*"/g, '""');
121
+ return [...bare.matchAll(/\d?>>?\s*([^\s&]+)/g)].filter((m) => !/^&\d$/.test(m[1])).map((m) => path.dirname(path.resolve(at, m[1])));
122
+ }
123
+
124
+ export const allowed = (cmd) => !refusal(cmd);
125
+
126
+ function main() {
127
+ const argv = process.argv.slice(2);
128
+ const cmd = commandOf(argv);
129
+ if (!cmd) { console.log('usage: node .claude/skills/orion/scripts/quiet.mjs <test, build or install command>'); process.exit(2); }
130
+ const why = refusal(cmd);
131
+ if (why) {
132
+ console.log(`quiet: ${why}; run this one directly: ${mask(cmd).slice(0, 120)}`);
133
+ process.exit(2);
134
+ }
135
+ for (const d of redirectDirs(cmd)) { try { fs.mkdirSync(d, { recursive: true }); } catch { /* the shell reports it */ } }
136
+ const root = workspaceRoot(process.cwd());
137
+ const logs = path.join(root, 'project-context', 'logs');
138
+ fs.mkdirSync(logs, { recursive: true });
139
+ // The logs stay out of git: an ignore file of their own, never an edit to the project's own .gitignore.
140
+ const ignore = path.join(logs, '.gitignore');
141
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, '*\n');
142
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..*/, '');
143
+ const slug = cmd.replace(/[^\w]+/g, '-').slice(0, 40).replace(/-+$/, '');
144
+ const log = path.join(logs, `${stamp}-${slug}.log`);
145
+ const t0 = Date.now();
146
+ const r = spawnSync(cmd, { shell: true, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024,
147
+ env: { ...process.env, FORCE_COLOR: '0', npm_config_progress: 'false', npm_config_fund: 'false', npm_config_audit: 'false' } });
148
+ const raw = mask(`${r.stdout || ''}${r.stderr || ''}`);
149
+ fs.writeFileSync(log, raw);
150
+ const code = r.status === null ? 1 : r.status;
151
+ const cap = Number(process.env.ORION_QUIET_LINES) || 60;
152
+ const kept = summarize(raw, cap);
153
+ const secs = ((Date.now() - t0) / 1000).toFixed(1);
154
+ console.log(`$ ${mask(cmd)}\nexit ${code} · ${secs}s · ${raw.split('\n').length} lines of output, ${kept.length} kept`);
155
+ if (kept.length) console.log(kept.join('\n'));
156
+ console.log(`full log: ${path.relative(process.cwd(), log) || log}`);
157
+ process.exit(code);
158
+ }
159
+
160
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
@@ -8,7 +8,7 @@
8
8
  * Run report: `# <story> · test report`; a bold verdict (✅ ⚠️ ❌) in the first lines; the facts table (| Story |);
9
9
  * Coverage, What was added, Run it yourself; a <details> block for engineers; the footer.
10
10
  * Assessment: `# <suite> · assessment`; the verdict; the facts table (| Suite |, | Baseline run |, | Findings |); Top
11
- * issues, Fix it (`/orion fix A-…`); a <details> block holding the full findings table (| F | Rule | …); the footer. Above the
11
+ * issues, Fix it (how to ask for fixes in plain words); a <details> block holding the full findings table (| F | Rule | …); the footer. Above the
12
12
  * details block: at most 45 lines, and no decision ids (D-nnn), gate numbers, agent names, rule codes, temporary-folder
13
13
  * paths or a bare "unknown". Each finding names what to change.
14
14
  * Exit code: 0 passes · 1 findings · 2 wrong arguments or unreadable file.
@@ -20,7 +20,7 @@ const AGENTS = 'requirement-analyst|environment-discovery|codebase-analyst|autom
20
20
  const BANNED = [
21
21
  [/\bD-\d{3}\b/, 'a decision id: move it to the details block'],
22
22
  [/\bGate \d\b/, 'a gate number: say what happened in plain words'],
23
- [new RegExp(`\\b(${AGENTS})\\b`), 'an agent name: say what was done, not who did it'],
23
+ [new RegExp(`(?<![\\w./-])(${AGENTS})(?![\\w/-]|\\.\\w)`), 'an agent name: say what was done, not who did it'], // not inside a name such as performance-reviewer.web.app
24
24
  [/\b[UPM]\d{1,2}\b(?!\/)/, 'a rule code: describe the issue in plain words'],
25
25
  [/\/tmp\/|\\Temp\\|AppData/, 'a temporary-folder path: use a path inside the workspace'],
26
26
  [/\(unknown\)|: unknown\b|\bunknown\./, 'a bare "unknown": say what was not checked and why'],
@@ -36,9 +36,12 @@ export function checkReport(text) {
36
36
  if (!/^# .+ · (test report|assessment)$/.test(lines[0] || '')) out.push("first line: '# <story title> · test report' (or '# <suite folder> · assessment')");
37
37
  const verdicts = assess ? '✅ In good shape · ⚠️ Works, needs fixes · ❌ Serious issues' : '✅ Ready to accept · ⚠️ Ready, with notes · ❌ Not ready';
38
38
  if (!lines.slice(1, 5).some((l) => /^\*\*.*(✅|⚠️|❌)/.test(l))) out.push(`no bold verdict (${verdicts}) in the first lines`);
39
+ // A template placeholder left in (`<what was built…>`, `<none | one line each…>`): fill it or remove the line.
40
+ // The template itself (its title is a placeholder) is checked for shape only.
41
+ if (!/^# </.test(lines[0] || '')) lines.forEach((l, i) => { if (/<[A-Za-z✅⚠❌][^<>\n=]*\s[^<>\n=]*>/.test(l) && !/<\/?(details|summary)\b[^>]*>/.test(l) && !/^\s*(```| )/.test(l)) out.push(`line ${i + 1}: a template placeholder is left: ${l.trim().slice(0, 80)}`); });
39
42
  const facts = assess ? [/^\| Suite \|/m, /^\| Baseline run \|/m, /^\| Findings \|/m] : [/^\| Story \|/m];
40
43
  if (!facts.every((rx) => rx.test(text))) out.push(assess ? 'no facts table (| Suite |, | Baseline run |, | Findings |, | Date |)' : 'no facts table (| Story | … |, | App |, | Tests |, | Runs |, | Date |)');
41
- const need = assess ? ['## Top issues', '## Fix it', '/orion fix A-', '<details>', '<summary>All findings and details for engineers</summary>']
44
+ const need = assess ? ['## Top issues', '## Fix it', '<details>', '<summary>All findings and details for engineers</summary>']
42
45
  : ['## Coverage', '## What was added', '## Run it yourself', '<details>', '<summary>Details for engineers</summary>'];
43
46
  for (const h of need) if (!text.includes(h)) out.push(`missing: ${h}`);
44
47
  if (assess && !/^\| F \| Rule \|/m.test(text.split('<details>')[1] || '')) out.push('the full findings table (| F | Rule | … |) is not inside the details block');
@@ -0,0 +1,186 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Report draft: writes the run report (templates/project-context/report.md) filled from the run's own data, so an agent
4
+ * completes a few lines instead of writing a report by hand and fixing report_check findings one by one. In a measured
5
+ * single-agent run (Cursor, 2026-11-19) writing the report took about ten rounds of check and fix.
6
+ *
7
+ * Usage (from the workspace root):
8
+ * node .claude/skills/orion/scripts/report_make.mjs --project <test project> --story <KEY> --run <run id>
9
+ * [--title "<story title>"] [--app <base URL>] [--command "npm test"] [--out project-context/runs/<run id>.report.md]
10
+ * Reads: project-context/test-designs/<story>/design.md (the AC table `| AC… | Meaning |` and the case table
11
+ * `| ID | What it checks | … | AC |`), project-context/results/<run id>-*.json (results_parse output; the runner's raw
12
+ * .pw.json is skipped), the run file's `fail checks <done>/<new>` line, the project's package.json and its git status.
13
+ * Writes the draft (it never overwrites a report without --force) and prints the lines still to fill: each is a
14
+ * `<…>` placeholder that report_check reports until it is filled or removed.
15
+ * Exit code: 0 written · 1 nothing to report (no results files) · 2 wrong arguments.
16
+ */
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { spawnSync } from 'node:child_process';
20
+ import { pathToFileURL } from 'node:url';
21
+
22
+ /** Rows of the first Markdown table whose header matches `head`. */
23
+ export function table(text, head) {
24
+ const lines = text.replace(/\r/g, '').split('\n');
25
+ const i = lines.findIndex((l) => head.test(l));
26
+ if (i < 0) return [];
27
+ const cols = lines[i].split('|').slice(1, -1).map((c) => c.trim());
28
+ const rows = [];
29
+ for (let j = i + 2; j < lines.length && lines[j].trim().startsWith('|'); j++) {
30
+ const cells = lines[j].split('|').slice(1, -1).map((c) => c.trim());
31
+ rows.push(Object.fromEntries(cols.map((c, k) => [c, cells[k] ?? ''])));
32
+ }
33
+ return rows;
34
+ }
35
+
36
+ /** Per case id: how many recorded runs it passed first time, out of how many it ran in. */
37
+ export function tally(resultFiles, story) {
38
+ const out = new Map();
39
+ for (const f of resultFiles) {
40
+ let d;
41
+ try { d = JSON.parse(fs.readFileSync(f, 'utf8')); } catch { continue; }
42
+ for (const t of d.tests || []) {
43
+ if (!t.test_id || (t.story && t.story !== story)) continue;
44
+ const id = String(t.test_id).replace(/^.*:/, '');
45
+ const c = out.get(id) || { pass: 0, runs: 0, title: t.title, file: t.file };
46
+ c.runs++;
47
+ if (t.status === 'passed' && (t.attempts || 1) === 1) c.pass++;
48
+ out.set(id, c);
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ const pick = (o, ...names) => { for (const n of names) for (const k of Object.keys(o)) if (k.toLowerCase().startsWith(n)) return o[k]; return ''; };
55
+
56
+ /** Files as at most 6 lines: the test files by name, the rest by folder with a count. */
57
+ export function grouped(files, testFiles = []) {
58
+ if (files.length > 10) {
59
+ const tests = files.filter((f) => testFiles.includes(f));
60
+ const folders = [...new Set(files.filter((f) => !tests.includes(f)).map((f) => (f.includes('/') ? f.split('/')[0] + '/' : 'project root')))];
61
+ return [...tests.slice(0, 4).map((f) => `- **Tests:** \`${f}\``), `- **With them:** ${files.length - tests.length} files in ${folders.slice(0, 8).map((x) => (x === 'project root' ? x : `\`${x}\``)).join(', ')}${folders.length > 8 ? ' and more' : ''}`].join('\n');
62
+ }
63
+ const by = new Map();
64
+ for (const f of files) { const d = path.posix.dirname(f); by.set(d, [...(by.get(d) || []), path.posix.basename(f)]); }
65
+ const lines = [...by].map(([d, fs]) => (fs.length <= 2 ? fs.map((x) => `\`${d === '.' ? x : `${d}/${x}`}\``).join(', ') : d === '.' ? `${fs.length} files in the project root` : `\`${d}/\` (${fs.length} files)`));
66
+ return (lines.length > 6 ? [...lines.slice(0, 5), `and ${lines.length - 5} more folders (git status)`] : lines).map((l) => `- ${l}`).join('\n');
67
+ }
68
+
69
+ export function draft(o, data) {
70
+ const { acRows, caseRows, counts, runs, fail, tool, testDir, command, files, date } = data;
71
+ const ids = [...counts.keys()].sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
72
+ const allPass = ids.length && ids.every((id) => counts.get(id).pass === counts.get(id).runs && counts.get(id).runs >= 3);
73
+ const passedEach = runs ? `${ids.filter((id) => counts.get(id).pass === counts.get(id).runs).length}/${ids.length}` : '0';
74
+ const verdict = allPass ? '✅ Ready to accept' : '<⚠️ Ready, with notes | ❌ Not ready>';
75
+ const failLine = fail ? (fail[0] === fail[1] ? 'each new test also failed when its check was broken' : `fail check: ${fail[0]} of ${fail[1]} new tests`) : '<each new test also failed when its check was broken | fail check not run: reason>';
76
+ const covered = new Set();
77
+ const cov = [];
78
+ const caseOf = (id) => caseRows.find((r) => pick(r, 'id') === id) || {};
79
+ const res = (id) => (counts.has(id) ? `${counts.get(id).pass === counts.get(id).runs ? '✅' : '❌'} ${counts.get(id).pass}/${counts.get(id).runs}` : 'not run');
80
+ for (const ac of acRows) {
81
+ const acId = pick(ac, 'ac');
82
+ const cases = caseRows.filter((r) => pick(r, 'ac').split(/[,\s]+/).includes(acId));
83
+ if (!cases.length) { cov.push(`| ${pick(ac, 'meaning', 'criterion', 'requirement')} | not covered: <reason> | — |`); continue; }
84
+ const cids = cases.map((c) => pick(c, 'id'));
85
+ cids.forEach((id) => covered.add(id));
86
+ const results = [...new Set(cids.map(res))];
87
+ const tests = cids.length === 1 ? `${cids[0]} ${pick(cases[0], 'what')}` : cids.join(', ');
88
+ cov.push(`| ${pick(ac, 'meaning', 'criterion', 'requirement')} | ${tests} | ${results.length === 1 ? results[0] + (cids.length > 1 ? ' each' : '') : cids.map((id) => `${id} ${res(id)}`).join(' · ')} |`);
89
+ }
90
+ for (const id of ids) if (!covered.has(id)) cov.push(`| ${pick(caseOf(id), 'what') || counts.get(id).title} *(added)* | ${id} ${pick(caseOf(id), 'what') || counts.get(id).title} | ${res(id)} |`);
91
+ const n = ids.length;
92
+ const title = o.title || `<${o.story} story title>`;
93
+ return `# ${title} · test report
94
+
95
+ **${verdict}**: ${allPass ? `${n} new test${n === 1 ? '' : 's'}, all passed in ${runs} run${runs === 1 ? '' : 's'} in a row` : '<what was built and how it ran>'}${allPass && fail && fail[0] === fail[1] ? '; each failed when its check was broken' : ''}.
96
+
97
+ | | |
98
+ |---|---|
99
+ | Story | ${o.story}${o.title ? ` · ${o.title}` : ''} |
100
+ | App | ${o.app || '<base URL> (<test environment>)'} |
101
+ | Tests | ${n} ${tool} tests · \`${testDir}\` |
102
+ | Runs | ${runs} runs, retries off: ${passedEach} passed each time · ${failLine} |
103
+ | Date | ${date} |
104
+
105
+ ## Coverage
106
+ | Requirement | Test | Result |
107
+ |---|---|---|
108
+ ${cov.join('\n') || '| <requirement> | <TS-n> | <result> |'}
109
+
110
+ ## Needs your attention
111
+ - ${allPass ? 'Nothing: every requirement above has a passing test.' : '<one line each, most important first, each ending with what to do>'}
112
+
113
+ ## What was added
114
+ ${files.length ? grouped(files, data.testFiles || []) : '- <files>'}
115
+
116
+ ## Run it yourself
117
+ \`\`\`
118
+ cd ${o.project}
119
+ ${command}
120
+ \`\`\`
121
+
122
+ <details>
123
+ <summary>Details for engineers</summary>
124
+
125
+ - **Runs:** ${runs} recorded runs in \`project-context/results/\` (${o.run}-1 … ${o.run}-${runs}); the run summary page is \`${path.join(o.project, 'test-summary', 'index.html').split(path.sep).join('/')}\`.
126
+ - **Review:** <blocking findings n (fixed) · suggestions n>
127
+ - **Failures and fixes during the run:** <none | one line each: test · cause · what was done>
128
+ - **Approvals:** <setup confirmed · test cases accepted · installs approved>
129
+ - **Not checked:** <anything not confirmed, and why | nothing>
130
+
131
+ </details>
132
+
133
+ _Written by Orion's agents from checked results. Not yet accepted._
134
+ `;
135
+ }
136
+
137
+ function main() {
138
+ const argv = process.argv.slice(2);
139
+ const o = { force: false };
140
+ for (let i = 0; i < argv.length; i++) {
141
+ const k = argv[i];
142
+ if (k === '--force') o.force = true;
143
+ else if (k.startsWith('--')) o[k.slice(2)] = argv[++i];
144
+ }
145
+ if (!o.project || !o.story || !o.run) { console.log('usage: node .claude/skills/orion/scripts/report_make.mjs --project <test project> --story <KEY> --run <run id> [--title …] [--app <url>] [--out <file>]'); process.exit(2); }
146
+ const out = o.out || path.join('project-context', 'runs', `${o.run}.report.md`);
147
+ if (fs.existsSync(out) && !o.force) { console.log(`report_make: ${out} exists; pass --force to write a new draft over it`); process.exit(2); }
148
+ const resDir = path.join('project-context', 'results');
149
+ const resultFiles = fs.existsSync(resDir) ? fs.readdirSync(resDir).filter((f) => f.startsWith(o.run) && f.endsWith('.json') && !/\.(pw|raw|report)\.json$/.test(f)).sort().map((f) => path.join(resDir, f)) : [];
150
+ if (!resultFiles.length) { console.log(`report_make: no results files for ${o.run} in ${resDir} (results_parse after each counted run)`); process.exit(1); }
151
+ const designFile = path.join('project-context', 'test-designs', o.story, 'design.md');
152
+ const design = fs.existsSync(designFile) ? fs.readFileSync(designFile, 'utf8') : '';
153
+ const acRows = table(design, /^\|\s*AC\b[^|]*\|\s*(Meaning|Criterion|Requirement)/i);
154
+ const caseRows = table(design, /^\|\s*ID\s*\|\s*What it checks/i);
155
+ const counts = tally(resultFiles, o.story);
156
+ const runFile = path.join('project-context', 'runs', `${o.run}.md`);
157
+ const rf = fs.existsSync(runFile) ? fs.readFileSync(runFile, 'utf8') : '';
158
+ const fm = rf.match(/fail checks (\d+)\/(\d+)/);
159
+ const pkgFile = path.join(o.project, 'package.json');
160
+ const pkg = fs.existsSync(pkgFile) ? JSON.parse(fs.readFileSync(pkgFile, 'utf8')) : null;
161
+ const deps = pkg ? { ...pkg.dependencies, ...pkg.devDependencies } : {};
162
+ const ts = fs.existsSync(path.join(o.project, 'tsconfig.json'));
163
+ const tool = deps['@playwright/test'] ? `UI · Playwright + ${ts ? 'TypeScript' : 'JavaScript'}` : fs.existsSync(path.join(o.project, 'pom.xml')) ? 'Java' : fs.existsSync(path.join(o.project, 'pytest.ini')) ? 'Python (pytest)' : '<tool + language>';
164
+ // Results name files relative to the runner's test folder (`ui/x.spec.js`): find each one in the project.
165
+ const all = [];
166
+ const walk = (d, rel) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) { if (['node_modules', '.git', 'test-results', 'playwright-report', 'test-summary'].includes(e.name)) continue; const r = rel ? `${rel}/${e.name}` : e.name; if (e.isDirectory()) walk(path.join(d, e.name), r); else all.push(r); } };
167
+ if (fs.existsSync(o.project)) walk(o.project, '');
168
+ const testFiles = [...new Set([...counts.values()].map((c) => c.file).filter(Boolean).map((f) => f.replace(/^(\.\.\/)+/, '')).map((f) => all.find((a) => a === f || a.endsWith(`/${f}`)) || f))];
169
+ const testDir = testFiles.length ? path.posix.join(o.project.split(path.sep).join('/'), path.posix.dirname(testFiles[0])) : o.project;
170
+ const command = o.command || (pkg && pkg.scripts && pkg.scripts.test ? 'npm test' : '<one command>');
171
+ let files = [];
172
+ // Changed and new files, relative to the project (git ls-files answers relative to the folder it runs in).
173
+ const git = spawnSync('git', ['ls-files', '--modified', '--others', '--exclude-standard'], { cwd: o.project, encoding: 'utf8' });
174
+ if (git.status === 0 && git.stdout.trim()) files = [...new Set(git.stdout.trim().split('\n'))].filter((f) => !/(^|\/)(node_modules|test-results|playwright-report|test-summary|auth)\/|\.env$|package-lock\.json$/.test(f));
175
+ if (!files.length) files = testFiles;
176
+ const runs = Math.max(0, ...[...counts.values()].map((c) => c.runs));
177
+ const date = new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
178
+ const text = draft(o, { testFiles, acRows, caseRows, counts, runs, fail: fm ? [Number(fm[1]), Number(fm[2])] : null, tool, testDir, command, files, date });
179
+ fs.mkdirSync(path.dirname(out), { recursive: true });
180
+ fs.writeFileSync(out, text);
181
+ const todo = text.split('\n').map((l, i) => [i + 1, l]).filter(([, l]) => /<[^<>\n]*\s[^<>\n]*>/.test(l) && !/<\/?(details|summary)>/.test(l));
182
+ console.log(`report draft: ${out} · ${counts.size} cases · ${runs} runs${design ? '' : ' · no design.md: coverage from results only'}`);
183
+ console.log(todo.length ? `fill ${todo.length} line(s), then run report_check.mjs ${out}:\n${todo.map(([n, l]) => ` ${n}: ${l.slice(0, 120)}`).join('\n')}` : `nothing to fill; run report_check.mjs ${out}`);
184
+ }
185
+
186
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
@@ -4,7 +4,7 @@
4
4
  * counted run (execution skill); the Orion graph and the failure analyst read its output.
5
5
  *
6
6
  * Usage (from the workspace root):
7
- * node .claude/skills/orion/scripts/results_parse.mjs <report file or folder> [...] --run <run id> [--attempt-run <n>]
7
+ * node .claude/skills/orion/scripts/results_parse.mjs <report file or folder> [...] --run <run id>-<n>
8
8
  * [--out project-context/results/<run id>.json]
9
9
  *
10
10
  * Reads: JUnit XML (Playwright `junit`, Maven Surefire/Failsafe, Gradle, pytest `--junitxml`, Cypress and WebdriverIO
@@ -159,7 +159,7 @@ function main() {
159
159
  if (!inputs.length || !opt.run) usage();
160
160
  if (!/^[\w.-]+$/.test(opt.run)) usage('--run takes a run id such as 20261112-1430');
161
161
 
162
- const rows = []; const sources = []; const skipped = [];
162
+ const rows = []; const sources = []; const skipped = []; const runErrors = [];
163
163
  for (const f of reportFiles(inputs)) {
164
164
  let text;
165
165
  try { text = fs.readFileSync(f, 'utf8').replace(/^/, ''); } catch { usage(`can't read ${f}`); }
@@ -167,7 +167,19 @@ function main() {
167
167
  let found = [];
168
168
  let format = null;
169
169
  if (/^\s*\{/.test(text)) {
170
- try { const j = JSON.parse(text); if (Array.isArray(j.suites) && j.stats) { format = 'playwright-json'; found = parsePlaywrightJson(j, rel); } } catch { /* not JSON */ }
170
+ try {
171
+ const j = JSON.parse(text);
172
+ if (Array.isArray(j.suites) && j.stats) { format = 'playwright-json'; found = parsePlaywrightJson(j, rel); }
173
+ // The starters' run summary (test-summary/results.json), written on every run by reporters/summaryReporter.
174
+ else if (j.format === 'orion-summary/1' && Array.isArray(j.tests)) {
175
+ format = 'orion-summary';
176
+ found = j.tests.map((t) => ({ title: String(t.title || ''), file: String(t.file || '').replace(/:\d+$/, ''), project: t.project || null,
177
+ status: ['passed', 'failed', 'flaky', 'skipped'].includes(t.status) ? t.status : 'failed', duration_ms: t.duration_ms ?? null,
178
+ attempts: t.attempts || 1, failure_sig: t.failure_sig ? signature(String(t.failure_sig)) : null, source: rel }));
179
+ }
180
+ // A run that failed before any test (global setup, sign-in, config) lists it in errors[]: say so, never "no tests".
181
+ if (Array.isArray(j.errors) && j.errors.length) runErrors.push(`${rel}: ${String(j.errors[0].message || j.errors[0].value || j.errors[0]).split('\n')[0].replace(/((?:password|passwd|token|secret)\s*[=:]\s*)\S+/gi, '$1***').slice(0, 200)}`);
182
+ } catch { /* not JSON */ }
171
183
  } else if (/<TestRun\b/.test(text)) { format = 'trx'; found = parseTrx(text, rel); }
172
184
  else if (/<testsuites?\b/.test(text)) { format = 'junit'; found = parseJUnit(text, rel); }
173
185
  if (!format) { skipped.push(rel); continue; }
@@ -191,6 +203,7 @@ function main() {
191
203
  for (const t of tests) totals[t.status]++;
192
204
  const report = { format: FORMAT, run_id: opt.run, sources, skipped_files: skipped, totals, tests };
193
205
  const text = `${JSON.stringify(report, null, 2)}\n`;
206
+ if (!tests.length && runErrors.length) { console.log(`results: the run failed before any test ran: ${runErrors[0]}`); process.exit(1); }
194
207
  if (!tests.length) { console.log(`results: no test results in ${inputs.join(', ')}${skipped.length ? ` (not reports: ${skipped.join(', ')})` : ''}`); process.exit(1); }
195
208
  if (opt.out) {
196
209
  insideWorkspace(opt.out, '--out');
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Rules digest: prints only the section of a skill or reference file that a step needs, instead of the whole file.
4
+ * In measured runs the agent's largest tool output was Orion's own rule files dumped whole (`conversation.md`,
5
+ * `setup-card.md`, 9–24 KB per read) and then re-read on every later turn (evals/workflows/runs/2026-11-18-cost-
6
+ * breakdown.md). Orion's own version of the "knowledge graph instead of whole files" idea, for its rules.
7
+ *
8
+ * Usage (from the workspace root; a plugin install: run it from the skill's own folder):
9
+ * node .claude/skills/orion/scripts/rules.mjs <file> --list the sections, each with its size
10
+ * node .claude/skills/orion/scripts/rules.mjs <file> <words>... the section(s) whose title holds all the words
11
+ * node .claude/skills/orion/scripts/rules.mjs <file> --all the whole file (only when you need all of it)
12
+ * <file>: a path, or a short name looked up under .claude/skills/ (`conversation`, `setup-card`, `orion/SKILL`,
13
+ * `execution/SKILL`, `delivery-formats`, …).
14
+ * Sections are the Markdown headings (##, ###) and the top-level numbered items of a list (`3.`, `3b.`, `10.`), whose
15
+ * title is their bold text. Fenced code blocks inside a section stay with it. Output is capped at 8 KB unless --all.
16
+ * Exit code: 0 printed · 1 no section matched (the list is printed instead) · 2 wrong arguments or no such file.
17
+ */
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { fileURLToPath, pathToFileURL } from 'node:url';
21
+
22
+ const CAP = 8 * 1024;
23
+
24
+ function resolve(name) {
25
+ if (fs.existsSync(name) && fs.statSync(name).isFile()) return name;
26
+ const roots = ['.claude/skills', path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..')];
27
+ for (const root of roots) {
28
+ if (!fs.existsSync(root)) continue;
29
+ const want = name.replace(/\.md$/, '').toLowerCase();
30
+ const hits = [];
31
+ const walk = (d) => {
32
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
33
+ const p = path.join(d, e.name);
34
+ if (e.isDirectory()) { if (!['templates', 'node_modules', 'scripts'].includes(e.name)) walk(p); }
35
+ else if (e.name.endsWith('.md')) {
36
+ const rel = p.replace(/\\/g, '/').toLowerCase().replace(/\.md$/, '');
37
+ if (rel.endsWith(`/${want}`)) hits.push(p);
38
+ }
39
+ }
40
+ };
41
+ walk(root);
42
+ if (hits.length === 1) return hits[0];
43
+ if (hits.length > 1) { console.log(`rules: "${name}" is ambiguous: ${hits.join(', ')}`); process.exit(2); }
44
+ }
45
+ return null;
46
+ }
47
+
48
+ /** Sections of a Markdown file: headings and top-level numbered items, with their line ranges. */
49
+ export function sections(text) {
50
+ const lines = text.split('\n');
51
+ const starts = [];
52
+ let fence = false;
53
+ lines.forEach((l, i) => {
54
+ if (/^\s*(```|~~~)/.test(l)) fence = !fence;
55
+ if (fence) return;
56
+ const h = l.match(/^(#{2,4})\s+(.*)/);
57
+ const n = l.match(/^(\d+[a-z]?)\.\s+(?:\*\*(.+?)\*\*)?(.*)/);
58
+ if (h) starts.push({ line: i, level: h[1].length, title: h[2].trim() });
59
+ else if (n) starts.push({ line: i, level: 9, title: `${n[1]}. ${(n[2] || n[3]).trim().slice(0, 90)}` });
60
+ });
61
+ return starts.map((s, k) => {
62
+ let end = lines.length;
63
+ for (let j = k + 1; j < starts.length; j++) {
64
+ if (starts[j].level <= s.level || (s.level === 9 && starts[j].level === 9) || (s.level < 9 && starts[j].level < 9 && starts[j].level <= s.level)) { end = starts[j].line; break; }
65
+ }
66
+ const body = lines.slice(s.line, end).join('\n').replace(/\s+$/, '');
67
+ return { title: s.title, start: s.line + 1, bytes: Buffer.byteLength(body), body };
68
+ });
69
+ }
70
+
71
+ function main() {
72
+ const [name, ...rest] = process.argv.slice(2);
73
+ if (!name) { console.log('usage: node .claude/skills/orion/scripts/rules.mjs <file> (--list | --all | <words>...)'); process.exit(2); }
74
+ const file = resolve(name);
75
+ if (!file) { console.log(`rules: no such file: ${name}`); process.exit(2); }
76
+ const text = fs.readFileSync(file, 'utf8');
77
+ if (rest[0] === '--all') { process.stdout.write(text); return; }
78
+ const secs = sections(text);
79
+ const list = () => {
80
+ console.log(`${file} · ${Buffer.byteLength(text)} bytes · ${secs.length} sections (read one with: rules.mjs ${name} <words from its title>)`);
81
+ for (const s of secs) console.log(` ${String(s.start).padStart(4)} ${(s.bytes / 1024).toFixed(1).padStart(5)} KB ${s.title}`);
82
+ };
83
+ if (!rest.length || rest[0] === '--list') { list(); return; }
84
+ const words = rest.join(' ').toLowerCase().split(/\s+/).filter(Boolean);
85
+ const hits = secs.filter((s) => words.every((w) => s.title.toLowerCase().includes(w)));
86
+ if (!hits.length) { console.log(`rules: no section of ${file} has "${rest.join(' ')}" in its title`); list(); process.exit(1); }
87
+ let out = hits.map((s) => `<!-- ${file}:${s.start} · ${s.title} -->\n${s.body}`).join('\n\n');
88
+ if (Buffer.byteLength(out) > CAP) out = `${out.slice(0, CAP)}\n… cut at 8 KB: narrow the words, or use --all`;
89
+ console.log(out);
90
+ }
91
+
92
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
@@ -20,6 +20,16 @@
20
20
  * state <stack|ui_map|design|build|run|heals|code> "<value>" replaces that Run state line (code: the header line)
21
21
  * metric <name>=<value> [<name>=<value> …] sets fields of the Metrics line (`stopped` defaults to now when given
22
22
  * as `stopped=now`); `+1` adds one to a number (e.g. delegations=+1)
23
+ * Read-only (nothing is written; use them alone, not with `+`):
24
+ * status where the run stands, for a run cut off or picked up in a new session:
25
+ * each gate's state, the first gate not ✓ (the loop's next step), the
26
+ * gates already passed (not redone unless their inputs changed), the Run
27
+ * state lines and the last 3 log rows. Exit 0 open · 4 COMPLETE (gate 8 ✓)
28
+ * budget [--usage <usage.json>] minutes since the run started (and est. USD from usage_report.mjs's
29
+ * totals.usd_est, Claude Code only; else "unknown") against the run budget
30
+ * in project-context/retry-policy.md ("Run budget"; defaults 60 min, USD 10).
31
+ * Minutes are wall time since the run started, waits for the user included.
32
+ * Exit 0 within · 3 over (ask the user at the next gate: carry on or stop)
23
33
  * Output: one line per action. Exit code: 0 done · 1 the run file or a row wasn't found · 2 wrong arguments.
24
34
  * Never writes secrets: refuses a value that looks like `password=…`, a bearer token or a JWT.
25
35
  */
@@ -153,8 +163,65 @@ function apply(lines, act, t) {
153
163
  return lines;
154
164
  }
155
165
 
166
+ /** `status`: where a run stands, so a new session continues it instead of starting over. */
167
+ function status(file, lines) {
168
+ const gates = [];
169
+ for (const l of lines) {
170
+ const m = l.match(/^\| ([1-8]) \| (\S+) \| ([^|]*)\| ([^|]*)\| ([^|]*)\| ([^|]*)\| ([^|]*)\|/);
171
+ if (m) gates.push({ gate: +m[1], state: m[2], agent: m[3].trim(), task: m[4].trim(), status: m[7].trim() });
172
+ }
173
+ if (gates.length !== 8) die(1, `${file}: expected 8 gate rows, found ${gates.length}`);
174
+ const req = (lines.find((l) => /^requirement: /.test(l)) || '').slice(13);
175
+ console.log(`run: ${path.basename(file, '.md')} · ${req}`);
176
+ console.log(`gates: ${gates.map((g) => `${g.gate} ${g.state}`).join(' ')}`);
177
+ const done = gates.filter((g) => g.state === '✓').map((g) => g.gate);
178
+ const next = gates.find((g) => g.state !== '✓');
179
+ if (!next) { console.log('state: COMPLETE (gate 8 ✓): nothing to resume'); process.exit(4); }
180
+ console.log(`passed: ${done.length ? done.join(', ') : 'none'} (not redone unless the requirement, the code or the app changed since)`);
181
+ console.log(`next: gate ${next.gate} (${next.state}${next.task ? `, task: ${next.task}` : ''}${next.status ? `, last status: ${next.status}` : ''}) · ${next.agent}`);
182
+ for (const l of lines.filter((x) => /^- (stack|ui_map|design|build|run|heals): /.test(x))) {
183
+ console.log(`state ${/<[^>]+>/.test(l) ? `${l.slice(2, l.indexOf(':'))}: not recorded` : l.slice(2)}`);
184
+ }
185
+ const i = lines.findIndex((l) => /^### Log/.test(l));
186
+ const log = i < 0 ? [] : lines.slice(i + 3).filter((l, k, arr) => l.startsWith('|') && arr.slice(0, k).every((x) => x.startsWith('|')));
187
+ for (const l of log.slice(-3)) console.log(`log ${l}`);
188
+ }
189
+
190
+ /** `budget`: minutes (and est. USD where known) against the run budget in retry-policy.md. */
191
+ function budget(file, lines, rest) {
192
+ const req = (lines.find((l) => /^requirement: /.test(l)) || '');
193
+ const st = req.match(/started (\d{4}-\d\d-\d\dT\d\d:\d\d)/);
194
+ if (!st) die(1, `${file}: no start time on the requirement line`);
195
+ const mins = Math.round((Date.now() - new Date(st[1]).getTime()) / 60000);
196
+ const policy = path.join('project-context', 'retry-policy.md');
197
+ const ptext = fs.existsSync(policy) ? fs.readFileSync(policy, 'utf8') : '';
198
+ const limMin = +((ptext.match(/^- minutes:\s*(\d+)/m) || [])[1] || 60);
199
+ const limUsd = +((ptext.match(/^- usd:\s*([\d.]+)/m) || [])[1] || 10);
200
+ let usd = 'unknown';
201
+ const ui = rest.indexOf('--usage');
202
+ if (ui >= 0) {
203
+ const f = rest[ui + 1];
204
+ try { const v = JSON.parse(fs.readFileSync(f, 'utf8')).totals?.usd_est; if (typeof v === 'number') usd = v; } catch { /* stays unknown */ }
205
+ }
206
+ const over = [];
207
+ if (mins > limMin) over.push(`${mins} min of ${limMin}`);
208
+ if (typeof usd === 'number' && usd > limUsd) over.push(`est. USD ${usd.toFixed(2)} of ${limUsd}`);
209
+ console.log(`budget: ${mins} min of ${limMin} (wall time, waits included) · est. USD ${typeof usd === 'number' ? usd.toFixed(2) : 'unknown'} of ${limUsd}${ptext ? '' : ' (defaults: no project-context/retry-policy.md)'}`);
210
+ if (over.length) {
211
+ console.log(`over: ${over.join(', ')}: at the next gate, ask the user one line: carry on (and by how much) or stop here with what exists`);
212
+ process.exit(3);
213
+ }
214
+ }
215
+
156
216
  function main() {
157
217
  const argv = process.argv.slice(2);
218
+ if (['status', 'budget'].includes(argv[1])) {
219
+ const file = argv[0];
220
+ if (!file || !fs.existsSync(file)) die(file ? 1 : 2, file ? `no run file ${file}` : 'usage: run_state.mjs <run file> status | budget [--usage <usage.json>]');
221
+ insideWorkspace(file, 'the run file');
222
+ const lines = fs.readFileSync(file, 'utf8').split('\n');
223
+ return argv[1] === 'status' ? status(file, lines) : budget(file, lines, argv.slice(2));
224
+ }
158
225
  if (argv[0] === 'init') return init(argv.slice(1));
159
226
  const file = argv[0];
160
227
  if (!file || !fs.existsSync(file)) die(file ? 1 : 2, file ? `no run file ${file}` : 'usage: run_state.mjs <run file> <action> [+ <action> …] | init <key> …');