@maestrofrontier/frontier 1.4.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 (43) hide show
  1. package/AGENTS.md +214 -0
  2. package/CLAUDE.md +29 -0
  3. package/LICENSE +21 -0
  4. package/README.md +521 -0
  5. package/bin/maestro.cjs +75 -0
  6. package/commands/compress.md +36 -0
  7. package/commands/context-bar.md +30 -0
  8. package/commands/frontier.md +124 -0
  9. package/commands/settings.md +101 -0
  10. package/commands/terse.md +23 -0
  11. package/commands/update.md +59 -0
  12. package/docs/orchestration.md +168 -0
  13. package/frontier/cli.cjs +248 -0
  14. package/frontier/config.cjs +441 -0
  15. package/frontier/dispatch.cjs +255 -0
  16. package/frontier/judge.cjs +92 -0
  17. package/frontier/run.cjs +148 -0
  18. package/frontier/schema.cjs +112 -0
  19. package/frontier/semaphore.cjs +49 -0
  20. package/frontier/synthesize.cjs +79 -0
  21. package/hooks/frontier-autorun.cjs +124 -0
  22. package/hooks/hooks.json +103 -0
  23. package/hooks/maestro-doctrine-guard.cjs +81 -0
  24. package/hooks/maestro-gate-reminder.cjs +58 -0
  25. package/hooks/maestro-gate-telemetry.cjs +77 -0
  26. package/hooks/maestro-loop-guard.cjs +76 -0
  27. package/hooks/maestro-phase-scope.cjs +118 -0
  28. package/hooks/maestro-statusline-sync.cjs +152 -0
  29. package/hooks/maestro-subagent-guard.cjs +148 -0
  30. package/hooks/maestro-terse-mode.cjs +189 -0
  31. package/hooks/maestro-toolbudget-advisory.cjs +127 -0
  32. package/integrations/README.md +87 -0
  33. package/integrations/cline/skills/frontier/SKILL.md +75 -0
  34. package/integrations/codex/prompts/frontier.md +66 -0
  35. package/integrations/codex/prompts/update.md +36 -0
  36. package/integrations/cursor/commands/frontier.md +63 -0
  37. package/integrations/cursor/commands/update.md +34 -0
  38. package/integrations/gemini/commands/frontier.toml +76 -0
  39. package/integrations/windsurf/workflows/frontier.md +70 -0
  40. package/package.json +52 -0
  41. package/scripts/install.cjs +490 -0
  42. package/settings/cli.cjs +140 -0
  43. package/settings/config.cjs +309 -0
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ // Maestro PostToolUse phase-scope guard. Enforces AGENTS.md S7.1
3
+ // structurally: max 5 files modified per phase. Counts distinct files
4
+ // touched by Edit/Write/NotebookEdit -- plus Bash mutations whose
5
+ // target path is statically extractable (redirects, sed -i, tee, mv,
6
+ // cp, rm, mkdir, touch) -- since the last real user prompt (one turn
7
+ // ~ one phase for interactive work) and warns once per turn when the
8
+ // count exceeds MAESTRO_PHASE_FILE_CAP (default 5). Targets with
9
+ // shell expansion ($, backticks, globs) are skipped: a missed count
10
+ // is cheaper than a false warning. git commit / npm install mutate
11
+ // but name no file; they are out of scope for a file counter.
12
+ //
13
+ // Wire with matcher "Edit|Write|NotebookEdit|Bash" so it only runs on
14
+ // file-modifying tools. Soft warning via additionalContext -- never
15
+ // blocks; the agent decides whether the scope is justified (e.g. a
16
+ // user-approved bulk rename). Degrades silently on missing payload
17
+ // fields. Payload fields verified against code.claude.com/docs/en/hooks
18
+ // (PostToolUse input: tool_name, tool_input, transcript_path;
19
+ // output: hookSpecificOutput.additionalContext), 2026-06-10.
20
+ //
21
+ // .cjs so Node treats it as CommonJS regardless of any "type": "module"
22
+ // package.json in a parent directory of the install location.
23
+ //
24
+ // Install: see README "Claude Code: Phase-Scope Guard".
25
+
26
+ const fs = require('fs');
27
+
28
+ const MUTATORS = new Set(['Edit', 'Write', 'NotebookEdit']);
29
+ const MARKER = 'Maestro phase-scope guard:';
30
+
31
+ // Best-effort file targets of a Bash command's mutating constructs.
32
+ function bashTargets(cmd) {
33
+ const files = [];
34
+ if (typeof cmd !== 'string') return files;
35
+ const strip = t => t.replace(/^["']+|["']+$/g, '');
36
+ const ok = t => t && !t.startsWith('-') && !/[$`*?{}()\[\]<>]/.test(t) && t !== '/dev/null' && !/^nul$/i.test(t);
37
+ let m;
38
+ const redir = /(?<![-=<>])>{1,2}\s*([^\s;&|<>]+)/g;
39
+ while ((m = redir.exec(cmd))) { const t = strip(m[1]); if (ok(t)) files.push(t); }
40
+ for (let seg of cmd.split(/(?:&&|\|\||[;|\n])/)) {
41
+ seg = seg.replace(/(?<![-=<>])>{1,2}\s*[^\s;&|<>]+/g, ' ');
42
+ const toks = seg.trim().split(/\s+/).filter(Boolean);
43
+ while (toks.length && (toks[0] === 'sudo' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(toks[0]))) toks.shift();
44
+ const name = toks[0];
45
+ if (!name) continue;
46
+ const args = toks.slice(1).filter(a => !a.startsWith('-')).map(strip).filter(ok);
47
+ if ((name === 'mv' || name === 'cp') && args.length >= 2) files.push(args[args.length - 1]);
48
+ else if (name === 'rm' || name === 'mkdir' || name === 'touch' || name === 'tee') files.push(...args);
49
+ else if (name === 'sed' && /(^|\s)-i/.test(seg) && args.length) files.push(args[args.length - 1]);
50
+ }
51
+ return files;
52
+ }
53
+
54
+ let data = {};
55
+ try { data = JSON.parse(fs.readFileSync(0, 'utf8')); } catch { process.exit(0); }
56
+
57
+ let lines = [];
58
+ if (data.transcript_path && fs.existsSync(data.transcript_path)) {
59
+ try {
60
+ const buf = fs.readFileSync(data.transcript_path, 'utf8');
61
+ lines = (buf.length > 4000000 ? buf.slice(-4000000) : buf).split(/\r?\n/);
62
+ } catch {}
63
+ }
64
+
65
+ // Locate the last genuine user prompt (typed text, not a tool_result
66
+ // carrier). Everything after it is the current turn.
67
+ let turnStart = 0;
68
+ const parsed = lines.map(l => { try { return JSON.parse(l); } catch { return null; } });
69
+ for (let i = 0; i < parsed.length; i++) {
70
+ const e = parsed[i];
71
+ if (!e || e.type !== 'user' || e.isMeta || !e.message) continue;
72
+ const c = e.message.content;
73
+ const genuine = typeof c === 'string'
74
+ ? true
75
+ : Array.isArray(c) && c.some(x => x && x.type === 'text') && !c.some(x => x && x.type === 'tool_result');
76
+ if (genuine) turnStart = i;
77
+ }
78
+
79
+ // Fire once per turn.
80
+ for (let i = turnStart; i < lines.length; i++) {
81
+ if (lines[i].includes(MARKER)) process.exit(0);
82
+ }
83
+
84
+ const files = new Set();
85
+ for (let i = turnStart; i < parsed.length; i++) {
86
+ const e = parsed[i];
87
+ if (!e || e.type !== 'assistant' || !e.message || !Array.isArray(e.message.content)) continue;
88
+ for (const item of e.message.content) {
89
+ if (!item || item.type !== 'tool_use' || !item.input) continue;
90
+ if (MUTATORS.has(item.name)) {
91
+ const p = item.input.file_path || item.input.notebook_path;
92
+ if (p) files.add(p);
93
+ } else if (item.name === 'Bash') {
94
+ for (const t of bashTargets(item.input.command)) files.add(t);
95
+ }
96
+ }
97
+ }
98
+ // The triggering call may not be in the transcript yet.
99
+ if (data.tool_input) {
100
+ if (MUTATORS.has(data.tool_name)) {
101
+ const p = data.tool_input.file_path || data.tool_input.notebook_path;
102
+ if (p) files.add(p);
103
+ } else if (data.tool_name === 'Bash') {
104
+ for (const t of bashTargets(data.tool_input.command)) files.add(t);
105
+ }
106
+ }
107
+
108
+ const cap = parseInt(process.env.MAESTRO_PHASE_FILE_CAP, 10) || 5;
109
+ if (files.size > cap) {
110
+ process.stdout.write(JSON.stringify({
111
+ hookSpecificOutput: {
112
+ hookEventName: 'PostToolUse',
113
+ additionalContext: `${MARKER} ${files.size} distinct files modified this turn exceeds the max-${cap}-files-per-phase rule (AGENTS.md S7.1). Complete and verify the current phase before expanding scope, or split the remaining work into a follow-up phase. If the user explicitly approved a wider batch (e.g. a bulk rename), proceed.`
114
+ }
115
+ }));
116
+ }
117
+
118
+ process.exit(0);
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ // Maestro status-line sync hook (SessionStart).
3
+ //
4
+ // Problem it solves: the context-bar status line is a STANDALONE copy the
5
+ // user installs once (curl into ~/.claude/statusline/, per docs/context-bar.md)
6
+ // and wires into ~/.claude/settings.json. A Claude Code plugin cannot edit
7
+ // settings.json or copy that file at install time, so when the plugin updates,
8
+ // the wired copy goes stale -- the user keeps seeing the old render (e.g. the
9
+ // "1.00M" token format) while the plugin already ships the fix. This hook
10
+ // closes that gap: on every session start it refreshes the wired copy from the
11
+ // plugin's shipped version.
12
+ //
13
+ // Refresh-if-present ONLY. It never creates the file: an absent context-bar.sh
14
+ // means the user never opted into the status line, and the plugin must not
15
+ // change anyone's status line uninvited (same opt-in rule as terse mode). It
16
+ // only overwrites a file that already exists and whose content differs.
17
+ //
18
+ // Source of truth: ${CLAUDE_PLUGIN_ROOT}/statusline/ (the installed plugin),
19
+ // falling back to this hook's own ../statusline when the env var is unset.
20
+ //
21
+ // Targets: the canonical ~/.claude/statusline/ (the documented install dir,
22
+ // and what the vibe-ads-style ad wrappers chain to), plus the dir resolved
23
+ // from settings.json statusLine.command when that resolves to a real
24
+ // context-bar script. Deduped.
25
+ //
26
+ // Hardened I/O (symlink refusal, O_NOFOLLOW, atomic temp+rename, size cap)
27
+ // mirrors hooks/maestro-terse-mode.cjs. The destination lives at a predictable
28
+ // path under ~/.claude -- a symlink-attack target -- so never write through a
29
+ // link. The source is trusted shipped plugin content.
30
+ //
31
+ // Always silent, never throws, exit 0: a maintenance hook must never break or
32
+ // clutter a session. It writes at most twice (.sh, .ps1) and only right after
33
+ // an update changed the shipped script.
34
+ //
35
+ // .cjs so Node treats it as CommonJS regardless of a parent package.json.
36
+
37
+ 'use strict';
38
+
39
+ const fs = require('fs');
40
+ const os = require('os');
41
+ const path = require('path');
42
+
43
+ const SCRIPTS = ['context-bar.sh', 'context-bar.ps1'];
44
+ const MAX_SCRIPT_BYTES = 1 << 16; // 64 KB cap; the scripts are ~6 KB
45
+
46
+ const claudeDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
47
+
48
+ function sourceDir() {
49
+ const root = process.env.CLAUDE_PLUGIN_ROOT;
50
+ if (root) return path.join(root, 'statusline');
51
+ return path.join(__dirname, '..', 'statusline');
52
+ }
53
+
54
+ // Read a regular file, refusing symlinks and oversized files. Returns a Buffer
55
+ // or null. Buffer (not utf8) so a byte-exact compare/copy survives any encoding.
56
+ function safeReadFile(p) {
57
+ try {
58
+ let st;
59
+ try { st = fs.lstatSync(p); } catch { return null; }
60
+ if (st.isSymbolicLink() || !st.isFile()) return null;
61
+ if (st.size > MAX_SCRIPT_BYTES) return null;
62
+ const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
63
+ let fd;
64
+ try {
65
+ if (O_NOFOLLOW === 0) { try { if (fs.lstatSync(p).isSymbolicLink()) return null; } catch {} }
66
+ fd = fs.openSync(p, fs.constants.O_RDONLY | O_NOFOLLOW);
67
+ const buf = Buffer.alloc(st.size);
68
+ const n = fs.readSync(fd, buf, 0, st.size, 0);
69
+ return buf.slice(0, n);
70
+ } finally {
71
+ if (fd !== undefined) fs.closeSync(fd);
72
+ }
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ // Atomic overwrite via temp+rename, refusing to write through a symlinked dir
79
+ // or destination. mode sets the final permission bits.
80
+ function safeWriteFile(dest, buf, mode) {
81
+ try {
82
+ const dir = path.dirname(dest);
83
+ try { if (fs.lstatSync(dir).isSymbolicLink()) return false; } catch { return false; }
84
+ try {
85
+ if (fs.lstatSync(dest).isSymbolicLink()) return false;
86
+ } catch (e) {
87
+ if (e.code !== 'ENOENT') return false;
88
+ }
89
+ const tempPath = path.join(dir, '.' + path.basename(dest) + '.' + process.pid + '.' + Date.now() + '.tmp');
90
+ const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
91
+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW;
92
+ let fd;
93
+ try {
94
+ if (O_NOFOLLOW === 0) { try { if (fs.lstatSync(tempPath).isSymbolicLink()) return false; } catch {} }
95
+ fd = fs.openSync(tempPath, flags, mode);
96
+ fs.writeSync(fd, buf, 0, buf.length, 0);
97
+ try { fs.fchmodSync(fd, mode); } catch {}
98
+ } finally {
99
+ if (fd !== undefined) fs.closeSync(fd);
100
+ }
101
+ fs.renameSync(tempPath, dest);
102
+ return true;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ // The dir Claude Code is actually pointed at, when settings.json resolves to a
109
+ // real context-bar script. Reused from settings/config.cjs so there is one
110
+ // resolver. Best-effort: any failure just drops this candidate.
111
+ function resolvedTargetDir() {
112
+ try {
113
+ const cfg = require('../settings/config.cjs');
114
+ const r = cfg.resolveStatuslineDir();
115
+ if (r && r.scriptOk && r.dir) return r.dir;
116
+ } catch {}
117
+ return null;
118
+ }
119
+
120
+ function syncDir(dir, srcDir) {
121
+ for (const name of SCRIPTS) {
122
+ const src = safeReadFile(path.join(srcDir, name));
123
+ if (!src) continue;
124
+ const destPath = path.join(dir, name);
125
+ // Refresh-if-present: skip if the user never installed this script here.
126
+ let dst;
127
+ try {
128
+ const st = fs.lstatSync(destPath);
129
+ if (st.isSymbolicLink() || !st.isFile()) continue;
130
+ dst = safeReadFile(destPath);
131
+ } catch {
132
+ continue; // ENOENT -> not installed here -> do not create
133
+ }
134
+ if (dst && dst.equals(src)) continue; // already current
135
+ const mode = name.endsWith('.sh') ? 0o755 : 0o644;
136
+ safeWriteFile(destPath, src, mode);
137
+ }
138
+ }
139
+
140
+ function run() {
141
+ const srcDir = sourceDir();
142
+ const dirs = new Set([path.join(claudeDir, 'statusline')]);
143
+ const resolved = resolvedTargetDir();
144
+ if (resolved) dirs.add(resolved);
145
+ for (const dir of dirs) syncDir(dir, srcDir);
146
+ }
147
+
148
+ // Drain stdin (the harness pipes the SessionStart payload) but ignore it; we
149
+ // act unconditionally on session start. Garbage stdin must not throw.
150
+ try { fs.readFileSync(0, 'utf8'); } catch {}
151
+ try { run(); } catch {}
152
+ process.exit(0);
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ // Maestro SubagentStop guard. Enforces AGENTS.md S7.3 structurally.
3
+ // - Warn on stop with orphaned background_tasks (all agents)
4
+ // - Warn if a file-modifying agent ran no type-check/lint/test
5
+ // - Warn if a file-modifying agent's final text carries none of the
6
+ // S7.3 status tokens (VERIFIED / PENDING_REVIEW / UNVERIFIED / FAIL)
7
+ //
8
+ // Read-only agents (Explore, Plan, or any agent with no file mutation
9
+ // in its transcript) are exempt from the verification warning:
10
+ // research and audit agents have nothing to verify, and a warning on
11
+ // stop extends the agent's turn so its reply to the warning would
12
+ // displace the final report the orchestrator is waiting for.
13
+ //
14
+ // Fires at most once per agent: decision:block re-prompts the
15
+ // agent, which stops again and re-triggers this hook. Without the
16
+ // once-guard the warning loops and pushes the real report out of the
17
+ // final message entirely. The guard is a marker file in the temp dir
18
+ // keyed by the agent transcript path -- the block reason is injected
19
+ // into the conversation, NOT written to the transcript file, so
20
+ // grepping the transcript for our own warning never matches
21
+ // (observed live 2026-06-10). The transcript check is kept as a
22
+ // secondary guard for harness versions that do persist it.
23
+ //
24
+ // Feedback channel: {"decision":"block","reason":...} -- the only
25
+ // SubagentStop output the harness honors (additionalContext is not
26
+ // supported on this event). Blocks the stop exactly once; the agent
27
+ // is told to restate its final report so the orchestrator still
28
+ // receives it.
29
+ //
30
+ // .cjs so Node treats it as CommonJS regardless of any "type": "module"
31
+ // package.json in a parent directory of the install location.
32
+ //
33
+ // Install: see README "Claude Code: Verification Hook".
34
+
35
+ const fs = require('fs');
36
+ const os = require('os');
37
+ const path = require('path');
38
+ const crypto = require('crypto');
39
+
40
+ let data = {};
41
+ try { data = JSON.parse(fs.readFileSync(0, 'utf8')); } catch { process.exit(0); }
42
+
43
+ // Prefer the subagent's own transcript (agent_transcript_path, since
44
+ // Claude Code 2.0.42) over the session transcript.
45
+ const txPath = data.agent_transcript_path || data.transcript_path;
46
+ let txText = '';
47
+ if (txPath && fs.existsSync(txPath)) {
48
+ try {
49
+ const buf = fs.readFileSync(txPath, 'utf8');
50
+ txText = buf.length > 2000000 ? buf.slice(-2000000) : buf;
51
+ } catch {}
52
+ }
53
+
54
+ // Fire once per agent: marker file keyed by transcript path (or
55
+ // session id). MAESTRO_GUARD_STATE_DIR overrides the marker dir for
56
+ // tests. Transcript check kept as a secondary guard.
57
+ const guardKey = data.agent_transcript_path || data.transcript_path || data.session_id || '';
58
+ const stateDir = process.env.MAESTRO_GUARD_STATE_DIR || os.tmpdir();
59
+ const marker = guardKey
60
+ ? path.join(stateDir, 'maestro-guard-' + crypto.createHash('sha1').update(String(guardKey)).digest('hex').slice(0, 16))
61
+ : null;
62
+ if (marker && fs.existsSync(marker)) process.exit(0);
63
+ if (txText.includes('Maestro guard:')) process.exit(0);
64
+
65
+ const warnings = [];
66
+
67
+ // background_tasks in the SubagentStop payload is machine-wide (all
68
+ // sessions), not scoped to this agent (observed live 2026-06-10: a
69
+ // fixture-builder agent was warned about unrelated sessions' tasks).
70
+ // Only warn when the agent's own transcript shows it spawned
71
+ // background work; agents that spawned nothing are exempt.
72
+ const spawnRe = /"run_in_background"\s*:\s*true|"name"\s*:\s*"TaskCreate"/;
73
+ const bg = Array.isArray(data.background_tasks) ? data.background_tasks : [];
74
+ const active = bg.filter(t => t && (t.status === 'running' || t.status === 'pending' || t.status === 'active'));
75
+ if (active.length && spawnRe.test(txText)) {
76
+ warnings.push(`${active.length} background task(s) still active. Wait or stop before declaring complete (AGENTS.md S7.3).`);
77
+ }
78
+
79
+ // Read-only exemption: known read-only agent types (agent_type, since
80
+ // Claude Code 2.1.69), or no file-mutating activity in the transcript.
81
+ // Mutation = Edit/Write/NotebookEdit tool calls, plus Bash mutations:
82
+ // redirects, sed -i, tee/mv/cp/rm/mkdir/touch, git commit/apply,
83
+ // migrations, package installs. Bash patterns are tested against the
84
+ // parsed command strings only, never raw transcript text -- arrows
85
+ // (->, =>) and redirect-ish chars in prose must not flip a research
86
+ // agent into the writer path (a false nag eats its final report).
87
+ const READ_ONLY_TYPES = new Set(['explore', 'plan']);
88
+ const agentType = String(data.agent_type || '').toLowerCase();
89
+ const toolMutRe = /"name"\s*:\s*"(Edit|Write|NotebookEdit)"/;
90
+ const bashMutRe = /(?<![-=<>])>{1,2}\s*[^\s&|<>]|(^|[\s;&|(])(sed\s+(-\S+\s+)*-i|tee\s|mv\s|cp\s|rm\s|mkdir\s|touch\s|git\s+(commit|apply)\b|apply_migration|(npm|pnpm|yarn)\s+(i|install|add)\b)/;
91
+ let bashMutation = false;
92
+ for (const line of txText.split(/\r?\n/)) {
93
+ let obj;
94
+ try { obj = JSON.parse(line); } catch { continue; }
95
+ if (!obj || obj.type !== 'assistant' || !obj.message || !Array.isArray(obj.message.content)) continue;
96
+ for (const c of obj.message.content) {
97
+ if (c && c.type === 'tool_use' && c.name === 'Bash' && c.input &&
98
+ typeof c.input.command === 'string' && bashMutRe.test(c.input.command)) {
99
+ bashMutation = true;
100
+ break;
101
+ }
102
+ }
103
+ if (bashMutation) break;
104
+ }
105
+ const readOnly = READ_ONLY_TYPES.has(agentType) || (txText !== '' && !toolMutRe.test(txText) && !bashMutation);
106
+
107
+ const verifyRe = /(tsc\s+--noEmit|eslint|pytest|jest|vitest|\bgo\s+test\b|\bcargo\s+test\b|npm\s+(?:run\s+)?test|pnpm\s+test|yarn\s+test|ruff\s+check|mypy|prettier\s+--check|biome\s+check)/i;
108
+ if (!readOnly && txText && !verifyRe.test(txText)) {
109
+ warnings.push('No type-check/lint/test detected after file modifications. Verify before complete, or state "no checker configured" (AGENTS.md S7.3).');
110
+ }
111
+
112
+ // S7.3 status vocabulary: a file-modifying agent's final text must
113
+ // carry one of the four status tokens. Case-sensitive on purpose --
114
+ // the doctrine tokens are uppercase, and lowercase "fail"/"verified"
115
+ // in prose are not status declarations.
116
+ const statusRe = /\b(VERIFIED|PENDING_REVIEW|UNVERIFIED|FAIL)\b/;
117
+ if (!readOnly && txText) {
118
+ let finalText = '';
119
+ for (const line of txText.split(/\r?\n/)) {
120
+ let obj;
121
+ try { obj = JSON.parse(line); } catch { continue; }
122
+ if (obj && obj.type === 'assistant' && obj.message && Array.isArray(obj.message.content)) {
123
+ const t = obj.message.content
124
+ .filter(c => c && c.type === 'text' && typeof c.text === 'string')
125
+ .map(c => c.text).join('\n');
126
+ if (t) finalText = t;
127
+ }
128
+ }
129
+ if (finalText && !statusRe.test(finalText)) {
130
+ warnings.push('Final report carries no status token. State exactly one of VERIFIED / PENDING_REVIEW / UNVERIFIED / FAIL, with the named gap if not VERIFIED (AGENTS.md S7.3).');
131
+ }
132
+ }
133
+
134
+ if (warnings.length) {
135
+ if (marker) { try { fs.writeFileSync(marker, String(Date.now())); } catch {} }
136
+ // SubagentStop supports only decision:block + reason as a feedback
137
+ // channel (additionalContext is not honored on this event). Blocking
138
+ // the stop feeds the reason back to the subagent, which addresses it
139
+ // and stops again; the marker file above keeps that second stop silent.
140
+ const payload = {
141
+ decision: 'block',
142
+ reason: 'Maestro guard:\n- ' + warnings.join('\n- ') +
143
+ '\nAfter addressing this, restate your complete final report. Only your last message is returned to the orchestrator.'
144
+ };
145
+ process.stdout.write(JSON.stringify(payload));
146
+ }
147
+
148
+ process.exit(0);
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ // Maestro terse-mode hook. One file, two events (dispatch on
3
+ // hook_event_name):
4
+ // - SessionStart: resolve the level (env > config > off), write the
5
+ // flag file, inject the level-filtered ruleset from
6
+ // skills/terse/SKILL.md (single source of truth) as
7
+ // additionalContext.
8
+ // - UserPromptSubmit: track level switches (/maestro:terse, /terse,
9
+ // natural-language deactivation) in the flag file and emit a
10
+ // one-line reminder every turn while active -- per-turn
11
+ // reinforcement defeats style drift after context compression
12
+ // (same pattern as maestro-gate-reminder).
13
+ //
14
+ // Level resolution: MAESTRO_TERSE_LEVEL env var, then terseLevel in
15
+ // $XDG_CONFIG_HOME/maestro/config.json (~/.config/maestro fallback,
16
+ // %APPDATA%\maestro on Windows), then 'off'. Off by default:
17
+ // installing the plugin must not change anyone's output style.
18
+ //
19
+ // Flag I/O ported from Caveman (MIT): symlink-refusing, O_NOFOLLOW,
20
+ // atomic temp+rename, 0600, 64-byte read cap, level whitelist. A
21
+ // predictable flag path under ~/.claude is a symlink-attack target;
22
+ // never write through one, never inject unvalidated bytes into model
23
+ // context.
24
+ //
25
+ // .cjs so Node treats it as CommonJS regardless of any "type": "module"
26
+ // package.json in a parent directory of the install location.
27
+
28
+ const fs = require('fs');
29
+ const os = require('os');
30
+ const path = require('path');
31
+
32
+ const LEVELS = ['lite', 'full', 'ultra'];
33
+ const MAX_FLAG_BYTES = 64;
34
+
35
+ const claudeDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
36
+ const flagPath = path.join(claudeDir, '.maestro-terse');
37
+
38
+ function configDir() {
39
+ if (process.env.XDG_CONFIG_HOME) return path.join(process.env.XDG_CONFIG_HOME, 'maestro');
40
+ if (process.platform === 'win32') {
41
+ return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'maestro');
42
+ }
43
+ return path.join(os.homedir(), '.config', 'maestro');
44
+ }
45
+
46
+ function defaultLevel() {
47
+ const env = String(process.env.MAESTRO_TERSE_LEVEL || '').toLowerCase();
48
+ if (env === 'off' || LEVELS.includes(env)) return env;
49
+ try {
50
+ const cfg = JSON.parse(fs.readFileSync(path.join(configDir(), 'config.json'), 'utf8'));
51
+ const v = String(cfg.terseLevel || '').toLowerCase();
52
+ if (v === 'off' || LEVELS.includes(v)) return v;
53
+ } catch {}
54
+ return 'off';
55
+ }
56
+
57
+ function safeWriteFlag(level) {
58
+ try {
59
+ const dir = path.dirname(flagPath);
60
+ fs.mkdirSync(dir, { recursive: true });
61
+ try { if (fs.lstatSync(dir).isSymbolicLink()) return; } catch { return; }
62
+ try {
63
+ if (fs.lstatSync(flagPath).isSymbolicLink()) return;
64
+ } catch (e) {
65
+ if (e.code !== 'ENOENT') return;
66
+ }
67
+ const tempPath = path.join(dir, `.maestro-terse.${process.pid}.${Date.now()}`);
68
+ const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
69
+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW;
70
+ let fd;
71
+ try {
72
+ if (O_NOFOLLOW === 0) { try { if (fs.lstatSync(tempPath).isSymbolicLink()) return; } catch {} }
73
+ fd = fs.openSync(tempPath, flags, 0o600);
74
+ fs.writeSync(fd, String(level));
75
+ try { fs.fchmodSync(fd, 0o600); } catch {}
76
+ } finally {
77
+ if (fd !== undefined) fs.closeSync(fd);
78
+ }
79
+ fs.renameSync(tempPath, flagPath);
80
+ } catch {}
81
+ }
82
+
83
+ function readFlag() {
84
+ try {
85
+ let st;
86
+ try { st = fs.lstatSync(flagPath); } catch { return null; }
87
+ if (st.isSymbolicLink() || !st.isFile()) return null;
88
+ if (st.size > MAX_FLAG_BYTES) return null;
89
+ const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
90
+ let fd, out;
91
+ try {
92
+ if (O_NOFOLLOW === 0) { try { if (fs.lstatSync(flagPath).isSymbolicLink()) return null; } catch {} }
93
+ fd = fs.openSync(flagPath, fs.constants.O_RDONLY | O_NOFOLLOW);
94
+ const buf = Buffer.alloc(MAX_FLAG_BYTES);
95
+ const n = fs.readSync(fd, buf, 0, MAX_FLAG_BYTES, 0);
96
+ out = buf.slice(0, n).toString('utf8');
97
+ } finally {
98
+ if (fd !== undefined) fs.closeSync(fd);
99
+ }
100
+ const raw = out.trim().toLowerCase();
101
+ return LEVELS.includes(raw) ? raw : null;
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ function removeFlag() {
108
+ try { fs.unlinkSync(flagPath); } catch {}
109
+ }
110
+
111
+ function sessionStart() {
112
+ const level = defaultLevel();
113
+ if (level === 'off' || !LEVELS.includes(level)) { removeFlag(); return; }
114
+ safeWriteFlag(level);
115
+
116
+ let body = '';
117
+ try {
118
+ const skill = fs.readFileSync(path.join(__dirname, '..', 'skills', 'terse', 'SKILL.md'), 'utf8');
119
+ // Strip frontmatter and maintainer HTML comments, then keep only
120
+ // the active level's intensity row and example lines.
121
+ body = skill
122
+ .replace(/^---[\s\S]*?---\s*/, '')
123
+ .replace(/<!--[\s\S]*?-->\s*/g, '')
124
+ .split('\n')
125
+ .filter(line => {
126
+ const row = line.match(/^\|\s*\*\*(\S+?)\*\*\s*\|/);
127
+ if (row) return row[1] === level;
128
+ const ex = line.match(/^- (\S+?):\s/);
129
+ if (ex) return ex[1] === level;
130
+ return true;
131
+ })
132
+ .join('\n');
133
+ } catch {
134
+ body = 'Respond terse. All technical substance stay. Only fluff die.\n' +
135
+ 'Drop articles/filler/pleasantries/hedging. Fragments OK. ' +
136
+ 'Code/commits/PRs: write normal. Off: "stop terse" / "normal mode".';
137
+ }
138
+
139
+ process.stdout.write(JSON.stringify({
140
+ hookSpecificOutput: {
141
+ hookEventName: 'SessionStart',
142
+ additionalContext: 'MAESTRO TERSE ACTIVE — level: ' + level + '\n\n' + body
143
+ }
144
+ }));
145
+ }
146
+
147
+ function promptSubmit(data) {
148
+ const prompt = String(data.prompt || '').trim().toLowerCase();
149
+
150
+ if (prompt.startsWith('/maestro:terse') || prompt.startsWith('/terse')) {
151
+ const arg = (prompt.split(/\s+/)[1] || '').toLowerCase();
152
+ if (arg === 'off') {
153
+ removeFlag();
154
+ } else if (LEVELS.includes(arg)) {
155
+ safeWriteFlag(arg);
156
+ } else {
157
+ // Bare invocation: explicit opt-in. Use the configured default,
158
+ // or 'full' when the default is off.
159
+ const d = defaultLevel();
160
+ safeWriteFlag(LEVELS.includes(d) ? d : 'full');
161
+ }
162
+ }
163
+
164
+ if (/\b(stop|disable|deactivate|turn off)\b.*\bterse\b/.test(prompt) ||
165
+ /\bterse\b.*\b(stop|disable|off)\b/.test(prompt) ||
166
+ /\bnormal mode\b/.test(prompt)) {
167
+ removeFlag();
168
+ }
169
+
170
+ const active = readFlag();
171
+ if (active) {
172
+ process.stdout.write(JSON.stringify({
173
+ hookSpecificOutput: {
174
+ hookEventName: 'UserPromptSubmit',
175
+ additionalContext: 'MAESTRO TERSE ACTIVE (' + active + '). ' +
176
+ 'Drop articles/filler/pleasantries/hedging. Fragments OK. ' +
177
+ 'Code/commits/security: write normal.'
178
+ }
179
+ }));
180
+ }
181
+ }
182
+
183
+ let data = {};
184
+ try { data = JSON.parse(fs.readFileSync(0, 'utf8')); } catch { process.exit(0); }
185
+
186
+ if (data.hook_event_name === 'SessionStart') sessionStart();
187
+ else if (data.hook_event_name === 'UserPromptSubmit') promptSubmit(data);
188
+
189
+ process.exit(0);