osuite 2.11.0 → 2.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/GOVERNED_TOOLS.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Native Tool Compatibility And Recovery
2
2
 
3
3
  This opt-in API is introduced in 2.11.0; it is not part of 2.10.2. Confirm the
4
- chosen version with `npm view osuite@2.11.0 version` before installing. A source
4
+ chosen version with `npm view osuite@2.11.2 version` before installing. A source
5
5
  checkout alone does not establish npm availability or server compatibility;
6
6
  consult the verified release record before enabling it for a workspace.
7
7
 
@@ -142,9 +142,18 @@ creates a different scope: never use that as a recovery shortcut.
142
142
  | `OUTCOME_UNKNOWN` | Inspect the resource separately; do not automatically resend. |
143
143
  | `POLICY_DENIED` / expiry / cancellation | Respect the terminal refusal. A new intention needs explicit operator action. |
144
144
  | `CURRENT_AUTHORITY_UNAVAILABLE` | Restore current server/identity configuration; never fall back to ungoverned execution. |
145
+ | `JOURNAL_BUSY` | Preserve the same ID and journal; inspect contention and existing status. No automatic resend or state reset. |
145
146
  | `JOURNAL_MISSING` / invalid journal | Restore the correct durable journal; do not initialize an empty replacement to replay old IDs. |
146
147
  | `ABORTED` | The local waiter stopped. This does not revoke approval or undo a dispatched effect. |
147
148
 
149
+ Since 2.11.1, `error.recovery` and `status.recovery` expose a bounded `nextStep`,
150
+ `preserveOperationId: true`, and an explanatory `message` for the UI. They contain
151
+ no native arguments or result payloads. Show them alongside the stable error
152
+ code; do not treat them as a grant, a promise of resumability, or an automatic
153
+ retry instruction. `retryAutomatically` remains false on errors. After an
154
+ unknown dispatch, `reconcile_without_resend` means inspect the resource, not
155
+ call the wrapper with a new ID.
156
+
148
157
  Restart can resume a held review. It cannot infer that a request was not sent
149
158
  from a timeout, missing response, crashed process, or lost completion report.
150
159
  Only an exact server record that is still pending can repair an uncertain
@@ -179,6 +188,12 @@ permissions, symlinks/hardlinks and invalid database paths are rejected. SQLite
179
188
  uses transactional CAS and full durability. The default limit is 10,000 retained
180
189
  operations; exhaustion stops new work. Normal opening never creates a missing
181
190
  database. Explicit initialization is a provisioning action, not recovery.
191
+ Version 2.11.2 changes the default `journalOptions.busyTimeoutMs`
192
+ from 100 to 1,000 ms; the supported range remains 0-5,000 ms. This is a bounded
193
+ local write-lock budget, not extra approval time or an operation retry policy.
194
+ After the dispatch fence commits, the existing five-second admission-receipt
195
+ age limit is checked again immediately before the callback. An expired receipt
196
+ leaves an uncertain fence; it is never renewed or automatically retried.
182
197
  Do not delete completed or unknown rows
183
198
  to make room: they are replay tombstones. Plan scoped lifecycle/retention with
184
199
  the operator, retain the WAL correctly, and never share this database over an
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # OSuite SDK (v2.11.0)
1
+ # OSuite SDK (v2.11.2)
2
2
 
3
3
  **Governed action SDK for AI agents.**
4
4
 
@@ -6,7 +6,7 @@ The OSuite SDK helps teams route approvals, record governed decisions, and produ
6
6
 
7
7
  The opt-in Node 24 `osuite/governed-tools` entry preserves native tool calls
8
8
  and adds durable approval recovery. See [Native Tool Compatibility](GOVERNED_TOOLS.md).
9
- It is not in the published 2.10.2 package and does not enable Hook or a gateway.
9
+ It was introduced in 2.11.0 and does not enable Hook or a gateway.
10
10
 
11
11
  ## Installation
12
12
 
@@ -25,8 +25,8 @@ node /absolute/path/to/osuite-sdk/sdk/cli.js doctor
25
25
  node /absolute/path/to/osuite-sdk/sdk/cli.js try
26
26
  ```
27
27
 
28
- For this version, use `npx osuite@2.11.0 connect` after confirming availability
29
- with `npm view osuite@2.11.0 version`. A source checkout or this document alone
28
+ For this version, use `npx osuite@2.11.2 connect` only after confirming availability
29
+ with `npm view osuite@2.11.2 version`. A source checkout or this document alone
30
30
  does not establish registry publication, and npm's `latest` may differ from the
31
31
  checked-out version. The stable credential-recovery behavior and the new
32
32
  native-call operation journal are different mechanisms.
@@ -44,7 +44,7 @@ credential paths are refused. The client durably saves a recovery journal before
44
44
  acknowledging a replacement, so reconnect does not revoke the old key before the
45
45
  new credential can be recovered. Historical exposure still requires key rotation.
46
46
 
47
- New 2.10.1 hook installations need Node.js 18 or newer and Git for repository
47
+ Since 2.10.1, new hook installations need Node.js 18 or newer and Git for repository
48
48
  safety checks. Python is not required for the packaged Node hooks or MCP bridge.
49
49
  Existing Python installations remain legacy until explicitly migrated. Custom
50
50
  registrations and intentionally disabled hooks are preserved, not silently
@@ -63,6 +63,52 @@ acknowledgement only after an eligible human approves and the server freshly
63
63
  redeems that exact grant. A missing, denied or unconfirmed grant does not execute.
64
64
  Slack and email notifications require configured workspace channels.
65
65
 
66
+ ## Failure Handling In 2.11.1
67
+
68
+ The Hook's local guard-failure default is now `block`, including non-strict
69
+ profiles. Invalid or oversized input, malformed responses, signing failures,
70
+ redirects and request/authentication rejections are not availability fallbacks.
71
+ An explicit non-strict `GUARD_FAILURE_MODE=allow` (or a verified administrator
72
+ posture) can permit an **ungoverned** action only for a classified transport
73
+ failure or HTTP 500/502/503/504. Strict and scoped mandatory profiles never use
74
+ that fallback. An outage allowance is not an approval or an admission receipt.
75
+
76
+ Current posture rejection is retained in the local authenticated cache. A late
77
+ response that started before the rejection cannot clear it; a fresh valid
78
+ server response is required. An independent rejection marker survives contention
79
+ on the configuration cache lock. Authentication/revocation/conflict errors in
80
+ guard, admission and approval reads also invalidate cached posture. Preserve the private state directory: deleting
81
+ or restoring old state is not a supported recovery path.
82
+
83
+ The native-tool wrapper has no offline fallback. Its errors and status now
84
+ include `recovery.nextStep` and `recovery.message`. These are presentation hints,
85
+ not authority to execute or resend. Keep the same operation ID after a held
86
+ review, and reconcile uncertain outcomes with the resource without replaying
87
+ the write. Successful native results remain unchanged.
88
+
89
+ A Hook returning an explicit refusal and a host losing the Hook process are
90
+ different cases. A host may continue after a callback crash, unsupported output
91
+ or host-enforced timeout. This patch hardens OSuite's handled error paths; it
92
+ does not change vendor host behavior or make endpoint Hooks unbypassable. Use
93
+ mandatory resource-side enforcement where that guarantee is required.
94
+
95
+ New Claude Code pre-tool registrations include `onFailure: block`, supported
96
+ by Claude Code 2.1.295 and later and tested on 2.1.300. Existing custom or disabled
97
+ registrations are preserved; `doctor` warns when the failure policy is absent.
98
+ That setting is not a guarantee for older Claude versions or other hosts.
99
+
100
+ ## Concurrent Recovery In 2.11.2
101
+
102
+ Version 2.11.2 rechecks bounded atomic state-file replacements without trusting
103
+ detached data or relaxing symlink/hardlink checks. The opt-in native journal
104
+ waits up to 1,000 ms for a write lock by default, with no transaction or action
105
+ replay. A pre-send exhausted lock remains `JOURNAL_BUSY`; it is not permission
106
+ to change the business ID or clear state. Admission age is checked again after
107
+ the durable dispatch fence, so local I/O cannot silently extend its validity.
108
+ These source corrections are not present in immutable `2.11.1`. Verify a
109
+ published version and its provenance before deploying it; no new Hook is enabled
110
+ by this source update.
111
+
66
112
  ## The Governance Loop
67
113
 
68
114
  The default SDK transports requests; it does not execute your tool. The opt-in
package/cli.js CHANGED
@@ -695,11 +695,19 @@ function writeCheckLine(status, label, detail) {
695
695
 
696
696
  // A telemetry-only result must never count as successful governance.
697
697
  async function verifyProjectHooks(runtimes) {
698
- const installations = findHookInstallations(process.cwd(), runtimes);
698
+ const installations = findHookInstallations(process.cwd(), runtimes, { diagnose: true });
699
699
  const checks = [];
700
700
  for (const installation of installations) {
701
+ const { diagnostics } = installation;
702
+ writeCheckLine(diagnostics.status === 'current' ? 'ok' : 'warn', 'Hook freshness', `${installation.label}: ${diagnostics.status === 'current'
703
+ ? 'managed Node runtime and launcher bytes match this CLI; not a registry/latest-version or native-host verification'
704
+ : 'Not verified against this CLI\'s packaged Node runtime; probe success cannot establish installation freshness'}`);
705
+ diagnostics.warnings.forEach(warning => writeCheckLine('warn', 'Install warning', `${installation.label}: ${warning}`));
706
+ if (diagnostics.status !== 'current') {
707
+ writeCheckLine('warn', 'Install next step', `Upgrade the OSuite CLI, then run osuite connect ${installation.runtime}; review preserved custom differences before replacing files. Disabled hooks remain disabled.`);
708
+ }
701
709
  const check = await runHookCheck({ projectRoot: process.cwd(), installation, shellEnv: SHELL_ENV });
702
- check.steps.forEach((step) => writeCheckLine(step.ok ? 'ok' : 'fail', step.label, `${installation.label}: ${step.detail}`));
710
+ check.steps.forEach((step) => writeCheckLine(step.ok ? 'ok' : step.warning ? 'warn' : 'fail', step.label, `${installation.label}: ${step.detail}`));
703
711
  (check.warnings || []).forEach((warning) => writeCheckLine('warn', 'Hook warning', `${installation.label}: ${warning}`));
704
712
  checks.push({ installation, ...check });
705
713
  }
@@ -1181,6 +1189,7 @@ async function doctor() {
1181
1189
 
1182
1190
  write(c('OSuite Doctor', `${ANSI.bold}${ANSI.cyan}`));
1183
1191
  write(c('Checking the local developer entry point.', ANSI.dim));
1192
+ write(c('Project diagnosis does not enumerate system-managed, plugin, or global hook copies.', ANSI.dim));
1184
1193
  write('');
1185
1194
 
1186
1195
  const credentialChecks = [...CLI_CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.identity.json`, `${file}.connect.json`, `${file}.connect.lock`]), MCP_MIGRATION_PATH, '.env']
