@sentropic/h2a 0.98.7-rc.2 → 0.98.7-rc.4
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.
- package/.codex-plugin/plugin.json +1 -0
- package/dist/bin.js +3 -0
- package/dist/bin.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +38 -38
- package/dist/cli.js.map +1 -1
- package/dist/focus-build.d.ts +10 -0
- package/dist/focus-build.d.ts.map +1 -0
- package/dist/focus-build.js +175 -0
- package/dist/focus-build.js.map +1 -0
- package/dist/hosts/native-convergence.d.ts +36 -0
- package/dist/hosts/native-convergence.d.ts.map +1 -1
- package/dist/hosts/native-convergence.js +60 -4
- package/dist/hosts/native-convergence.js.map +1 -1
- package/dist/hosts/native-files.d.ts +5 -0
- package/dist/hosts/native-files.d.ts.map +1 -1
- package/dist/hosts/native-files.js +4 -0
- package/dist/hosts/native-files.js.map +1 -1
- package/dist/hosts/native-inspection.js +1 -1
- package/dist/hosts/native-inspection.js.map +1 -1
- package/dist/hosts/native-questions.d.ts +2 -0
- package/dist/hosts/native-questions.d.ts.map +1 -0
- package/dist/hosts/native-questions.js +22 -0
- package/dist/hosts/native-questions.js.map +1 -0
- package/dist/hosts/native-toml.d.ts.map +1 -1
- package/dist/hosts/native-toml.js +2 -0
- package/dist/hosts/native-toml.js.map +1 -1
- package/dist/hosts/plugin.d.ts +27 -0
- package/dist/hosts/plugin.d.ts.map +1 -1
- package/dist/hosts/plugin.js +28 -2
- package/dist/hosts/plugin.js.map +1 -1
- package/dist/hosts/vibe-discovery.js +1 -1
- package/dist/hosts/vibe-discovery.js.map +1 -1
- package/dist/hosts/vibe-equipment.d.ts +1 -0
- package/dist/hosts/vibe-equipment.d.ts.map +1 -1
- package/dist/hosts/vibe-equipment.js +14 -1
- package/dist/hosts/vibe-equipment.js.map +1 -1
- package/dist/runtime/mcp/tools.d.ts.map +1 -1
- package/dist/runtime/mcp/tools.js +5 -4
- package/dist/runtime/mcp/tools.js.map +1 -1
- package/focus-kit/dossier.schema.json +193 -0
- package/focus-kit/dossier.template.json +39 -0
- package/focus-kit/ecosystem.json +853 -0
- package/focus-kit/renderer-manifest.json +24 -0
- package/focus-kit/renderer.html +278 -0
- package/focus-kit/validator.mjs +789 -0
- package/hooks/hooks.json +11 -1
- package/hooks/workspace-scope-grant.mjs +22 -0
- package/hooks/workspace-scope-guard.mjs +277 -0
- package/hooks/workspace-scope-shell.mjs +558 -0
- package/hooks/workspace-scope-state.mjs +71 -0
- package/package.json +12 -6
- package/skills/h2a/SKILL.md +19 -0
- package/skills/h2a-run/SKILL.md +19 -0
- package/skills/harness/SKILL.md +19 -0
- package/skills/harness/track-report/SKILL.md +78 -5
- package/skills/harness/using-harness/SKILL.md +19 -0
package/hooks/hooks.json
CHANGED
|
@@ -1,7 +1,17 @@
|
|
|
1
1
|
{
|
|
2
|
-
"description": "
|
|
2
|
+
"description": "Enforces workspace ownership and prevents manual H2A MCP bypass.",
|
|
3
3
|
"hooks": {
|
|
4
|
+
"SessionStart": [
|
|
5
|
+
{
|
|
6
|
+
"matcher": ".*",
|
|
7
|
+
"hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT}}/hooks/workspace-scope-guard.mjs\" --initialize-session true", "timeout": 15 }]
|
|
8
|
+
}
|
|
9
|
+
],
|
|
4
10
|
"PreToolUse": [
|
|
11
|
+
{
|
|
12
|
+
"matcher": ".*",
|
|
13
|
+
"hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT}}/hooks/workspace-scope-guard.mjs\"", "timeout": 15 }]
|
|
14
|
+
},
|
|
5
15
|
{
|
|
6
16
|
"matcher": "Bash",
|
|
7
17
|
"hooks": [
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// OWNER terminal only. The signing key must be inaccessible to agent processes.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { createPrivateKey, sign } from 'node:crypto';
|
|
5
|
+
import { appendRecord, canonical, options, validGrant } from './workspace-scope-state.mjs';
|
|
6
|
+
import { repoIdentity } from './workspace-scope-shell.mjs';
|
|
7
|
+
|
|
8
|
+
try {
|
|
9
|
+
const args = options(process.argv.slice(2));
|
|
10
|
+
if (!args.repo) throw new Error('An exact --repo is required');
|
|
11
|
+
const grant = { schema: 1, owner: args.owner, workspace: canonical(args.workspace),
|
|
12
|
+
session: args.session, repo: repoIdentity(args.repo, process.cwd()), action: args.action, ref: args.ref, expires: args.expires };
|
|
13
|
+
if (!validGrant(grant, grant, grant)) throw new Error('Exact owner/workspace/session/repo/action/ref and future expiry required');
|
|
14
|
+
const key = createPrivateKey(fs.readFileSync(args.key));
|
|
15
|
+
if (key.asymmetricKeyType !== 'ed25519') throw new Error('An owner Ed25519 key is required');
|
|
16
|
+
const signature = sign(null, Buffer.from(JSON.stringify(grant)), key).toString('base64');
|
|
17
|
+
appendRecord(grant.workspace, 'grants.jsonl', { grant, signature });
|
|
18
|
+
process.stdout.write(JSON.stringify({ recorded: true, grant }) + '\n');
|
|
19
|
+
} catch (error) {
|
|
20
|
+
process.stderr.write(`Grant not recorded: ${error.message}\n`);
|
|
21
|
+
process.exitCode = 2;
|
|
22
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { appendRecord, canonical, findGrant, inside, options, readRecords, stateDir } from './workspace-scope-state.mjs';
|
|
7
|
+
import { branchBump, classify, git, manifestAtBaseline, patchContent, prBump, publishedBump, repository, uncertainPath } from './workspace-scope-shell.mjs';
|
|
8
|
+
|
|
9
|
+
let context, host = 'claude';
|
|
10
|
+
const quoteShell = value => "'" + value.replace(/'/g, "'\\''") + "'";
|
|
11
|
+
function literal(value) {
|
|
12
|
+
if (/^"(?:[^"\\]|\\[\s\S])*"$/.test(value) || /^'(?:[^'\\]|\\[\s\S])*'$/.test(value) || /^`(?:[^`\\]|\\[\s\S])*`$/.test(value) && !value.includes('${')) {
|
|
13
|
+
const body=value.slice(1,-1); let decoded='';
|
|
14
|
+
for (let i=0;i<body.length;i++) {
|
|
15
|
+
if (body[i]!=='\\') { decoded+=body[i]; continue; }
|
|
16
|
+
const escape=body[++i];
|
|
17
|
+
if (escape==='\n') continue;
|
|
18
|
+
if (escape==='\r') { if(body[i+1]==='\n') i++; continue; }
|
|
19
|
+
if (escape==='x' || escape==='u') {
|
|
20
|
+
const braced=escape==='u' && body[i+1]==='{';
|
|
21
|
+
const end=braced?body.indexOf('}',i+2):i+(escape==='x'?2:4);
|
|
22
|
+
const digits=body.slice(i+(braced?2:1),end+(braced?0:1));
|
|
23
|
+
if (end<0 || !/^[a-f\d]+$/i.test(digits) || !braced && digits.length!==(escape==='x'?2:4)) throw new Error('Invalid JS escape');
|
|
24
|
+
decoded+=String.fromCodePoint(Number.parseInt(digits,16)); i=end; continue;
|
|
25
|
+
}
|
|
26
|
+
if (/[1-9]/.test(escape ?? '') || escape==='0' && /\d/.test(body[i+1] ?? '')) throw new Error('Legacy JS escape');
|
|
27
|
+
decoded+=({n:'\n',r:'\r',t:'\t',b:'\b',f:'\f',v:'\v',0:'\0'})[escape] ?? escape;
|
|
28
|
+
}
|
|
29
|
+
return decoded;
|
|
30
|
+
}
|
|
31
|
+
throw new Error('Dynamic command envelope');
|
|
32
|
+
}
|
|
33
|
+
function fields(source) {
|
|
34
|
+
const tokens=jsTokens(source), result={}; let start=1, depth=0;
|
|
35
|
+
if (tokens[0]?.value !== '{') throw new Error('Expected command object');
|
|
36
|
+
for (let i=1;i<tokens.length;i++) {
|
|
37
|
+
const token=tokens[i];
|
|
38
|
+
if (!token.string && ['{','[','('].includes(token.value)) depth++;
|
|
39
|
+
if (!token.string && ['}',']',')'].includes(token.value)) depth--;
|
|
40
|
+
if (!token.string && (token.value === ',' && depth === 0 || depth === -1)) {
|
|
41
|
+
if (i>start) {
|
|
42
|
+
const key=tokens[start].value;
|
|
43
|
+
if (!/^\w+$/.test(key) || tokens[start+1]?.value !== ':' || i<start+3 || Object.hasOwn(result,key))
|
|
44
|
+
throw new Error('Unsupported or duplicate command object member');
|
|
45
|
+
result[key]=source.slice(tokens[start+2].start,tokens[i-1].end);
|
|
46
|
+
}
|
|
47
|
+
start=i+1;
|
|
48
|
+
if (depth === -1) return {result,end:token.end};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
throw new Error('Unclosed command envelope');
|
|
52
|
+
}
|
|
53
|
+
// Lex JavaScript without running it. Strings/comments cannot introduce calls;
|
|
54
|
+
// every reference to the tools capability must be a direct, static invocation.
|
|
55
|
+
function jsTokens(source) {
|
|
56
|
+
const tokens = [];
|
|
57
|
+
for (let i = 0; i < source.length;) {
|
|
58
|
+
if (/\s/.test(source[i])) { i++; continue; }
|
|
59
|
+
if (source.startsWith('//',i)) { while (i < source.length && source[i] !== '\n') i++; continue; }
|
|
60
|
+
if (source.startsWith('/*',i)) { const end=source.indexOf('*/',i+2); if(end<0) throw new Error('Unclosed comment'); i=end+2; continue; }
|
|
61
|
+
const start=i;
|
|
62
|
+
if ('"\'`'.includes(source[i])) {
|
|
63
|
+
const quote=source[i++]; let escaped=false;
|
|
64
|
+
while(i<source.length) { const c=source[i++]; if(escaped) escaped=false; else if(c==='\\') escaped=true; else if(c===quote) break; }
|
|
65
|
+
tokens.push({value:literal(source.slice(start,i)), string:true, start, end:i}); continue;
|
|
66
|
+
}
|
|
67
|
+
const name=source.slice(i).match(/^[\w$]+/);
|
|
68
|
+
i+=name?name[0].length:1;
|
|
69
|
+
tokens.push({value:source.slice(start,i),start,end:i});
|
|
70
|
+
}
|
|
71
|
+
return tokens;
|
|
72
|
+
}
|
|
73
|
+
function refuse(code, request = {}, detail = '') {
|
|
74
|
+
const selectors = { repo: request.repo ?? '', action: request.action ?? '', ref: request.ref ?? '', session: context.session ?? '' };
|
|
75
|
+
const reason = `[H2A_SCOPE:${code}] ${request.action ?? 'Tool action'} refused. ${JSON.stringify(selectors)} Hand this action to the owning conductor; use the plain explicit form or request an exact recorded owner grant.${detail ? ' ' + detail : ''}`;
|
|
76
|
+
let auditCode = code;
|
|
77
|
+
try { appendRecord(context.workspace, 'audit.jsonl', { at: new Date().toISOString(), type: 'refusal',
|
|
78
|
+
workspace: context.workspace, session: context.session, ...request, code }); }
|
|
79
|
+
catch { auditCode = 'AUDIT_UNAVAILABLE'; }
|
|
80
|
+
process.stderr.write(reason + (auditCode !== code ? ' Audit unavailable; action remains refused.' : '') + '\n');
|
|
81
|
+
process.stdout.write(JSON.stringify({ ...(host === 'muse' ? {} : { decision: ['vibe', 'agy'].includes(host) ? 'deny' : 'block' }), code: auditCode, reason, ...selectors,
|
|
82
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } }));
|
|
83
|
+
process.exit(['vibe', 'agy'].includes(host) ? 0 : 2);
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const args = options(process.argv.slice(2)); host = args.host ?? host;
|
|
87
|
+
// Installers pin --workspace. Packaged plugins use host-owned startup env/cwd,
|
|
88
|
+
// never payload cwd or a command's env assignments as session authority.
|
|
89
|
+
const hookCwd = canonical(process.cwd());
|
|
90
|
+
let workspace = canonical(args.workspace ?? process.env.CLAUDE_PROJECT_DIR ?? process.env.CODEX_WORKSPACE_ROOT ?? hookCwd);
|
|
91
|
+
context = { workspace, session: args.session ?? process.env.H2A_SCOPE_SESSION ?? '', ownerKey: args['owner-key'] ?? process.env.H2A_SCOPE_OWNER_KEY, ...repository(workspace) };
|
|
92
|
+
let raw = '';
|
|
93
|
+
for await (const chunk of process.stdin) { raw += chunk; if (raw.length > 2_000_000) refuse('UNVERIFIABLE', {}, 'Hook payload too large.'); }
|
|
94
|
+
const payload = JSON.parse(raw || '{}');
|
|
95
|
+
// Host session id selects a grant, but cannot redefine the workspace/key.
|
|
96
|
+
context.session ||= payload.session_id ?? payload.sessionId ?? payload.thread_id ?? payload.conversationId ?? '';
|
|
97
|
+
const sessionStore = args['session-store'] ? canonical(args['session-store']) : host === 'agy' && !args.workspace ? hookCwd : undefined;
|
|
98
|
+
if (sessionStore) {
|
|
99
|
+
if (!context.session) refuse('UNVERIFIABLE', {}, 'Missing native session identity.');
|
|
100
|
+
const bindings = readRecords(sessionStore, 'sessions.jsonl').filter(row => row.session === context.session);
|
|
101
|
+
if (!bindings.length) {
|
|
102
|
+
if (host === 'agy') {
|
|
103
|
+
if (args['initialize-session'] !== 'true' || !Array.isArray(payload.workspacePaths) || payload.workspacePaths.length !== 1 ||
|
|
104
|
+
typeof payload.workspacePaths[0] !== 'string' || !isAbsolute(payload.workspacePaths[0]) || !fs.statSync(payload.workspacePaths[0]).isDirectory())
|
|
105
|
+
refuse('UNVERIFIABLE', {}, 'Agy requires a single workspacePaths entry at SessionStart.');
|
|
106
|
+
workspace = canonical(payload.workspacePaths[0]);
|
|
107
|
+
}
|
|
108
|
+
appendRecord(sessionStore, 'sessions.jsonl', { session: context.session, workspace, at: new Date().toISOString() });
|
|
109
|
+
context = { ...context, workspace, ...repository(workspace) };
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
if (new Set(bindings.map(row => row.workspace)).size !== 1) refuse('UNVERIFIABLE', {}, 'Conflicting native session bindings.');
|
|
113
|
+
workspace = canonical(bindings[0].workspace);
|
|
114
|
+
context = { ...context, workspace, ...repository(workspace) };
|
|
115
|
+
}
|
|
116
|
+
if (host === 'agy' && args['initialize-session'] === 'true') { process.stdout.write('{}'); process.exit(0); }
|
|
117
|
+
}
|
|
118
|
+
if (!args.workspace && !sessionStore) {
|
|
119
|
+
if (!context.session) refuse('UNVERIFIABLE', {}, 'Missing host session identity.');
|
|
120
|
+
if (args['initialize-session'] === 'true') {
|
|
121
|
+
appendRecord(workspace, 'sessions.jsonl', { session: context.session, workspace, at: new Date().toISOString() });
|
|
122
|
+
if (host === 'agy') process.stdout.write('{}');
|
|
123
|
+
process.exit(0);
|
|
124
|
+
}
|
|
125
|
+
let bound = false;
|
|
126
|
+
try {
|
|
127
|
+
bound = readRecords(workspace, 'sessions.jsonl').some(row => row.session === context.session && row.workspace === workspace);
|
|
128
|
+
} catch { /* Missing binding refuses; foreign cwd cannot become a new workspace. */ }
|
|
129
|
+
if (!bound) refuse('UNVERIFIABLE', {}, 'No SessionStart binding in this workspace; reload the session plugin.');
|
|
130
|
+
}
|
|
131
|
+
// Establish authority before recording a baseline. Publication status comes
|
|
132
|
+
// from this pinned tree, so a temporary private:true cannot launder a bump.
|
|
133
|
+
const baselines = readRecords(workspace, 'baselines.jsonl');
|
|
134
|
+
const baseline = baselines.find(row => row.session === context.session && row.path === context.path)?.base ??
|
|
135
|
+
git(context.path, ['merge-base', 'origin/main', 'HEAD']) ?? git(context.path, ['merge-base', 'main', 'HEAD']);
|
|
136
|
+
if (baseline && !baselines.some(row => row.session === context.session && row.path === context.path))
|
|
137
|
+
appendRecord(workspace, 'baselines.jsonl', { session: context.session, path: context.path, base: baseline });
|
|
138
|
+
context.baseline=baseline;
|
|
139
|
+
const toolName = payload.tool_name ?? payload.toolCall?.name ?? '';
|
|
140
|
+
let input = payload.tool_input ?? payload.arguments ?? payload.toolCall?.args ?? {};
|
|
141
|
+
if (typeof input === 'string' && !/patch|exec$/.test(toolName)) {
|
|
142
|
+
try { input = JSON.parse(input); } catch { /* raw custom tool input */ }
|
|
143
|
+
}
|
|
144
|
+
// Antigravity's native camelCase tool payload. workspacePaths belongs to the
|
|
145
|
+
// host event, not toolCall.args; only SessionStart can establish its binding.
|
|
146
|
+
if (host === 'agy') input = { ...input, command: input.command ?? input.CommandLine,
|
|
147
|
+
cwd: input.cwd ?? input.Cwd, file_path: input.file_path ?? input.TargetFile,
|
|
148
|
+
content: input.content ?? input.CodeContent, old_string: input.old_string ?? input.TargetContent,
|
|
149
|
+
new_string: input.new_string ?? input.ReplacementContent,
|
|
150
|
+
replace_all: input.replace_all ?? input.AllowMultiple,
|
|
151
|
+
start_line: input.StartLine, end_line: input.EndLine,
|
|
152
|
+
edits: input.edits ?? input.ReplacementChunks?.map(edit => ({ old_string: edit.TargetContent, new_string: edit.ReplacementContent,
|
|
153
|
+
replace_all: edit.AllowMultiple, start_line: edit.StartLine, end_line: edit.EndLine })) };
|
|
154
|
+
const targetPath = resolve(workspace, input.workdir ?? input.cwd ?? payload.cwd ?? (sessionStore && host !== 'agy' ? hookCwd : workspace));
|
|
155
|
+
const targetCwd = canonical(targetPath);
|
|
156
|
+
context.toolEnv = input.env && typeof input.env === 'object' ? input.env : {};
|
|
157
|
+
const requests = [];
|
|
158
|
+
const envelopePatches = [];
|
|
159
|
+
const envelope = typeof input === 'string' ? input : input.code;
|
|
160
|
+
if (/^(?:functions\.)?exec$/.test(toolName) && typeof envelope === 'string') {
|
|
161
|
+
// Extract only literal commands from the JS orchestration envelope. Never
|
|
162
|
+
// evaluate agent JS. Dynamic shell/tool expressions are unverifiable.
|
|
163
|
+
const tokens=jsTokens(envelope);
|
|
164
|
+
if (tokens.some(token=>!token.string && ['globalThis','Reflect','eval','Function','import','\\'].includes(token.value)))
|
|
165
|
+
throw new Error('Reflective command envelope');
|
|
166
|
+
for (let i=0;i<tokens.length;i++) {
|
|
167
|
+
if (tokens[i].string || tokens[i].value !== 'tools') continue;
|
|
168
|
+
let name, open;
|
|
169
|
+
if (tokens[i+1]?.value==='.' && !tokens[i+2]?.string) { name=tokens[i+2]?.value; open=i+3; }
|
|
170
|
+
else if (tokens[i+1]?.value==='[' && tokens[i+2]?.string && tokens[i+3]?.value===']') { name=tokens[i+2].value; open=i+4; }
|
|
171
|
+
if (!['exec_command','apply_patch'].includes(name) || tokens[open]?.value!=='(') throw new Error('Indirect tools capability');
|
|
172
|
+
const argument=tokens[open+1];
|
|
173
|
+
const rest=envelope.slice(argument.start);
|
|
174
|
+
if (name==='exec_command') {
|
|
175
|
+
const {result}=fields(rest);
|
|
176
|
+
const command=literal(result.cmd ?? result.command ?? '');
|
|
177
|
+
const cwd=result.workdir ?? result.cwd;
|
|
178
|
+
const env=result.env ? Object.fromEntries(Object.entries(fields(result.env).result).map(([k,v])=>[k,literal(v)])) : {};
|
|
179
|
+
const selected=cwd?resolve(targetCwd,literal(cwd)):targetCwd;
|
|
180
|
+
requests.push(...classify(command,canonical(selected),{...context,toolEnv:env}).map(request=>
|
|
181
|
+
({...request,uncertain:request.uncertain || uncertainPath(selected)})));
|
|
182
|
+
} else if (argument.value==='{') envelopePatches.push(literal(fields(rest).result.patch ?? ''));
|
|
183
|
+
else {
|
|
184
|
+
if (!argument.string || tokens[open+2]?.value!==')') throw new Error('Dynamic patch');
|
|
185
|
+
envelopePatches.push(argument.value);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
let command = input.command ?? input.cmd;
|
|
190
|
+
if (Array.isArray(command)) command = command.map(quoteShell).join(' ');
|
|
191
|
+
else if (typeof command === 'string' && Array.isArray(input.args)) command = [command, ...input.args].map(quoteShell).join(' ');
|
|
192
|
+
if (typeof command === 'string') requests.push(...classify(command, targetCwd, context));
|
|
193
|
+
// Codex apply_patch accepts a string; Claude uses file_path + strings/content.
|
|
194
|
+
const edits = [];
|
|
195
|
+
if (typeof input.file_path === 'string' || typeof input.path === 'string') {
|
|
196
|
+
if (/edit|write|patch|create|replace/i.test(toolName)) {
|
|
197
|
+
const selected = resolve(targetCwd, input.file_path ?? input.path), path = canonical(selected);
|
|
198
|
+
let old = ''; try { old = fs.readFileSync(path, 'utf8'); } catch { /* new file */ }
|
|
199
|
+
let content = input.content ?? old;
|
|
200
|
+
// Native ranges refer to the original file. Apply from bottom to top so
|
|
201
|
+
// an earlier chunk cannot shift the lines selected by a later chunk.
|
|
202
|
+
const replacements=[...(input.edits ?? [input])].sort((a,b)=>(b.start_line ?? 0)-(a.start_line ?? 0));
|
|
203
|
+
for (const edit of replacements) if (typeof edit.old_string === 'string') {
|
|
204
|
+
const replace = text => edit.replace_all ? text.split(edit.old_string).join(edit.new_string ?? '') : text.replace(edit.old_string,edit.new_string ?? '');
|
|
205
|
+
if (edit.start_line !== undefined || edit.end_line !== undefined) {
|
|
206
|
+
const lines=content.split('\n'), start=edit.start_line, end=edit.end_line;
|
|
207
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start<1 || end<start || end>lines.length) throw new Error('Invalid edit range');
|
|
208
|
+
const selected=lines.slice(start-1,end).join('\n');
|
|
209
|
+
if (!selected.includes(edit.old_string)) throw new Error('Unmatched edit range');
|
|
210
|
+
content=[...lines.slice(0,start-1),replace(selected),...lines.slice(end)].join('\n');
|
|
211
|
+
} else content=replace(content);
|
|
212
|
+
}
|
|
213
|
+
edits.push({ path, old, content, uncertain: uncertainPath(selected) });
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
for (const patch of [typeof input === 'string' && !envelopePatches.length ? input : input.patch ?? input.input, ...envelopePatches]) {
|
|
217
|
+
if (typeof patch !== 'string') continue;
|
|
218
|
+
for (const line of patch.split('\n')) {
|
|
219
|
+
const match = line.match(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/);
|
|
220
|
+
if (match) {
|
|
221
|
+
const selected=resolve(targetCwd,match[1]), path=canonical(selected);
|
|
222
|
+
edits.push({ path, patch, uncertain:uncertainPath(selected) });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
for (const edit of edits) {
|
|
227
|
+
const repo = repository(dirname(edit.path));
|
|
228
|
+
let bump=false;
|
|
229
|
+
if (basename(edit.path) === 'package.json') {
|
|
230
|
+
const content=edit.patch ? patchContent(edit.path,edit.patch,targetCwd) : edit.content;
|
|
231
|
+
const old=edit.old ?? (fs.existsSync(edit.path) ? fs.readFileSync(edit.path,'utf8') : '{}');
|
|
232
|
+
const base=manifestAtBaseline(edit.path,repo.path === context.path ? baseline : undefined);
|
|
233
|
+
bump=publishedBump(base ?? old,content) || publishedBump(old,content);
|
|
234
|
+
}
|
|
235
|
+
requests.push({ action: 'file.write', repo: repo.repo, ref: edit.path, uncertain:edit.uncertain, foreign: !inside(workspace, edit.path) || repo.path !== context.path,
|
|
236
|
+
code: inside(stateDir(workspace), edit.path) ? 'OWNER_ONLY' :
|
|
237
|
+
bump ? 'VERSION_BUMP' : undefined });
|
|
238
|
+
}
|
|
239
|
+
function authorize(code, request) {
|
|
240
|
+
const authorization = findGrant(context, { ...request,
|
|
241
|
+
action: ['VERSION_BUMP', 'RELEASE_ONLY'].includes(code) ? 'release' : request.action });
|
|
242
|
+
if (!authorization) refuse(code, request);
|
|
243
|
+
try { appendRecord(workspace, 'audit.jsonl', { at: new Date().toISOString(), type: 'grant-used',
|
|
244
|
+
workspace, session: context.session, request, authorization }); }
|
|
245
|
+
catch { refuse('AUDIT_UNAVAILABLE', request); }
|
|
246
|
+
}
|
|
247
|
+
const trustPaths = [stateDir(workspace), ...(sessionStore ? [stateDir(sessionStore)] : []),
|
|
248
|
+
...(context.ownerKey ? [context.ownerKey] : []), fileURLToPath(new URL('.',import.meta.url)),
|
|
249
|
+
...[workspace,homedir()].flatMap(root=>['.muse/hooks.json','.muse/.h2a-scope-install','.claude/settings.json',
|
|
250
|
+
'.claude/settings.local.json','.agents/hooks.json','.vibe/hooks.toml','.gemini/config/hooks.json'].map(path=>join(root,path)))].map(canonical);
|
|
251
|
+
for (const request of requests) {
|
|
252
|
+
if (uncertainPath(targetPath)) request.uncertain=true;
|
|
253
|
+
if (request.action.startsWith('file.') && trustPaths.some(path=>inside(path,request.ref) ||
|
|
254
|
+
['file.rm','file.chmod','file.chown'].includes(request.action) && inside(request.ref,path))) request.code = 'OWNER_ONLY';
|
|
255
|
+
if (request.action === 'owner.grant' || request.code === 'OWNER_ONLY') refuse('OWNER_ONLY', request);
|
|
256
|
+
if (request.uncertain) refuse('UNVERIFIABLE', request);
|
|
257
|
+
if (request.foreign) authorize('FOREIGN_WORKSPACE', request);
|
|
258
|
+
if (request.code) authorize(request.code, request);
|
|
259
|
+
if (request.release) authorize('RELEASE_ONLY', request);
|
|
260
|
+
if (request.checkVersions) {
|
|
261
|
+
for (const revision of request.versionRefs ?? [request.revision]) {
|
|
262
|
+
const bump = branchBump(request.cwd, revision, repository(request.cwd).path === context.path ? baseline : undefined);
|
|
263
|
+
if (bump === undefined) refuse('UNVERIFIABLE', request, 'Cannot establish package version baseline.');
|
|
264
|
+
if (bump) authorize('VERSION_BUMP', request);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (['gh.pr.merge', 'gh.pr.ready'].includes(request.action)) {
|
|
268
|
+
const bump = prBump(request);
|
|
269
|
+
if (bump === undefined) refuse('UNVERIFIABLE', request, 'Cannot inspect the PR diff.');
|
|
270
|
+
if (bump) authorize('VERSION_BUMP', request);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
if (['vibe', 'agy'].includes(host)) process.stdout.write('{"decision":"allow"}');
|
|
274
|
+
} catch (error) {
|
|
275
|
+
if (!context) context = { workspace: process.cwd(), session: '' };
|
|
276
|
+
refuse('UNVERIFIABLE', {}, error instanceof SyntaxError ? 'Malformed hook input.' : 'Scope could not be verified.');
|
|
277
|
+
}
|