harness-everything 0.57.3 → 0.58.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 (44) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.releaserc.json +2 -0
  4. package/CHANGELOG.md +15 -0
  5. package/benchmarks/results/live-host/agy-2026-11-22/README.md +49 -0
  6. package/benchmarks/results/live-host/agy-2026-11-23/README.md +48 -0
  7. package/ci/action-gate.test.js +162 -0
  8. package/ci/doc-capability-consistency.test.js +11 -1
  9. package/ci/mechanism-2aa-codex-action-gate-policy.test.js +37 -0
  10. package/ci/mechanism-2ao-plugin-sync.test.js +235 -2
  11. package/ci/mechanism-2w-platform-compatibility.test.js +13 -2
  12. package/ci/mechanism-2x-release-automation.test.js +3 -1
  13. package/ci/mechanism-agy-hooks.test.js +1096 -0
  14. package/ci/mechanism-agy-plugin-package.test.js +76 -0
  15. package/docs/codex-action-gate.md +2 -0
  16. package/docs/platform-capabilities.md +3 -1
  17. package/docs/platform-compatibility.json +34 -1
  18. package/hooks/scripts/action-gate.js +71 -5
  19. package/hooks/scripts/agy-post-tool.js +124 -0
  20. package/hooks/scripts/agy-pre-invocation.js +185 -0
  21. package/hooks/scripts/agy-pre-tool.js +158 -0
  22. package/hooks/scripts/agy-session-start.js +54 -0
  23. package/hooks/scripts/agy-stop.js +152 -0
  24. package/hooks/scripts/lib/agy-adapter-core.js +168 -0
  25. package/hooks/scripts/state-persist.js +50 -10
  26. package/opencode-plugin/plugin.json +1 -1
  27. package/package.json +1 -1
  28. package/plugins/harness-everything/.antigravity-plugin/plugin.json +18 -0
  29. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  30. package/plugins/harness-everything/hooks/scripts/action-gate.js +71 -5
  31. package/plugins/harness-everything/hooks/scripts/agy-post-tool.js +124 -0
  32. package/plugins/harness-everything/hooks/scripts/agy-pre-invocation.js +185 -0
  33. package/plugins/harness-everything/hooks/scripts/agy-pre-tool.js +158 -0
  34. package/plugins/harness-everything/hooks/scripts/agy-session-start.js +54 -0
  35. package/plugins/harness-everything/hooks/scripts/agy-stop.js +152 -0
  36. package/plugins/harness-everything/hooks/scripts/lib/agy-adapter-core.js +168 -0
  37. package/plugins/harness-everything/hooks/scripts/state-persist.js +50 -10
  38. package/plugins/harness-everything/hooks.json +44 -0
  39. package/plugins/harness-everything/plugin.json +1 -1
  40. package/plugins/harness-everything/rules/AGENTS.md +111 -0
  41. package/sbom.cdx.json +7 -7
  42. package/scripts/plugin-sync.js +105 -14
  43. package/scripts/sync-openai-plugin.js +16 -1
  44. package/scripts/sync-release-version.js +1 -0