@@ -1246,7 +1255,13 @@ async function doctor() {
1246
1255
  write(' export OSUITE_API_KEY=<workspace-api-key>');
1247
1256
  }
1248
1257
  hookChecks.filter((check) => !check.ok).forEach((check) => {
1249
- write(` ${check.installation.label} is not governed yet. Fix the FAIL line above, or run osuite connect ${check.installation.runtime} to reinstall, then run osuite doctor again.`);
1258
+ if (!check.installation.hostEnabled) {
1259
+ write(` ${check.installation.label} hooks remain disabled by project settings; doctor did not enable or reinstall anything.`);
1260
+ } else if (check.installation.diagnostics.canProbe === false && !check.installation.problems.length) {
1261
+ write(` ${check.installation.label} direct hook probe is not verified. Review the WARN lines above, then run osuite doctor again.`);
1262
+ } else {
1263
+ write(` ${check.installation.label} is not governed yet. Fix the FAIL line above, then run osuite doctor again.`);
1264
+ }
1250
1265
  });
1251
1266
  process.exitCode = 1;
1252
1267
  return false;
@@ -1255,6 +1270,7 @@ async function doctor() {
1255
1270
  write(c('Your OSuite CLI is ready.', ANSI.green));
1256
1271
  hookChecks.forEach((check) => {
1257
1272
  write(` ${check.installation.label} direct hook probe was governed and reached OSuite; verify host invocation after starting the runtime.`);
1273
+ if (check.installation.diagnostics.status !== 'current') write(` ${check.installation.label} installation freshness remains not verified; the probe does not certify a current Node installation.`);
1258
1274
  });
1259
1275
  return true;
1260
1276
  }
@@ -112,6 +112,7 @@ export function createStudioAuthority(config, journalPath) {
112
112
  reject(claimed ? 'OUTCOME_UNKNOWN' : 'CURRENT_AUTHORITY_UNAVAILABLE');
113
113
  } catch (error) {
114
114
  if (claimed) settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
115
+ if (!claimed && error?.name === 'OperationJournalError' && error.code === 'JOURNAL_BUSY') reject('JOURNAL_BUSY');
115
116
  throw error;
116
117
  }
117
118
  }
@@ -7,13 +7,41 @@ export const ADMISSION_PATH = 'studio-current-action';
7
7
  const unsafeKeys = new Set(['__proto__', 'prototype', 'constructor']);
8
8
  const id = value => safeId(value) && value.length <= 128;
9
9
 
10
+ const recoveryMessages = Object.freeze({
11
+ review_same_operation: 'Open the existing review URL. Resume with the same operation ID and unchanged arguments only after review; current authority is checked again. Status reads never execute the tool.',
12
+ read_business_result: 'This operation already completed. Read the original result from your application store; OSuite retains its digest, not the full output. Do not send the tool call again.',
13
+ reconcile_without_resend: 'Keep the operation ID and journal. Read the existing action and resource evidence with an authorized operator; an unknown or mismatched result is not proof that nothing executed. Do not resend.',
14
+ restore_connection: 'Restore the correct connection and current credentials, then read status for the same operation ID. Do not replace its ID or clear its journal to work around rejection.',
15
+ repair_journal: 'Preserve the journal and stop new sends. Ask an operator to inspect storage permissions, capacity and verified backups; never reinitialize a missing journal on the restart path.',
16
+ check_current_authority: 'Keep the same operation ID and arguments. A call must pass fresh authority checks before execution; this local status is not permission to execute.',
17
+ stop: 'This operation is denied, expired or cancelled. Stop and consult the policy owner. Changing its ID is not a way to bypass that decision.',
18
+ inspect_configuration: 'Check the supported runtime, input, mapping and connection configuration. Keep any existing operation ID and journal; do not automatically repeat a possibly sent call.',
19
+ });
20
+
21
+ function recoveryGuidance(code, state) {
22
+ let nextStep;
23
+ if (code === 'ALREADY_COMPLETED' || (state === 'completed' && code !== 'BINDING_MISMATCH')) nextStep = 'read_business_result';
24
+ else if (['OUTCOME_UNKNOWN', 'UNCERTAIN', 'BINDING_MISMATCH', 'CONFLICT'].includes(code)) nextStep = 'reconcile_without_resend';
25
+ else if (code?.startsWith('JOURNAL_')) nextStep = 'repair_journal';
26
+ else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = 'restore_connection';
27
+ else if (['POLICY_DENIED', 'APPROVAL_EXPIRED', 'CANCELLED'].includes(code)
28
+ || ['denied', 'expired', 'cancelled'].includes(state)) nextStep = 'stop';
29
+ else if (code === 'AWAITING_APPROVAL' || (!code && state === 'held')) nextStep = 'review_same_operation';
30
+ else if (['requesting', 'redeeming', 'dispatching', 'uncertain', 'uncertain_request', 'uncertain_redemption'].includes(state)) nextStep = 'reconcile_without_resend';
31
+ else if (!code && state === 'prepared') nextStep = 'check_current_authority';
32
+ else nextStep = 'inspect_configuration';
33
+ return Object.freeze({ nextStep, preserveOperationId: true, message: recoveryMessages[nextStep] });
34
+ }
35
+
10
36
  export class GovernedToolError extends Error {
11
37
  constructor(code, status = null) {
12
- super(`OSuite ${code}: no automatic repeat of this operation.`);
38
+ const recovery = recoveryGuidance(code, status?.state);
39
+ super(`OSuite ${code}: ${recovery.message}`);
13
40
  this.name = 'GovernedToolError';
14
41
  this.code = code;
15
- this.status = status;
42
+ this.status = status === null ? null : Object.freeze({ ...status, recovery });
16
43
  this.retryAutomatically = false;
44
+ this.recovery = recovery;
17
45
  }
18
46
  }
19
47
  export function reject(code, status) { throw new GovernedToolError(code, status); }
@@ -131,12 +159,12 @@ export function matchesStoredAction(payload, record, config) {
131
159
  } catch { return false; }
132
160
  }
133
161
 
134
- export function publicStatus(record, baseUrl) {
162
+ export function publicStatus(record, baseUrl, failureCode = null) {
135
163
  if (!record) return null;
136
164
  return Object.freeze({ operationId: record.operationId, actionId: record.actionId, state: record.state,
137
165
  resultDigest: record.resultDigest || null, reportState: record.reportState,
138
166
  reviewUrl: `${baseUrl}/approvals?action=${encodeURIComponent(record.actionId)}`,
139
167
  replayUrl: `${baseUrl}/replay/${encodeURIComponent(record.actionId)}`,
140
168
  admissionPath: ADMISSION_PATH, coverage: COVERAGE, retryAutomatically: false,
141
- resultRetained: false });
169
+ resultRetained: false, recovery: recoveryGuidance(failureCode, record.state) });
142
170
  }
@@ -140,6 +140,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
140
140
  reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
141
141
  }
142
142
  if (!journal.settle(scope, operationId, owner, admitted.phase, 'dispatching')) reject('OPERATION_BUSY', status(local(operationId)));
143
+ // Durable local I/O can outlive the admission, even without an await.
144
+ if (aborted() || closed || performance.now() - admitted.receivedAt > 5000) {
145
+ try { journal.settle(scope, operationId, owner, 'dispatching', 'uncertain'); }
146
+ catch { /* The committed dispatch fence still forbids replay if cleanup cannot write. */ }
147
+ reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
148
+ }
143
149
  let result, resultDigest = null, state = 'completed', thrown = false;
144
150
  try { result = await execute(invocation.params); }
145
151
  catch { thrown = true; state = 'uncertain'; }
@@ -177,7 +183,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
177
183
  const record = local(operationId);
178
184
  if (!record) return null;
179
185
  const observed = await authority.read(record);
