harness-everything 1.0.0 → 1.0.1

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.
@@ -10,7 +10,7 @@
10
10
  "name": "harness-everything",
11
11
  "source": "./",
12
12
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
13
- "version": "1.0.0",
13
+ "version": "1.0.1",
14
14
  "author": {
15
15
  "name": "Miya Daniel"
16
16
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-everything",
3
3
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
4
- "version": "1.0.0",
4
+ "version": "1.0.1",
5
5
  "author": {
6
6
  "name": "Miya Daniel"
7
7
  },
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [1.0.1](https://github.com/dyphn1/Harness-everything/compare/v1.0.0...v1.0.1) (2026-11-24)
6
+
7
+ ### Bug Fixes
8
+
9
+ * **agy:** bound stop continuation per work revision and normalize post-tool outcomes ([#516](https://github.com/dyphn1/Harness-everything/issues/516)) ([0fd30f5](https://github.com/dyphn1/Harness-everything/commit/0fd30f5f841212495b6278778e541f5e439093b6))
10
+ * **hooks:** match ledger lessons through pipelines and plain redirects ([#518](https://github.com/dyphn1/Harness-everything/issues/518)) ([509e010](https://github.com/dyphn1/Harness-everything/commit/509e01014bfcf8c2b7f3b6071ecf921860d50083))
11
+
5
12
  ## [1.0.0](https://github.com/dyphn1/Harness-everything/compare/v0.58.0...v1.0.0) (2026-11-24)
6
13
 
7
14
  ### ⚠ BREAKING CHANGES
@@ -170,8 +170,6 @@ test('source and packaged matchers bound simple command sequences and reject uns
170
170
  ];
171
171
  const unsupported = [
172
172
  "echo 'git commit; echo done'",
173
- 'git commit | cat',
174
- 'cat | git commit',
175
173
  '(git commit)',
176
174
  'git commit <<EOF\nmessage\nEOF',
177
175
  'git commit;',
@@ -186,6 +184,77 @@ test('source and packaged matchers bound simple command sequences and reject uns
186
184
  }
187
185
  });
188
186
 
187
+ test('source and packaged matchers recognize pipeline members and literal redirects', () => {
188
+ const expected = { tool: 'shell', executable: 'git', subcommand: 'commit' };
189
+ const supported = [
190
+ 'git commit -m "A"',
191
+ 'cd /x && git commit -m "A"',
192
+ 'git commit --dry-run -m "A"',
193
+ 'git commit -m "A" 2>&1',
194
+ 'git commit -m "A" 2>&1 | tail -3',
195
+ 'git commit -m "A" | cat',
196
+ 'echo before | git commit -m "A"',
197
+ 'git 2>&1 commit -m "A"',
198
+ '2>errors.log git commit -m "A"',
199
+ 'git commit 2>&1 -m "A"',
200
+ 'git commit -m "A" >out.log',
201
+ 'git commit -m "A" >out#log',
202
+ 'git commit -m "A" >> "out file.log"',
203
+ 'git commit -m "A" < input.txt',
204
+ 'git commit -m "A" &>combined.log',
205
+ 'git commit -m "A" 2> errors.log',
206
+ 'git commit -m "A | B"',
207
+ 'git commit -m A \\| cat',
208
+ 'git commit -m "A" # | cat is comment text'
209
+ ];
210
+ const unsupported = [
211
+ "echo 'git commit | cat'",
212
+ 'echo before > git commit',
213
+ 'echo before # git commit | cat',
214
+ 'env git commit',
215
+ 'git commit |',
216
+ '| git commit',
217
+ 'git commit | | cat',
218
+ 'git commit |& cat',
219
+ 'git commit &',
220
+ 'git commit &>>out.log',
221
+ 'git commit 2>&-',
222
+ 'git commit 2>&1-',
223
+ 'git commit 2>&1suffix',
224
+ '2 >errors.log git commit',
225
+ "'2'>errors.log git commit",
226
+ 'name2>errors.log git commit',
227
+ 'git commit >',
228
+ 'git commit > # missing redirect target',
229
+ 'git commit >#missing-target',
230
+ 'git commit >""',
231
+ 'git commit >"$OUT"',
232
+ 'git commit >*.log',
233
+ 'git commit <<EOF\nmessage\nEOF',
234
+ 'git commit <<< message',
235
+ 'git commit > >(tee out.log)',
236
+ 'cat <(git commit)',
237
+ '(git commit)',
238
+ 'echo "$(git commit)"',
239
+ 'echo "`git commit`"'
240
+ ];
241
+ for (const implementation of [matcher, packagedMatcher]) {
242
+ for (const command of supported) {
243
+ assert.deepEqual(implementation.normalizeGitCommitCommand(command), expected, command);
244
+ const result = implementation.matchLedgerLessons(input({
245
+ event: { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } }
246
+ }));
247
+ assert.deepEqual(result?.ids, ['E-0003'], command);
248
+ }
249
+ for (const command of unsupported) {
250
+ assert.equal(implementation.normalizeGitCommitCommand(command), null, command);
251
+ assert.equal(implementation.matchLedgerLessons(input({
252
+ event: { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } }
253
+ })), null, command);
254
+ }
255
+ }
256
+ });
257
+
189
258
  test('source and packaged matchers accept an empty Git config value', () => {
190
259
  const expected = { tool: 'shell', executable: 'git', subcommand: 'commit' };
191
260
  for (const implementation of [matcher, packagedMatcher]) {
@@ -225,7 +294,6 @@ test('simple command segments select commit lessons without matching quoted text
225
294
  }
226
295
  for (const command of [
227
296
  "echo 'git commit; echo done'",
228
- 'git commit | cat',
229
297
  '(git commit)',
230
298
  'git commit <<EOF\nmessage\nEOF',
231
299
  'env git commit'
@@ -272,6 +340,40 @@ test('failure lessons require a known outcome and an exact diagnostic', () => {
272
340
  }
273
341
  });
274
342
 
343
+ test('a pipeline keeps the per-session action and failure reminder policy', () => {
344
+ const state = stateDir('pipeline-once');
345
+ const base = input({ stateDir: state, sessionIdentity: 'session:pipeline-once' });
346
+ const action = matcher.matchLedgerLessons(base);
347
+ assert.deepEqual(action?.ids, ['E-0003']);
348
+ assert.equal(matcher.matchLedgerLessons(base), null, 'a duplicate action stays silent');
349
+
350
+ const failureInput = {
351
+ ...base,
352
+ event: {
353
+ phase: 'failure',
354
+ tool: 'shell',
355
+ command: 'git commit -m "Bad Subject" 2>&1 | tail -3',
356
+ outcome: { failed: false, output: COMMITLINT_OUTPUT }
357
+ }
358
+ };
359
+ const failure = matcher.matchLedgerLessons(failureInput);
360
+ assert.deepEqual(failure?.ids, ['E-0003'], 'an exact diagnostic can recover a pipeline masked by zero status');
361
+ assert.equal(matcher.matchLedgerLessons(failureInput), null, 'a duplicate failure stays silent');
362
+
363
+ const unknown = matcher.matchLedgerLessons({
364
+ ...failureInput,
365
+ sessionIdentity: 'session:pipeline-unknown',
366
+ event: { ...failureInput.event, outcome: { failed: 'unknown', output: COMMITLINT_OUTPUT } }
367
+ });
368
+ assert.equal(unknown, null, 'an unknown pipeline outcome stays silent');
369
+ const redirectedZero = matcher.matchLedgerLessons({
370
+ ...failureInput,
371
+ sessionIdentity: 'session:redirected-zero',
372
+ event: { ...failureInput.event, command: 'git commit -m "Bad Subject" 2>&1', outcome: { failed: false, output: COMMITLINT_OUTPUT } }
373
+ });
374
+ assert.equal(redirectedZero, null, 'a redirect alone remains one command and cannot recover a zero status');
375
+ });
376
+
275
377
  test('the real generator and runtime accept quoted identity and match scalars', () => {
276
378
  const root = workspace('generated quoted record');
277
379
  const ledger = path.join(root, '.agents', 'harness-everything', 'errors');
@@ -0,0 +1,472 @@
1
+ 'use strict';
2
+
3
+ const assert = require('assert');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { spawnSync } = require('child_process');
8
+
9
+ const HOOK_REL = path.join('hooks', 'scripts', 'agy-post-tool.js');
10
+ const PACKAGED_POST_TOOL_REL = path.join('plugins', 'harness-everything', 'hooks', 'scripts', 'agy-post-tool.js');
11
+ const PACKAGED_STOP_REL = path.join('plugins', 'harness-everything', 'hooks', 'scripts', 'agy-stop.js');
12
+ const { getSessionDir } = require(path.join('..', 'hooks', 'scripts', 'lib', 'harness-state'));
13
+ const { mapAgyPayloadToStatePersist } = require(path.join('..', 'hooks', 'scripts', 'agy-post-tool'));
14
+
15
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-516-agy-post-tool-'));
16
+ const tempStateHome = path.join(tempRoot, 'state-home');
17
+ fs.mkdirSync(tempStateHome, { recursive: true });
18
+
19
+ const originalStateHome = process.env.HARNESS_STATE_HOME;
20
+ process.env.HARNESS_STATE_HOME = tempStateHome;
21
+
22
+ function runHookRel(scriptRel, payload, expectedShape = {}) {
23
+ const childEnv = { ...process.env, HARNESS_STATE_HOME: tempStateHome };
24
+ delete childEnv.HARNESS_REQUIRE_VERIFICATION;
25
+ const run = spawnSync(process.execPath, [scriptRel], {
26
+ input: JSON.stringify(payload),
27
+ encoding: 'utf8',
28
+ env: childEnv,
29
+ timeout: 20000
30
+ });
31
+ assert.strictEqual(run.status, 0, `${scriptRel} exited non-zero: ${run.stderr}`);
32
+ let parsed;
33
+ try {
34
+ parsed = JSON.parse(run.stdout.trim());
35
+ } catch (_) {
36
+ assert.fail(`${scriptRel} stdout is not valid JSON: "${run.stdout}"`);
37
+ }
38
+ if (expectedShape.emptyObject) {
39
+ assert.deepStrictEqual(parsed, {}, `${scriptRel} must always emit {}`);
40
+ }
41
+ return parsed;
42
+ }
43
+
44
+ function runPostTool(payload) {
45
+ return runHookRel(HOOK_REL, payload, { emptyObject: true });
46
+ }
47
+
48
+ function runPackagedPostTool(payload) {
49
+ return runHookRel(PACKAGED_POST_TOOL_REL, payload, { emptyObject: true });
50
+ }
51
+
52
+ function runPackagedStop(payload) {
53
+ const parsed = runHookRel(PACKAGED_STOP_REL, payload);
54
+ assert.ok(parsed && (parsed.decision === 'allow' || parsed.decision === 'continue'), `unexpected Stop output: ${JSON.stringify(parsed)}`);
55
+ return parsed;
56
+ }
57
+
58
+ function readHandoff(ws, convId) {
59
+ const handoffFile = path.join(getSessionDir(ws, convId), 'handoff-state.json');
60
+ assert.ok(fs.existsSync(handoffFile), `handoff-state.json must exist for ${convId}`);
61
+ return JSON.parse(fs.readFileSync(handoffFile, 'utf8'));
62
+ }
63
+
64
+ function makeWs(name) {
65
+ const ws = path.join(tempRoot, name);
66
+ fs.mkdirSync(ws, { recursive: true });
67
+ return ws;
68
+ }
69
+
70
+ try {
71
+ // 1. Existing numeric exitCode 0 / nonzero & conflicting numeric codes
72
+ {
73
+ const ws = makeWs('ws-numeric');
74
+ const conv = 'conv-516-numeric';
75
+
76
+ runPostTool({
77
+ conversationId: conv,
78
+ workspacePaths: [ws],
79
+ toolCall: { name: 'write_file', args: { Path: path.join(ws, 'a.js'), Content: '1' } }
80
+ });
81
+ const afterEdit = readHandoff(ws, conv);
82
+ assert.ok(afterEdit.lastEditAt > 0, 'write_file must set lastEditAt');
83
+
84
+ // Numeric nonzero in toolResponse.exit_code -> failed
85
+ runPostTool({
86
+ conversationId: conv,
87
+ workspacePaths: [ws],
88
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
89
+ toolResponse: { exit_code: 2 }
90
+ });
91
+ const afterFail = readHandoff(ws, conv);
92
+ assert.strictEqual(afterFail.status, 'failed');
93
+ assert.strictEqual(afterFail.exitCode, 2);
94
+ assert.ok(!afterFail.lastVerifyAt, 'nonzero exit_code must not grant lastVerifyAt');
95
+
96
+ // Conflicting numeric codes (0 + 1) -> nonzero wins, stays failed
97
+ runPostTool({
98
+ conversationId: conv,
99
+ workspacePaths: [ws],
100
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
101
+ exitCode: 0,
102
+ toolResponse: { exit_code: 1 }
103
+ });
104
+ const afterConflictNum = readHandoff(ws, conv);
105
+ assert.strictEqual(afterConflictNum.status, 'failed');
106
+ assert.strictEqual(afterConflictNum.exitCode, 1);
107
+ assert.ok(!afterConflictNum.lastVerifyAt, 'conflicting numeric 0 and 1 must not grant lastVerifyAt');
108
+
109
+ // Unrecognized command + numeric exitCode: 0 -> no verification credit
110
+ runPostTool({
111
+ conversationId: conv,
112
+ workspacePaths: [ws],
113
+ toolCall: { name: 'run_command', args: { CommandLine: 'node -e "console.log(1)"', Cwd: ws } },
114
+ exitCode: 0
115
+ });
116
+ const afterUnrecognized = readHandoff(ws, conv);
117
+ assert.ok(!afterUnrecognized.lastVerifyAt, 'unrecognized command with exitCode: 0 must not grant lastVerifyAt');
118
+
119
+ // Recognized check + numeric exitCode: 0 -> advances lastVerifyAt & clears failed
120
+ runPostTool({
121
+ conversationId: conv,
122
+ workspacePaths: [ws],
123
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
124
+ exitCode: 0
125
+ });
126
+ const afterPass = readHandoff(ws, conv);
127
+ assert.strictEqual(afterPass.status, 'idle');
128
+ assert.strictEqual(afterPass.lastVerifyExitCode, 0);
129
+ assert.ok(afterPass.lastVerifyAt >= afterEdit.lastEditAt, 'recognized check with exitCode: 0 must advance lastVerifyAt');
130
+ }
131
+
132
+ // 2. Structured status / error flags & string toolResponse normalization
133
+ {
134
+ const ws = makeWs('ws-structured');
135
+
136
+ const failurePayloads = [
137
+ { label: 'toolResponse.isError', extra: { toolResponse: { isError: true } } },
138
+ { label: 'toolResponse.is_error', extra: { toolResponse: { is_error: true, exitCode: 0 } } },
139
+ { label: 'toolResponse.success=false', extra: { toolResponse: { success: false } } },
140
+ { label: 'toolResponse.ok=false', extra: { toolResponse: { ok: false, exitCode: 0 } } },
141
+ { label: 'toolResponse.status=failed', extra: { toolResponse: { status: 'failed', exitCode: 0 } } },
142
+ { label: 'payload.status=error', extra: { status: 'error' } },
143
+ { label: 'payload.interrupted=true', extra: { interrupted: true } }
144
+ ];
145
+
146
+ for (const item of failurePayloads) {
147
+ const conv = `conv-516-${item.label}`;
148
+ runPostTool({
149
+ conversationId: conv,
150
+ workspacePaths: [ws],
151
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
152
+ ...item.extra
153
+ });
154
+ const state = readHandoff(ws, conv);
155
+ assert.strictEqual(state.status, 'failed', `${item.label} must record status: failed`);
156
+ assert.ok(!state.lastVerifyAt, `${item.label} must not grant lastVerifyAt`);
157
+ }
158
+
159
+ // Positive control: isError: false WITH numeric exitCode: 0 advances lastVerifyAt
160
+ const convPos = 'conv-516-isError-false-pos';
161
+ runPostTool({
162
+ conversationId: convPos,
163
+ workspacePaths: [ws],
164
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
165
+ toolResponse: { isError: false, exitCode: 0 }
166
+ });
167
+ const posState = readHandoff(ws, convPos);
168
+ assert.strictEqual(posState.status, 'idle');
169
+ assert.strictEqual(posState.lastVerifyExitCode, 0);
170
+ assert.ok(posState.lastVerifyAt > 0, 'isError: false with exitCode: 0 must grant lastVerifyAt');
171
+
172
+ // Negative control: success/completed flags WITHOUT numeric exitCode: 0 must NOT credit shell verification
173
+ for (const [idx, extra] of [
174
+ { toolResponse: { isError: false } },
175
+ { toolResponse: { success: true } },
176
+ { toolResponse: { ok: true } },
177
+ { toolResponse: { status: 'completed' } }
178
+ ].entries()) {
179
+ const convNeg = `conv-516-no-exitcode-${idx}`;
180
+ runPostTool({
181
+ conversationId: convNeg,
182
+ workspacePaths: [ws],
183
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
184
+ ...extra
185
+ });
186
+ const negState = readHandoff(ws, convNeg);
187
+ assert.strictEqual(negState.status, 'idle');
188
+ assert.ok(!negState.lastVerifyAt, 'structured success without exitCode: 0 must not credit shell verification');
189
+ assert.ok(!negState.lastEditAt, 'recognized shell verification without exitCode must not bump lastEditAt');
190
+ }
191
+
192
+ // String toolResponse/result preserves stdout without trusting text as exit code
193
+ const mappedStr = mapAgyPayloadToStatePersist({
194
+ conversationId: 'conv-516-str',
195
+ workspacePaths: [ws],
196
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
197
+ toolResponse: 'Command exited with code 0.'
198
+ });
199
+ assert.ok(mappedStr, 'string toolResponse must map to a state-persist payload');
200
+ assert.strictEqual(mappedStr.tool_response.stdout, 'Command exited with code 0.', 'string toolResponse must be preserved as stdout');
201
+ assert.strictEqual(mappedStr.exitCode, undefined, 'string toolResponse must not be trusted as exitCode');
202
+ }
203
+
204
+ // 3. Unidentified text markers in stdout / output / string toolResponse stay unknown; explicit host error + marker 0 stays failed
205
+ {
206
+ const ws = makeWs('ws-text-markers');
207
+ const conv = 'conv-516-text';
208
+
209
+ // Seed an edit and a pending failure to verify nothing is cleared or credited by text-only markers
210
+ runPostTool({
211
+ conversationId: conv,
212
+ workspacePaths: [ws],
213
+ toolCall: { name: 'write_file', args: { Path: path.join(ws, 'app.js'), Content: '1' } }
214
+ });
215
+ runPostTool({
216
+ conversationId: conv,
217
+ workspacePaths: [ws],
218
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
219
+ error: 'prior failure'
220
+ });
221
+ const baseline = readHandoff(ws, conv);
222
+ assert.strictEqual(baseline.status, 'failed');
223
+
224
+ const unknownMarkerPayloads = [
225
+ { toolResponse: { stdout: 'Command exited with code 0.' } },
226
+ { output: 'Command exited with code 0.' },
227
+ { toolResponse: 'Command exited with code 0.' },
228
+ { result: 'Command exited with code 0.' },
229
+ { toolResponse: { stdout: 'Command exited with code 0.\nCommand exited with code 1.' } },
230
+ { output: 'Command exited with code 0.\nCommand exited with code 1.' }
231
+ ];
232
+
233
+ for (const extra of unknownMarkerPayloads) {
234
+ runPostTool({
235
+ conversationId: conv,
236
+ workspacePaths: [ws],
237
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
238
+ ...extra
239
+ });
240
+ const after = readHandoff(ws, conv);
241
+ assert.strictEqual(after.status, 'failed', 'unknown/stdout text markers must preserve existing failed state');
242
+ assert.strictEqual(after.lastEditAt, baseline.lastEditAt, 'recognized check with unknown text marker must not bump lastEditAt');
243
+ assert.ok(!after.lastVerifyAt, 'unknown/stdout text markers must not grant lastVerifyAt');
244
+ }
245
+
246
+ // Explicit host error + marker 0 (or exitCode 0) stays failed
247
+ for (const [idx, extra] of [
248
+ { error: 'explicit host error', exitCode: 0 },
249
+ { error: 'Command exited with code 0.' },
250
+ { error: 'explicit host error', output: 'Command exited with code 0.' }
251
+ ].entries()) {
252
+ const convErr = `conv-516-explicit-err-${idx}`;
253
+ runPostTool({
254
+ conversationId: convErr,
255
+ workspacePaths: [ws],
256
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
257
+ ...extra
258
+ });
259
+ const errState = readHandoff(ws, convErr);
260
+ assert.strictEqual(errState.status, 'failed', `explicit host error case ${idx} must fail`);
261
+ assert.ok(!errState.lastVerifyAt, `explicit host error case ${idx} must not grant lastVerifyAt`);
262
+ }
263
+ }
264
+
265
+ // 4. P516-B2 repair rows: error normalization precedence, no generic pending/background bypass, text-only lookalikes, and packaged PostToolUse -> handoff -> Stop positive control
266
+ {
267
+ const ws = makeWs('ws-b2-repair');
268
+
269
+ // Row 1: blank top-level error + nonblank nested error + exitCode 0 -> failed, verification stale, packaged Stop continue
270
+ for (const [idx, variant] of [
271
+ { error: ' ', toolResponse: { error: 'explicit host error' }, exitCode: 0 },
272
+ { error: '\t\n ', tool_response: { error: 'nested tool_response error', exitCode: 0 } },
273
+ { error: ' ', result: { error: { message: 'nested result error' } }, exitCode: 0 }
274
+ ].entries()) {
275
+ const conv = `conv-516-b2-nested-err-${idx}`;
276
+ runPackagedPostTool({
277
+ conversationId: conv,
278
+ workspacePaths: [ws],
279
+ toolCall: { name: 'write_file', args: { Path: path.join(ws, `edit-${idx}.js`), Content: '1' } }
280
+ });
281
+ const afterEdit = readHandoff(ws, conv);
282
+ assert.ok(afterEdit.lastEditAt > 0, `row 1.${idx}: write_file must set lastEditAt`);
283
+
284
+ const mapped = mapAgyPayloadToStatePersist({
285
+ conversationId: conv,
286
+ workspacePaths: [ws],
287
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
288
+ ...variant
289
+ });
290
+ assert.strictEqual(mapped.hook_event_name, 'PostToolUseFailure', `row 1.${idx}: blank top-level error must fall back to nested error`);
291
+ assert.strictEqual(mapped.exitCode, undefined, `row 1.${idx}: exitCode 0 must be withheld on explicit nested error`);
292
+
293
+ runPackagedPostTool({
294
+ conversationId: conv,
295
+ workspacePaths: [ws],
296
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
297
+ ...variant
298
+ });
299
+ const state = readHandoff(ws, conv);
300
+ assert.strictEqual(state.status, 'failed', `row 1.${idx}: blank top-level error + nonblank nested error + exitCode 0 must stay failed`);
301
+ assert.ok(!state.lastVerifyAt, `row 1.${idx}: must leave lastVerifyAt unset (verification stale)`);
302
+
303
+ const stopRes = runPackagedStop({
304
+ conversationId: conv,
305
+ workspacePaths: [ws],
306
+ continuationActive: false,
307
+ terminationReason: 'NO_TOOL_CALL'
308
+ });
309
+ assert.strictEqual(stopRes.decision, 'continue', `row 1.${idx}: packaged Stop must return continue`);
310
+ assert.ok(stopRes.reason.includes('pending tool failure'), `row 1.${idx}: Stop reason must cite pending tool failure`);
311
+ }
312
+
313
+ // Row 2: status: "queued" (and background: true) + recognized check + numeric zero -> normal credit (no bypass)
314
+ for (const [idx, extra] of [
315
+ { status: 'queued', exitCode: 0 },
316
+ { background: true, exitCode: 0 },
317
+ { toolResponse: { status: 'queued', exit_code: 0 } },
318
+ { toolResponse: { background: true, exitCode: 0 } },
319
+ { isBackground: true, exitCode: 0 }
320
+ ].entries()) {
321
+ const conv = `conv-516-b2-queued-verify-${idx}`;
322
+ runPackagedPostTool({
323
+ conversationId: conv,
324
+ workspacePaths: [ws],
325
+ toolCall: { name: 'write_file', args: { Path: path.join(ws, `q-${idx}.js`), Content: '1' } }
326
+ });
327
+ const afterEdit = readHandoff(ws, conv);
328
+ assert.ok(afterEdit.lastEditAt > 0);
329
+
330
+ const checkPayload = {
331
+ conversationId: conv,
332
+ workspacePaths: [ws],
333
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
334
+ ...extra
335
+ };
336
+ const mapped = mapAgyPayloadToStatePersist(checkPayload);
337
+ assert.ok(mapped !== null, `row 2.${idx}: generic queued/background metadata must not bypass state-persist`);
338
+
339
+ runPackagedPostTool(checkPayload);
340
+ const afterVerify = readHandoff(ws, conv);
341
+ assert.strictEqual(afterVerify.status, 'idle', `row 2.${idx}: recognized check with exitCode 0 must stay idle`);
342
+ assert.strictEqual(afterVerify.lastVerifyExitCode, 0, `row 2.${idx}: must record lastVerifyExitCode 0`);
343
+ assert.ok(afterVerify.lastVerifyAt >= afterEdit.lastEditAt, `row 2.${idx}: must advance lastVerifyAt normally`);
344
+
345
+ const stopRes = runPackagedStop({
346
+ conversationId: conv,
347
+ workspacePaths: [ws],
348
+ continuationActive: false,
349
+ terminationReason: 'NO_TOOL_CALL'
350
+ });
351
+ assert.deepStrictEqual(stopRes, { decision: 'allow' }, `row 2.${idx}: packaged Stop must allow after credited zero`);
352
+ }
353
+
354
+ // Row 3: status: "queued" (and background: true) on an in-workspace write_file -> edit persisted (no bypass)
355
+ for (const [idx, extra] of [
356
+ { status: 'queued' },
357
+ { background: true },
358
+ { toolResponse: { status: 'queued' } }
359
+ ].entries()) {
360
+ const conv = `conv-516-b2-queued-write-${idx}`;
361
+ const writePayload = {
362
+ conversationId: conv,
363
+ workspacePaths: [ws],
364
+ toolCall: { name: 'write_file', args: { Path: path.join(ws, `write-${idx}.js`), Content: 'export const x = 1;' } },
365
+ ...extra
366
+ };
367
+ const mapped = mapAgyPayloadToStatePersist(writePayload);
368
+ assert.ok(mapped !== null, `row 3.${idx}: write_file with generic metadata must not bypass state-persist`);
369
+
370
+ runPackagedPostTool(writePayload);
371
+ const afterWrite = readHandoff(ws, conv);
372
+ assert.ok(afterWrite.lastEditAt > 0, `row 3.${idx}: in-workspace write_file with ${JSON.stringify(extra)} must persist lastEditAt`);
373
+
374
+ const stopRes = runPackagedStop({
375
+ conversationId: conv,
376
+ workspacePaths: [ws],
377
+ continuationActive: false,
378
+ terminationReason: 'model_stop'
379
+ });
380
+ assert.strictEqual(stopRes.decision, 'continue', `row 3.${idx}: unverified persisted edit must make packaged Stop continue`);
381
+ }
382
+
383
+ // Row 4: text-only "Command exited with code 0." / "Tool is running as a background task" in stdout -> no credit, no bypass
384
+ for (const [idx, caseDef] of [
385
+ { cmd: 'npm test', extra: { toolResponse: { stdout: 'Command exited with code 0.' } } },
386
+ { cmd: 'npm test', extra: { output: 'Command exited with code 0.' } },
387
+ { cmd: 'npm test', extra: { toolResponse: { stdout: 'Tool is running as a background task' } } },
388
+ { cmd: 'npm test', extra: { output: 'Tool is running as a background task' } },
389
+ { cmd: 'node dev-server.js', extra: { toolResponse: { stdout: 'Tool is running as a background task' } } },
390
+ { cmd: 'node dev-server.js', extra: { output: 'Tool is running as a background task' } }
391
+ ].entries()) {
392
+ const conv = `conv-516-b2-text-only-${idx}`;
393
+ runPackagedPostTool({
394
+ conversationId: conv,
395
+ workspacePaths: [ws],
396
+ toolCall: { name: 'write_file', args: { Path: path.join(ws, `t-${idx}.js`), Content: '1' } }
397
+ });
398
+ const before = readHandoff(ws, conv);
399
+
400
+ const textPayload = {
401
+ conversationId: conv,
402
+ workspacePaths: [ws],
403
+ toolCall: { name: 'run_command', args: { CommandLine: caseDef.cmd, Cwd: ws } },
404
+ ...caseDef.extra
405
+ };
406
+ const mapped = mapAgyPayloadToStatePersist(textPayload);
407
+ assert.ok(mapped !== null, `row 4.${idx}: text-only lookalike must not bypass state-persist`);
408
+ assert.strictEqual(mapped.exitCode, undefined, `row 4.${idx}: text-only lookalike must not synthesize exitCode`);
409
+
410
+ runPackagedPostTool(textPayload);
411
+ const after = readHandoff(ws, conv);
412
+ assert.ok(!after.lastVerifyAt, `row 4.${idx}: text-only lookalike must not grant verification credit`);
413
+ if (caseDef.cmd === 'npm test') {
414
+ assert.strictEqual(after.lastEditAt, before.lastEditAt, `row 4.${idx}: recognized check with unknown text must preserve lastEditAt`);
415
+ }
416
+
417
+ const stopRes = runPackagedStop({
418
+ conversationId: conv,
419
+ workspacePaths: [ws],
420
+ continuationActive: false,
421
+ terminationReason: 'NO_TOOL_CALL'
422
+ });
423
+ assert.strictEqual(stopRes.decision, 'continue', `row 4.${idx}: packaged Stop must continue when no verification credit was earned`);
424
+ }
425
+
426
+ // Row 5: positive control - clean numeric zero on a recognized check -> credit + packaged Stop allow
427
+ {
428
+ const conv = 'conv-516-b2-positive-control';
429
+ runPackagedPostTool({
430
+ conversationId: conv,
431
+ workspacePaths: [ws],
432
+ toolCall: { name: 'write_file', args: { Path: path.join(ws, 'pos.js'), Content: '1' } }
433
+ });
434
+ const afterEdit = readHandoff(ws, conv);
435
+ assert.strictEqual(
436
+ runPackagedStop({
437
+ conversationId: conv,
438
+ workspacePaths: [ws],
439
+ continuationActive: false,
440
+ terminationReason: 'NO_TOOL_CALL'
441
+ }).decision,
442
+ 'continue',
443
+ 'row 5: packaged Stop must continue before verification'
444
+ );
445
+
446
+ runPackagedPostTool({
447
+ conversationId: conv,
448
+ workspacePaths: [ws],
449
+ toolCall: { name: 'run_command', args: { CommandLine: 'npm test', Cwd: ws } },
450
+ exitCode: 0
451
+ });
452
+ const afterVerify = readHandoff(ws, conv);
453
+ assert.strictEqual(afterVerify.status, 'idle');
454
+ assert.strictEqual(afterVerify.lastVerifyExitCode, 0);
455
+ assert.ok(afterVerify.lastVerifyAt >= afterEdit.lastEditAt, 'row 5: clean numeric zero must advance lastVerifyAt');
456
+
457
+ const stopAllow = runPackagedStop({
458
+ conversationId: conv,
459
+ workspacePaths: [ws],
460
+ continuationActive: false,
461
+ terminationReason: 'NO_TOOL_CALL'
462
+ });
463
+ assert.deepStrictEqual(stopAllow, { decision: 'allow' }, 'row 5: packaged Stop must allow after clean numeric zero');
464
+ }
465
+ }
466
+
467
+ console.log('AGY PostToolUse completion normalization (P516-B) verified.');
468
+ } finally {
469
+ if (originalStateHome === undefined) delete process.env.HARNESS_STATE_HOME;
470
+ else process.env.HARNESS_STATE_HOME = originalStateHome;
471
+ fs.rmSync(tempRoot, { recursive: true, force: true });
472
+ }