osuite 2.10.2 → 2.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.',