180
- return Object.freeze({ ...status(record), remote: Object.freeze({ available: observed.available,
186
+ let failureCode = observed.mismatch ? 'BINDING_MISMATCH' : observed.available ? null : 'CURRENT_AUTHORITY_UNAVAILABLE';
187
+ // Refine held-call guidance without changing durable execution state.
188
+ if (!failureCode && record.state === 'held'
189
+ && (['blocked', 'denied', 'expired', 'cancelled'].includes(observed.action.status)
190
+ || ['denied', 'expired', 'cancelled'].includes(observed.body?.approval?.state))) failureCode = 'POLICY_DENIED';
191
+ return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), remote: Object.freeze({ available: observed.available,
181
192
  status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
182
193
  },
183
194
  close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
@@ -198,7 +198,7 @@ export class OperationJournal {
198
198
  const config = dataObject(options, ['maxOperations', 'busyTimeoutMs', 'create'], 'JOURNAL_CONFIG');
199
199
  const create = config.create === undefined ? true : config.create;
200
200
  this.#maxOperations = config.maxOperations === undefined ? 10000 : config.maxOperations;
201
- this.#busyTimeoutMs = config.busyTimeoutMs === undefined ? 100 : config.busyTimeoutMs;
201
+ this.#busyTimeoutMs = config.busyTimeoutMs === undefined ? 1000 : config.busyTimeoutMs;
202
202
  if (typeof create !== 'boolean' || !Number.isSafeInteger(this.#maxOperations) || this.#maxOperations < 1
203
203
  || !Number.isSafeInteger(this.#busyTimeoutMs) || this.#busyTimeoutMs < 0 || this.#busyTimeoutMs > 5000) fail('JOURNAL_CONFIG');
204
204
  if (typeof path !== 'string' || !isAbsolute(path) || path.length > 4096 || path.includes('\0')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.11.0",
3
+ "version": "2.11.2",
4
4
  "description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/projectHooks.js CHANGED
@@ -121,7 +121,10 @@ export function mergeHookSettings(existingText, templateText) {
121
121
  return existing;
122
122
  }
123
123
  migrated.push({ event, matcher: group.matcher, command: replacement.command });
124
- return { ...existing, ...replacement };
124
+ // Migrating a stock command is not consent to change its host failure policy.
125
+ const runtimeReplacement = { ...replacement };
126
+ delete runtimeReplacement.onFailure;
127
+ return { ...existing, ...runtimeReplacement };
125
128
  }) }));
126
129
  const present = next.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []));
127
130
  for (const group of Array.isArray(groups) ? groups : []) {
@@ -237,6 +240,7 @@ export function buildNodeRuntimeBootstrap(runtime, bootstrap = {}, { projectRoot
237
240
  files[`${directory}/hooks/osuite_${script}.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runHookCli } from '../runtime/hook.mjs';\nawait runHookCli({ host: ${literal(host)}, runtimeId: ${literal(runtimeId)}, installDir: fileURLToPath(new URL('..', import.meta.url)), event: ${literal(event)} });\n`;
238
241
  const absolute = path.join(path.resolve(projectRoot), directory, `hooks/osuite_${script}.mjs`);
239
242
  const handler = { type: 'command', command: `node ${shellQuote(absolute)}`, timeout: 60 };
243
+ if (host === 'claude' && event === 'PreToolUse') handler.onFailure = 'block';
240
244
  if (host === 'codex') handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"`;
241
245
  settings.hooks[event] = [{ hooks: [handler] }];
242
246
  }
@@ -608,13 +612,136 @@ function findCommand(settings, event, script, flat = false) {
608
612
  .find((hook) => typeof hook?.command === 'string' && hookScriptName(hook.command).replace(/\.(py|mjs)$/, '') === script.replace(/\.(py|mjs)$/, '')) || null;
609
613
  }
610
614
 
611
- /** OSuite hooks registered in this project, with anything that stops them from running. */
612
- export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIME_HOOKS)) {
615
+ function managedFileStatus(projectRoot, relativePath, expected) {
616
+ try {
617
+ let absolute = fs.realpathSync(projectRoot);
618
+ const parts = relativePath.split('/');
619
+ for (let index = 0; index < parts.length; index += 1) {
620
+ absolute = path.join(absolute, parts[index]);
621
+ const stat = fs.lstatSync(absolute);
622
+ if (stat.isSymbolicLink() || (index < parts.length - 1 ? !stat.isDirectory() : !stat.isFile())) return 'unverified';
623
+ if (index === parts.length - 1 && expected !== undefined && stat.size !== Buffer.byteLength(expected)) return 'different';
624
+ }
625
+ // Only callers' known managed paths reach here, never a path parsed from a command.
626
+ return expected === undefined || fs.readFileSync(absolute).equals(Buffer.from(expected)) ? 'current' : 'different';
627
+ } catch (error) {
628
+ return error.code === 'ENOENT' ? 'missing' : 'unverified';
629
+ }
630
+ }
631
+
632
+ function isManagedHookCommand(command, projectRoot, relativePath) {
633
+ if (typeof command !== 'string') return false;
634
+ const executable = relativePath.endsWith('.py') ? 'python3' : 'node';
635
+ const text = command.trim();
636
+ // Recognize the former stock Codex template without evaluating its substitution.
637
+ if (relativePath.startsWith('.codex/') && executable === 'python3'
638
+ && text === `python3 "$(git rev-parse --show-toplevel)/${relativePath}"`) return true;
639
+ if (!text.startsWith(`${executable} `)) return false;
640
+ const word = text.slice(executable.length + 1).trim();
641
+ let file;
642
+ if (word.startsWith("'") && word.endsWith("'")) {
643
+ file = word.slice(1, -1).replace(/'\\''/g, "'");
644
+ if (`'${file.replace(/'/g, "'\\''")}'` !== word) return false;
645
+ } else if (/^"[^"$`\\]*"$/.test(word)) file = word.slice(1, -1);
646
+ else if (/^[a-zA-Z0-9_./:@+-]+$/.test(word)) file = word;
647
+ else return false;
648
+ if (file === relativePath || file === `./${relativePath}`) return true;
649
+ const suffix = `${path.sep}${relativePath.split('/').join(path.sep)}`;
650
+ if (!path.isAbsolute(file) || !file.endsWith(suffix)) return false;
651
+ try {
652
+ // A project-root alias is still this installation; arbitrary script paths are not.
653
+ return fs.realpathSync(file.slice(0, -suffix.length) || path.parse(file).root) === fs.realpathSync(projectRoot);
654
+ } catch {
655
+ return false;
656
+ }
657
+ }
658
+
659
+ function diagnoseHookInstallation(projectRoot, installation, registered) {
660
+ const spec = RUNTIME_HOOKS[installation.runtime];
661
+ const warnings = [];
662
+ const files = [];
663
+ const registrations = [];
664
+ let canProbe = Boolean(installation.pretool);
665
+ let bundle;
666
+ try {
667
+ bundle = buildNodeRuntimeBootstrap(installation.runtime, {}, { projectRoot });
668
+ } catch {
669
+ warnings.push('Packaged Node runtime could not be read; installation freshness is not verified');
670
+ canProbe = false;
671
+ }
672
+ const expectedSettings = bundle && JSON.parse(bundle.files[bundle.node_runtime.settings_path]);
673
+ const hasNode = registered.some(hook => hookScriptName(hook.command).endsWith('.mjs'));
674
+ if (hasNode && bundle) {
675
+ for (const [relativePath, expected] of Object.entries(bundle.files)) {
676
+ if (!relativePath.startsWith(`${spec.dir}/runtime/`) && !relativePath.startsWith(`${spec.dir}/hooks/`)) continue;
677
+ const status = managedFileStatus(projectRoot, relativePath, expected);
678
+ files.push({ relativePath, status });
679
+ if (status !== 'current') {
680
+ canProbe = false;
681
+ warnings.push(status === 'different'
682
+ ? `${relativePath} differs from this CLI's packaged Node bytes (outdated or customized); not verified`
683
+ : status === 'missing' ? `${relativePath} is missing; not verified`
684
+ : `${relativePath} is a symlink, not a regular managed file, or unreadable; not verified`);
685
+ }
686
+ }
687
+ }
688
+ for (const hook of registered) {
689
+ const script = hookScriptName(hook.command);
690
+ const relativePath = `${spec.dir}/hooks/${script}`;
691
+ const legacy = script.endsWith('.py');
692
+ const expected = expectedSettings && eventHooks(expectedSettings, hook.event, spec.flatHooks)
693
+ .find(item => hookScriptName(item.command).replace(/\.mjs$/, '') === script.replace(/\.(py|mjs)$/, ''));
694
+ const recognized = Boolean(expected) && ['command', undefined].includes(hook.type)
695
+ && isManagedHookCommand(hook.command, projectRoot, relativePath)
696
+ && (hook.commandWindows === undefined || hook.commandWindows === expected.commandWindows
697
+ || isManagedHookCommand(hook.commandWindows, projectRoot, relativePath));
698
+ const status = recognized ? legacy ? 'legacy' : 'current' : 'unverified';
699
+ registrations.push({ settingsPath: hook.settingsPath, event: hook.event, command: hook.command, status });
700
+ const location = `${hook.settingsPath} ${hook.event}`;
701
+ if (installation.runtime === 'claude' && hook.event === 'PreToolUse' && hook.onFailure !== 'block') {
702
+ warnings.push(`${location} lacks onFailure: 'block'; native crashes/timeouts may fail open. Review explicitly: this option requires Claude Code 2.1.295 or newer; installed host version support is not verified. Existing settings were preserved.`);
703
+ }
704
+ if (legacy) warnings.push(`${location} registers legacy Python ${script}; current Node version is not verified`);
705
+ if (!recognized) {
706
+ canProbe = false;
707
+ warnings.push(`${location}: custom path or unrecognized command for ${script} was preserved; not verified and will not be executed by doctor`);
708
+ } else if (legacy && managedFileStatus(projectRoot, relativePath) !== 'current') {
709
+ // The direct probe invokes pre/post only; legacy Stop/Session gaps remain warnings.
710
+ if ([spec.preEvent || 'PreToolUse', spec.postEvent || 'PostToolUse'].includes(hook.event)) canProbe = false;
711
+ warnings.push(`${relativePath} is missing or is not a regular managed file; legacy installation is not verified`);
712
+ }
713
+ }
714
+ const byEvent = new Map();
715
+ for (const hook of registrations) {
716
+ const key = `${hook.event}:${hookScriptName(hook.command).replace(/\.(py|mjs)$/, '')}`;
717
+ if (!byEvent.has(key)) byEvent.set(key, []);
718
+ byEvent.get(key).push(hook);
719
+ }
720
+ for (const group of byEvent.values()) {
721
+ if (group.length < 2) continue;
722
+ canProbe = false;
723
+ warnings.push(`Duplicate ${group[0].event} registrations were preserved in ${group.map(hook => hook.settingsPath).join(', ')}; not verified as a single invocation, even while disabled`);
724
+ }
725
+ if (hasNode && expectedSettings) {
726
+ for (const event of Object.keys(expectedSettings.hooks)) {
727
+ if (!registrations.some(hook => hook.event === event)) warnings.push(`No packaged ${event} registration found; the complete Node installation is not verified`);
728
+ }
729
+ }
730
+ return { status: hasNode && !warnings.length ? 'current' : 'not_verified', canProbe, registrations, files, warnings };
731
+ }
732
+
733
+ /**
734
+ * OSuite hooks registered in this project, with anything that stops them from running.
735
+ * Opt-in diagnosis adds read-only byte/registration checks without changing the legacy
736
+ * inventory shape. It compares this CLI's package, not registry or global/plugin copies.
737
+ */
738
+ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIME_HOOKS), { diagnose = false } = {}) {
613
739
  return runtimes.flatMap((runtime) => {
614
740
  const spec = RUNTIME_HOOKS[runtime];
615
741
  if (!spec) return [];
616
742
  const problems = [];
617
743
  const disabledReasons = [];
744
+ const registrations = [];
618
745
  let pretoolCount = 0;
619
746
  let posttoolCount = 0;
620
747
  let pretool = null;
@@ -629,8 +756,18 @@ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIM
629
756
  problems.push(`${settingsPath} is not valid JSON, so ${spec.label} cannot load its hooks`);
630
757
  return;
631
758
  }
759
+ if (!isPlainObject(settings)) {
760
+ problems.push(`${settingsPath} must contain a JSON object, so ${spec.label} cannot load its hooks`);
761
+ return;
762
+ }
632
763
  disabledHookSettings(settings).forEach((reason) => disabledReasons.push(`${settingsPath}: ${runtime === 'cursor'
633
764
  ? 'explicit disableAllHooks intent was preserved; this is not a documented Cursor host control' : reason}`));
765
+ if (diagnose) {
766
+ for (const event of Object.keys(settings.hooks || {})) {
767
+ eventHooks(settings, event, spec.flatHooks).filter(hook => typeof hook?.command === 'string' && hookScriptName(hook.command))
768
+ .forEach(hook => registrations.push({ ...hook, settingsPath, event }));
769
+ }
770
+ }
634
771
  const preEvent = spec.preEvent || 'PreToolUse', postEvent = spec.postEvent || 'PostToolUse';
635
772
  const pre = findCommand(settings, preEvent, 'osuite_pretool.py', spec.flatHooks);
636
773
  const post = findCommand(settings, postEvent, 'osuite_posttool.py', spec.flatHooks);
@@ -665,8 +802,10 @@ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIM
665
802
  });
