harness-reflex 0.1.0 → 0.3.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 (121) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +103 -23
  3. package/USER_GUIDE.md +121 -43
  4. package/dist/adapters/agy.js +1 -1
  5. package/dist/adapters/agy.js.map +1 -1
  6. package/dist/adapters/codex.d.ts +133 -4
  7. package/dist/adapters/codex.js +325 -2
  8. package/dist/adapters/codex.js.map +1 -1
  9. package/dist/backend/defaults.d.ts +31 -0
  10. package/dist/backend/defaults.js +32 -0
  11. package/dist/backend/defaults.js.map +1 -0
  12. package/dist/backend/jev.js +6 -5
  13. package/dist/backend/jev.js.map +1 -1
  14. package/dist/backend/mock.d.ts +12 -1
  15. package/dist/backend/mock.js +34 -0
  16. package/dist/backend/mock.js.map +1 -1
  17. package/dist/backend/simple-jev.js +5 -4
  18. package/dist/backend/simple-jev.js.map +1 -1
  19. package/dist/backend/types.d.ts +34 -0
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/cli/index.js +5 -3
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/core/closing.d.ts +90 -0
  24. package/dist/core/closing.js +111 -0
  25. package/dist/core/closing.js.map +1 -0
  26. package/dist/core/evidence.d.ts +119 -0
  27. package/dist/core/evidence.js +209 -0
  28. package/dist/core/evidence.js.map +1 -0
  29. package/dist/core/judge.d.ts +221 -0
  30. package/dist/core/judge.js +251 -0
  31. package/dist/core/judge.js.map +1 -0
  32. package/dist/core/orchestrate-closing.d.ts +237 -0
  33. package/dist/core/orchestrate-closing.js +250 -0
  34. package/dist/core/orchestrate-closing.js.map +1 -0
  35. package/dist/core/orchestrate-correction.d.ts +209 -0
  36. package/dist/core/orchestrate-correction.js +141 -0
  37. package/dist/core/orchestrate-correction.js.map +1 -0
  38. package/dist/core/orchestrate-host.d.ts +225 -0
  39. package/dist/core/orchestrate-host.js +80 -0
  40. package/dist/core/orchestrate-host.js.map +1 -0
  41. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  42. package/dist/core/orchestrate-stagnation.js +270 -0
  43. package/dist/core/orchestrate-stagnation.js.map +1 -0
  44. package/dist/core/orchestrate.d.ts +357 -0
  45. package/dist/core/orchestrate.js +418 -0
  46. package/dist/core/orchestrate.js.map +1 -0
  47. package/dist/core/policy.d.ts +122 -0
  48. package/dist/core/policy.js +102 -0
  49. package/dist/core/policy.js.map +1 -0
  50. package/dist/core/prune-plan.d.ts +141 -0
  51. package/dist/core/prune-plan.js +390 -0
  52. package/dist/core/prune-plan.js.map +1 -0
  53. package/dist/core/score.d.ts +2 -2
  54. package/dist/core/score.js.map +1 -1
  55. package/dist/core/text.d.ts +36 -0
  56. package/dist/core/text.js +66 -0
  57. package/dist/core/text.js.map +1 -0
  58. package/dist/hook/cli.d.ts +9 -0
  59. package/dist/hook/cli.js +52 -0
  60. package/dist/hook/cli.js.map +1 -0
  61. package/dist/hook/contract.d.ts +125 -0
  62. package/dist/hook/contract.js +159 -0
  63. package/dist/hook/contract.js.map +1 -0
  64. package/dist/hook/decision.d.ts +97 -0
  65. package/dist/hook/decision.js +955 -0
  66. package/dist/hook/decision.js.map +1 -0
  67. package/dist/hook/memory-store.d.ts +81 -0
  68. package/dist/hook/memory-store.js +157 -0
  69. package/dist/hook/memory-store.js.map +1 -0
  70. package/dist/hook/payload.d.ts +55 -0
  71. package/dist/hook/payload.js +129 -0
  72. package/dist/hook/payload.js.map +1 -0
  73. package/dist/hook/run.d.ts +48 -0
  74. package/dist/hook/run.js +218 -0
  75. package/dist/hook/run.js.map +1 -0
  76. package/dist/hook/store-port.d.ts +72 -0
  77. package/dist/hook/store-port.js +2 -0
  78. package/dist/hook/store-port.js.map +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +1 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/ports/audit.d.ts +18 -0
  83. package/dist/ports/audit.js +11 -0
  84. package/dist/ports/audit.js.map +1 -0
  85. package/dist/ports/clock.d.ts +14 -0
  86. package/dist/ports/clock.js +11 -0
  87. package/dist/ports/clock.js.map +1 -0
  88. package/dist/ports/decision.d.ts +75 -0
  89. package/dist/ports/decision.js +2 -0
  90. package/dist/ports/decision.js.map +1 -0
  91. package/dist/ports/index.d.ts +14 -0
  92. package/dist/ports/index.js +2 -0
  93. package/dist/ports/index.js.map +1 -0
  94. package/dist/ports/log.d.ts +22 -0
  95. package/dist/ports/log.js +12 -0
  96. package/dist/ports/log.js.map +1 -0
  97. package/dist/ports/state.d.ts +46 -0
  98. package/dist/ports/state.js +13 -0
  99. package/dist/ports/state.js.map +1 -0
  100. package/dist/state/clock.d.ts +40 -0
  101. package/dist/state/clock.js +43 -0
  102. package/dist/state/clock.js.map +1 -0
  103. package/dist/state/file-store.d.ts +340 -0
  104. package/dist/state/file-store.js +849 -0
  105. package/dist/state/file-store.js.map +1 -0
  106. package/dist/state/paths.d.ts +41 -0
  107. package/dist/state/paths.js +73 -0
  108. package/dist/state/paths.js.map +1 -0
  109. package/docs/USER_GUIDE.en.md +79 -36
  110. package/docs/claude-code.md +281 -0
  111. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  112. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  113. package/docs/dsh-plugin.md +54 -54
  114. package/docs/release-checklist-v0.1.0.md +32 -21
  115. package/docs/release-handbook-porting-notes.md +11 -11
  116. package/docs/release-handbook.md +55 -30
  117. package/docs/release-notes-v0.1.0.md +27 -14
  118. package/docs/release-notes-v0.3.0.md +152 -0
  119. package/docs/research/claude-code-harness.md +607 -0
  120. package/docs/research/pi-harness.md +621 -0
  121. package/package.json +16 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payload.js","sourceRoot":"","sources":["../../src/hook/payload.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAOH,uCAAuC;AACvC,SAAS,GAAG,CAAC,KAAc;IACzB,OAA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C,GAAG,CAAC,CAAC,CAAC;QAChC,IAAI,KAAK;YAAE,UAAU,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrC,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/**\n * The payload normalizer: the one place a host's stdin vocabulary is mapped onto\n * the fields `HookDecision` reads.\n *\n * Every host speaks `{session_id, tool_name, tool_input, tool_use_id,\n * tool_response}`, which is already the decision's vocabulary, so this\n * function's real job is the handful of places the hosts differ:\n *\n * 1. **Subagent identity.** Claude's `agent_id` is what the closing decision\n * keys on; a host may spell it `agent_id` or `subagent_id`, so both fold into\n * `agent_id` with the explicit one winning.\n * 2. **The event name.** A host may repeat which event it fired inside the\n * payload (`hook_event_name`); keeping it means an audit line names the event\n * the host actually fired rather than only our subcommand spelling.\n * 3. **The tool call id.** Kimi names a call `tool_call_id` where Claude says\n * `tool_use_id`. Both fold onto `tool_use_id`, because that field is the\n * PreToolUse dedupe key: without it two *different* calls of the same command\n * would look like a replay and the stagnation count would never advance.\n * 4. **The tool output.** Kimi's PostToolUse carries the text as a `tool_output`\n * string (the host truncates it to 2000 characters); Claude carries\n * `tool_response`. When only the Kimi spelling is present it is forwarded\n * under `tool_response`, which {@link toolResponseText} reads as a plain\n * string. That is what lets the ledger record a prune candidate at all; Kimi\n * treats PostToolUse as observation-only, so the replacement still does not\n * reach the model (documented in the package README).\n * 5. **Host-only context** (`turn_id`, `cwd`, `model`, `permission_mode`,\n * `transcript_path`, `prompt`, `client_type`, `session_title`) is passed\n * through untouched. The decision ignores it, but dropping it would make the\n * audit ledger less useful than the host it describes. `turn_id` deliberately\n * does *not* reach the decision: the decision counts turns from its own\n * ledger, so a host counter there would double-count.\n *\n * `argv` is never consulted. Codex does not forward handler `args` (measured: a\n * handler declared with `args: [\"session-start\"]` runs with `argv = []`), so\n * trusting it would silently lose the event; the payload is the authority.\n *\n * The function is deliberately **total and additive**: it never throws and never\n * invents a field, so applying it to a payload that is already in the decision's\n * vocabulary is a no-op. That is what lets {@link runHook} run it for every host\n * without changing any existing behavior — and why the Claude Code fixtures keep\n * asserting byte-identical output after it was introduced.\n *\n * @module hook/payload\n */\n\n/** The fields a normalized payload may carry, in the decision's vocabulary. */\nexport interface NormalizedHookPayload extends Record<string, unknown> {\n session_id?: string;\n}\n\n/** Read one non-empty string field. */\nfunction str(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/** Read one plain-object field, rejecting arrays and null. */\nfunction obj(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** The extra host context worth keeping for the audit ledger. */\nconst PASS_THROUGH_FIELDS = [\n 'turn_id',\n 'cwd',\n 'model',\n 'permission_mode',\n 'transcript_path',\n 'prompt',\n 'hook_event_name',\n 'client_type',\n 'session_title'\n] as const;\n\n/**\n * Convert a host's hook payload into the shape `HookDecision` reads.\n * @param payload - the raw object the host wrote to stdin.\n * @returns the normalized payload; `session_id` is copied only when present, so\n * the caller keeps its own fail-open decision for a missing session.\n */\nexport function normalizeHookPayload(payload: Record<string, unknown>): NormalizedHookPayload {\n const normalized: NormalizedHookPayload = {};\n\n const sessionId = str(payload.session_id);\n if (sessionId) normalized.session_id = sessionId;\n\n const toolName = str(payload.tool_name);\n if (toolName) normalized.tool_name = toolName;\n\n const toolInput = obj(payload.tool_input);\n if (toolInput) normalized.tool_input = toolInput;\n\n // A host may name the call `tool_call_id`; fold it onto the dedupe key field.\n const toolUseId = str(payload.tool_use_id) ?? str(payload.tool_call_id);\n if (toolUseId) normalized.tool_use_id = toolUseId;\n\n // The result arrives either as an object (Claude) or as plain text under\n // another name (Kimi's `tool_output`); the decision reads both spellings.\n if (payload.tool_response !== undefined) {\n normalized.tool_response = payload.tool_response;\n } else {\n const toolOutput = str(payload.tool_output);\n if (toolOutput) normalized.tool_response = toolOutput;\n }\n\n // Subagent identity, under either spelling, folded to Claude's field name.\n const agentId = str(payload.agent_id) ?? str(payload.subagent_id);\n if (agentId) normalized.agent_id = agentId;\n\n // A Stop retry guard must survive: without it a blocking Stop hook is retried\n // A Stop retry guard must survive: without it a blocking Stop hook is retried\n // until the host's own cap, which the Codex probe measured as unbounded.\n if (payload.stop_hook_active !== undefined) normalized.stop_hook_active = payload.stop_hook_active;\n const lastAssistant = str(payload.last_assistant_message);\n if (lastAssistant) normalized.last_assistant_message = lastAssistant;\n // A failure payload may name the error; accept the spelling without\n // overwriting a field the host already set.\n const error = str(payload.error);\n if (error) normalized.error = error;\n\n const source = str(payload.source);\n if (source) normalized.source = source;\n const reason = str(payload.reason);\n if (reason) normalized.reason = reason;\n\n // Pass the host-only context through rather than dropping it.\n for (const key of PASS_THROUGH_FIELDS) {\n const value = str(payload[key]);\n if (value) normalized[key] = value;\n }\n\n return normalized;\n}\n"]}
@@ -0,0 +1,48 @@
1
+ import { type HookClock } from '../state/clock.js';
2
+ import { FileStateStore } from '../state/file-store.js';
3
+ import { type HookOutput } from './contract.js';
4
+ import { type HookConfig, type HookModeMap } from './decision.js';
5
+ import type { DecisionBackend } from '../backend/types.js';
6
+ export { DEFAULT_CAPABILITY_MODES, DEFAULT_HOOK_CONFIG, dedupeKeyFor, resolveHookModes, type HookCapability, type HookConfig, type HookModeMap } from './decision.js';
7
+ export { MemoryStateStore } from './memory-store.js';
8
+ export type { HookStorePort } from './store-port.js';
9
+ export declare const MAX_STDIN_BYTES: number;
10
+ export interface HookStdin {
11
+ text: string;
12
+ overflow: boolean;
13
+ }
14
+ /** The result of one invocation, before the CLI serializes it. */
15
+ export interface HookRunResult {
16
+ /** The stdout object; `null` means "write nothing" (unsupported platform). */
17
+ output: HookOutput | null;
18
+ /** Process exit code; non-zero means "abandoned", which every host fails open. */
19
+ code: number;
20
+ /** Machine reason for stderr/audit; never part of stdout. */
21
+ error?: string;
22
+ }
23
+ /** Injectable seams, used by the fixtures and by the CLI. */
24
+ export declare function readStdinCapped(stream: NodeJS.ReadableStream, limit?: number): Promise<HookStdin>;
25
+ /** A stable JSON rendering so equal objects produce equal input digests. */
26
+ export interface HookRunResult {
27
+ /** The stdout object; `null` means "write nothing" (unsupported platform). */
28
+ output: HookOutput | null;
29
+ /** Process exit code; non-zero means "abandoned", which every host fails open. */
30
+ code: number;
31
+ /** Machine reason for stderr/audit; never part of stdout. */
32
+ error?: string;
33
+ }
34
+ /** Injectable seams, used by the fixtures and by the CLI. */
35
+ export interface HookRunOptions {
36
+ env?: NodeJS.ProcessEnv;
37
+ platform?: NodeJS.Platform;
38
+ backend?: DecisionBackend;
39
+ store?: FileStateStore;
40
+ clock?: HookClock;
41
+ config?: Partial<HookConfig>;
42
+ /** Explicit per-capability modes; when omitted, they are resolved from `env`. */
43
+ modes?: Partial<HookModeMap>;
44
+ readStdin?: () => Promise<HookStdin>;
45
+ stderr?: (message: string) => void;
46
+ }
47
+ /** A stable label for `meta.mode`, the only place a single mode string is stored. */
48
+ export declare function runHook(eventArg: string | undefined, options?: HookRunOptions): Promise<HookRunResult>;
@@ -0,0 +1,218 @@
1
+ /**
2
+ * The `harness-reflex hook <event>` entry point.
3
+ *
4
+ * Two rules shape every line below:
5
+ *
6
+ * 1. **stdout is protocol, never diagnostics.** The host may splice stdout into
7
+ * model-visible text, so only the JSON object named by `hook/contract` is
8
+ * returned; everything else goes to stderr.
9
+ * 2. **A decision is the only thing that can block.** F1 events fail open with
10
+ * `{}` on a timeout, a crash, malformed input, or a backend error; F2 events
11
+ * are silent even then; F3 (`stop`/`substop`) blocks only when the normal
12
+ * closing decision produced `contradicted` evidence. An exception is never
13
+ * converted into a veto.
14
+ *
15
+ * This module owns only what a child process adds to a decision: reading stdin
16
+ * under a cap, the per-event deadline, signal handling, and the exit code. The
17
+ * decision itself lives in `decision.ts` and knows nothing about processes, so an
18
+ * in-process host can call the same code without forking.
19
+ *
20
+ * The external state is the {@link FileStateStore}: one process per event, so
21
+ * the only continuity between `PreToolUse` and `Stop` is what was appended.
22
+ *
23
+ * @module hook/run
24
+ */
25
+ import { createDecisionBackend } from '../backend/factory.js';
26
+ import { normalizeHookPayload } from './payload.js';
27
+ import { clockFromEnv } from '../state/clock.js';
28
+ import { FileStateStore } from '../state/file-store.js';
29
+ import { assertSupportedPlatform, resolveStateRoot } from '../state/paths.js';
30
+ import { emptyHookOutput, parseHookEventName } from './contract.js';
31
+ import { DEFAULT_HOOK_CONFIG, HookDecision, dedupeKeyFor, modeLabel, resolveHookModes, stringField } from './decision.js';
32
+ export { DEFAULT_CAPABILITY_MODES, DEFAULT_HOOK_CONFIG, dedupeKeyFor, resolveHookModes } from './decision.js';
33
+ export { MemoryStateStore } from './memory-store.js';
34
+ export const MAX_STDIN_BYTES = 8 * 1024 * 1024;
35
+ /** Injectable seams, used by the fixtures and by the CLI. */
36
+ export function readStdinCapped(stream, limit = MAX_STDIN_BYTES) {
37
+ return new Promise((resolve, reject) => {
38
+ let total = 0;
39
+ let overflow = false;
40
+ let chunks = [];
41
+ stream.on('data', (chunk) => {
42
+ if (overflow)
43
+ return;
44
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
45
+ total += buffer.length;
46
+ if (total > limit) {
47
+ overflow = true;
48
+ chunks = [];
49
+ return;
50
+ }
51
+ chunks.push(buffer);
52
+ });
53
+ stream.on('end', () => {
54
+ resolve({ text: overflow ? '' : Buffer.concat(chunks).toString('utf8'), overflow });
55
+ });
56
+ stream.on('error', reject);
57
+ });
58
+ }
59
+ /** A stable label for `meta.mode`, the only place a single mode string is stored. */
60
+ export async function runHook(eventArg, options = {}) {
61
+ const env = options.env ?? process.env;
62
+ const platform = options.platform ?? process.platform;
63
+ const stderr = options.stderr ?? ((message) => process.stderr.write(`${message}\n`));
64
+ try {
65
+ assertSupportedPlatform(platform);
66
+ }
67
+ catch (error) {
68
+ stderr(error.message);
69
+ return { output: null, code: 2, error: 'unsupported-platform' };
70
+ }
71
+ const parsedEvent = parseHookEventName(eventArg);
72
+ if (parsedEvent.kind === 'codex-only') {
73
+ // Recognized, but this runtime has nothing to say about it. Read stdin so the
74
+ // host does not see a broken pipe, then answer the only safe thing: no
75
+ // instruction. No store is touched, so a stream of these costs nothing.
76
+ try {
77
+ await (options.readStdin ?? (() => readStdinCapped(process.stdin)))();
78
+ }
79
+ catch {
80
+ // A broken stdin on a no-op event is still a no-op.
81
+ }
82
+ return { output: emptyHookOutput(), code: 0 };
83
+ }
84
+ const event = parsedEvent.kind === 'canonical' ? parsedEvent.event : undefined;
85
+ if (!event) {
86
+ stderr(`harness-reflex hook: unknown event "${eventArg ?? ''}" (expected one of pretooluse, posttooluse, postfailure, stop, substop, sessionstart, sessionend)`);
87
+ return { output: emptyHookOutput(), code: 0, error: 'unknown-event' };
88
+ }
89
+ const modes = { ...resolveHookModes(env), ...(options.modes ?? {}) };
90
+ const mode = modeLabel(modes);
91
+ if (mode === 'off')
92
+ return { output: emptyHookOutput(), code: 0 };
93
+ const clock = options.clock ?? clockFromEnv(env);
94
+ let stdin;
95
+ try {
96
+ stdin = await (options.readStdin ?? (() => readStdinCapped(process.stdin)))();
97
+ }
98
+ catch (error) {
99
+ stderr(`harness-reflex hook: stdin read failed: ${error.message}`);
100
+ return { output: emptyHookOutput(), code: 0, error: 'stdin-read' };
101
+ }
102
+ if (stdin.overflow) {
103
+ stderr(`harness-reflex hook: stdin exceeds ${MAX_STDIN_BYTES} bytes; failing open`);
104
+ return { output: emptyHookOutput(), code: 0, error: 'stdin-too-large' };
105
+ }
106
+ let payload;
107
+ try {
108
+ const parsed = JSON.parse(stdin.text);
109
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
110
+ throw new Error('payload is not an object');
111
+ payload = parsed;
112
+ }
113
+ catch (error) {
114
+ stderr(`harness-reflex hook: malformed stdin JSON: ${error.message}`);
115
+ return { output: emptyHookOutput(), code: 0, error: 'bad-json' };
116
+ }
117
+ // Fold the host's field spellings into the decision's vocabulary. The
118
+ // normalizer is total and additive, so this is a no-op for a payload that is
119
+ // already in the expected shape (the Claude Code path is unchanged).
120
+ payload = normalizeHookPayload(payload);
121
+ const sessionId = stringField(payload.session_id);
122
+ if (!sessionId) {
123
+ stderr('harness-reflex hook: stdin JSON has no session_id; failing open');
124
+ return { output: emptyHookOutput(), code: 0, error: 'missing-session-id' };
125
+ }
126
+ const config = { ...DEFAULT_HOOK_CONFIG, ...options.config };
127
+ // The audit ledger records which harness produced a decision. `cc` is the
128
+ // historical default; a second host tags itself through
129
+ // `HARNESS_REFLEX_HARNESS` so the ledger is not misleading about its origin.
130
+ // The default is unchanged, so existing sessions keep their directory names.
131
+ const harness = stringField(env.HARNESS_REFLEX_HARNESS);
132
+ // Session boundaries are counted by GC; they carry no decision and no ledger.
133
+ if (event === 'sessionstart' || event === 'sessionend') {
134
+ const store = options.store ?? new FileStateStore({ root: resolveStateRoot(env), clock, harness });
135
+ const backend = options.backend ?? createDecisionBackend();
136
+ const runtime = new HookDecision({ store, backend, config, modes, sessionId, clock, stderr });
137
+ const timeoutMs = config.eventBudgets[event].budgetMs;
138
+ const output = await withTimeout(Promise.resolve().then(() => runtime.handle(event, payload, config.eventBudgets[event])), timeoutMs, () => stderr(`harness-reflex hook: ${event} exceeded ${timeoutMs} ms; failing open`));
139
+ return { output: output ?? emptyHookOutput(), code: 0 };
140
+ }
141
+ const store = options.store ?? new FileStateStore({ root: resolveStateRoot(env), clock, harness });
142
+ const backend = options.backend ?? createDecisionBackend();
143
+ store.ensureSession(sessionId, mode);
144
+ const key = dedupeKeyFor(event, payload);
145
+ // Fast replay path: a committed decision is returned verbatim.
146
+ const committed = store.readDecision(sessionId, key);
147
+ if (committed !== undefined)
148
+ return { output: committed, code: 0 };
149
+ if (store.ledgerHasKey(sessionId, key))
150
+ return { output: emptyHookOutput(), code: 0 };
151
+ // Concurrent duplicates of one tool_use_id: exactly one process decides, the
152
+ // others are an explicit no-op (or replay the decision if it just committed).
153
+ if (!store.claimDecision(sessionId, key).acquired) {
154
+ const raced = store.readDecision(sessionId, key);
155
+ return { output: raced ?? emptyHookOutput(), code: 0 };
156
+ }
157
+ // Re-check after winning the claim: the previous owner may have committed and
158
+ // released between our first read and the exclusive create.
159
+ const committedAfterClaim = store.readDecision(sessionId, key);
160
+ if (committedAfterClaim !== undefined) {
161
+ store.releaseDecisionClaim(sessionId, key);
162
+ return { output: committedAfterClaim, code: 0 };
163
+ }
164
+ if (store.ledgerHasKey(sessionId, key)) {
165
+ store.releaseDecisionClaim(sessionId, key);
166
+ return { output: emptyHookOutput(), code: 0 };
167
+ }
168
+ const runtime = new HookDecision({ store, backend, config, modes, sessionId, clock, stderr });
169
+ const timeoutMs = config.eventBudgets[event].budgetMs;
170
+ const output = await withTimeout(runtime.handle(event, payload, config.eventBudgets[event]), timeoutMs, () => {
171
+ runtime.abort();
172
+ runtime.auditError(event, 'hook-timeout', `decision exceeded ${timeoutMs} ms`, key);
173
+ stderr(`harness-reflex hook: ${event} exceeded ${timeoutMs} ms; failing open`);
174
+ }, (error) => {
175
+ runtime.auditError(event, 'handler-error', error?.message ?? 'unknown error', key);
176
+ store.releaseDecisionClaim(sessionId, key);
177
+ stderr(`harness-reflex hook: ${event} failed: ${error?.message ?? 'unknown error'}`);
178
+ });
179
+ return { output: output ?? emptyHookOutput(), code: 0 };
180
+ }
181
+ /** Resolve a promise at a deadline, running one best-effort callback first. */
182
+ function withTimeout(promise, ms, onTimeout, onError) {
183
+ return new Promise((resolve) => {
184
+ let settled = false;
185
+ const timer = setTimeout(() => {
186
+ if (settled)
187
+ return;
188
+ settled = true;
189
+ try {
190
+ onTimeout();
191
+ }
192
+ catch {
193
+ // the fail-open path must itself never throw
194
+ }
195
+ resolve(undefined);
196
+ }, Math.max(1, ms));
197
+ promise.then((value) => {
198
+ if (settled)
199
+ return;
200
+ settled = true;
201
+ clearTimeout(timer);
202
+ resolve(value);
203
+ }, (error) => {
204
+ if (settled)
205
+ return;
206
+ settled = true;
207
+ clearTimeout(timer);
208
+ try {
209
+ onError?.(error);
210
+ }
211
+ catch {
212
+ // the fail-open path must itself never throw
213
+ }
214
+ resolve(undefined);
215
+ });
216
+ });
217
+ }
218
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/hook/run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,YAAY,EAAkB,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAkD,MAAM,eAAe,CAAC;AACpH,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,WAAW,EAGZ,MAAM,eAAe,CAAC;AAGvB,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,EAIjB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAIrD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAgB/C,6DAA6D;AAC7D,MAAM,UAAU,eAAe,CAAC,MAA6B,EAAE,KAAK,GAAG,eAAe;IACpF,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,QAAQ,GAAG,KAAK,CAAC;QACrB,IAAI,MAAM,GAAa,EAAE,CAAC;QAC1B,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAsB,EAAE,EAAE;YAC3C,IAAI,QAAQ;gBAAE,OAAO;YACrB,MAAM,MAAM,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AA6C;YAC/C,CAAC;YACD,OAAO,CAAC,SAAS,CAAC,CAAC;QACrB,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * The `harness-reflex hook <event>` entry point.\n *\n * Two rules shape every line below:\n *\n * 1. **stdout is protocol, never diagnostics.** The host may splice stdout into\n * model-visible text, so only the JSON object named by `hook/contract` is\n * returned; everything else goes to stderr.\n * 2. **A decision is the only thing that can block.** F1 events fail open with\n * `{}` on a timeout, a crash, malformed input, or a backend error; F2 events\n * are silent even then; F3 (`stop`/`substop`) blocks only when the normal\n * closing decision produced `contradicted` evidence. An exception is never\n * converted into a veto.\n *\n * This module owns only what a child process adds to a decision: reading stdin\n * under a cap, the per-event deadline, signal handling, and the exit code. The\n * decision itself lives in `decision.ts` and knows nothing about processes, so an\n * in-process host can call the same code without forking.\n *\n * The external state is the {@link FileStateStore}: one process per event, so\n * the only continuity between `PreToolUse` and `Stop` is what was appended.\n *\n * @module hook/run\n */\nimport { createDecisionBackend } from '../backend/factory.js';\nimport { normalizeHookPayload } from './payload.js';\nimport { clockFromEnv, type HookClock } from '../state/clock.js';\nimport { FileStateStore } from '../state/file-store.js';\nimport { assertSupportedPlatform, resolveStateRoot } from '../state/paths.js';\nimport { emptyHookOutput, parseHookEventName, type HookEvent, type HookMode, type HookOutput } from './contract.js';\nimport {\n DEFAULT_HOOK_CONFIG,\n HookDecision,\n dedupeKeyFor,\n modeLabel,\n resolveHookModes,\n stringField,\n type HookConfig,\n type HookModeMap\n} from './decision.js';\nimport type { DecisionBackend } from '../backend/types.js';\n\nexport {\n DEFAULT_CAPABILITY_MODES,\n DEFAULT_HOOK_CONFIG,\n dedupeKeyFor,\n resolveHookModes,\n type HookCapability,\n type HookConfig,\n type HookModeMap\n} from './decision.js';\nexport { MemoryStateStore } from './memory-store.js';\nexport type { HookStorePort } from './store-port.js';\n\n\nexport const MAX_STDIN_BYTES = 8 * 1024 * 1024;\nexport interface HookStdin {\n text: string;\n overflow: boolean;\n}\n\n/** The result of one invocation, before the CLI serializes it. */\nexport interface HookRunResult {\n /** The stdout object; `null` means \"write nothing\" (unsupported platform). */\n output: HookOutput | null;\n /** Process exit code; non-zero means \"abandoned\", which every host fails open. */\n code: number;\n /** Machine reason for stderr/audit; never part of stdout. */\n error?: string;\n}\n\n/** Injectable seams, used by the fixtures and by the CLI. */\nexport function readStdinCapped(stream: NodeJS.ReadableStream, limit = MAX_STDIN_BYTES): Promise<HookStdin> {\n return new Promise((resolve, reject) => {\n let total = 0;\n let overflow = false;\n let chunks: Buffer[] = [];\n stream.on('data', (chunk: Buffer | string) => {\n if (overflow) return;\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));\n total += buffer.length;\n if (total > limit) {\n overflow = true;\n chunks = [];\n return;\n }\n chunks.push(buffer);\n });\n stream.on('end', () => {\n resolve({ text: overflow ? '' : Buffer.concat(chunks).toString('utf8'), overflow });\n });\n stream.on('error', reject);\n });\n}\n\n/** A stable JSON rendering so equal objects produce equal input digests. */\nexport interface HookRunResult {\n /** The stdout object; `null` means \"write nothing\" (unsupported platform). */\n output: HookOutput | null;\n /** Process exit code; non-zero means \"abandoned\", which every host fails open. */\n code: number;\n /** Machine reason for stderr/audit; never part of stdout. */\n error?: string;\n}\n\n/** Injectable seams, used by the fixtures and by the CLI. */\nexport interface HookRunOptions {\n env?: NodeJS.ProcessEnv;\n platform?: NodeJS.Platform;\n backend?: DecisionBackend;\n store?: FileStateStore;\n clock?: HookClock;\n config?: Partial<HookConfig>;\n /** Explicit per-capability modes; when omitted, they are resolved from `env`. */\n modes?: Partial<HookModeMap>;\n readStdin?: () => Promise<HookStdin>;\n stderr?: (message: string) => void;\n}\n\n/** A stable label for `meta.mode`, the only place a single mode string is stored. */\nexport async function runHook(eventArg: string | undefined, options: HookRunOptions = {}): Promise<HookRunResult> {\n const env = options.env ?? process.env;\n const platform = options.platform ?? process.platform;\n const stderr = options.stderr ?? ((message: string) => process.stderr.write(`${message}\\n`));\n try {\n assertSupportedPlatform(platform);\n } catch (error) {\n stderr((error as Error).message);\n return { output: null, code: 2, error: 'unsupported-platform' };\n }\n const parsedEvent = parseHookEventName(eventArg);\n if (parsedEvent.kind === 'codex-only') {\n // Recognized, but this runtime has nothing to say about it. Read stdin so the\n // host does not see a broken pipe, then answer the only safe thing: no\n // instruction. No store is touched, so a stream of these costs nothing.\n try {\n await (options.readStdin ?? (() => readStdinCapped(process.stdin)))();\n } catch {\n // A broken stdin on a no-op event is still a no-op.\n }\n return { output: emptyHookOutput(), code: 0 };\n }\n const event = parsedEvent.kind === 'canonical' ? parsedEvent.event : undefined;\n if (!event) {\n stderr(`harness-reflex hook: unknown event \"${eventArg ?? ''}\" (expected one of pretooluse, posttooluse, postfailure, stop, substop, sessionstart, sessionend)`);\n return { output: emptyHookOutput(), code: 0, error: 'unknown-event' };\n }\n const modes: HookModeMap = { ...resolveHookModes(env), ...(options.modes ?? {}) };\n const mode = modeLabel(modes);\n if (mode === 'off') return { output: emptyHookOutput(), code: 0 };\n const clock = options.clock ?? clockFromEnv(env);\n let stdin: HookStdin;\n try {\n stdin = await (options.readStdin ?? (() => readStdinCapped(process.stdin)))();\n } catch (error) {\n stderr(`harness-reflex hook: stdin read failed: ${(error as Error).message}`);\n return { output: emptyHookOutput(), code: 0, error: 'stdin-read' };\n }\n if (stdin.overflow) {\n stderr(`harness-reflex hook: stdin exceeds ${MAX_STDIN_BYTES} bytes; failing open`);\n return { output: emptyHookOutput(), code: 0, error: 'stdin-too-large' };\n }\n let payload: Record<string, unknown>;\n try {\n const parsed = JSON.parse(stdin.text) as unknown;\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('payload is not an object');\n payload = parsed as Record<string, unknown>;\n } catch (error) {\n stderr(`harness-reflex hook: malformed stdin JSON: ${(error as Error).message}`);\n return { output: emptyHookOutput(), code: 0, error: 'bad-json' };\n }\n // Fold the host's field spellings into the decision's vocabulary. The\n // normalizer is total and additive, so this is a no-op for a payload that is\n // already in the expected shape (the Claude Code path is unchanged).\n payload = normalizeHookPayload(payload) as Record<string, unknown>;\n const sessionId = stringField(payload.session_id);\n if (!sessionId) {\n stderr('harness-reflex hook: stdin JSON has no session_id; failing open');\n return { output: emptyHookOutput(), code: 0, error: 'missing-session-id' };\n }\n const config: HookConfig = { ...DEFAULT_HOOK_CONFIG, ...options.config };\n // The audit ledger records which harness produced a decision. `cc` is the\n // historical default; a second host tags itself through\n // `HARNESS_REFLEX_HARNESS` so the ledger is not misleading about its origin.\n // The default is unchanged, so existing sessions keep their directory names.\n const harness = stringField(env.HARNESS_REFLEX_HARNESS);\n // Session boundaries are counted by GC; they carry no decision and no ledger.\n if (event === 'sessionstart' || event === 'sessionend') {\n const store = options.store ?? new FileStateStore({ root: resolveStateRoot(env), clock, harness });\n const backend = options.backend ?? createDecisionBackend();\n const runtime = new HookDecision({ store, backend, config, modes, sessionId, clock, stderr });\n const timeoutMs = config.eventBudgets[event].budgetMs;\n const output = await withTimeout(\n Promise.resolve().then(() => runtime.handle(event, payload, config.eventBudgets[event])),\n timeoutMs,\n () => stderr(`harness-reflex hook: ${event} exceeded ${timeoutMs} ms; failing open`)\n );\n return { output: output ?? emptyHookOutput(), code: 0 };\n }\n const store = options.store ?? new FileStateStore({ root: resolveStateRoot(env), clock, harness });\n const backend = options.backend ?? createDecisionBackend();\n store.ensureSession(sessionId, mode);\n const key = dedupeKeyFor(event, payload);\n // Fast replay path: a committed decision is returned verbatim.\n const committed = store.readDecision(sessionId, key) as HookOutput | undefined;\n if (committed !== undefined) return { output: committed, code: 0 };\n if (store.ledgerHasKey(sessionId, key)) return { output: emptyHookOutput(), code: 0 };\n // Concurrent duplicates of one tool_use_id: exactly one process decides, the\n // others are an explicit no-op (or replay the decision if it just committed).\n if (!store.claimDecision(sessionId, key).acquired) {\n const raced = store.readDecision(sessionId, key) as HookOutput | undefined;\n return { output: raced ?? emptyHookOutput(), code: 0 };\n }\n // Re-check after winning the claim: the previous owner may have committed and\n // released between our first read and the exclusive create.\n const committedAfterClaim = store.readDecision(sessionId, key) as HookOutput | undefined;\n if (committedAfterClaim !== undefined) {\n store.releaseDecisionClaim(sessionId, key);\n return { output: committedAfterClaim, code: 0 };\n }\n if (store.ledgerHasKey(sessionId, key)) {\n store.releaseDecisionClaim(sessionId, key);\n return { output: emptyHookOutput(), code: 0 };\n }\n const runtime = new HookDecision({ store, backend, config, modes, sessionId, clock, stderr });\n const timeoutMs = config.eventBudgets[event].budgetMs;\n const output = await withTimeout(\n runtime.handle(event, payload, config.eventBudgets[event]),\n timeoutMs,\n () => {\n runtime.abort();\n runtime.auditError(event, 'hook-timeout', `decision exceeded ${timeoutMs} ms`, key);\n stderr(`harness-reflex hook: ${event} exceeded ${timeoutMs} ms; failing open`);\n },\n (error) => {\n runtime.auditError(event, 'handler-error', (error as Error)?.message ?? 'unknown error', key);\n store.releaseDecisionClaim(sessionId, key);\n stderr(`harness-reflex hook: ${event} failed: ${(error as Error)?.message ?? 'unknown error'}`);\n }\n );\n return { output: output ?? emptyHookOutput(), code: 0 };\n}\n\n/** Resolve a promise at a deadline, running one best-effort callback first. */\nfunction withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n onTimeout: () => void,\n onError?: (error: unknown) => void\n): Promise<T | undefined> {\n return new Promise((resolve) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n try {\n onTimeout();\n } catch {\n // the fail-open path must itself never throw\n }\n resolve(undefined);\n }, Math.max(1, ms));\n promise.then(\n (value) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n onError?.(error);\n } catch {\n // the fail-open path must itself never throw\n }\n resolve(undefined);\n }\n );\n });\n}\n"]}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The storage contract one hook decision needs.
3
+ *
4
+ * `FileStateStore` implements it today, because the command-hook contract gives
5
+ * each event its own process and that process has no memory to carry. An
6
+ * *in-process* host (the DSH plugin, a pi extension, an opencode plugin) does
7
+ * carry memory and must not pay for a file round trip per tool call, so the
8
+ * orchestration in `decision.ts` is written against this interface instead of
9
+ * against the file implementation directly.
10
+ *
11
+ * The interface is deliberately the same shape the file store already has: an
12
+ * adapter over memory is a few dozen lines and behavioural parity is checkable
13
+ * by running the same decision fixtures over both.
14
+ *
15
+ * @module hook/store-port
16
+ */
17
+ import type { HookLedgerRecord, LockAttempt, RetentionResult, SessionEvent, SessionState } from '../state/file-store.js';
18
+ /** Where a decision may persist its state. */
19
+ export interface HookStorePort {
20
+ /** Tag recorded on every ledger line (`cc`, `dsh`, `pi`, …). */
21
+ readonly harness: string;
22
+ /** Ensure the session exists before the first decision. */
23
+ ensureSession(sessionId: string, mode: string): void;
24
+ /** Read the discardable turn/budget cache. */
25
+ readState(sessionId: string): SessionState;
26
+ /**
27
+ * One locked read-modify-write of the state cache.
28
+ *
29
+ * An in-process implementation may resolve without a real lock: only one
30
+ * decision per session runs at a time inside one process, and the host is
31
+ * single-threaded between awaits.
32
+ */
33
+ updateState<T>(sessionId: string, mutate: (state: SessionState) => T): LockAttempt<T>;
34
+ /** Append one observation. */
35
+ appendEvent(sessionId: string, record: SessionEvent): void;
36
+ /** Append one auditable decision or skip. */
37
+ appendLedger(sessionId: string, record: HookLedgerRecord): void;
38
+ /**
39
+ * Read the newest observations of one session.
40
+ *
41
+ * **Oldest first.** The tail is read in file order, which is append order,
42
+ * and it stays that way: `core/judge` counts trailing runs from the *end* of
43
+ * the array, so handing it a newest-first array would make it count the
44
+ * newest replay rather than the run that just happened. The previous version
45
+ * of this comment said "newest first", which contradicted both
46
+ * implementations and every `oldest first` contract in `core/judge`.
47
+ * @param sessionId - the session.
48
+ * @param limit - maximum observations to return.
49
+ * @returns the last `limit` observations, oldest first.
50
+ */
51
+ readEvents(sessionId: string, limit: number): SessionEvent[];
52
+ /** Whether an observation with this dedupe key was already appended. */
53
+ eventsHaveKey(sessionId: string, key: string): boolean;
54
+ /** Whether a ledger line with this dedupe key was already written. */
55
+ ledgerHasKey(sessionId: string, key: string): boolean;
56
+ /** The committed output of a previous delivery, if any. */
57
+ readDecision(sessionId: string, key: string): Record<string, unknown> | undefined;
58
+ /** Commit one decision's output so a redelivery replays it. */
59
+ writeDecision(sessionId: string, key: string, output: Record<string, unknown>): void;
60
+ /** Take (or discover) the exclusive claim on one decision key. */
61
+ claimDecision(sessionId: string, key: string): LockAttempt<unknown>;
62
+ /** Release the claim, whether or not this process won it. */
63
+ releaseDecisionClaim(sessionId: string, key: string): void;
64
+ /** Retain a pruned payload's original under its digest. */
65
+ retainOriginal(sessionId: string, digest: string, text: string): RetentionResult;
66
+ /** Read back a retained original, or `undefined` when it is gone. */
67
+ readOriginal(sessionId: string, digest: string): string | undefined;
68
+ /** Drop expired session directories, never the one named by `keep`. */
69
+ gcSessions(retentionMs: number | undefined, keep: string): void;
70
+ /** Enforce one session's retained-original cap. */
71
+ gcOriginals(sessionId: string): string[];
72
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=store-port.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-port.js","sourceRoot":"","sources":["../../src/hook/store-port.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The storage contract one hook decision needs.\n *\n * `FileStateStore` implements it today, because the command-hook contract gives\n * each event its own process and that process has no memory to carry. An\n * *in-process* host (the DSH plugin, a pi extension, an opencode plugin) does\n * carry memory and must not pay for a file round trip per tool call, so the\n * orchestration in `decision.ts` is written against this interface instead of\n * against the file implementation directly.\n *\n * The interface is deliberately the same shape the file store already has: an\n * adapter over memory is a few dozen lines and behavioural parity is checkable\n * by running the same decision fixtures over both.\n *\n * @module hook/store-port\n */\nimport type {\n HookLedgerRecord,\n LockAttempt,\n RetentionResult,\n SessionEvent,\n SessionState\n} from '../state/file-store.js';\n\n/** Where a decision may persist its state. */\nexport interface HookStorePort {\n /** Tag recorded on every ledger line (`cc`, `dsh`, `pi`, …). */\n readonly harness: string;\n\n /** Ensure the session exists before the first decision. */\n ensureSession(sessionId: string, mode: string): void;\n\n /** Read the discardable turn/budget cache. */\n readState(sessionId: string): SessionState;\n\n /**\n * One locked read-modify-write of the state cache.\n *\n * An in-process implementation may resolve without a real lock: only one\n * decision per session runs at a time inside one process, and the host is\n * single-threaded between awaits.\n */\n updateState<T>(sessionId: string, mutate: (state: SessionState) => T): LockAttempt<T>;\n\n /** Append one observation. */\n appendEvent(sessionId: string, record: SessionEvent): void;\n\n /** Append one auditable decision or skip. */\n appendLedger(sessionId: string, record: HookLedgerRecord): void;\n\n /**\n * Read the newest observations of one session.\n *\n * **Oldest first.** The tail is read in file order, which is append order,\n * and it stays that way: `core/judge` counts trailing runs from the *end* of\n * the array, so handing it a newest-first array would make it count the\n * newest replay rather than the run that just happened. The previous version\n * of this comment said \"newest first\", which contradicted both\n * implementations and every `oldest first` contract in `core/judge`.\n * @param sessionId - the session.\n * @param limit - maximum observations to return.\n * @returns the last `limit` observations, oldest first.\n */\n readEvents(sessionId: string, limit: number): SessionEvent[];\n\n /** Whether an observation with this dedupe key was already appended. */\n eventsHaveKey(sessionId: string, key: string): boolean;\n\n /** Whether a ledger line with this dedupe key was already written. */\n ledgerHasKey(sessionId: string, key: string): boolean;\n\n /** The committed output of a previous delivery, if any. */\n readDecision(sessionId: string, key: string): Record<string, unknown> | undefined;\n\n /** Commit one decision's output so a redelivery replays it. */\n writeDecision(sessionId: string, key: string, output: Record<string, unknown>): void;\n\n /** Take (or discover) the exclusive claim on one decision key. */\n claimDecision(sessionId: string, key: string): LockAttempt<unknown>;\n\n /** Release the claim, whether or not this process won it. */\n releaseDecisionClaim(sessionId: string, key: string): void;\n\n /** Retain a pruned payload's original under its digest. */\n retainOriginal(sessionId: string, digest: string, text: string): RetentionResult;\n\n /** Read back a retained original, or `undefined` when it is gone. */\n readOriginal(sessionId: string, digest: string): string | undefined;\n\n /** Drop expired session directories, never the one named by `keep`. */\n gcSessions(retentionMs: number | undefined, keep: string): void;\n\n /** Enforce one session's retained-original cap. */\n gcOriginals(sessionId: string): string[];\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './backend/types.js';
2
+ export * from './backend/defaults.js';
2
3
  export * from './backend/mock.js';
3
4
  export * from './backend/jev.js';
4
5
  export * from './backend/simple-jev.js';
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './backend/types.js';
2
+ export * from './backend/defaults.js';
2
3
  export * from './backend/mock.js';
3
4
  export * from './backend/jev.js';
4
5
  export * from './backend/simple-jev.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,yBAAyB,CAAC;AACxC,cAAc,sBAAsB,CAAC;AAErC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AAEjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC","sourcesContent":["export * from './backend/types.js';\nexport * from './backend/mock.js';\nexport * from './backend/jev.js';\nexport * from './backend/simple-jev.js';\nexport * from './backend/factory.js';\n\nexport * from './core/gate.js';\nexport * from './core/score.js';\nexport * from './core/prune.js';\nexport * from './core/stagnation.js';\nexport * from './core/route.js';\nexport * from './core/ledger.js';\nexport * from './core/calibrate.js';\nexport * from './core/screen.js';\n\nexport * from './mcp/server.js';\nexport * from './adapters/claude.js';\nexport * from './adapters/codex.js';\nexport * from './adapters/agy.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,yBAAyB,CAAC;AACxC,cAAc,sBAAsB,CAAC;AAErC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AAEjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC","sourcesContent":["export * from './backend/types.js';\nexport * from './backend/defaults.js';\nexport * from './backend/mock.js';\nexport * from './backend/jev.js';\nexport * from './backend/simple-jev.js';\nexport * from './backend/factory.js';\n\nexport * from './core/gate.js';\nexport * from './core/score.js';\nexport * from './core/prune.js';\nexport * from './core/stagnation.js';\nexport * from './core/route.js';\nexport * from './core/ledger.js';\nexport * from './core/calibrate.js';\nexport * from './core/screen.js';\n\nexport * from './mcp/server.js';\nexport * from './adapters/claude.js';\nexport * from './adapters/codex.js';\nexport * from './adapters/agy.js';\n"]}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Audit-sink port.
3
+ *
4
+ * A decision that was *planned* must be auditable even when it was not applied,
5
+ * and a host's audit channel may be its session log, a file, or a test spy. The
6
+ * core produces the record; writing it somewhere durable is the host's job.
7
+ *
8
+ * @module ports/audit
9
+ */
10
+ /** A sink for one decision record, scoped to the session it belongs to. */
11
+ export interface AuditSinkPort<Record> {
12
+ /**
13
+ * Append one record, best-effort.
14
+ * @param record - the decision to retain.
15
+ * @param session - the session it belongs to, when one is visible.
16
+ */
17
+ write(record: Record, session: unknown): void;
18
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Audit-sink port.
3
+ *
4
+ * A decision that was *planned* must be auditable even when it was not applied,
5
+ * and a host's audit channel may be its session log, a file, or a test spy. The
6
+ * core produces the record; writing it somewhere durable is the host's job.
7
+ *
8
+ * @module ports/audit
9
+ */
10
+ export {};
11
+ //# sourceMappingURL=audit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.js","sourceRoot":"","sources":["../../src/ports/audit.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG","sourcesContent":["/**\n * Audit-sink port.\n *\n * A decision that was *planned* must be auditable even when it was not applied,\n * and a host's audit channel may be its session log, a file, or a test spy. The\n * core produces the record; writing it somewhere durable is the host's job.\n *\n * @module ports/audit\n */\n\n/** A sink for one decision record, scoped to the session it belongs to. */\nexport interface AuditSinkPort<Record> {\n /**\n * Append one record, best-effort.\n * @param record - the decision to retain.\n * @param session - the session it belongs to, when one is visible.\n */\n write(record: Record, session: unknown): void;\n}\n"]}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Clock port.
3
+ *
4
+ * The decision core never reads the wall clock itself: latency accounting is a
5
+ * pure function of two readings, so a test (or a replay) supplies its own
6
+ * readings and the reported costs stay reproducible.
7
+ *
8
+ * @module ports/clock
9
+ */
10
+ /** A monotonic-enough source of milliseconds for latency accounting. */
11
+ export interface ClockPort {
12
+ /** Current time in milliseconds. */
13
+ now(): number;
14
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Clock port.
3
+ *
4
+ * The decision core never reads the wall clock itself: latency accounting is a
5
+ * pure function of two readings, so a test (or a replay) supplies its own
6
+ * readings and the reported costs stay reproducible.
7
+ *
8
+ * @module ports/clock
9
+ */
10
+ export {};
11
+ //# sourceMappingURL=clock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.js","sourceRoot":"","sources":["../../src/ports/clock.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG","sourcesContent":["/**\n * Clock port.\n *\n * The decision core never reads the wall clock itself: latency accounting is a\n * pure function of two readings, so a test (or a replay) supplies its own\n * readings and the reported costs stay reproducible.\n *\n * @module ports/clock\n */\n\n/** A monotonic-enough source of milliseconds for latency accounting. */\nexport interface ClockPort {\n /** Current time in milliseconds. */\n now(): number;\n}\n"]}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Decision-backend ports.
3
+ *
4
+ * The core asks questions; which transport answers them (a hosted gateway, an
5
+ * in-process model, a mock) is chosen by the composition root. These interfaces
6
+ * are intentionally *narrow*: they describe only the calls the intervention
7
+ * decision surface makes, so a host adapter supplies a couple of methods rather
8
+ * than the whole backend contract.
9
+ *
10
+ * @module ports/decision
11
+ */
12
+ import type { ActionStep, GateResponse, PruneResponse, StagnationCheckResponse } from '../backend/types.js';
13
+ /** One stagnation verdict request: the window, plus the question it is asked in. */
14
+ export interface StagnationBackendPort {
15
+ /**
16
+ * Judge one observed action window.
17
+ * @param goal - why the run is judged, when the caller knows.
18
+ * @param history - observed steps, oldest first.
19
+ * @returns the verdict and its recommended intervention.
20
+ */
21
+ check(goal: string | undefined, history: readonly ActionStep[]): Promise<StagnationCheckResponse>;
22
+ }
23
+ /** One prune request, narrowed to what the intervention surface sends. */
24
+ export interface PruneBackendOptionsPort {
25
+ intent?: string;
26
+ measureOnly?: boolean;
27
+ pruneJudgeMinChars?: number;
28
+ }
29
+ /** The reduction service, as the prune plan consumes it. */
30
+ export interface PruneBackendPort {
31
+ /**
32
+ * Ask for one reduction candidate.
33
+ * @param output - the payload to reduce.
34
+ * @param options - intent and measurement flags.
35
+ * @returns the candidate plus its provenance and sizes.
36
+ */
37
+ prune(output: string, options?: PruneBackendOptionsPort): Promise<PruneResponse>;
38
+ }
39
+ /** One completion-claim sentence classification. */
40
+ export interface ClaimClassificationPort {
41
+ statement: string;
42
+ /** Whether the winning criterion says the sentence claims completion. */
43
+ isClaim: boolean;
44
+ /** Probability of the completion-claim criterion, in `[0, 1]`. */
45
+ confidence: number;
46
+ }
47
+ /** The classification answer for one closing candidate batch. */
48
+ export interface ClaimClassificationResponsePort {
49
+ results: ClaimClassificationPort[];
50
+ latencyMs: number;
51
+ }
52
+ /** One batch of candidate sentences a closing check must classify. */
53
+ export interface ClaimClassificationRequestPort {
54
+ statements: string[];
55
+ intent: string;
56
+ context?: string;
57
+ }
58
+ /** The verification half of a closing judgment. */
59
+ export interface ClosingBackendPort {
60
+ /** Classify which candidate sentences really claim completion. */
61
+ classifyClaims(request: ClaimClassificationRequestPort): Promise<ClaimClassificationResponsePort>;
62
+ /** Verify completion claims against the assembled evidence. */
63
+ verify(assertions: Array<{
64
+ statement: string;
65
+ criteria?: string;
66
+ }>, evidence: string, options?: {
67
+ latchCacheKey?: string;
68
+ }): Promise<GateResponse>;
69
+ }
70
+ /** The whole decision surface of one composition, grouped for convenience. */
71
+ export interface DecisionBackendPort {
72
+ stagnation: StagnationBackendPort;
73
+ prune: PruneBackendPort;
74
+ closing: ClosingBackendPort;
75
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=decision.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decision.js","sourceRoot":"","sources":["../../src/ports/decision.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Decision-backend ports.\n *\n * The core asks questions; which transport answers them (a hosted gateway, an\n * in-process model, a mock) is chosen by the composition root. These interfaces\n * are intentionally *narrow*: they describe only the calls the intervention\n * decision surface makes, so a host adapter supplies a couple of methods rather\n * than the whole backend contract.\n *\n * @module ports/decision\n */\nimport type {\n ActionStep,\n GateResponse,\n PruneResponse,\n StagnationCheckResponse\n} from '../backend/types.js';\n\n/** One stagnation verdict request: the window, plus the question it is asked in. */\nexport interface StagnationBackendPort {\n /**\n * Judge one observed action window.\n * @param goal - why the run is judged, when the caller knows.\n * @param history - observed steps, oldest first.\n * @returns the verdict and its recommended intervention.\n */\n check(goal: string | undefined, history: readonly ActionStep[]): Promise<StagnationCheckResponse>;\n}\n\n/** One prune request, narrowed to what the intervention surface sends. */\nexport interface PruneBackendOptionsPort {\n intent?: string;\n measureOnly?: boolean;\n pruneJudgeMinChars?: number;\n}\n\n/** The reduction service, as the prune plan consumes it. */\nexport interface PruneBackendPort {\n /**\n * Ask for one reduction candidate.\n * @param output - the payload to reduce.\n * @param options - intent and measurement flags.\n * @returns the candidate plus its provenance and sizes.\n */\n prune(output: string, options?: PruneBackendOptionsPort): Promise<PruneResponse>;\n}\n\n/** One completion-claim sentence classification. */\nexport interface ClaimClassificationPort {\n statement: string;\n /** Whether the winning criterion says the sentence claims completion. */\n isClaim: boolean;\n /** Probability of the completion-claim criterion, in `[0, 1]`. */\n confidence: number;\n}\n\n/** The classification answer for one closing candidate batch. */\nexport interface ClaimClassificationResponsePort {\n results: ClaimClassificationPort[];\n latencyMs: number;\n}\n\n/** One batch of candidate sentences a closing check must classify. */\nexport interface ClaimClassificationRequestPort {\n statements: string[];\n intent: string;\n context?: string;\n}\n\n/** The verification half of a closing judgment. */\nexport interface ClosingBackendPort {\n /** Classify which candidate sentences really claim completion. */\n classifyClaims(request: ClaimClassificationRequestPort): Promise<ClaimClassificationResponsePort>;\n /** Verify completion claims against the assembled evidence. */\n verify(\n assertions: Array<{ statement: string; criteria?: string }>,\n evidence: string,\n options?: { latchCacheKey?: string }\n ): Promise<GateResponse>;\n}\n\n/** The whole decision surface of one composition, grouped for convenience. */\nexport interface DecisionBackendPort {\n stagnation: StagnationBackendPort;\n prune: PruneBackendPort;\n closing: ClosingBackendPort;\n}\n"]}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The ports of the intervention decision core.
3
+ *
4
+ * Interfaces and pure types only: nothing here reads a file, holds a socket, or
5
+ * knows what a host is. Composition roots implement these and inject them into
6
+ * the core.
7
+ *
8
+ * @module ports
9
+ */
10
+ export type { ClockPort } from './clock.js';
11
+ export type { ClaimClassificationPort, ClaimClassificationRequestPort, ClaimClassificationResponsePort, ClosingBackendPort, DecisionBackendPort, PruneBackendOptionsPort, PruneBackendPort, StagnationBackendPort } from './decision.js';
12
+ export type { BudgetSnapshot, BudgetStorePort, StateStorePort } from './state.js';
13
+ export type { AuditSinkPort } from './audit.js';
14
+ export type { LoggerPort, LogLevel } from './log.js';
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/ports/index.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The ports of the intervention decision core.\n *\n * Interfaces and pure types only: nothing here reads a file, holds a socket, or\n * knows what a host is. Composition roots implement these and inject them into\n * the core.\n *\n * @module ports\n */\nexport type { ClockPort } from './clock.js';\nexport type {\n ClaimClassificationPort,\n ClaimClassificationRequestPort,\n ClaimClassificationResponsePort,\n ClosingBackendPort,\n DecisionBackendPort,\n PruneBackendOptionsPort,\n PruneBackendPort,\n StagnationBackendPort\n} from './decision.js';\nexport type { BudgetSnapshot, BudgetStorePort, StateStorePort } from './state.js';\nexport type { AuditSinkPort } from './audit.js';\nexport type { LoggerPort, LogLevel } from './log.js';\n"]}