harness-everything 1.0.1 → 1.1.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 (31) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +14 -0
  4. package/ci/mechanism-394-ledger-match.test.js +219 -0
  5. package/ci/mechanism-496-claude-capture.test.js +342 -0
  6. package/ci/mechanism-496-codex-capture.test.js +508 -0
  7. package/ci/mechanism-496-local-error-cli-edges.test.js +234 -0
  8. package/ci/mechanism-496-local-error-cli.test.js +517 -0
  9. package/ci/mechanism-496-local-error-store.test.js +731 -0
  10. package/ci/mechanism-496-opencode-capture.test.js +483 -0
  11. package/ci/mechanism-496-review-fixes.test.js +278 -0
  12. package/hooks/scripts/codex-ledger-lesson.js +103 -27
  13. package/hooks/scripts/ledger-lesson.js +94 -23
  14. package/hooks/scripts/lib/ledger-match.js +39 -3
  15. package/hooks/scripts/lib/local-error-source.js +127 -0
  16. package/hooks/scripts/lib/local-errors.js +597 -0
  17. package/hooks/scripts/lib/observations.js +1 -1
  18. package/opencode-plugin/index.mjs +86 -1
  19. package/opencode-plugin/plugin.json +1 -1
  20. package/package.json +2 -1
  21. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  22. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  23. package/plugins/harness-everything/hooks/scripts/codex-ledger-lesson.js +103 -27
  24. package/plugins/harness-everything/hooks/scripts/ledger-lesson.js +94 -23
  25. package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +39 -3
  26. package/plugins/harness-everything/hooks/scripts/lib/local-error-source.js +127 -0
  27. package/plugins/harness-everything/hooks/scripts/lib/local-errors.js +597 -0
  28. package/plugins/harness-everything/hooks/scripts/lib/observations.js +1 -1
  29. package/plugins/harness-everything/plugin.json +1 -1
  30. package/sbom.cdx.json +7 -7
  31. package/scripts/errors-local.js +357 -0