666
803
  }
667
804
  }
668
- return [{ runtime, label: spec.label, installDir: spec.dir, pretool, posttool,
669
- hostEnabled: disabledReasons.length === 0, disabledReasons, problems: [...problems, ...disabledReasons] }];
805
+ const installation = { runtime, label: spec.label, installDir: spec.dir, pretool, posttool,
806
+ hostEnabled: disabledReasons.length === 0, disabledReasons, problems: [...problems, ...disabledReasons] };
807
+ if (diagnose) installation.diagnostics = diagnoseHookInstallation(projectRoot, installation, registrations);
808
+ return [installation];
670
809
  });
671
810
  }
672
811
 
@@ -793,6 +932,12 @@ export async function runHookCheck({
793
932
  state.hostEnabled = true;
794
933
  steps.push({ label: 'Host hooks enabled', ok: true, detail: 'project settings permit hooks; actual host invocation is not verified by this direct probe' });
795
934
 
935
+ if (installation.diagnostics?.canProbe === false) {
936
+ steps.push({ label: 'Hook probe', ok: false, warning: true,
937
+ detail: 'Not verified: direct probe skipped because installation bytes or registered commands need review; nothing was reinstalled or enabled' });
938
+ return result(false);
939
+ }
940
+
796
941
  const credentials = hookCredentials(projectRoot, installation, shellEnv);
797
942
  if (!credentials.baseUrl || !credentials.apiKey) {
798
943
  return fail('Hook credentials', `OSUITE_BASE_URL and OSUITE_API_KEY are not set in ${credentials.envFile} or the shell; governance cannot be verified`);
@@ -1,5 +1,5 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
- import { canonicalJson, isObject, safeId, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
2
+ import { canonicalJson, isObject, isTransientFailure, safeId, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
3
3
 
4
4
  export const REVIEW_DECISIONS = new Set(['require_approval', 'require_dual_approval']);
5
5
  const DECISIONS = new Set(['allow', 'warn', 'block', ...REVIEW_DECISIONS]);
@@ -142,9 +142,11 @@ function installCheck(payload, context) {
142
142
  export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(), beforeRelease = async () => true } = {}) {
143
143
  const guard = await api.request('POST', '/api/guard', context);
144
144
  if (!guard.ok) {
145
- const failOpen = config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY && !config.ruleRollout?.enabled
146
- && config.guardFailureMode === 'allow' && ![401, 403, 409].includes(guard.status)
147
- && !['signing_unavailable', 'invalid_response', 'invalid_request'].includes(guard.error);
145
+ // Rejection, bad evidence and unknown errors are not availability failures.
146
+ if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status });
147
+ const failOpen = ['observe', 'enforce'].includes(config.mode)
148
+ && config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY && !config.ruleRollout?.enabled
149
+ && config.guardFailureMode === 'allow';
148
150
  return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
149
151
  }
150
152
  const requestedDecision = guard.body?.decision;
@@ -155,13 +157,18 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
155
157
  if (requestedDecision === 'block') {
156
158
  // Observation still persists the would-block result, but never calls it authority.
157
159
  const observeOnly = config.mode === 'observe' && !rollout.binding;
158
- if (observeOnly) await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
160
+ if (observeOnly) {
161
+ const recorded = await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
162
+ if (!recorded.ok && (!isTransientFailure(recorded) || config.guardFailureMode !== 'allow')) {
163
+ return closed('admission_unconfirmed', { rejectedStatus: recorded.status });
164
+ }
165
+ }
159
166
  return finish({ ...closed('policy_block'), observeOnly, response: guard.body });
160
167
  }
161
168
  const created = await api.request('POST', '/api/actions', {
162
169
  ...context, status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running',
163
170
  });
164
- if (!created.ok) return closed('admission_unconfirmed');
171
+ if (!created.ok) return closed('admission_unconfirmed', { rejectedStatus: created.status });
165
172
  if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
166
173
  const diagnostic = installCheck(created.body, context);
167
174
  if (diagnostic) return finish(diagnostic);
@@ -180,7 +187,7 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
180
187
  timeoutMs: Math.max(1, Math.min(2500, deadline - now())),
181
188
  });
182
189
  if (!polled.ok) {
183
- if ([401, 403].includes(polled.status)) return closed('approval_access_rejected', { actionId: expected.actionId });
190
+ if ([401, 403, 409].includes(polled.status)) return closed('approval_access_rejected', { actionId: expected.actionId, rejectedStatus: polled.status });
184
191
  continue;
185
192
  }
186
193
  const action = polled.body?.action || polled.body;
@@ -199,7 +206,7 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
199
206
  }
200
207
  // GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
201
208
  const current = await api.request('POST', '/api/actions', { ...context, status: 'running' });