@@ -112,10 +112,13 @@ function normalizeActionDescriptor(payload, options = {}) {
112
112
  const tool = toolNameOf(payload);
113
113
  const input = toolInputOf(payload);
114
114
  const explicit = explicitActionDescriptor(payload);
115
- const codexPrUpdate = detectHost(payload, options.host) === 'codex' && isPullRequestUpdateTool(tool);
116
- const toolFamily = inferToolFamily(tool, codexPrUpdate ? null : explicit);
115
+ const codex = detectHost(payload, options.host) === 'codex';
116
+ const codexPrUpdate = codex && isPullRequestUpdateTool(tool);
117
+ const codexIssueMutation = codex && isRoutineIssueTool(tool);
118
+ const protectedMcpMutation = codexPrUpdate || codexIssueMutation;
119
+ const toolFamily = inferToolFamily(tool, protectedMcpMutation ? null : explicit);
117
120
  const inferred = inferStructuredAction(tool, explicit);
118
- const action = codexPrUpdate && !STRUCTURED_GATED_ACTIONS.has(inferred) ? 'mutate' : inferred;
121
+ const action = protectedMcpMutation && !STRUCTURED_GATED_ACTIONS.has(inferred) ? 'mutate' : inferred;
119
122
  const classification = STRUCTURED_GATED_ACTIONS.has(action)
120
123
  ? 'gated'
121
124
  : (STRUCTURED_SAFE_ACTIONS.has(action) ? 'safe' : 'unknown');
@@ -146,6 +149,49 @@ function isPullRequestUpdateTool(name) {
146
149
  return name.split('__').pop() === 'update_pull_request' || name === 'mcp__codex_apps__github_update_pull_request';
147
150
  }
148
151
 
152
+ const ISSUE_COMMENT_TOOLS = new Set([
153
+ 'mcp__codex_apps__github__add_comment_to_issue',
154
+ 'mcp__codex_apps__github_add_comment_to_issue',
155
+ ]);
156
+ const ISSUE_COMPLETED_CLOSE_TOOLS = new Set([
157
+ 'mcp__codex_apps__github__update_issue',
158
+ 'mcp__codex_apps__github_update_issue',
159
+ ]);
160
+ // Both Issue exceptions require an owner/name repository selector; an ownerless
161
+ // name is uncertain and must keep the original gate.
162
+ const OWNER_REPO_SELECTOR = /^[^/\s]+\/[^/\s]+$/;
163
+
164
+ function isRoutineIssueTool(name) {
165
+ return ISSUE_COMMENT_TOOLS.has(name) || ISSUE_COMPLETED_CLOSE_TOOLS.has(name);
166
+ }
167
+
168
+ function hasExactKeys(input, expected) {
169
+ const keys = Object.keys(input);
170
+ return keys.length === expected.length && expected.every(key => Object.prototype.hasOwnProperty.call(input, key));
171
+ }
172
+
173
+ function isRoutineIssueComment(payload) {
174
+ const input = toolInputOf(payload);
175
+ return ISSUE_COMMENT_TOOLS.has(toolNameOf(payload))
176
+ && input && typeof input === 'object' && !Array.isArray(input)
177
+ && hasExactKeys(input, ['repo_full_name', 'pr_number', 'comment'])
178
+ && typeof input.repo_full_name === 'string' && input.repo_full_name.trim() !== ''
179
+ && OWNER_REPO_SELECTOR.test(input.repo_full_name)
180
+ && Number.isSafeInteger(input.pr_number) && input.pr_number > 0
181
+ && typeof input.comment === 'string' && input.comment.trim() !== '';
182
+ }
183
+
184
+ function isRoutineIssueCompletedClose(payload) {
185
+ const input = toolInputOf(payload);
186
+ return ISSUE_COMPLETED_CLOSE_TOOLS.has(toolNameOf(payload))
187
+ && input && typeof input === 'object' && !Array.isArray(input)
188
+ && hasExactKeys(input, ['repository_full_name', 'issue_number', 'state', 'state_reason'])
189
+ && typeof input.repository_full_name === 'string' && input.repository_full_name.trim() !== ''
190
+ && OWNER_REPO_SELECTOR.test(input.repository_full_name)
191
+ && Number.isSafeInteger(input.issue_number) && input.issue_number > 0
192
+ && input.state === 'closed' && input.state_reason === 'completed';
193
+ }
194
+
149
195
  function isPullRequestMetadataUpdate(payload) {
150
196
  if (!isPullRequestUpdateTool(toolNameOf(payload))) return false;
151
197
  const input = toolInputOf(payload);
@@ -173,6 +219,26 @@ function structuredRule(payload, options = {}) {
173
219
  && isPullRequestMetadataUpdate(payload) && !(hint && hint.required)) {
174
220
  return { descriptor, rule: null, hostDeferred: true };
175
221
  }
222
+ if (detectHost(payload, options.host) === 'codex' && descriptor.action === 'mutate'
223
+ && isRoutineIssueComment(payload) && !(hint && hint.required)) {
224
+ return {
225
+ descriptor,
226
+ rule: null,
227
+ hostDeferred: true,
228
+ hostDeferredId: 'routine-issue-comment',
229
+ hostDeferredReason: 'Codex routine Issue comments defer to native task scope and permissions.',
230
+ };
231
+ }
232
+ if (detectHost(payload, options.host) === 'codex' && descriptor.action === 'mutate'
233
+ && isRoutineIssueCompletedClose(payload) && !(hint && hint.required)) {
234
+ return {
235
+ descriptor,
236
+ rule: null,
237
+ hostDeferred: true,
238
+ hostDeferredId: 'routine-issue-completed-close',
239
+ hostDeferredReason: 'Codex routine Issue completed-close operations defer to native task scope and permissions.',
240
+ };
241
+ }
176
242
  if (descriptor.classification === 'gated') {
177
243
  return {
178
244
  descriptor,
@@ -495,8 +561,8 @@ function evaluatePreToolUse(payload, options = {}) {
495
561
 
496
562
  if (!rule) {
497
563
  const record = structured.hostDeferred ? recordDecision(payload, {
498
- id: 'routine-pr-metadata-update',
499
- reason: 'Codex PR title/body metadata update defers to native task scope and permissions.',
564
+ id: structured.hostDeferredId || 'routine-pr-metadata-update',
565
+ reason: structured.hostDeferredReason || 'Codex PR title/body metadata update defers to native task scope and permissions.',
500
566
  }, table, host, 'deferred-to-host', { ...options, sessionDir: context.sessionDir }) : null;
501
567
  return {
502
568
  kind: 'allow',
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) PostToolUse Hook Adapter
6
+ *
7
+ * Captures tool outcomes, tracks execution errors and file edits for state persistence.
8
+ * Bridges AGY tool execution to Harness session state (handoff-state.json).
9
+ * Returns empty JSON object `{}` on stdout as required by AGY protocol.
10
+ */
11
+
12
+ const path = require('path');
13
+ const { spawnSync } = require('child_process');
14
+ const {
15
+ readJsonStdin,
16
+ getAgySessionId,
17
+ getAgyEffectiveCwd
18
+ } = require('./lib/agy-adapter-core');
19
+
20
+ const FILE_MUTATION_TOOLS = new Set([
21
+ 'write_file',
22
+ 'write_to_file',
23
+ 'edit_file',
24
+ 'replace_file_content',
25
+ 'multi_replace_file_content'
26
+ ]);
27
+
28
+ function mapAgyPayloadToStatePersist(payload) {
29
+ const safePayload = payload && typeof payload === 'object' ? payload : {};
30
+ const sessionId = getAgySessionId(safePayload);
31
+ const workspaceCwd = getAgyEffectiveCwd(safePayload);
32
+ const toolCall = (safePayload.toolCall && typeof safePayload.toolCall === 'object') ? safePayload.toolCall : {};
33
+ const rawToolName = toolCall.name || safePayload.tool_name || safePayload.toolName || safePayload.tool || '';
34
+ const args = (toolCall.args && typeof toolCall.args === 'object')
35
+ ? toolCall.args
36
+ : ((safePayload.tool_input && typeof safePayload.tool_input === 'object') ? safePayload.tool_input : {});
37
+
38
+ let toolName = rawToolName;
39
+ let toolInput = { ...args };
40
+ let effectiveCwd = workspaceCwd;
41
+
42
+ if (rawToolName === 'run_command') {
43
+ toolName = 'Bash';
44
+ const command = String(args.CommandLine || args.command || '').trim();
45
+ const commandCwd = (typeof args.Cwd === 'string' && args.Cwd.trim())
46
+ || (typeof args.cwd === 'string' && args.cwd.trim())
47
+ || workspaceCwd;
48
+ effectiveCwd = commandCwd;
49
+ toolInput = {
50
+ command,
51
+ ...(commandCwd ? { cwd: commandCwd } : {})
52
+ };
53
+ } else if (FILE_MUTATION_TOOLS.has(rawToolName)) {
54
+ toolName = 'Write';
55
+ const filePath = args.TargetFile || args.Path || args.path || args.targetFile || args.filePath || args.file_path || '';
56
+ toolInput = { ...args, file_path: filePath };
57
+ }
58
+
59
+ const toolResponse = safePayload.toolResponse || safePayload.tool_response || safePayload.result || {};
60
+ const rawError = safePayload.error || toolResponse.error || '';
61
+ const error = typeof rawError === 'string' ? rawError : (rawError ? JSON.stringify(rawError) : '');
62
+ const stdout = toolResponse.stdout || (typeof safePayload.output === 'string' ? safePayload.output : '') || '';
63
+ const stderr = toolResponse.stderr || (typeof error === 'string' ? error : '') || '';
64
+
65
+ const rawExitCodes = [
66
+ safePayload.exitCode,
67
+ safePayload.exit_code,
68
+ toolResponse.exitCode,
69
+ toolResponse.exit_code
70
+ ].filter(Number.isInteger);
71
+ const exitCode = rawExitCodes.find(code => code !== 0) ?? rawExitCodes[0];
72
+
73
+ const isFailed = Boolean(error && error.trim()) || (exitCode !== undefined && exitCode !== 0);
74
+
75
+ return {
76
+ hook_event_name: isFailed ? 'PostToolUseFailure' : 'PostToolUse',
77
+ session_id: sessionId,
78
+ sessionId: sessionId,
79
+ conversationId: sessionId,
80
+ cwd: effectiveCwd,
81
+ workspace_root: workspaceCwd,
82
+ workspacePaths: (Array.isArray(safePayload.workspacePaths) && safePayload.workspacePaths.length > 0)
83
+ ? safePayload.workspacePaths
84
+ : [workspaceCwd],
85
+ tool_name: toolName,
86
+ tool_input: toolInput,
87
+ tool_response: {
88
+ stdout,
89
+ stderr,
90
+ ...(exitCode !== undefined ? { exitCode } : {})
91
+ },
92
+ error: isFailed ? (error || stderr || `Command exited with code ${exitCode}`) : '',
93
+ ...(exitCode !== undefined ? { exitCode } : {})
94
+ };
95
+ }
96
+
97
+ async function main() {
98
+ const payload = await readJsonStdin();
99
+
100
+ try {
101
+ const mapped = mapAgyPayloadToStatePersist(payload);
102
+ const statePersistScript = path.join(__dirname, 'state-persist.js');
103
+ spawnSync(process.execPath, [statePersistScript, '--agy'], {
104
+ input: JSON.stringify(mapped),
105
+ encoding: 'utf8',
106
+ env: process.env,
107
+ timeout: 10000
108
+ });
109
+ } catch (err) {
110
+ if (process.env.HARNESS_DEBUG) {
111
+ console.error('[AGY-PostToolUse] State persistence error:', err);
112
+ }
113
+ }
114
+
115
+ process.stdout.write('{}\n');
116
+ }
117
+
118
+ if (require.main === module) {
119
+ main().catch(() => {
120
+ process.stdout.write('{}\n');
121
+ });
122
+ }
123
+
124
+ module.exports = { main, mapAgyPayloadToStatePersist };
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) PreInvocation Hook Adapter
6
+ *
7
+ * Runs before model invocation. Invokes the Harness kernel router and ledger lessons
8
+ * ONCE per user turn (deduplicated across tool-call roundtrips within a turn), then
9
+ * returns systemMessage injectSteps in AGY's required protojson format.
10
+ * Bridges AGY conversationId to session_id for workflow persistence.
11
+ */
12
+
13
+ const crypto = require('crypto');
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { spawnSync } = require('child_process');
17
+ const {
18
+ readJsonStdin,
19
+ resolveKernelRouter,
20
+ getAgySessionId,
21
+ getAgyEffectiveCwd,
22
+ normalizeAgyStatePayload
23
+ } = require('./lib/agy-adapter-core');
24
+ const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
25
+
26
+ const DEDUP_STATE_FILE = 'agy-pre-invocation-state.json';
27
+
28
+ function hashUserInput(text) {
29
+ return crypto.createHash('sha256').update(String(text || ''), 'utf8').digest('hex').slice(0, 16);
30
+ }
31
+
32
+ function readDedupState(filePath) {
33
+ try {
34
+ if (!fs.existsSync(filePath)) return null;
35
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
36
+ return parsed && typeof parsed === 'object' ? parsed : null;
37
+ } catch (_) {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ function writeDedupState(filePath, state) {
43
+ try {
44
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
45
+ const temp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
46
+ fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', 'utf8');
47
+ fs.renameSync(temp, filePath);
48
+ } catch (_) {
49
+ // Best-effort marker write; never fail invocation on state IO.
50
+ }
51
+ }
52
+
53
+ function shouldSkipInjection(payload, userInput, dedupFile) {
54
+ const hasInvNum = payload && payload.invocationNum !== undefined && payload.invocationNum !== null && payload.invocationNum !== '';
55
+ const invNum = hasInvNum ? Number(payload.invocationNum) : 0;
56
+ const hasInitialSteps = payload && payload.initialNumSteps !== undefined && payload.initialNumSteps !== null && payload.initialNumSteps !== '';
57
+ const inputHash = hashUserInput(userInput);
58
+ const turnKey = hasInitialSteps
59
+ ? `step:${payload.initialNumSteps}:${inputHash}`
60
+ : `input:${inputHash}`;
61
+
62
+ if (!dedupFile) {
63
+ return {
64
+ skip: Number.isFinite(invNum) && invNum > 0,
65
+ turnKey,
66
+ invNum: Number.isFinite(invNum) ? invNum : 0,
67
+ base: 0
68
+ };
69
+ }
70
+
71
+ const saved = readDedupState(dedupFile);
72
+ const sameTurn = Boolean(saved && saved.turnKey === turnKey);
73
+
74
+ if (sameTurn) {
75
+ // When initialNumSteps is absent and a host explicitly sends invocationNum: 0
76
+ // (or restarts at 0 after a previous positive invocation), treat it as a new turn.
77
+ if (!hasInitialSteps && (saved.sawPositiveInvocation || hasInvNum) && Number.isFinite(invNum) && invNum === 0) {
78
+ return { skip: false, turnKey, invNum: 0, base: 0 };
79
+ }
80
+ if (Number.isFinite(invNum) && invNum > 0 && !saved.sawPositiveInvocation) {
81
+ writeDedupState(dedupFile, { ...saved, sawPositiveInvocation: true, updatedAt: new Date().toISOString() });
82
+ }
83
+ return { skip: true, turnKey, invNum: Number.isFinite(invNum) ? invNum : 0, base: saved.base || 0 };
84
+ }
85
+
86
+ // Not the same turnKey: guard against mid-turn calls (both 0-based and 1-based).
87
+ if (Number.isFinite(invNum) && invNum > 1) {
88
+ return { skip: true, turnKey, invNum, base: (saved && saved.base) || 0 };
89
+ }
90
+ if (Number.isFinite(invNum) && invNum === 1 && (!hasInitialSteps || (saved && saved.base === 0))) {
91
+ return { skip: true, turnKey, invNum, base: 0 };
92
+ }
93
+
94
+ const base = Number.isFinite(invNum) && invNum === 1 ? 1 : 0;
95
+ return { skip: false, turnKey, invNum: Number.isFinite(invNum) ? invNum : 0, base };
96
+ }
97
+
98
+ async function main() {
99
+ const payload = await readJsonStdin();
100
+ const userInput = payload.lastUserInput || payload.prompt || '';
101
+ const routerScript = resolveKernelRouter();
102
+
103
+ if (!routerScript || !String(userInput).trim()) {
104
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
105
+ return;
106
+ }
107
+
108
+ const sessionId = getAgySessionId(payload);
109
+ const effectiveCwd = getAgyEffectiveCwd(payload);
110
+ const normalizedPayload = normalizeAgyStatePayload(payload, effectiveCwd);
111
+
112
+ let dedupFile = null;
113
+ if (sessionId) {
114
+ try {
115
+ const root = getWorkspaceRoot(normalizedPayload) || effectiveCwd;
116
+ const sessionDir = getSessionDir(root, sessionId);
117
+ dedupFile = path.join(sessionDir, DEDUP_STATE_FILE);
118
+ } catch (_) {
119
+ dedupFile = null;
120
+ }
121
+ }
122
+
123
+ const dedup = shouldSkipInjection(payload, userInput, dedupFile);
124
+ if (dedup.skip) {
125
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
126
+ return;
127
+ }
128
+
129
+ try {
130
+ const routerInput = {
131
+ hook_event_name: 'UserPromptSubmit',
132
+ prompt: userInput,
133
+ lastUserInput: userInput,
134
+ cwd: effectiveCwd,
135
+ conversationId: sessionId,
136
+ session_id: sessionId,
137
+ sessionId: sessionId,
138
+ ...(payload.workspacePaths ? { workspacePaths: payload.workspacePaths } : {})
139
+ };
140
+
141
+ const run = spawnSync(process.execPath, [routerScript], {
142
+ input: JSON.stringify(routerInput),
143
+ encoding: 'utf8',
144
+ env: process.env,
145
+ timeout: 20000
146
+ });
147
+
148
+ const context = String(run.stdout || '').trim();
149
+ if (context) {
150
+ if (dedupFile) {
151
+ writeDedupState(dedupFile, {
152
+ turnKey: dedup.turnKey,
153
+ base: dedup.base,
154
+ sawPositiveInvocation: dedup.invNum > 0,
155
+ updatedAt: new Date().toISOString()
156
+ });
157
+ }
158
+ const response = {
159
+ injectSteps: [
160
+ {
161
+ systemMessage: {
162
+ systemMessage: context
163
+ }
164
+ }
165
+ ]
166
+ };
167
+ process.stdout.write(JSON.stringify(response) + '\n');
168
+ return;
169
+ }
170
+ } catch (err) {
171
+ if (process.env.HARNESS_DEBUG) {
172
+ console.error('[AGY-PreInvocation] Routing error:', err);
173
+ }
174
+ }
175
+
176
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
177
+ }
178
+
179
+ if (require.main === module) {
180
+ main().catch(() => {
181
+ process.stdout.write(JSON.stringify({ injectSteps: [] }) + '\n');
182
+ });
183
+ }
184
+
185
+ module.exports = { main, shouldSkipInjection };
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) PreToolUse Hook Adapter
6
+ *
7
+ * Intercepts tool execution to enforce:
8
+ * - Worktree and filesystem boundary containment for file writes
9
+ * (allows writes inside any workspacePaths entry, cwd, or artifactDirectoryPath).
10
+ * - Canonical Action Gate policies (destructive operations, forced pushes, publish, reset).
11
+ *
12
+ * Returns protojson: {"decision": "allow" | "deny" | "ask", "reason": "..."}
13
+ */
14
+
15
+ const {
16
+ readJsonStdin,
17
+ getAgySessionId,
18
+ getAgyWorkspacePaths,
19
+ getAgyEffectiveCwd,
20
+ isOutOfBoundsPath
21
+ } = require('./lib/agy-adapter-core');
22
+ const { evaluatePreToolUse } = require('./action-gate');
23
+
24
+ const FILE_MUTATION_TOOLS = new Set([
25
+ 'write_file',
26
+ 'edit_file',
27
+ 'write_to_file',
28
+ 'replace_file_content',
29
+ 'multi_replace_file_content'
30
+ ]);
31
+
32
+ function extractToolCall(payload) {
33
+ if (!payload || typeof payload !== 'object') {
34
+ return { id: undefined, name: '', args: {} };
35
+ }
36
+ const raw = payload.toolCall && typeof payload.toolCall === 'object' ? payload.toolCall : null;
37
+ const name = (raw && raw.name) || payload.tool_name || payload.toolName || payload.tool || '';
38
+ const args = (raw && raw.args && typeof raw.args === 'object')
39
+ ? raw.args
40
+ : ((payload.tool_input && typeof payload.tool_input === 'object') ? payload.tool_input : {});
41
+ const id = (raw && raw.id) || payload.tool_use_id || payload.toolUseId || undefined;
42
+ return { id, name, args };
43
+ }
44
+
45
+ function collectAllowedWriteRoots(cwd, context = {}) {
46
+ const payload = (context && context.payload) || {};
47
+ const roots = [];
48
+ if (Array.isArray(context.workspacePaths)) {
49
+ for (const entry of context.workspacePaths) {
50
+ if (typeof entry === 'string' && entry.trim()) roots.push(entry.trim());
51
+ }
52
+ }
53
+ for (const entry of getAgyWorkspacePaths(payload)) {
54
+ roots.push(entry);
55
+ }
56
+ if (typeof cwd === 'string' && cwd.trim()) {
57
+ roots.push(cwd.trim());
58
+ }
59
+ const artifactDir = context.artifactDirectoryPath || payload.artifactDirectoryPath;
60
+ if (typeof artifactDir === 'string' && artifactDir.trim()) {
61
+ roots.push(artifactDir.trim());
62
+ }
63
+ return [...new Set(roots)];
64
+ }
65
+
66
+ function evaluateToolCall(toolCall, cwd, context = {}) {
67
+ if (!toolCall || !toolCall.name) {
68
+ return { decision: 'allow' };
69
+ }
70
+
71
+ const name = toolCall.name;
72
+ const args = (toolCall.args && typeof toolCall.args === 'object') ? toolCall.args : {};
73
+
74
+ // 1. Filesystem boundary containment for file mutations
75
+ if (FILE_MUTATION_TOOLS.has(name)) {
76
+ const rawPath = args.TargetFile ?? args.Path ?? args.path ?? args.targetFile ?? args.filePath ?? args.file_path;
77
+ const filePath = typeof rawPath === 'string' ? rawPath.trim() : '';
78
+ if (!filePath) {
79
+ return {
80
+ decision: 'deny',
81
+ reason: `Harness boundary guard: missing target file path for ${name}.`
82
+ };
83
+ }
84
+
85
+ const allowedRoots = collectAllowedWriteRoots(cwd, context);
86
+ if (isOutOfBoundsPath(filePath, allowedRoots, cwd)) {
87
+ return {
88
+ decision: 'deny',
89
+ reason: `Harness boundary guard: modification outside workspace root is forbidden (${filePath}).`
90
+ };
91
+ }
92
+ return { decision: 'allow' };
93
+ }
94
+
95
+ // 2. Command safety via canonical Action Gate
96
+ if (name === 'run_command') {
97
+ const command = String(args.CommandLine || args.command || '').trim();
98
+ if (!command) {
99
+ return { decision: 'allow' };
100
+ }
101
+
102
+ const payload = context.payload || {};
103
+ const sessionId = context.sessionId || getAgySessionId(payload) || undefined;
104
+ const commandCwd = (typeof args.Cwd === 'string' && args.Cwd.trim())
105
+ || (typeof args.cwd === 'string' && args.cwd.trim())
106
+ || cwd;
107
+ const toolUseId = toolCall.id || payload.tool_use_id || payload.toolUseId || undefined;
108
+
109
+ const actionPayload = {
110
+ hook_event_name: 'PreToolUse',
111
+ tool_name: 'Bash',
112
+ tool_input: { command },
113
+ ...(toolUseId ? { tool_use_id: toolUseId } : {}),
114
+ cwd: commandCwd,
115
+ ...(cwd ? { workspace_root: cwd } : {}),
116
+ ...(sessionId ? { session_id: sessionId, sessionId } : {})
117
+ };
118
+
119
+ const gateResult = evaluatePreToolUse(actionPayload, { host: 'agy' });
120
+
121
+ if (gateResult.kind === 'block') {
122
+ const reason = gateResult.rule
123
+ ? `[Harness actionGate:${gateResult.rule.id}] ${gateResult.rule.reason}`
124
+ : (gateResult.stderr || 'Harness action gate: command rejected.');
125
+ return { decision: 'deny', reason };
126
+ }
127
+
128
+ if (gateResult.kind === 'ask') {
129
+ const reason = gateResult.rule
130
+ ? `[Harness actionGate:${gateResult.rule.id}] ${gateResult.rule.reason}`
131
+ : 'Harness action gate: confirmation required.';
132
+ return { decision: 'ask', reason };
133
+ }
134
+
135
+ return { decision: 'allow' };
136
+ }
137
+
138
+ return { decision: 'allow' };
139
+ }
140
+
141
+ async function main() {
142
+ const payload = await readJsonStdin();
143
+ const cwd = getAgyEffectiveCwd(payload);
144
+ const toolCall = extractToolCall(payload);
145
+ const sessionId = getAgySessionId(payload) || undefined;
146
+
147
+ const result = evaluateToolCall(toolCall, cwd, { sessionId, payload });
148
+ process.stdout.write(JSON.stringify(result) + '\n');
149
+ }
150
+
151
+ if (require.main === module) {
152
+ main().catch(err => {
153
+ // Fail closed on evaluation failure if error occurs
154
+ process.stdout.write(JSON.stringify({ decision: 'deny', reason: `Internal hook error: ${err.message}` }) + '\n');
155
+ });
156
+ }
157
+
158
+ module.exports = { main, evaluateToolCall, extractToolCall };
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Antigravity (AGY) SessionStart Hook Adapter
6
+ *
7
+ * Runs once when a new conversation session begins.
8
+ * Binds session workspace identity (when provided) and injects Harness bootstrap message.
9
+ */
10
+
11
+ const {
12
+ readJsonStdin,
13
+ getAgySessionId,
14
+ normalizeAgyStatePayload
15
+ } = require('./lib/agy-adapter-core');
16
+ const { getWorkspaceRoot } = require('./lib/harness-state');
17
+
18
+ async function main() {
19
+ const payload = await readJsonStdin();
20
+
21
+ try {
22
+ const sessionId = getAgySessionId(payload);
23
+ const hasWorkspaceHint = Boolean(
24
+ (typeof payload.cwd === 'string' && payload.cwd.trim()) ||
25
+ (Array.isArray(payload.workspacePaths) && payload.workspacePaths.some(entry => typeof entry === 'string' && entry.trim()))
26
+ );
27
+ if (sessionId && hasWorkspaceHint) {
28
+ const normalized = normalizeAgyStatePayload(payload);
29
+ getWorkspaceRoot(normalized);
30
+ }
31
+ } catch (_) {
32
+ // Session workspace binding is best-effort and must never fail startup.
33
+ }
34
+
35
+ const response = {
36
+ injectSteps: [
37
+ {
38
+ systemMessage: {
39
+ systemMessage: 'Harness Skills OS active. Operating under AGENTS.md invariant-first routing.'
40
+ }
41
+ }
42
+ ]
43
+ };
44
+
45
+ process.stdout.write(JSON.stringify(response) + '\n');
46
+ }
47
+
48
+ if (require.main === module) {
49
+ main().catch(() => {
50
+ process.stdout.write('{}\n');
51
+ });
52
+ }
53
+
54
+ module.exports = { main };