@@ -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.1",
13
+ "version": "1.1.0",
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.1",
4
+ "version": "1.1.0",
5
5
  "author": {
6
6
  "name": "Miya Daniel"
7
7
  },
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [1.1.0](https://github.com/dyphn1/Harness-everything/compare/v1.0.1...v1.1.0) (2026-11-25)
6
+
7
+ ### Features
8
+
9
+ * **errors:** add the local error store and provisional lesson cli ([#496](https://github.com/dyphn1/Harness-everything/issues/496)) ([7c220a1](https://github.com/dyphn1/Harness-everything/commit/7c220a18d0eb5630e8a9c49fedeb67a97a9806f3))
10
+ * **hooks:** capture claude bash failures and deliver provisional lessons ([#496](https://github.com/dyphn1/Harness-everything/issues/496)) ([b6ba4bc](https://github.com/dyphn1/Harness-everything/commit/b6ba4bc5804d57ea420603ace51eabe8fa178092))
11
+ * **hooks:** capture codex and opencode shell failures and deliver provisional lessons ([#496](https://github.com/dyphn1/Harness-everything/issues/496)) ([5cddd27](https://github.com/dyphn1/Harness-everything/commit/5cddd272ae59caf9cfa6872076ed6646beabd372))
12
+ * **hooks:** share the ledger match validator and add a read-only repo match peek ([#496](https://github.com/dyphn1/Harness-everything/issues/496)) ([a1c6c9a](https://github.com/dyphn1/Harness-everything/commit/a1c6c9a905c6195e428897ce33011cb364ac443e)), closes [#518](https://github.com/dyphn1/Harness-everything/issues/518)
13
+
14
+ ### Bug Fixes
15
+
16
+ * **errors:** prefer newest provisional lessons and tighten the local error cli ([#496](https://github.com/dyphn1/Harness-everything/issues/496)) ([7bcc66d](https://github.com/dyphn1/Harness-everything/commit/7bcc66d3d127198e049a2a2115eac052e7662aaa))
17
+ * **errors:** redact full authorization values and expire local records on read ([#496](https://github.com/dyphn1/Harness-everything/issues/496)) ([0dfaae2](https://github.com/dyphn1/Harness-everything/commit/0dfaae299bb4ca6a29c3ecfcc207fd1341640951))
18
+
5
19
  ## [1.0.1](https://github.com/dyphn1/Harness-everything/compare/v1.0.0...v1.0.1) (2026-11-24)
6
20
 
7
21
  ### Bug Fixes
@@ -696,3 +696,222 @@ test('an unavailable dedupe directory is silent and never falls back', () => {
696
696
  fs.writeFileSync(blocker, 'not a directory');
697
697
  assert.equal(select(input({ stateDir: path.join(blocker, 'session') })), null);
698
698
  });
699
+
700
+ test('R-518 P2/P3: unspaced single-char middle pipeline members match and trailing unescaped redirect backslashes are rejected', () => {
701
+ const expected = { tool: 'shell', executable: 'git', subcommand: 'commit' };
702
+ const supported = [
703
+ 'x|y|git commit -m "A"',
704
+ 'a|b|c|git commit -m "A"',
705
+ 'x | y | git commit -m "A"',
706
+ 'x||y||git commit -m "A"',
707
+ 'git commit -m "A" > out\\\\',
708
+ 'git commit -m "A" > "out\\\\"',
709
+ "git commit -m \"A\" > 'out\\'",
710
+ 'git commit -m "A" > out\\ file.log'
711
+ ];
712
+ const unsupported = [
713
+ 'x|||git commit -m "A"',
714
+ 'git commit ||| echo done',
715
+ 'x| |git commit -m "A"',
716
+ 'git commit -m "A" > out\\',
717
+ 'git commit -m "A" > \\',
718
+ 'git commit -m "A" > out\\\\\\'
719
+ ];
720
+ for (const implementation of [matcher, packagedMatcher]) {
721
+ for (const command of supported) {
722
+ assert.deepEqual(implementation.normalizeGitCommitCommand(command), expected, command);
723
+ const result = implementation.matchLedgerLessons(input({
724
+ event: { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } }
725
+ }));
726
+ assert.deepEqual(result?.ids, ['E-0003'], command);
727
+ }
728
+ for (const command of unsupported) {
729
+ assert.equal(implementation.normalizeGitCommitCommand(command), null, command);
730
+ assert.equal(implementation.matchLedgerLessons(input({
731
+ event: { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } }
732
+ })), null, command);
733
+ }
734
+ }
735
+ });
736
+
737
+ test('exports validateMatch and read-only peekRepoMatches without taking claims or applying reminder caps', () => {
738
+ for (const implementation of [matcher, packagedMatcher]) {
739
+ assert.equal(typeof implementation.validateMatch, 'function', 'validateMatch is exported');
740
+ assert.deepEqual(implementation.validateMatch({
741
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }]
742
+ }), {
743
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }]
744
+ });
745
+ assert.throws(() => implementation.validateMatch({ invalidKey: [] }), /invalid match/);
746
+
747
+ assert.equal(typeof implementation.peekRepoMatches, 'function', 'peekRepoMatches is exported');
748
+
749
+ const freshState = stateDir('peek-no-claim');
750
+ const actionInput = input({ stateDir: freshState });
751
+ assert.deepEqual(implementation.peekRepoMatches(actionInput), ['E-0003'], 'first peek returns matching repo id');
752
+ assert.deepEqual(implementation.peekRepoMatches(actionInput), ['E-0003'], 'second peek still returns matching repo id');
753
+ assert.equal(fs.existsSync(freshState), false, 'peek does not create stateDir or write claim files');
754
+
755
+ const delivered = implementation.matchLedgerLessons(actionInput);
756
+ assert.deepEqual(delivered?.ids, ['E-0003'], 'matchLedgerLessons still delivers once after two peeks');
757
+ assert.equal(implementation.matchLedgerLessons(actionInput), null, 'duplicate delivery stays silent');
758
+ assert.deepEqual(implementation.peekRepoMatches(actionInput), ['E-0003'],
759
+ 'peek still reports repo match after delivery claim is exhausted');
760
+
761
+ assert.deepEqual(implementation.peekRepoMatches({
762
+ workspaceRoot: GENERATED_E3_ROOT,
763
+ event: {
764
+ phase: 'failure',
765
+ tool: 'shell',
766
+ command: 'git commit -m "Bad Subject"',
767
+ outcome: { failed: true, output: COMMITLINT_OUTPUT }
768
+ }
769
+ }), ['E-0003'], 'peek works for failure phase without sessionIdentity or stateDir');
770
+
771
+ for (const command of ['git status', 'echo "git commit"', '']) {
772
+ assert.deepEqual(implementation.peekRepoMatches({
773
+ workspaceRoot: GENERATED_E3_ROOT,
774
+ event: { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } }
775
+ }), [], `unknown command returns empty: ${command}`);
776
+ }
777
+ assert.deepEqual(implementation.peekRepoMatches(null), [], 'null input fails open to []');
778
+
779
+ const oversizedCue = E3_TEXT.replace(/(^## Cue\r?\n\r?\n)[\s\S]*?(\r?\n\r?\n## What happened)/m,
780
+ (_, start, end) => `${start}${'C'.repeat(1500)}${end}`);
781
+ const oversizedRoot = repoWorkspace('peek oversized repo', { recordText: oversizedCue });
782
+ assert.equal(implementation.matchLedgerLessons(input({ workspaceRoot: oversizedRoot })), null,
783
+ 'oversized repo excerpt is skipped by reminder cap in matchLedgerLessons');
784
+ assert.deepEqual(implementation.peekRepoMatches({
785
+ workspaceRoot: oversizedRoot,
786
+ event: { phase: 'action', tool: 'shell', command: 'git commit', outcome: { failed: 'unknown' } }
787
+ }), ['E-0003'], 'peek ignores reminder char cap and still returns repo match');
788
+
789
+ assert.deepEqual(implementation.peekRepoMatches({
790
+ workspaceRoot: workspace('peek no repo'),
791
+ event: { phase: 'action', tool: 'shell', command: 'git commit', outcome: { failed: 'unknown' } },
792
+ provisionalSource: localSource([PROVISIONAL_FIXTURE[0]])
793
+ }), [], 'peek is repo-only and ignores provisionalSource');
794
+ }
795
+ });
796
+
797
+ test('peekRepoMatches keeps every matching repo id across shared signatures while preserving delivery collapse and bounds', () => {
798
+ const syncEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => key !== 'HARNESS_SYSTEM_ONE_MODE'));
799
+ const buildSameSignatureRepo = (name, count) => {
800
+ const root = workspace(name);
801
+ const ledger = path.join(root, '.agents', 'harness-everything', 'errors');
802
+ for (let index = 1; index <= count; index += 1) {
803
+ const id = `E-${String(index).padStart(4, '0')}`;
804
+ const recordText = index === 1
805
+ ? E3_TEXT.replace(/^id:\s*E-0003$/m, 'id: E-0001')
806
+ : E3_TEXT
807
+ .replace(/^id:\s*E-0003$/m, `id: ${id}`)
808
+ .replace(/^## Lesson\r?\n\r?\n[\s\S]*?(?=\r?\n\r?\n## Evidence)/m,
809
+ `## Lesson\n\nSAME_SIGNATURE_SECOND_LESSON_SENTINEL_${id}`);
810
+ write(path.join(ledger, `${id}-commitlint-subject.md`), recordText);
811
+ }
812
+ const generated = spawnSync(process.execPath, [ERRORS_SYNC, '--root', root], {
813
+ cwd: ROOT,
814
+ env: syncEnv,
815
+ encoding: 'utf8'
816
+ });
817
+ assert.equal(generated.status, 0, generated.stderr);
818
+ return { root, ledger };
819
+ };
820
+
821
+ const pair = buildSameSignatureRepo('peek-same-sig-pair', 2);
822
+ const single = buildSameSignatureRepo('peek-same-sig-single', 1);
823
+ const pairIndexPath = path.join(pair.ledger, 'index.jsonl');
824
+ const pairRows = fs.readFileSync(pairIndexPath, 'utf8').trim().split('\n');
825
+
826
+ const reversedRoot = workspace('peek-same-sig-reversed');
827
+ const reversedLedger = path.join(reversedRoot, '.agents', 'harness-everything', 'errors');
828
+ for (const file of fs.readdirSync(pair.ledger)) {
829
+ if (file.endsWith('.md')) {
830
+ write(path.join(reversedLedger, file), fs.readFileSync(path.join(pair.ledger, file), 'utf8'));
831
+ }
832
+ }
833
+ write(path.join(reversedLedger, 'index.jsonl'), `${[...pairRows].reverse().join('\n')}\n`);
834
+
835
+ const duplicateIdRoot = workspace('peek-same-sig-dup-id');
836
+ const duplicateIdLedger = path.join(duplicateIdRoot, '.agents', 'harness-everything', 'errors');
837
+ for (const file of fs.readdirSync(pair.ledger)) {
838
+ if (file.endsWith('.md')) {
839
+ write(path.join(duplicateIdLedger, file), fs.readFileSync(path.join(pair.ledger, file), 'utf8'));
840
+ }
841
+ }
842
+ write(path.join(duplicateIdLedger, 'index.jsonl'), `${[pairRows[0], pairRows[0], pairRows[1]].join('\n')}\n`);
843
+
844
+ const atCap = buildSameSignatureRepo('peek-same-sig-cap-32', 32);
845
+ const overCap = buildSameSignatureRepo('peek-same-sig-over-33', 33);
846
+ const expected32 = Array.from({ length: 32 }, (_, idx) => `E-${String(idx + 1).padStart(4, '0')}`);
847
+
848
+ const actionEvent = { phase: 'action', tool: 'shell', command: 'git commit', outcome: { failed: 'unknown' } };
849
+ const failureEvent = {
850
+ phase: 'failure',
851
+ tool: 'shell',
852
+ command: 'git commit -m "Bad Subject"',
853
+ outcome: { failed: true, output: COMMITLINT_OUTPUT }
854
+ };
855
+
856
+ for (const implementation of [matcher, packagedMatcher]) {
857
+ assert.deepEqual(
858
+ implementation.peekRepoMatches({ workspaceRoot: pair.root, event: actionEvent }),
859
+ ['E-0001', 'E-0002'],
860
+ 'peek returns both ids for two same-signature repo records at action'
861
+ );
862
+ assert.deepEqual(
863
+ implementation.peekRepoMatches({ workspaceRoot: pair.root, event: failureEvent }),
864
+ ['E-0001', 'E-0002'],
865
+ 'peek returns both ids for two same-signature repo records at failure'
866
+ );
867
+ assert.deepEqual(
868
+ implementation.peekRepoMatches({ workspaceRoot: reversedRoot, event: actionEvent }),
869
+ ['E-0001', 'E-0002'],
870
+ 'peek keeps deterministic id order regardless of index order'
871
+ );
872
+ assert.deepEqual(
873
+ implementation.peekRepoMatches({ workspaceRoot: duplicateIdRoot, event: actionEvent }),
874
+ ['E-0001', 'E-0002'],
875
+ 'peek deduplicates repeated id rows'
876
+ );
877
+
878
+ const baselineDelivery = implementation.matchLedgerLessons(input({
879
+ workspaceRoot: single.root,
880
+ stateDir: stateDir('delivery-single'),
881
+ event: actionEvent
882
+ }));
883
+ const pairDelivery = implementation.matchLedgerLessons(input({
884
+ workspaceRoot: pair.root,
885
+ stateDir: stateDir('delivery-pair'),
886
+ event: actionEvent
887
+ }));
888
+ assert.deepEqual(pairDelivery?.ids, ['E-0001'], 'delivery still collapses same-signature records to one lesson');
889
+ assert.equal(pairDelivery?.text, baselineDelivery?.text, 'delivery text for same-signature pair is unchanged');
890
+ assert.ok(!pairDelivery?.text.includes('SAME_SIGNATURE_SECOND_LESSON_SENTINEL'),
891
+ 'second same-signature lesson is not delivered');
892
+
893
+ const pairFailureDelivery = implementation.matchLedgerLessons(input({
894
+ workspaceRoot: pair.root,
895
+ stateDir: stateDir('delivery-pair-failure'),
896
+ event: failureEvent
897
+ }));
898
+ const baselineFailureDelivery = implementation.matchLedgerLessons(input({
899
+ workspaceRoot: single.root,
900
+ stateDir: stateDir('delivery-single-failure'),
901
+ event: failureEvent
902
+ }));
903
+ assert.deepEqual(pairFailureDelivery?.ids, ['E-0001'], 'failure delivery still collapses same-signature records');
904
+ assert.equal(pairFailureDelivery?.text, baselineFailureDelivery?.text, 'failure delivery text is unchanged');
905
+
906
+ assert.deepEqual(
907
+ implementation.peekRepoMatches({ workspaceRoot: atCap.root, event: actionEvent }),
908
+ expected32,
909
+ 'peek returns all 32 unique ids up to the candidate bound'
910
+ );
911
+ assert.deepEqual(
912
+ implementation.peekRepoMatches({ workspaceRoot: overCap.root, event: actionEvent }),
913
+ [],
914
+ 'peek enforces the 32-candidate bound by failing open above cap'
915
+ );
916
+ }
917
+ });
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const assert = require('node:assert/strict');
5
+ const { spawnSync } = require('node:child_process');
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
9
+ const test = require('node:test');
10
+
11
+ const ROOT = path.resolve(__dirname, '..');
12
+ const CANONICAL_ADAPTER = path.join(ROOT, 'hooks/scripts/ledger-lesson.js');
13
+ const PACKAGED_ADAPTER = path.join(ROOT, 'plugins/harness-everything/hooks/scripts/ledger-lesson.js');
14
+ const ERRORS_SYNC = path.join(ROOT, 'scripts/errors-sync.js');
15
+ const ERRORS_LOCAL = path.join(ROOT, 'scripts/errors-local.js');
16
+ const LEDGER = path.join(ROOT, '.agents/harness-everything/errors');
17
+ const E3_FILE = fs.readdirSync(LEDGER).find(file => /^E-0003-[a-z0-9-]+\.md$/.test(file));
18
+ const COMMITLINT_OUTPUT = fs.readFileSync(
19
+ path.join(__dirname, 'fixtures/394-ledger-match/commitlint-subject-case.txt'),
20
+ 'utf8'
21
+ );
22
+
23
+ // E-0011: canonicalize temp root with realpathSync.native to expand Windows 8.3 short paths.
24
+ const TMP = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), '496-claude-capture-')));
25
+ let serial = 0;
26
+
27
+ test.after(() => fs.rmSync(TMP, { recursive: true, force: true }));
28
+
29
+ function isolatedEnv(caseDir, overrides = {}) {
30
+ const homeDir = path.join(caseDir, 'home');
31
+ const stateHome = path.join(caseDir, 'state-home');
32
+ const obsDir = path.join(caseDir, 'observations');
33
+ fs.mkdirSync(homeDir, { recursive: true });
34
+ fs.mkdirSync(stateHome, { recursive: true });
35
+ const env = {
36
+ ...process.env,
37
+ HOME: homeDir,
38
+ USERPROFILE: homeDir,
39
+ HARNESS_STATE_HOME: stateHome,
40
+ HARNESS_OBSERVATIONS_DIR: obsDir,
41
+ ...overrides
42
+ };
43
+ delete env.HARNESS_SYSTEM_ONE_MODE;
44
+ delete env.CLAUDE_PROJECT_DIR;
45
+ delete env.CODEX_PROJECT_DIR;
46
+ delete env.HARNESS_WORKSPACE_ROOT;
47
+ delete env.FABLE_WORKSPACE_ROOT;
48
+ return { env, homeDir, stateHome, obsDir };
49
+ }
50
+
51
+ function newCaseWorkspace(name, { withLedger = true, envOverrides = {} } = {}) {
52
+ const caseDir = path.join(TMP, `${name}-${++serial}`);
53
+ const workspaceRoot = path.join(caseDir, 'workspace');
54
+ fs.mkdirSync(workspaceRoot, { recursive: true });
55
+ if (withLedger) {
56
+ const ledgerDir = path.join(workspaceRoot, '.agents/harness-everything/errors');
57
+ fs.mkdirSync(ledgerDir, { recursive: true });
58
+ fs.copyFileSync(path.join(LEDGER, E3_FILE), path.join(ledgerDir, E3_FILE));
59
+ const synced = spawnSync(process.execPath, [ERRORS_SYNC, '--root', workspaceRoot], {
60
+ cwd: ROOT,
61
+ encoding: 'utf8'
62
+ });
63
+ assert.equal(synced.status, 0, synced.stderr || 'errors-sync should succeed');
64
+ }
65
+ const envState = isolatedEnv(caseDir, envOverrides);
66
+ return { caseDir, workspaceRoot, ...envState };
67
+ }
68
+
69
+ function runHook(adapterPath, payload, env) {
70
+ return spawnSync(process.execPath, [adapterPath], {
71
+ cwd: ROOT,
72
+ env,
73
+ input: typeof payload === 'string' ? payload : JSON.stringify(payload),
74
+ encoding: 'utf8'
75
+ });
76
+ }
77
+
78
+ function runCli(args, cwd, env) {
79
+ return spawnSync(process.execPath, [ERRORS_LOCAL, ...args], {
80
+ cwd,
81
+ env,
82
+ encoding: 'utf8'
83
+ });
84
+ }
85
+
86
+ function listRecords(workspaceRoot, env, extraArgs = []) {
87
+ const res = runCli(['list', '--json', ...extraArgs], workspaceRoot, env);
88
+ assert.equal(res.status, 0, res.stderr || 'errors-local list should exit 0');
89
+ return JSON.parse(res.stdout);
90
+ }
91
+
92
+ function failurePayload(workspaceRoot, overrides = {}) {
93
+ return {
94
+ hook_event_name: 'PostToolUseFailure',
95
+ tool_name: 'Bash',
96
+ session_id: `sess-${serial}`,
97
+ tool_use_id: `toolu_${serial}_1`,
98
+ cwd: workspaceRoot,
99
+ tool_input: { command: 'git commit -m "Bad Subject"' },
100
+ error: COMMITLINT_OUTPUT,
101
+ ...overrides
102
+ };
103
+ }
104
+
105
+ function preToolPayload(workspaceRoot, overrides = {}) {
106
+ return {
107
+ hook_event_name: 'PreToolUse',
108
+ tool_name: 'Bash',
109
+ session_id: `sess-${serial}`,
110
+ tool_use_id: `toolu_${serial}_pre`,
111
+ cwd: workspaceRoot,
112
+ tool_input: { command: 'npm test' },
113
+ ...overrides
114
+ };
115
+ }
116
+
117
+ function runEndToEndA(adapterPath, label) {
118
+ const ctx = newCaseWorkspace(`e2e-a-${label}`);
119
+ const secretPath = path.join(ctx.homeDir, 'private-project', 'secret.txt');
120
+ const errorWithHome = `${COMMITLINT_OUTPUT}\nsee ${secretPath}\n`;
121
+
122
+ const hookRes = runHook(
123
+ adapterPath,
124
+ failurePayload(ctx.workspaceRoot, {
125
+ session_id: `e2e-a-session-${label}`,
126
+ tool_use_id: `toolu_e2e_a_${label}`,
127
+ exit_code: 1,
128
+ error: errorWithHome
129
+ }),
130
+ ctx.env
131
+ );
132
+
133
+ assert.equal(hookRes.status, 0, hookRes.stderr || 'failure hook exits 0');
134
+ assert.equal(hookRes.stderr, '', 'failure hook stays silent on stderr');
135
+ const out = JSON.parse(hookRes.stdout);
136
+ assert.equal(out.hookSpecificOutput.hookEventName, 'PostToolUseFailure');
137
+ assert.match(out.hookSpecificOutput.additionalContext, /Check the subject line against both rules/);
138
+
139
+ const records = listRecords(ctx.workspaceRoot, ctx.env);
140
+ assert.equal(records.length, 1, 'exactly one occurrence row captured');
141
+ const row = records[0];
142
+ assert.equal(row.kind, 'occurrence');
143
+ assert.equal(row.host, 'claude');
144
+ assert.equal(row.destination, 'unknown');
145
+ assert.equal(row.commandClass, 'git');
146
+ assert.equal(row.exitCode, 1);
147
+ assert.ok(row.sessionKey && !row.sessionKey.includes(`e2e-a-session-${label}`), 'sessionKey is opaque');
148
+ assert.ok(row.toolUseId && !row.toolUseId.includes(`toolu_e2e_a_${label}`), 'toolUseId is opaque');
149
+ assert.ok(row.outputExcerpt.includes('<home>'), 'home path is redacted in outputExcerpt');
150
+ assert.ok(!row.outputExcerpt.includes(ctx.homeDir), 'raw home path is not stored in outputExcerpt');
151
+ assert.ok(row.matchedLedgerIds.includes('E-0003'), `matchedLedgerIds should include E-0003, got ${JSON.stringify(row.matchedLedgerIds)}`);
152
+ }
153
+
154
+ function runEndToEndB(adapterPath, label) {
155
+ const ctx = newCaseWorkspace(`e2e-b-${label}`, { withLedger: false });
156
+ const lessonText = 'Run npm run build before npm test in this project';
157
+
158
+ const addRes = runCli(
159
+ [
160
+ 'add',
161
+ '--executable', 'npm',
162
+ '--subcommand', 'test',
163
+ '--lesson', lessonText,
164
+ '--destination', 'project'
165
+ ],
166
+ ctx.workspaceRoot,
167
+ ctx.env
168
+ );
169
+ assert.equal(addRes.status, 0, addRes.stderr || 'errors-local add exits 0');
170
+
171
+ const hookRes = runHook(
172
+ adapterPath,
173
+ preToolPayload(ctx.workspaceRoot, {
174
+ session_id: `e2e-b-session-${label}`,
175
+ tool_input: { command: 'npm test' }
176
+ }),
177
+ ctx.env
178
+ );
179
+ assert.equal(hookRes.status, 0, hookRes.stderr || 'PreToolUse hook exits 0');
180
+ assert.equal(hookRes.stderr, '', 'PreToolUse hook stays silent on stderr');
181
+ assert.ok(hookRes.stdout.trim(), 'PreToolUse hook emits provisional lesson context');
182
+ const out = JSON.parse(hookRes.stdout);
183
+ assert.equal(out.hookSpecificOutput.hookEventName, 'PreToolUse');
184
+ const text = out.hookSpecificOutput.additionalContext;
185
+ assert.ok(text.includes(lessonText), 'additionalContext contains provisional lesson text');
186
+ assert.match(text, /provisional/i, 'additionalContext labels lesson as provisional');
187
+ assert.doesNotMatch(text, /\b\d+\s*(?:times?|occurrences?|count|failures?)\b/i, 'no counts injected in lesson text');
188
+ }
189
+
190
+ test('Row 1 (End-to-end A): PostToolUseFailure Bash captures one redacted occurrence with matchedLedgerIds', () => {
191
+ runEndToEndA(CANONICAL_ADAPTER, 'canonical');
192
+ });
193
+
194
+ test('Row 2 (End-to-end B): CLI-added provisional lesson is delivered on next PreToolUse Bash without counts', () => {
195
+ runEndToEndB(CANONICAL_ADAPTER, 'canonical');
196
+ });
197
+
198
+ test('Row 3 & Row 6: capture is silent and unwritable store leaves lesson stdout and exit 0 unchanged', () => {
199
+ const normalCtx = newCaseWorkspace('silent-normal');
200
+ const blockedCtx = newCaseWorkspace('silent-unwritable');
201
+ // Create a regular file at HARNESS_OBSERVATIONS_DIR so store writes fail on all OSes (POSIX + Windows).
202
+ fs.writeFileSync(blockedCtx.obsDir, 'not-a-directory', 'utf8');
203
+
204
+ const normalRes = runHook(
205
+ CANONICAL_ADAPTER,
206
+ failurePayload(normalCtx.workspaceRoot, {
207
+ session_id: 'silent-session',
208
+ tool_use_id: 'toolu_silent_1'
209
+ }),
210
+ normalCtx.env
211
+ );
212
+ const blockedRes = runHook(
213
+ CANONICAL_ADAPTER,
214
+ failurePayload(blockedCtx.workspaceRoot, {
215
+ session_id: 'silent-session',
216
+ tool_use_id: 'toolu_silent_1'
217
+ }),
218
+ blockedCtx.env
219
+ );
220
+
221
+ assert.equal(normalRes.status, 0);
222
+ assert.equal(blockedRes.status, 0);
223
+ assert.equal(normalRes.stderr, '');
224
+ assert.equal(blockedRes.stderr, '');
225
+ assert.ok(normalRes.stdout.trim(), 'lesson output is emitted in normal case');
226
+ assert.equal(normalRes.stdout, blockedRes.stdout, 'stdout with capture equals stdout when store is unwritable');
227
+
228
+ // Positive control: normal case did capture a row, while blocked case could not.
229
+ assert.equal(listRecords(normalCtx.workspaceRoot, normalCtx.env).length, 1);
230
+ assert.equal(listRecords(blockedCtx.workspaceRoot, blockedCtx.env).length, 0);
231
+ });
232
+
233
+ test('Row 4: same tool_use_id is idempotent; different tool_use_id records second row with matchedLedgerIds even when delivery is silent', () => {
234
+ const ctx = newCaseWorkspace('idempotency');
235
+ const sessionId = 'idem-session';
236
+
237
+ // First failure: delivers lesson AND captures occurrence.
238
+ const first = runHook(
239
+ CANONICAL_ADAPTER,
240
+ failurePayload(ctx.workspaceRoot, {
241
+ session_id: sessionId,
242
+ tool_use_id: 'toolu_same'
243
+ }),
244
+ ctx.env
245
+ );
246
+ assert.equal(first.status, 0);
247
+ assert.ok(first.stdout.trim(), 'first failure delivers lesson');
248
+
249
+ // Duplicate with same tool_use_id: delivery is silent, store stays at 1 row.
250
+ const dup = runHook(
251
+ CANONICAL_ADAPTER,
252
+ failurePayload(ctx.workspaceRoot, {
253
+ session_id: sessionId,
254
+ tool_use_id: 'toolu_same'
255
+ }),
256
+ ctx.env
257
+ );
258
+ assert.equal(dup.status, 0);
259
+ assert.equal(dup.stdout, '', 'second delivery in same session is silent');
260
+ assert.equal(dup.stderr, '');
261
+
262
+ const afterDup = listRecords(ctx.workspaceRoot, ctx.env);
263
+ assert.equal(afterDup.length, 1, 'same tool_use_id is idempotent (1 row)');
264
+
265
+ // Second failure with different tool_use_id: delivery is silent, but a 2nd row is captured with matchedLedgerIds.
266
+ const second = runHook(
267
+ CANONICAL_ADAPTER,
268
+ failurePayload(ctx.workspaceRoot, {
269
+ session_id: sessionId,
270
+ tool_use_id: 'toolu_different'
271
+ }),
272
+ ctx.env
273
+ );
274
+ assert.equal(second.status, 0);
275
+ assert.equal(second.stdout, '', 'second distinct failure still has silent delivery');
276
+ assert.equal(second.stderr, '');
277
+
278
+ const afterSecond = listRecords(ctx.workspaceRoot, ctx.env);
279
+ assert.equal(afterSecond.length, 2, 'different tool_use_id creates a second row');
280
+ assert.equal(afterSecond[0].exitCode, null, 'nullable exitCode stays null when payload has no integer exit code');
281
+ assert.equal(afterSecond[1].exitCode, null);
282
+ assert.ok(afterSecond[0].matchedLedgerIds.includes('E-0003'));
283
+ assert.ok(afterSecond[1].matchedLedgerIds.includes('E-0003'), 'second silent failure still records matchedLedgerIds');
284
+ });
285
+
286
+ test('Row 5: PreToolUse, non-Bash PostToolUseFailure, and relative cwd do not capture rows', () => {
287
+ const ctx = newCaseWorkspace('no-capture-controls');
288
+
289
+ const preRes = runHook(
290
+ CANONICAL_ADAPTER,
291
+ preToolPayload(ctx.workspaceRoot, {
292
+ session_id: 'ctrl-sess',
293
+ tool_input: { command: 'git commit -m "Bad Subject"' }
294
+ }),
295
+ ctx.env
296
+ );
297
+ assert.equal(preRes.status, 0);
298
+ assert.ok(preRes.stdout.trim(), 'PreToolUse still delivers repo lesson');
299
+
300
+ const nonBashFail = runHook(
301
+ CANONICAL_ADAPTER,
302
+ failurePayload(ctx.workspaceRoot, {
303
+ session_id: 'ctrl-sess',
304
+ tool_name: 'Write',
305
+ tool_use_id: 'toolu_write_fail'
306
+ }),
307
+ ctx.env
308
+ );
309
+ assert.equal(nonBashFail.status, 0);
310
+ assert.equal(nonBashFail.stdout, '');
311
+
312
+ const relativeCwdFail = runHook(
313
+ CANONICAL_ADAPTER,
314
+ failurePayload('.', {
315
+ session_id: 'ctrl-sess',
316
+ tool_use_id: 'toolu_rel_cwd'
317
+ }),
318
+ ctx.env
319
+ );
320
+ assert.equal(relativeCwdFail.status, 0);
321
+ assert.equal(relativeCwdFail.stdout, '');
322
+
323
+ assert.equal(listRecords(ctx.workspaceRoot, ctx.env).length, 0, 'none of the negative controls created an occurrence row');
324
+
325
+ // Positive control in the same workspace confirms the oracle reaches the store.
326
+ const posRes = runHook(
327
+ CANONICAL_ADAPTER,
328
+ failurePayload(ctx.workspaceRoot, {
329
+ session_id: 'ctrl-sess',
330
+ tool_use_id: 'toolu_pos_ctrl'
331
+ }),
332
+ ctx.env
333
+ );
334
+ assert.equal(posRes.status, 0);
335
+ assert.equal(listRecords(ctx.workspaceRoot, ctx.env).length, 1, 'positive control captures exactly one row');
336
+ });
337
+
338
+ test('Row 7: packaged copy passes End-to-end A and End-to-end B', () => {
339
+ assert.ok(fs.existsSync(PACKAGED_ADAPTER), 'packaged ledger-lesson.js exists');
340
+ runEndToEndA(PACKAGED_ADAPTER, 'packaged');
341
+ runEndToEndB(PACKAGED_ADAPTER, 'packaged');
342
+ });