202
- if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId });
209
+ if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId, rejectedStatus: current.status });
203
210
  if (!rolloutAuthority(current.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
204
211
  result = finish(actionAdmission(current.body, 'allow', context, expected));
205
212
  if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
@@ -42,7 +42,7 @@ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claud
42
42
  baseUrl: get('BASE_URL').replace(/\/+$/, ''), apiKey: get('API_KEY'),
43
43
  privateKeyBase64: get('PRIVATE_KEY_BASE64').trim(),
44
44
  signatureMode: get('SIGNATURE_MODE', hardened ? 'required' : 'workspace_key_optional'),
45
- mode, guardFailureMode: mode === 'strict' ? 'block' : (get('GUARD_FAILURE_MODE', hardened ? 'block' : 'allow') === 'allow' ? 'allow' : 'block'),
45
+ mode, guardFailureMode: mode === 'strict' ? 'block' : (get('GUARD_FAILURE_MODE', 'block') === 'allow' ? 'allow' : 'block'),
46
46
  requireAssumptionCapture: get('REQUIRE_ASSUMPTION_CAPTURE') === 'true',
47
47
  approvalTimeoutSeconds: number('APPROVAL_TIMEOUT_SECONDS', 300, 1, 3600),
48
48
  approvalWaitMs: number('APPROVAL_WAIT_SECONDS', 30, 0, 40) * 1000,
package/runtime/hook.mjs CHANGED
@@ -2,13 +2,14 @@ import { randomUUID } from 'node:crypto';
2
2
  import { createApiClient, isObject, safeId } from './protocol.mjs';
3
3
  import { createStateStore } from './state.mjs';
4
4
  import { loadRuntimeConfig } from './config.mjs';
5
- import { resolveRemotePosture } from './posture.mjs';
5
+ import { captureRejectionFence, invalidatePostureCache, rejectionFenceUnchanged, resolveRemotePosture } from './posture.mjs';
6
6
  import { buildActionContext, deriveSessionId } from './context.mjs';
7
7
  import { admitAction, cavaFingerprint, matchesAction } from './admission.mjs';
8
8
  import { recordOutcome } from './outcome.mjs';
9
9
  import { validateGitPublication } from './git.mjs';
10
10
 
11
11
  const note = message => ({ exitCode: 0, stdout: message ? { systemMessage: `[OSuite] ${message}` } : {}, stderr: '' });
12
+ const accessChanged = 'Runtime access changed during this request. No execution is authorized. Do not retry automatically; reconcile in Studio.';
12
13
  export function deny(message) {
13
14
  const reason = `[OSuite] ${message}`;
14
15
  return { exitCode: 2, stderr: reason, stdout: { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } } };
@@ -20,6 +21,15 @@ export function applyPosture(config, posture) {
20
21
  requireAssumptionCapture: posture.require_assumption_capture, approvalTimeoutSeconds: posture.approval_timeout_seconds };
21
22
  }
22
23
 
24
+ export function trackPostureRejections(api, config, store, now = Date.now) {
25
+ return { request: async (...args) => {
26
+ const response = await api.request(...args);
27
+ // These requests use the same credential, including observational reads and outcome telemetry.
28
+ if ([401, 403, 409].includes(response.status)) invalidatePostureCache(config, store, now());
29
+ return response;
30
+ } };
31
+ }
32
+
23
33
  export async function emitRuntimeEvent(api, config, context, eventType, actionId = null, payload = {}) {
24
34
  return api.request('POST', `/api/runtime-sessions/${encodeURIComponent(context.runtime_session_id)}/events`, {
25
35
  event_id: `evt_${randomUUID()}`, runtime_session_id: context.runtime_session_id, event_type: eventType,
@@ -73,16 +83,18 @@ function updatePending(store, context, entry = null) {
73
83
  else store.remove(key);
74
84
  }
75
85
 
76
- async function stopHook(data, config, api, store) {
86
+ async function stopHook(data, config, api, store, fenceUnchanged) {
77
87
  const session = deriveSessionId(data, config), key = `pending:${session}`;
78
88
  const saved = store.read(key);
79
89
  if (!Array.isArray(saved) || !saved.length) return note();
80
90
  const retained = [], decided = [];
81
91
  const deadline = performance.now() + 3000;
82
92
  for (const entry of saved) {
93
+ if (!fenceUnchanged()) return note(accessChanged);
83
94
  if (!safeId(entry.action_id)) continue;
84
95
  if (performance.now() >= deadline) { retained.push(entry); continue; }
85
96
  const response = await api.request('GET', `/api/actions/${encodeURIComponent(entry.action_id)}`, undefined, { timeoutMs: Math.max(1, deadline - performance.now()) });
97
+ if ([401, 403, 409].includes(response.status) || !fenceUnchanged()) return note(accessChanged);
86
98
  if (!response.ok) { retained.push(entry); continue; }
87
99
  const action = response.body?.action || response.body;
88
100
  if (!matchesAction(response.body, entry, { actionId: entry.action_id, fingerprint: entry.fingerprint })) {
@@ -95,7 +107,9 @@ async function stopHook(data, config, api, store) {
95
107
  decided.push('A held action has an uncertain execution outcome. Do not retry automatically; reconcile its action/replay in Studio.');
96
108
  } else decided.push('A held action was denied, expired, or closed. Do not retry automatically; tell the user.');
97
109
  }
110
+ if (!fenceUnchanged()) return note(accessChanged);
98
111
  if (retained.length) store.write(key, retained); else store.remove(key);
112
+ if (!fenceUnchanged()) { store.write(key, saved); return note(accessChanged); }
99
113
  if (decided.length && !data.stop_hook_active) return { exitCode: 0, stderr: '', stdout: { decision: 'block', reason: `[OSuite] ${decided.join(' ')}` } };
100
114
  return note(decided.join(' ') || 'An action is still held for human review. No tool was executed by this hook.');
101
115
  }
@@ -112,33 +126,43 @@ export async function runHook(data, localConfig, dependencies = {}) {
112
126
  const apiFactory = dependencies.apiFactory || createApiClient;
113
127
  let api = dependencies.api || apiFactory(localConfig);
114
128
  if (event === 'PostToolUse' || event === 'PostToolUseFailure') {
115
- const result = await recordOutcome(localConfig, data, { api, store, now });
116
- return note(result.reason ? 'Tool outcome is not yet acknowledged. Evidence was retained; do not repeat the side effect.' : '');
129
+ const fence = captureRejectionFence(localConfig, store);
130
+ const result = await recordOutcome(localConfig, data, { api: trackPostureRejections(api, localConfig, store, now), store, now });
131
+ return note(result.reason ? 'Tool outcome is not yet acknowledged. Evidence was retained; do not repeat the side effect.'
132
+ : rejectionFenceUnchanged(localConfig, store, fence) === true ? '' : accessChanged);
117
133
  }
118
134
  const remote = await resolveRemotePosture(localConfig, { api, store, now: now() });
135
+ const fence = remote.rejectionFence;
136
+ const fenceUnchanged = () => rejectionFenceUnchanged(localConfig, store, fence) === true;
137
+ const checkedNote = message => fenceUnchanged() ? note(message) : pre ? deny(accessChanged) : note(accessChanged);
119
138
  const config = { ...applyPosture(localConfig, remote.posture), ruleRollout: remote.ruleRollout,
120
139
  orgId: remote.orgId || localConfig.orgId };
121
- api = dependencies.api || apiFactory(config);
122
- if (event === 'Stop') return stopHook(data, config, api, store);
140
+ api = trackPostureRejections(dependencies.api || apiFactory(config), localConfig, store, now);
141
+ if (event === 'Stop') {
142
+ const stopped = await stopHook(data, config, api, store, fenceUnchanged);
143
+ return fenceUnchanged() ? stopped : note(accessChanged);
144
+ }
123
145
  if (remote.blocked) return pre ? deny('Verified runtime posture is unavailable or expired. Execution is blocked; reconnect or restore access.')
124
146
  : note('Verified runtime posture is unavailable. Enforce hooks will block execution until it can be verified.');
125
147
  if (!pre && event !== 'SessionStart' && event !== 'SessionEnd') return note('Unsupported hook event; no execution decision was made.');
126
148
  const session = await openSession(api, config, data, store, now());
149
+ if (!fenceUnchanged()) return pre ? deny(accessChanged) : note(accessChanged);
127
150
  if (!pre) {
128
151
  await emitRuntimeEvent(api, config, { runtime_session_id: session }, event === 'SessionStart' ? 'session_started' : 'session_ended');
129
- return note(remote.available ? '' : 'Observe mode is active without verified remote posture. This is not governance authorization.');
152
+ return checkedNote(remote.available ? '' : 'Observe mode is active without verified remote posture. This is not governance authorization.');
130
153
  }
131
154
  const context = { ...initialContext, tool_name: data.tool_name };
132
155
  if (!remote.available) {
133
156
  rememberGap(store, 'posture_unavailable', now());
134
- return note('Not governed: remote posture is unavailable; explicit observe mode does not enforce OSuite policy.');
157
+ return checkedNote('Not governed: remote posture is unavailable; explicit observe mode does not enforce OSuite policy.');
135
158
  }
136
159
  await emitRuntimeEvent(api, config, context, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest, install_check: config.installCheck === true });
160
+ if (!fenceUnchanged()) return deny(accessChanged);
137
161
  const result = await admitAction(context, { api, config, ...dependencies.admission, beforeRelease: response => validateGitPublication(context, response) });
138
162
  if (result.degraded) {
139
163
  rememberGap(store, result.reason, now());
140
164
  await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, { decision: result.decision === 'allow' ? 'guard_unavailable' : 'guard_unavailable_blocked' });
141
- return result.decision === 'allow' ? note('Not governed: the guard is unavailable and this verified posture explicitly allows availability fallback. No authorization or completion is claimed.')
165
+ return result.decision === 'allow' ? checkedNote('Not governed: the guard is unavailable and this verified posture explicitly allows availability fallback. No authorization or completion is claimed.')
142
166
  : deny('Guard unavailable. Verified policy requires blocking this call.');
143
167
  }
144
168
  await flushGap(api, config, context, store);
@@ -154,17 +178,17 @@ export async function runHook(data, localConfig, dependencies = {}) {
154
178
  } catch { return deny('Cannot persist the exact-action receipt state. The admitted tool was not released; reconcile its action in Studio before retrying.'); }
155
179
  updatePending(store, context);
156
180
  await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.decision, install_check: config.installCheck === true });
157
- return note(config.mode === 'observe' && !result.ruleRolloutBinding ? 'Observe mode recorded a policy result; it does not enforce OSuite policy.' : result.decision === 'warn' ? 'OSuite authorized this call with a policy warning.' : '');
181
+ return checkedNote(config.mode === 'observe' && !result.ruleRolloutBinding ? 'Observe mode recorded a policy result; it does not enforce OSuite policy.' : result.decision === 'warn' ? 'OSuite authorized this call with a policy warning.' : '');
158
182
  }
159
183
  if (result.decision === 'require_approval') {
160
184
  if (result.observeOnly !== true) updatePending(store, context, { action_id: result.actionId, agent_id: config.agentId,
161
185
  runtime_session_id: session, tool_input_digest: context.tool_input_digest, fingerprint: cavaFingerprint(result.response) });
162
186
  await emitRuntimeEvent(api, config, context, 'tool_requires_approval', result.actionId, { decision: result.observeOnly === true ? 'observe_would_require_approval' : result.response?.decision?.decision || 'require_approval' });
163
- return result.observeOnly === true ? note('Observe mode: this call would require human approval; it is not authorized by a reviewer.')
187
+ return result.observeOnly === true ? checkedNote('Observe mode: this call would require human approval; it is not authorized by a reviewer.')
164
188
  : deny(`Human approval is still required for action ${result.actionId}. Do not run or automatically retry it. Review it in OSuite Studio.`);
165
189
  }
166
190
  await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: result.observeOnly === true ? 'observe_would_block' : 'block', reason: result.reason });
167
- return result.observeOnly === true ? note('Observe mode: OSuite policy would block this call. It is not authorized by OSuite.')
191
+ return result.observeOnly === true ? checkedNote('Observe mode: OSuite policy would block this call. It is not authorized by OSuite.')
168
192
  : deny(`OSuite policy did not authorize this exact action (${result.reason}). Do not retry automatically.`);
169
193
  } catch {
170
194
  return pre ? deny('Hook evidence or state is invalid. Execution is blocked; no successful admission is claimed.')
package/runtime/mcp.mjs CHANGED
@@ -3,8 +3,8 @@ import { setTimeout as delay } from 'node:timers/promises';
3
3
  import { createApiClient, isObject, safeId, sha256 } from './protocol.mjs';
4
4
  import { loadRuntimeConfig } from './config.mjs';
5
5
  import { createStateStore } from './state.mjs';
6
- import { resolveRemotePosture } from './posture.mjs';
7
- import { applyPosture, emitRuntimeEvent, openSession } from './hook.mjs';
6
+ import { rejectionFenceUnchanged, resolveRemotePosture } from './posture.mjs';
7
+ import { applyPosture, emitRuntimeEvent, openSession, trackPostureRejections } from './hook.mjs';
8
8
  import { buildActionContext } from './context.mjs';
9
9
  import { admitAction, cavaFingerprint, matchesAction } from './admission.mjs';
10
10
  import { validateGitPublication } from './git.mjs';
@@ -39,13 +39,17 @@ export function createMcpServer(localConfig, dependencies = {}) {
39
39
  let sessionId = `sess_${randomUUID()}`;
40
40
  const ensureStore = () => (store ||= createStateStore(localConfig));
41
41
  const baseApi = () => dependencies.api || createApiClient(localConfig);
42
+ const fenceUnchanged = active => rejectionFenceUnchanged(localConfig, ensureStore(), active.fence) === true;
43
+ const accessChanged = () => failure('Runtime access changed during this request. No execution is authorized. Do not retry automatically; reconcile in Studio.');
44
+ const checkedResult = (active, data, error = false) => fenceUnchanged(active) ? result(data, error) : accessChanged();
42
45
 
43
46
  async function current() {
44
47
  const remote = await resolveRemotePosture(localConfig, { api: baseApi(), store: ensureStore(), now: Date.now() });
48
+ const fence = remote.rejectionFence;
45
49
  if (!remote.available || remote.blocked) return null;
46
50
  const config = applyPosture(localConfig, remote.posture);
47
51
  if (config.signatureMode === 'required' && !config.privateKeyBase64) return null;
48
- return { config, api: dependencies.api || createApiClient(config) };
52
+ return { config, fence, api: trackPostureRejections(dependencies.api || createApiClient(config), localConfig, store) };
49
53
  }
50
54
 
51
55
  async function complete(args, state, { api, config }) {
@@ -79,7 +83,6 @@ export function createMcpServer(localConfig, dependencies = {}) {
79
83
  || response.body.event.payload?.status !== args.status || response.body.event.payload?.outcome_source !== 'mcp_caller_report') {
80
84
  return result({ recorded: false, action_id: args.action_id, message: 'Outcome event acknowledgement is pending. Do not repeat the side effect.' }, true);
81
85
  }
82
- store.remove(key);
83
86
  return result({ recorded: true, action_id: args.action_id, status: args.status, outcome_source: 'mcp_caller_report' });
84
87
  }
85
88
 
@@ -93,43 +96,56 @@ export function createMcpServer(localConfig, dependencies = {}) {
93
96
  const active = await current();
94
97
  if (!active) return failure('Verified runtime posture or required signing is unavailable; no execution is authorized.');
95
98
  const { api, config } = active;
96
- if (name === 'osuite_complete_action') return complete(args, state, active);
99
+ if (!fenceUnchanged(active)) return accessChanged();
100
+ if (name === 'osuite_complete_action') {
101
+ const completed = await complete(args, state, active);
102
+ if (completed.structuredContent.recorded !== true) return completed;
103
+ if (!fenceUnchanged(active)) return accessChanged();
104
+ const key = `mcp:${args.action_id}`;
105
+ store.remove(key);
106
+ if (!fenceUnchanged(active)) { store.write(key, state); return accessChanged(); }
107
+ return completed;
108
+ }
97
109
  if (name === 'osuite_record_assumption') {
98
110
  if (typeof args.assumption !== 'string' || !args.assumption.trim() || args.assumption.length > 4000) return failure('A bounded assumption is required.');
99
111
  const response = await api.request('POST', '/api/assumptions', { action_id: args.action_id, assumption: args.assumption,
100
112
  basis: typeof args.basis === 'string' ? args.basis.slice(0, 1000) : 'MCP caller statement', validated: false });
101
113
  if (!response.ok || !isObject(response.body?.assumption)) return failure('Assumption acknowledgement is pending.');
102
114
  await emitRuntimeEvent(api, config, state.context, 'assumption_recorded', args.action_id, { source: 'mcp_caller_report' });
103
- return result({ action_id: args.action_id, recorded: true, validated: false });
115
+ return checkedResult(active, { action_id: args.action_id, recorded: true, validated: false });
104
116
  }
105
117
  if (name === 'osuite_wait_for_approval') {
106
118
  const requested = Number(args.timeout_seconds ?? 30);
107
119
  const deadline = performance.now() + (Number.isFinite(requested) ? Math.max(0, Math.min(40, requested)) * 1000 : 0);
108
120
  do {
121
+ if (!fenceUnchanged(active)) return accessChanged();
109
122
  const response = await api.request('GET', `/api/actions/${encodeURIComponent(args.action_id)}`, undefined, { timeoutMs: 2000 });
110
- if ([401, 403].includes(response.status)) return failure('Approval access was rejected.');
123
+ if ([401, 403, 409].includes(response.status)) return failure('Approval access was rejected. Do not retry automatically; reconcile in Studio.');
124
+ if (!fenceUnchanged(active)) return accessChanged();
111
125
  if (response.ok) {
112
126
  const action = response.body?.action || response.body;
113
127
  if (!matchesAction(response.body, state.context, { actionId: args.action_id, fingerprint: state.fingerprint })) return failure('Approval evidence no longer matches the held tool input.');
114
128
  if (action.status === 'running') {
115
129
  const observed = Boolean(action.approved_by || action.approved_at) && action.approval_redeemed_at == null && action.timestamp_end == null;
116
- return result({ action_id: args.action_id, approved: false, approval_observed: observed, authorized: false, status: 'running',
130
+ return checkedResult(active, { action_id: args.action_id, approved: false, approval_observed: observed, authorized: false, status: 'running',
117
131
  message: observed ? 'Submit exactly the same tool input through osuite_preflight_action again. A GET does not redeem a grant or authorize execution.'
118
132
  : 'The outcome may be unknown or already consumed. Do not retry automatically; reconcile in Studio.' });
119
133
  }
120
- if (action.status !== 'pending_approval') return result({ action_id: args.action_id, approved: false, authorized: false, status: action.status, message: 'The held request is closed. Do not retry automatically.' });
134
+ if (action.status !== 'pending_approval') return checkedResult(active, { action_id: args.action_id, approved: false, authorized: false, status: action.status, message: 'The held request is closed. Do not retry automatically.' });
121
135
  }
122
136
  if (performance.now() >= deadline) break;
123
137
  await delay(Math.min(3000, deadline - performance.now()));
124
138
  } while (performance.now() < deadline);
125
- return result({ action_id: args.action_id, approved: false, authorized: false, status: 'timeout', message: 'Still held; do not execute this call.' });
139
+ return checkedResult(active, { action_id: args.action_id, approved: false, authorized: false, status: 'timeout', message: 'Still held; do not execute this call.' });
126
140
  }
127
141
  await openSession(api, config, { session_id: sessionId }, store);
128
- if (name === 'osuite_begin_session') return result({ runtime_session_id: sessionId, runtime_adapter_id: config.runtimeId, mode: config.mode, guard_failure_mode: config.guardFailureMode, coverage: COVERAGE });
142
+ if (!fenceUnchanged(active)) return accessChanged();
143
+ if (name === 'osuite_begin_session') return checkedResult(active, { runtime_session_id: sessionId, runtime_adapter_id: config.runtimeId, mode: config.mode, guard_failure_mode: config.guardFailureMode, coverage: COVERAGE });
129
144
  if (name === 'osuite_end_session') {
130
145
  await emitRuntimeEvent(api, config, { runtime_session_id: sessionId }, 'session_ended', null, { source: 'mcp_caller_report' });
146
+ if (!fenceUnchanged(active)) return accessChanged();
131
147
  const ended = sessionId; sessionId = `sess_${randomUUID()}`;
132
- return result({ ended_runtime_session_id: ended });
148
+ return checkedResult(active, { ended_runtime_session_id: ended });
133
149
  }
134
150
  if (typeof args.action_type !== 'string' || !args.action_type || args.action_type.length > 128 || typeof args.declared_goal !== 'string' || !args.declared_goal || args.declared_goal.length > 2000 || !Object.hasOwn(args, 'tool_input')) return failure('A bounded action_type, declared_goal and complete tool_input are required.');
135
151
  const data = { session_id: sessionId, tool_name: args.tool_name, tool_input: args.tool_input, tool_use_id: args.tool_use_id || `tool_${randomUUID()}` };
@@ -139,6 +155,7 @@ export function createMcpServer(localConfig, dependencies = {}) {
139
155
  if (args.reversible === false) context.reversible = false;
140
156
  const eventContext = { ...context, tool_name: args.tool_name };
141
157
  await emitRuntimeEvent(api, config, eventContext, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest, source: 'mcp_bridge' });
158
+ if (!fenceUnchanged(active)) return accessChanged();
142
159
  const admitted = await admitAction(context, { api, config: { ...config, approvalWaitMs: 0 }, beforeRelease: response => validateGitPublication(context, response) });
143
160
  if (admitted.actionId && (admitted.authorized || admitted.decision === 'require_approval')) {
144
161
  const key = `mcp:${admitted.actionId}`;
@@ -149,7 +166,7 @@ export function createMcpServer(localConfig, dependencies = {}) {
149
166
  }
150
167
  const eventType = admitted.degraded ? 'governance_unavailable' : admitted.authorized ? 'tool_allowed' : admitted.decision === 'require_approval' ? 'tool_requires_approval' : 'tool_blocked';
151
168
  await emitRuntimeEvent(api, config, eventContext, eventType, admitted.actionId, { decision: admitted.degraded ? 'guard_unavailable' : admitted.decision, source: 'mcp_bridge' });
152
- return result({ decision: admitted.decision, authorized: admitted.authorized === true && config.mode !== 'observe',
169
+ return checkedResult(active, { decision: admitted.decision, authorized: admitted.authorized === true && config.mode !== 'observe',
153
170
  action_id: admitted.actionId || null, runtime_session_id: sessionId, coverage: COVERAGE,
154
171
  ...(admitted.degraded ? { degraded: true } : {}),
155
172
  message: admitted.authorized ? 'Current policy admitted this exact input. This bridge did not execute it.' : 'No execution is authorized. Review the action in Studio; do not retry automatically.',
@@ -1,5 +1,5 @@
1
- import { createHmac, timingSafeEqual } from 'node:crypto';
2
- import { canonicalJson, isObject, safeId, sha256, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
1
+ import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { canonicalJson, isObject, isTransientFailure, safeId, sha256, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
3
3
 
4
4
  export const POSTURE_SCHEMA = 'osuite.runtime_posture.v1';
5
5
  const MAX_FRESHNESS_MS = 300000;
@@ -100,24 +100,91 @@ function configurationOnly(document) {
100
100
  ].map(key => [key, document[key]]));
101
101
  }
102
102
 
103
- function mac(document, config) {
104
- return createHmac('sha256', config.apiKey || '').update('osuite.posture-cache.v1\n').update(canonicalJson(document)).digest('hex');
103
+ function mac(document, config, generation = 0, rejected = false, fenceId = null) {
104
+ const hash = createHmac('sha256', config.apiKey || '').update('osuite.posture-cache.v1\n').update(canonicalJson(document));
105
+ if (generation > 0) hash.update(`\nrejection-generation:${generation}:${rejected}`);
106
+ if (fenceId !== null) hash.update(`\nrejection-fence:${fenceId}`);
107
+ return hash.digest('hex');
105
108
  }
106
109
 
107
- function cachedDocument(value, config, now) {
110
+ function cacheEntry(value, config, now) {
108
111
  try {
109
- if (!isObject(value) || !validDocument(value.document, config, now, true) || !/^[a-f0-9]{64}$/.test(value.mac)) return null;
110
- if (!timingSafeEqual(Buffer.from(value.mac, 'hex'), Buffer.from(mac(value.document, config), 'hex'))) return null;
111
- return value.document;
112
+ if (!isObject(value)) return null;
113
+ const generation = value.generation ?? 0, rejected = value.rejected ?? false;
114
+ const fenceId = value.fenceId ?? null;
115
+ if (!Number.isSafeInteger(generation) || generation < 0 || typeof rejected !== 'boolean'
116
+ || (fenceId !== null && !safeId(fenceId))
117
+ || (rejected && generation === 0)
118
+ || (value.document !== null && !validDocument(value.document, config, now, true))
119
+ || !/^[a-f0-9]{64}$/.test(value.mac)) return null;
120
+ if (!timingSafeEqual(Buffer.from(value.mac, 'hex'), Buffer.from(mac(value.document, config, generation, rejected, fenceId), 'hex'))) return null;
121
+ return { document: value.document, generation, rejected, fenceId };
112
122
  } catch { return null; }
113
123
  }
114
124
 
115
- function readCache(store, config, now) {
116
- try { return cachedDocument(store.read('posture'), config, now); } catch { return null; }
125
+ function signedCache(document, config, generation = 0, rejected = false, fenceId = null) {
126
+ return { document, mac: mac(document, config, generation, rejected, fenceId),
127
+ ...(generation > 0 ? { generation, rejected } : {}), ...(fenceId !== null ? { fenceId } : {}) };
128
+ }
129
+
130
+ function readEntry(store, config, now) {
131
+ try { return cacheEntry(store.read('posture'), config, now); } catch { return null; }
132
+ }
133
+
134
+ function fenceMac(id, config) {
135
+ return createHmac('sha256', config.apiKey || '').update(`osuite.posture-rejection.v1\n${id}`).digest('hex');
136
+ }
137
+
138
+ function readFence(store, config) {
139
+ try {
140
+ const value = store.read('posture-rejection');
141
+ if (value == null) return { valid: true, id: null };
142
+ if (value.schema !== 'osuite.posture-rejection.v1' || !safeId(value.id)
143
+ || !/^[a-f0-9]{64}$/.test(value.mac)
144
+ || !timingSafeEqual(Buffer.from(value.mac, 'hex'), Buffer.from(fenceMac(value.id, config), 'hex'))) return { valid: false };
145
+ return { valid: true, id: value.id };
146
+ } catch { return { valid: false }; }
147
+ }
148
+
149
+ export function captureRejectionFence(config, store) {
150
+ try {
151
+ const fence = readFence(store, config), raw = store.read('posture');
152
+ const entry = cacheEntry(raw, config, Date.now());
153
+ return Object.freeze({ valid: fence.valid && (raw == null || entry !== null), id: fence.id,
154
+ generation: entry?.generation || 0, rejected: entry?.rejected === true || (entry?.fenceId ?? null) !== fence.id });
155
+ } catch { return Object.freeze({ valid: false, rejected: true }); }
156
+ }
157
+
158
+ export function rejectionFenceUnchanged(config, store, before) {
159
+ const current = captureRejectionFence(config, store);
160
+ return before?.valid === true && before.rejected === false && current.valid && !current.rejected
161
+ && before.id === current.id && before.generation === current.generation;
162
+ }
163
+
164
+ export function invalidatePostureCache(config, store, now = Date.now()) {
165
+ const id = randomUUID();
166
+ // Independent atomic marker survives contention on the configuration lock.
167
+ // Never delete it to recover: a fresh response must bind the current marker.
168
+ store.write('posture-rejection', { schema: 'osuite.posture-rejection.v1', id, mac: fenceMac(id, config) });
169
+ return cacheEntry(store.update('posture', value => {
170
+ const latest = cacheEntry(value, config, now);
171
+ const generation = (latest?.generation || 0) + 1;
172
+ if (!Number.isSafeInteger(generation)) throw new Error('Cache generation exhausted');
173
+ return signedCache(latest?.document || null, config, generation, true, id);
174
+ }), config, now);
117
175
  }
118
176
 
119
177
  export async function resolveRemotePosture(config, { api, store, now = Date.now() }) {
120
178
  const capable = config.ruleRolloutCapability === RULE_ROLLOUT_CAPABILITY;
179
+ const startedFence = readFence(store, config);
180
+ if (!startedFence.valid) return { available: false, blocked: true, source: 'unavailable', posture: localPosture(config), revision: null };
181
+ // Detect existing storage failure before learning a decision we cannot retain.
182
+ // This probe is not authority and does not promise durability through later I/O failure.
183
+ try { store.write('posture-storage-probe', { schema: 'osuite.state-probe.v1', at: now }); }
184
+ catch { return { available: false, blocked: true, source: 'unavailable',
185
+ posture: offlinePosture(localPosture(config), readEntry(store, config, now)?.document?.posture), revision: null }; }
186
+ const startedGeneration = readEntry(store, config, now)?.generation || 0;
187
+ const rejectionFence = Object.freeze({ valid: true, id: startedFence.id, generation: startedGeneration, rejected: false });
121
188
  let acknowledged = null;
122
189
  if (capable) {
123
190
  const acknowledgement = await api.request('PUT', `/api/runtimes/${encodeURIComponent(config.runtimeId)}/posture`, {
@@ -125,6 +192,9 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
125
192
  }, { timeoutMs: 2000 });
126
193
  const value = acknowledgement.body;
127
194
  if (!acknowledgement.ok || !validAcknowledgement(value, config, now)) {
195
+ if (!isTransientFailure(acknowledgement)) {
196
+ try { invalidatePostureCache(config, store, now); } catch { /* This invocation still blocks. */ }
197
+ }
128
198
  return { available: false, blocked: true, source: 'unavailable', posture: localPosture(config), revision: null };
129
199
  }
130
200
  acknowledged = value;
@@ -132,37 +202,52 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
132
202
  const query = new URLSearchParams({ agent_id: config.agentId });
133
203
  if (config.provider) query.set('provider', config.provider);
134
204
  const response = await api.request('GET', `/api/runtimes/${encodeURIComponent(config.runtimeId)}/posture?${query}`, undefined, { timeoutMs: 2000 });
135
- const rejected = [401, 403, 409].includes(response.status);
136
- let cached = readCache(store, config, now);
137
- if (response.ok && response.status === 200 && validDocument(response.body, config, now)
138
- && (!capable || matchesAcknowledgement(response.body, acknowledged)) && preservesRolloutFloor(cached, response.body)
205
+ const validResponse = response.ok && response.status === 200 && validDocument(response.body, config, now)
206
+ && (!capable || matchesAcknowledgement(response.body, acknowledged));
207
+ const rejected = !validResponse && !isTransientFailure(response);
208
+ let entry = readEntry(store, config, now), cached = entry?.document;
209
+ if (rejected) {
210
+ try {
211
+ entry = invalidatePostureCache(config, store, now);
212
+ cached = entry?.document;
213
+ } catch {
214
+ return { available: false, blocked: true, source: 'unavailable',
215
+ posture: offlinePosture(localPosture(config), cached?.posture), revision: cached?.revision || null };
216
+ }
217
+ }
218
+ if (validResponse && preservesRolloutFloor(cached, response.body)
139
219
  && (!cached || Date.parse(response.body.issued_at) >= Date.parse(cached.issued_at))) {
140
220
  const document = configurationOnly(response.body);
141
221
  try {
142
222
  // The comparison and replacement share a cross-process lock. A stale
143
223
  // response must not replace a stronger configuration published meanwhile.
144
224
  const saved = store.update('posture', value => {
145
- const latest = cachedDocument(value, config, now);
146
- return latest && (Date.parse(latest.issued_at) > Date.parse(document.issued_at) || !preservesRolloutFloor(latest, document))
147
- ? value : { document, mac: mac(document, config) };
225
+ const latest = cacheEntry(value, config, now), previous = latest?.document;
226
+ // A request that began before a rejection cannot clear that rejection.
227
+ const currentFence = readFence(store, config);
228
+ if (!currentFence.valid || currentFence.id !== startedFence.id || (latest?.generation || 0) !== startedGeneration) return value;
229
+ return previous && (Date.parse(previous.issued_at) > Date.parse(document.issued_at) || !preservesRolloutFloor(previous, document))
230
+ ? value : signedCache(document, config, startedGeneration, false, startedFence.id);
148
231
  });
149
- cached = cachedDocument(saved, config, now);
150
- if (cached && canonicalJson(cached) === canonicalJson(document)) {
232
+ entry = cacheEntry(saved, config, now); cached = entry?.document;
233
+ if (rejectionFenceUnchanged(config, store, rejectionFence) && cached && canonicalJson(cached) === canonicalJson(document)) {
151
234
  return { available: true, blocked: false, source: 'remote', posture: document.posture, revision: document.revision,
152
- ruleRollout: document.rule_rollout, orgId: document.org_id };
235
+ ruleRollout: document.rule_rollout, orgId: document.org_id, rejectionFence };
153
236
  }
154
237
  } catch {
155
- const posture = offlinePosture(offlinePosture(localPosture(config), readCache(store, config, now)?.posture), document.posture);
156
- return { available: false, blocked: capable || posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
238
+ const posture = offlinePosture(offlinePosture(localPosture(config), readEntry(store, config, now)?.document?.posture), document.posture);
239
+ return { available: false, blocked: true, source: 'unavailable', posture, revision: cached?.revision || null };
157
240
  }
158
241
  }
159
242
  const posture = offlinePosture(localPosture(config), cached?.posture);
160
- // Revocation and explicit scope rejection invalidate cached authority immediately.
161
- if (!rejected && !(capable && response.ok) && cached && Date.parse(cached.valid_until) > now
243
+ // Rejection is retained across requests; a fresh valid response must clear it.
244
+ const fenced = !rejectionFenceUnchanged(config, store, rejectionFence);
245
+ if (!rejected && !entry?.rejected && !fenced && !(capable && response.ok) && cached && Date.parse(cached.valid_until) > now
162
246
  && validNegotiation(cached, config, now)) {
163
247
  if (capable && !matchesAcknowledgement(cached, acknowledged)) return { available: false, blocked: true, source: 'unavailable', posture, revision: cached.revision };
164
248
  return { available: true, blocked: false, source: 'cache', posture, revision: cached.revision,
165
- ruleRollout: cached.rule_rollout, orgId: cached.org_id };
249
+ ruleRollout: cached.rule_rollout, orgId: cached.org_id, rejectionFence };
166
250
  }
167
- return { available: false, blocked: rejected || capable || posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
251
+ return { available: false, blocked: rejected || fenced || entry?.rejected === true || capable || posture.mode !== 'observe',
252
+ source: 'unavailable', posture, revision: cached?.revision || null, rejectionFence };
168
253
  }
@@ -6,6 +6,21 @@ export const isObject = value => value !== null && typeof value === 'object' &&
6
6
  export const sha256 = value => createHash('sha256').update(value).digest('hex');
7
7
  export const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,199}$/.test(value) && !value.includes('..');
8
8
 
9
+ export const isTransientFailure = response => response?.ok === false && (
10
+ (response.status === 0 && ['timeout', 'transport_failure'].includes(response.error))
11
+ || (response.error === 'http_error' && [500, 502, 503, 504].includes(response.status))
12
+ );
13
+
14
+ const transientCodes = new Set(['ECONNREFUSED', 'ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT',
15
+ 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_SOCKET']);
16
+ function transientTransport(error) {
17
+ const cause = error?.cause || error;
18
+ if (cause?.errors !== undefined) return Array.isArray(cause.errors) && cause.errors.length > 0
19
+ && cause.errors.length <= 32 && (cause.code === undefined || transientCodes.has(cause.code))
20
+ && cause.errors.every(item => transientCodes.has(item?.code) && item.errors === undefined);
21
+ return transientCodes.has(cause?.code);
22
+ }
23
+
9
24
  export function canonicalJson(value) {
10
25
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
11
26
  if (isObject(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
@@ -33,6 +48,10 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
33
48
  const baseUrl = validatedBaseUrl(config.baseUrl, config);
34
49
  if (!baseUrl) return { ok: false, status: 0, error: 'invalid_base_url' };
35
50
  if (!config.apiKey) return { ok: false, status: 0, error: 'not_configured' };
51
+ if (typeof config.apiKey !== 'string' || !/^[\x21-\x7e]+$/.test(config.apiKey)
52
+ || !['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].includes(method)) {
53
+ return { ok: false, status: 0, error: 'invalid_request' };
54
+ }
36
55
  if (typeof endpoint !== 'string' || !endpoint.startsWith('/') || endpoint.startsWith('//')) {
37
56
  return { ok: false, status: 0, error: 'invalid_endpoint' };
38
57
  }
@@ -88,13 +107,14 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
88
107
  chunks.push(Buffer.from(value));
89
108
  }
90
109
  let parsed;
91
- try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch {
110
+ try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch {
92
111
  return { ok: false, status, error: 'invalid_response' };
93
112
  }
94
113
  if (!isObject(parsed)) return { ok: false, status, error: 'invalid_response' };
95
114
  return { ok: true, status, body: parsed };
96
- } catch {
97
- return { ok: false, status, error: controller.signal.aborted ? 'timeout' : 'transport_failure' };
115
+ } catch (error) {
116
+ return { ok: false, status, error: status ? 'invalid_response' : controller.signal.aborted ? 'timeout'
117
+ : transientTransport(error) ? 'transport_failure' : 'request_failed' };
98
118
  } finally { clearTimeout(timer); }
99
119
  },
100
120
  };
package/runtime/state.mjs CHANGED
@@ -5,16 +5,23 @@ import { randomUUID } from 'node:crypto';
5
5
  import { canonicalJson, sha256 } from './protocol.mjs';
6
6
 
7
7
  const MAX_STATE_BYTES = 2 * 1024 * 1024;
8
+ const MAX_STATE_CHECKS = 3;
8
9
 
9
10
  function checkedFile(filename) {
10
- try {
11
- const stat = fs.lstatSync(filename);
12
- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw new Error('Unsafe runtime state file');
13
- return stat;
14
- } catch (error) {
15
- if (error.code === 'ENOENT') return null;
16
- throw error;
11
+ for (let attempt = 0; attempt < MAX_STATE_CHECKS; attempt++) {
12
+ try {
13
+ const stat = fs.lstatSync(filename);
14
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Unsafe runtime state file');
15
+ // Atomic replacement can detach the inode during inspection; check the new path, never trust the old one.
16
+ if (stat.nlink === 0) continue;
17
+ if (stat.nlink !== 1) throw new Error('Unsafe runtime state file');
18
+ return stat;
19
+ } catch (error) {
20
+ if (error.code === 'ENOENT') return null;
21
+ throw error;
22
+ }
17
23
  }
24
+ throw new Error('Runtime state changed during inspection');
18
25
  }
19
26
 
20
27
  export function createStateStore(config) {
@@ -34,13 +41,18 @@ export function createStateStore(config) {
34
41
  path: filename,
35
42
  read(name) {
36
43
  const file = filename(name);
37
- if (!checkedFile(file)) return null;
38
- const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | fs.constants.O_NONBLOCK);
39
- try {
40
- const stat = fs.fstatSync(fd);
41
- if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_STATE_BYTES) throw new Error('Invalid runtime state file');
42
- return JSON.parse(fs.readFileSync(fd, 'utf8'));
43
- } finally { fs.closeSync(fd); }
44
+ for (let attempt = 0; attempt < MAX_STATE_CHECKS; attempt++) {
45
+ if (!checkedFile(file)) return null;
46
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | fs.constants.O_NONBLOCK);
47
+ try {
48
+ const stat = fs.fstatSync(fd);
49
+ if (!stat.isFile()) throw new Error('Invalid runtime state file');
50
+ if (stat.nlink === 0) continue;
51
+ if (stat.nlink !== 1 || stat.size > MAX_STATE_BYTES) throw new Error('Invalid runtime state file');
52
+ return JSON.parse(fs.readFileSync(fd, 'utf8'));
53
+ } finally { fs.closeSync(fd); }
54
+ }
55
+ throw new Error('Runtime state changed during read');
44
56
  },
45
57
  write(name, value) {
46
58
  const file = filename(name);