osuite 2.14.0 → 2.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/codexTrust.mjs ADDED
@@ -0,0 +1,107 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { loadRuntimeConfig } from './runtime/config.mjs';
6
+ import { canonicalJson, createApiClient, sha256 } from './runtime/protocol.mjs';
7
+ import { emitRuntimeEvent, openSession } from './runtime/hook.mjs';
8
+ import { createStateStore } from './runtime/state.mjs';
9
+
10
+ const review = 'Open codex in this project, trust the workspace if prompted, then use /hooks to review and trust the OSuite entries.';
11
+ const expected = { PreToolUse: 'preToolUse', PostToolUse: 'postToolUse', SessionStart: 'sessionStart', Stop: 'stop' };
12
+
13
+ function listNativeHooks({ projectRoot, env }) {
14
+ return new Promise(resolve => {
15
+ const child = spawn('codex', ['app-server', '--listen', 'stdio://'], {
16
+ cwd: projectRoot, env, stdio: ['pipe', 'pipe', 'ignore'],
17
+ });
18
+ const lines = createInterface({ input: child.stdout });
19
+ let finished = false;
20
+ let bytes = 0;
21
+ const finish = value => {
22
+ if (finished) return;
23
+ finished = true;
24
+ clearTimeout(timeout);
25
+ lines.close();
26
+ child.stdin.destroy();
27
+ child.kill();
28
+ resolve(value);
29
+ };
30
+ const timeout = setTimeout(() => finish(null), 3000);
31
+ child.on('error', () => finish(null));
32
+ child.on('close', () => finish(null));
33
+ child.stdin.on('error', () => finish(null));
34
+ child.stdout.on('data', chunk => { bytes += chunk.length; if (bytes > 524288) finish(null); });
35
+ lines.on('line', line => {
36
+ if (finished) return;
37
+ try {
38
+ const reply = JSON.parse(line);
39
+ if (reply.id === 2) finish(reply.result?.data?.find(entry => entry.cwd === projectRoot) || null);
40
+ } catch { finish(null); }
41
+ });
42
+ const messages = [
43
+ { id: 1, method: 'initialize', params: { clientInfo: { name: 'osuite', version: '1' }, capabilities: { experimentalApi: true } } },
44
+ { method: 'initialized' },
45
+ { id: 2, method: 'hooks/list', params: { cwds: [projectRoot] } },
46
+ ];
47
+ child.stdin.write(messages.map(message => JSON.stringify(message) + '\n').join(''));
48
+ });
49
+ }
50
+
51
+ export async function inspectCodexTrust({ projectRoot, installation, env = process.env, listHooks = listNativeHooks }) {
52
+ if (!installation?.pretool) return { status: 'missing', guidance: 'Run osuite connect codex in this project.' };
53
+ if (!installation.hostEnabled) return { status: 'disabled', guidance: 'Review the project hook enablement in Codex.' };
54
+ const root = fs.realpathSync(projectRoot);
55
+ const settings = path.join(root, '.codex/hooks.json');
56
+ const registrations = installation.diagnostics?.registrations || [];
57
+ if (installation.diagnostics?.status !== 'current' || !fs.lstatSync(settings, { throwIfNoEntry: false })?.isFile()
58
+ || Object.keys(expected).some(event => registrations.filter(hook => hook.event === event).length !== 1)) {
59
+ return { status: 'modified', guidance: 'Verify the installed OSuite hook files, then review their trust in Codex with /hooks.' };
60
+ }
61
+ const native = await listHooks({ projectRoot: root, env });
62
+ if (!Array.isArray(native?.hooks)) return { status: 'unavailable', guidance: 'Use a Codex CLI that supports hooks/list, then run osuite doctor.' };
63
+ const current = registrations.filter(hook => Object.hasOwn(expected, hook.event)).map(hook => native.hooks.find(entry =>
64
+ entry.sourcePath === settings && entry.eventName === expected[hook.event] && entry.command === hook.command));
65
+ if (current.some(hook => hook?.trustStatus === 'modified')) return { status: 'modified', guidance: review };
66
+ if (current.some(hook => !hook || !hook.enabled || hook.async || hook.matcher || !['trusted', 'managed'].includes(hook.trustStatus))) {
67
+ return { status: 'untrusted', guidance: review };
68
+ }
69
+ return { status: 'trusted', fingerprint: sha256(canonicalJson(current.map(hook => hook.currentHash || hook.command))) };
70
+ }
71
+
72
+ export async function auditCodexTrust(projectRoot, env, trust) {
73
+ try {
74
+ const config = loadRuntimeConfig({ host: 'codex', installDir: path.join(projectRoot, '.codex'), env });
75
+ if (!config.apiKey || !config.baseUrl) return;
76
+ const store = createStateStore(config);
77
+ const sessionId = `codex-trust-${sha256(fs.realpathSync(projectRoot)).slice(0, 32)}`;
78
+ const key = `trust:${sessionId}`;
79
+ const current = { status: trust.status, fingerprint: trust.fingerprint || null };
80
+ const previous = store.read(key);
81
+ if (canonicalJson(previous) === canonicalJson(current)) return;
82
+ const api = createApiClient(config);
83
+ await openSession(api, config, { session_id: sessionId }, store);
84
+ const response = await emitRuntimeEvent(api, config, { runtime_session_id: sessionId }, 'hook_trust_changed', null,
85
+ { previous: previous?.status || null, ...current });
86
+ if (response.ok && response.body?.ok) store.write(key, current);
87
+ } catch { /* The current trust verdict is still printed locally. */ }
88
+ }
89
+
90
+ export function codexExecArguments(args) {
91
+ const flagValues = new Set(['--model', '--sandbox']);
92
+ const flags = new Set(['--json', '--ephemeral', '--skip-git-repo-check']);
93
+ let prompt = false;
94
+ for (let index = 0; index < args.length; index += 1) {
95
+ const value = args[index];
96
+ if (value === '--') return args.length === index + 2 && !prompt;
97
+ if (flags.has(value) && !prompt) continue;
98
+ if (flagValues.has(value) && !prompt && args[index + 1] && !args[index + 1].startsWith('-')) {
99
+ const option = args[++index];
100
+ if (value === '--sandbox' && !['read-only', 'workspace-write'].includes(option)) return false;
101
+ continue;
102
+ }
103
+ if (value.startsWith('-') || prompt || ['resume', 'review'].includes(value)) return false;
104
+ prompt = true;
105
+ }
106
+ return prompt;
107
+ }
package/credentials.js CHANGED
@@ -1,238 +1 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import crypto from 'node:crypto';
4
- import { spawnSync } from 'node:child_process';
5
-
6
- export const CREDENTIAL_PATHS = ['.codex/.env', '.claude/.env', '.cursor/.env', '.osuite/.env'];
7
- const POSIX = process.platform !== 'win32';
8
- const NOFOLLOW = fs.constants.O_NOFOLLOW || 0;
9
-
10
- function metadata(file) {
11
- try { return fs.lstatSync(file); } catch (error) {
12
- if (error.code === 'ENOENT') return null;
13
- throw error;
14
- }
15
- }
16
-
17
- function sameFile(a, b) {
18
- return !a && !b || Boolean(a && b && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs);
19
- }
20
-
21
- function owned(stat) {
22
- return !POSIX || typeof process.getuid !== 'function' || stat.uid === process.getuid();
23
- }
24
-
25
- function safePath(projectRoot, relativePath, { create = false } = {}) {
26
- const root = fs.realpathSync(projectRoot);
27
- const absolute = path.resolve(root, relativePath);
28
- const relative = path.relative(root, absolute);
29
- if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
30
- throw new Error('Credential path must stay inside the project.');
31
- }
32
- let directory = root;
33
- const parts = relative.split(path.sep).slice(0, -1);
34
- for (const part of ['', ...parts]) {
35
- if (part) directory = path.join(directory, part);
36
- let stat = metadata(directory);
37
- if (!stat && create) {
38
- fs.mkdirSync(directory, { mode: 0o700 });
39
- if (POSIX) fs.chmodSync(directory, 0o700);
40
- syncDirectory(path.dirname(directory));
41
- stat = metadata(directory);
42
- }
43
- if (!stat) continue;
44
- if (stat.isSymbolicLink()) throw new Error('Refusing a symlink in the credential path.');
45
- if (!stat.isDirectory()) throw new Error('Credential parent must be a directory.');
46
- if (!owned(stat) || POSIX && (stat.mode & 0o022)) throw new Error('Unsafe credential directory ownership or write permissions.');
47
- }
48
- const stat = metadata(absolute);
49
- if (stat?.isSymbolicLink()) throw new Error('Refusing a symlinked credential file.');
50
- if (stat && (!stat.isFile() || stat.nlink !== 1 || !owned(stat))) {
51
- throw new Error('Unsafe credential file type, links, or ownership.');
52
- }
53
- return { root, absolute, relativePath: relative.split(path.sep).join('/'), stat };
54
- }
55
-
56
- function runGit(cwd, args) {
57
- // Inherited GIT_DIR/INDEX_FILE must not hide a tracked project credential.
58
- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
59
- // Metadata inspection must not execute repository-configured fsmonitor commands.
60
- return spawnSync('git', ['-c', 'core.fsmonitor=false', '-C', cwd, ...args], {
61
- encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'],
62
- });
63
- }
64
-
65
- function repositoryRoots(root, absolute) {
66
- const roots = new Set();
67
- let current = root;
68
- for (const part of ['', ...path.relative(root, path.dirname(absolute)).split(path.sep).filter(Boolean)]) {
69
- if (part) current = path.join(current, part);
70
- if (!metadata(current)) continue;
71
- const result = runGit(current, ['rev-parse', '--show-toplevel']);
72
- if (result.error) throw new Error('Git is required to check whether the credential path is tracked.');
73
- if (result.status === 0) roots.add(result.stdout.trim());
74
- else if (!result.stderr.includes('not a git repository')) throw new Error('Unable to verify Git credential protection.');
75
- }
76
- return [...roots];
77
- }
78
-
79
- function isTracked(root, absolute) {
80
- return repositoryRoots(root, absolute).some((repository) => {
81
- // A tracked .ENV aliases .env on common macOS/Windows filesystems.
82
- const result = runGit(repository, ['ls-files', '--error-unmatch', '--', `:(icase,literal)${path.relative(repository, absolute)}`]);
83
- if (result.status !== 0 && result.status !== 1) throw new Error('Unable to inspect the Git index for credentials.');
84
- return result.status === 0;
85
- });
86
- }
87
-
88
- function assertUntracked(target) {
89
- if (isTracked(target.root, target.absolute)) throw new Error('Refusing to write credentials to a tracked path. Remove it from Git and rotate any exposed credentials first.');
90
- }
91
-
92
- function syncDirectory(directory) {
93
- if (!POSIX) return;
94
- const fd = fs.openSync(directory, fs.constants.O_RDONLY | (fs.constants.O_DIRECTORY || 0) | NOFOLLOW);
95
- try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
96
- }
97
-
98
- function atomicWrite(target, body, mode, { credential = false } = {}) {
99
- const temporary = `${target.absolute}.osuite-tmp-${crypto.randomBytes(12).toString('hex')}`;
100
- let fd;
101
- try {
102
- fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, mode);
103
- if (POSIX) fs.fchmodSync(fd, mode);
104
- fs.writeFileSync(fd, body, 'utf8');
105
- fs.fsyncSync(fd);
106
- fs.closeSync(fd);
107
- fd = undefined;
108
- const latest = safePath(target.root, target.relativePath);
109
- if (!sameFile(target.stat, latest.stat)) throw new Error('Credential destination changed during the write; refusing to replace it.');
110
- if (credential) assertUntracked(latest);
111
- fs.renameSync(temporary, target.absolute);
112
- syncDirectory(path.dirname(target.absolute));
113
- } finally {
114
- if (fd !== undefined) fs.closeSync(fd);
115
- try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
116
- }
117
- }
118
-
119
- function protectIgnore(target) {
120
- const directory = path.dirname(target.absolute);
121
- const ignorePath = path.join(path.dirname(target.relativePath), '.gitignore');
122
- const ignore = safePath(target.root, ignorePath);
123
- const body = ignore.stat ? fs.readFileSync(ignore.absolute, 'utf8') : '';
124
- const name = path.basename(target.absolute);
125
- // A rule in the credential's own directory works in monorepos and nested repos.
126
- const rules = [`/${name}`, `/${name}.osuite-tmp-*`];
127
- const missing = rules.filter((rule) => !body.split(/\r?\n/).includes(rule));
128
- if (missing.length) {
129
- atomicWrite(ignore, `${body}${body && !body.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`, ignore.stat ? ignore.stat.mode & 0o777 : 0o644);
130
- }
131
- if (repositoryRoots(target.root, target.absolute).length) {
132
- const result = runGit(directory, ['check-ignore', '--no-index', '--', target.absolute]);
133
- if (result.status !== 0) throw new Error('Credential path is not ignored by Git; check conflicting ignore rules.');
134
- }
135
- }
136
-
137
- export function inspectCredentialFile(projectRoot, relativePath) {
138
- const result = { relativePath, exists: false, safe: false, problems: [], mode: null };
139
- try {
140
- const target = safePath(projectRoot, relativePath);
141
- result.exists = Boolean(target.stat);
142
- if (target.stat) {
143
- result.mode = POSIX ? `0${(target.stat.mode & 0o777).toString(8).padStart(3, '0')}` : null;
144
- if (POSIX && (target.stat.mode & 0o777) !== 0o600) result.problems.push(`unsafe mode ${result.mode}; expected 0600`);
145
- }
146
- if (isTracked(target.root, target.absolute)) result.problems.push('tracked by Git');
147
- if (target.stat) {
148
- const roots = repositoryRoots(target.root, target.absolute);
149
- if (roots.length && runGit(path.dirname(target.absolute), ['check-ignore', '--no-index', '--', target.absolute]).status !== 0) result.problems.push('not ignored by Git');
150
- }
151
- result.safe = result.problems.length === 0;
152
- } catch (error) {
153
- result.exists = true;
154
- result.problems.push(error.message);
155
- }
156
- return result;
157
- }
158
-
159
- export function prepareCredentialFile(projectRoot, relativePath) {
160
- let target = safePath(projectRoot, relativePath);
161
- assertUntracked(target);
162
- target = safePath(projectRoot, relativePath, { create: true });
163
- protectIgnore(target);
164
- return target;
165
- }
166
-
167
- export function writeCredentialFile(projectRoot, relativePath, body, options = {}) {
168
- const target = prepareCredentialFile(projectRoot, relativePath);
169
- // Interactive callers must not adopt a newer operator edit at this handoff.
170
- if (Object.hasOwn(options, 'expectedStat') && !sameFile(options.expectedStat, target.stat)) {
171
- throw new Error('Credential destination changed since it was read; refusing to replace it.');
172
- }
173
- atomicWrite(target, String(body), 0o600, { credential: true });
174
- return { relativePath: target.relativePath, status: 'written' };
175
- }
176
-
177
- export function readCredentialFile(projectRoot, relativePath) {
178
- const inspection = inspectCredentialFile(projectRoot, relativePath);
179
- if (!inspection.exists) return null;
180
- if (!inspection.safe) throw new Error(`Unsafe credential file: ${relativePath} (${inspection.problems.join('; ')}).`);
181
- const target = safePath(projectRoot, relativePath);
182
- const fd = fs.openSync(target.absolute, fs.constants.O_RDONLY | NOFOLLOW);
183
- try {
184
- if (!sameFile(target.stat, fs.fstatSync(fd))) throw new Error('Credential changed before reading.');
185
- return fs.readFileSync(fd, 'utf8');
186
- } finally { fs.closeSync(fd); }
187
- }
188
-
189
- export function removeCredentialFile(projectRoot, relativePath) {
190
- const target = safePath(projectRoot, relativePath);
191
- assertUntracked(target);
192
- if (!target.stat) return;
193
- fs.unlinkSync(target.absolute);
194
- syncDirectory(path.dirname(target.absolute));
195
- }
196
-
197
- export function acquireCredentialLock(projectRoot, relativePath) {
198
- prepareCredentialFile(projectRoot, relativePath);
199
- const lockPath = `${relativePath}.connect.lock`;
200
- let target = prepareCredentialFile(projectRoot, lockPath);
201
- if (target.stat) {
202
- let lock;
203
- try { lock = JSON.parse(readCredentialFile(projectRoot, lockPath)); } catch {
204
- throw new Error('Unsafe or unreadable credential lock; inspect its metadata before reconnecting.');
205
- }
206
- if (!Number.isSafeInteger(lock?.pid) || lock.pid < 1) throw new Error('Invalid credential lock.');
207
- let running = true;
208
- try { process.kill(lock.pid, 0); } catch (error) { if (error.code === 'ESRCH') running = false; }
209
- if (running) throw new Error('Another connect process owns this credential file. Wait for it to finish.');
210
- const latest = safePath(projectRoot, lockPath);
211
- if (!sameFile(target.stat, latest.stat)) throw new Error('Credential lock changed during recovery.');
212
- removeCredentialFile(projectRoot, lockPath);
213
- target = prepareCredentialFile(projectRoot, lockPath);
214
- }
215
- let fd;
216
- let lockStat;
217
- try {
218
- fd = fs.openSync(target.absolute, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, 0o600);
219
- if (POSIX) fs.fchmodSync(fd, 0o600);
220
- fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid })}\n`, 'utf8');
221
- fs.fsyncSync(fd);
222
- lockStat = fs.fstatSync(fd);
223
- } catch (error) {
224
- if (error.code === 'EEXIST') throw new Error('Another connect process owns this credential file.');
225
- throw error;
226
- } finally { if (fd !== undefined) fs.closeSync(fd); }
227
- syncDirectory(path.dirname(target.absolute));
228
- let released = false;
229
- const release = () => {
230
- if (released) return;
231
- released = true;
232
- process.removeListener('exit', release);
233
- const latest = safePath(projectRoot, lockPath);
234
- if (sameFile(lockStat, latest.stat)) removeCredentialFile(projectRoot, lockPath);
235
- };
236
- process.once('exit', release);
237
- return release;
238
- }
1
+ export * from './runtime/credentials.mjs';
@@ -6,6 +6,8 @@ import { createStateStore } from '../runtime/state.mjs';
6
6
  import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
7
7
  import { matchesStoredAction, reject } from './contract.mjs';
8
8
 
9
+ const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
10
+
9
11
  export function createStudioAuthority(config, journalPath) {
10
12
  const responseLimits = { maxResponseBytes: 1048576 };
11
13
  const baseApi = createApiClient(config, responseLimits);
@@ -46,7 +48,7 @@ export function createStudioAuthority(config, journalPath) {
46
48
  }
47
49
 
48
50
  async function read(record) {
49
- const response = await baseApi.request('GET', `/api/actions/${encodeURIComponent(record.actionId)}`);
51
+ const response = await baseApi.request('GET', `/api/actions/${encodeURIComponent(record.actionId)}`, undefined, receiptWindow);
50
52
  if (!response.ok) return { available: false, status: response.status };
51
53
  if (!matchesStoredAction(response.body, record, config)) return { available: false, status: response.status, mismatch: true };
52
54
  return { available: true, body: response.body, action: response.body.action || response.body };
@@ -67,7 +69,7 @@ export function createStudioAuthority(config, journalPath) {
67
69
  if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
68
70
  || actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
69
71
  || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE');
70
- let claimed = false, receivedAt = null;
72
+ let claimed = false, requestStartedAt = null;
71
73
  const claim = () => {
72
74
  if (claimed) reject('OUTCOME_UNKNOWN');
73
75
  if (aborted()) reject('ABORTED');
@@ -80,10 +82,10 @@ export function createStudioAuthority(config, journalPath) {
80
82
  config: effective,
81
83
  api: { async request(method, endpoint, body, options) {
82
84
  if (aborted()) reject('ABORTED');
83
- if (method === 'POST' && endpoint === '/api/actions') claim();
84
- const response = await api.request(method, endpoint, body, options);
85
- if (method === 'POST' && endpoint === '/api/actions') {
86
- receivedAt = performance.now();
85
+ const registering = method === 'POST' && endpoint === '/api/actions';
86
+ if (registering) { claim(); requestStartedAt = performance.now(); }
87
+ const response = await api.request(method, endpoint, body, registering ? receiptWindow : options);
88
+ if (registering) {
87
89
  if (!response.ok || !matchesStoredAction(response.body, record, config)
88
90
  || !cavaFingerprint(response.body)) {
89
91
  settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
@@ -100,7 +102,7 @@ export function createStudioAuthority(config, journalPath) {
100
102
  { actionId: record.actionId, fingerprint: record.fingerprint }).authorized);
101
103
  },
102
104
  });
103
- if (result.authorized) return { phase, receivedAt, response: result.response,
105
+ if (result.authorized) return { phase, dispatchDeadline: requestStartedAt + receiptWindow.timeoutMs, response: result.response,
104
106
  ruleExpiresAt: result.ruleRolloutBinding?.expires_at ?? null };
105
107
  if (result.reason === 'policy_block') {
106
108
  if (!claimed) claim();
@@ -128,7 +130,7 @@ export function createStudioAuthority(config, journalPath) {
128
130
  result_digest: resultDigest, result_retained: false, independent_resource_verification: false,
129
131
  ...(record.recovery ? { recovery: record.recovery, recovery_evidence_digest: record.errorCode?.slice('recovery_'.length) ?? null } : {}) }),
130
132
  ...(state === 'uncertain' ? { error_message: 'Native call outcome is uncertain; no automatic resend.' } : {}),
131
- });
133
+ }, receiptWindow);
132
134
  return response.ok && matchesStoredAction(response.body, record, config)
133
135
  && response.body.action?.status === (state === 'completed' ? 'completed' : 'failed')
134
136
  && typeof response.body.action?.timestamp_end === 'string';
@@ -30,7 +30,10 @@ function recoveryGuidance(code, state) {
30
30
  else if (['requesting', 'redeeming', 'dispatching', 'uncertain', 'uncertain_request', 'uncertain_redemption'].includes(state)) nextStep = 'reconcile_without_resend';
31
31
  else if (!code && state === 'prepared') nextStep = 'check_current_authority';
32
32
  else nextStep = 'inspect_configuration';
33
- return Object.freeze({ nextStep, preserveOperationId: true, message: recoveryMessages[nextStep] });
33
+ const message = code === 'RECOVERY_UNSUPPORTED' && state === 'uncertain'
34
+ ? 'No resource recovery contract was installed for this call. Keep the same operation ID and reconcile against the original receipt. An empty lookup is not permission to resend.'
35
+ : recoveryMessages[nextStep];
36
+ return Object.freeze({ nextStep, preserveOperationId: true, message });
34
37
  }
35
38
 
36
39
  export class GovernedToolError extends Error {
@@ -9,6 +9,15 @@ import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject,
9
9
  import { recoveryAdapter, recoveryScope, makeRecoveryInvocation, observeEvidence, validateEvidence, checkRecoveryAuthority } from './recovery.mjs';
10
10
 
11
11
  const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
12
+ const terminalCodes = Object.freeze({ denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' });
13
+
14
+ function terminalReview(action, approval) {
15
+ if (action === 'expired' || approval === 'expired') return 'expired';
16
+ if (action === 'cancelled' || approval === 'cancelled') return 'cancelled';
17
+ if (action === 'blocked' || action === 'denied' || approval === 'denied') return 'denied';
18
+ return null;
19
+ }
20
+
12
21
  function runOptions(options) {
13
22
  if (!options || typeof options !== 'object' || types.isProxy(options)) reject('INVALID_OPTIONS');
14
23
  const descriptors = Object.getOwnPropertyDescriptors(options);
@@ -83,8 +92,8 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
83
92
  return Object.freeze({ ...(recoveryAttempt || parent), parent, recoveryAttempt });
84
93
  };
85
94
  function stopForState(record) {
86
- const codes = { completed: 'ALREADY_COMPLETED', denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' };
87
- if (codes[record.state]) reject(codes[record.state], status(record));
95
+ if (record.state === 'completed') reject('ALREADY_COMPLETED', status(record));
96
+ if (Object.hasOwn(terminalCodes, record.state)) reject(terminalCodes[record.state], status(record));
88
97
  if (!['prepared', 'held', 'requesting', 'uncertain_request'].includes(record.state)) reject('OUTCOME_UNKNOWN', status(record));
89
98
  }
90
99
  function transitionHeld(record, next, owner) {
@@ -120,18 +129,16 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
120
129
  record = local(operationId);
121
130
  }
122
131
  if (!record.fingerprint || record.fingerprint !== cavaFingerprint(observed.body)) reject('BINDING_MISMATCH', status(record));
132
+ const terminal = terminalReview(action.status, observed.body.approval?.state);
133
+ if (terminal) {
134
+ transitionHeld(record, terminal, owner); stopForState(local(operationId));
135
+ }
123
136
  if (action.status === 'pending_approval') {
124
137
  if (performance.now() >= deadline) waiting();
125
138
  try { await delay(Math.min(200, deadline - performance.now()), undefined, { signal }); }
126
139
  catch { reject('ABORTED', status(record)); }
127
140
  continue;
128
141
  }
129
- if (['blocked', 'denied', 'expired', 'cancelled'].includes(action.status)
130
- || ['denied', 'expired', 'cancelled'].includes(observed.body.approval?.state)) {
131
- const state = action.status === 'expired' || observed.body.approval?.state === 'expired' ? 'expired'
132
- : action.status === 'cancelled' ? 'cancelled' : 'denied';
133
- transitionHeld(record, state, owner); stopForState(local(operationId));
134
- }
135
142
  if (action.status !== 'running' || action.timestamp_end != null || action.approval_redeemed_at != null
136
143
  || !action.approved_by || !action.approved_at) reject('OUTCOME_UNKNOWN', status(record));
137
144
  }
@@ -153,14 +160,18 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
153
160
  }
154
161
  // No await or user observer between this last check, the durable fence,
155
162
  // and invoking the original tool. This is not resource-side atomicity.
156
- if (aborted() || closed || performance.now() - admitted.receivedAt > 5000 || (recovery && !recovery.fresh())) {
163
+ const grantExpiry = admitted.phase === 'redeeming' ? Date.parse(admitted.response.action.approval_expires_at) : Infinity;
164
+ const ruleExpiry = admitted.ruleExpiresAt == null ? Infinity : Date.parse(admitted.ruleExpiresAt);
165
+ const current = () => performance.now() < admitted.dispatchDeadline && Date.now() < Math.min(grantExpiry, ruleExpiry)
166
+ && (!recovery || recovery.fresh());
167
+ if (aborted() || closed || !current()) {
157
168
  journal.settle(scope, operationId, owner, admitted.phase,
158
169
  admitted.phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
159
170
  reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
160
171
  }
161
172
  if (!journal.settle(scope, operationId, owner, admitted.phase, 'dispatching', dispatchPatch)) reject('OPERATION_BUSY', status(local(operationId)));
162
173
  // Durable local I/O can outlive the admission, even without an await.
163
- if (aborted() || closed || performance.now() - admitted.receivedAt > 5000 || (recovery && !recovery.fresh())) {
174
+ if (aborted() || closed || !current()) {
164
175
  try { journal.settle(scope, operationId, owner, 'dispatching', 'uncertain'); }
165
176
  catch { /* The committed dispatch fence still forbids replay if cleanup cannot write. */ }
166
177
  reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
@@ -216,10 +227,9 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
216
227
  const settings = runOptions(options);
217
228
  if (settings.aborted()) reject('ABORTED');
218
229
  const adapter = bindings[parent.params.name].recovery;
219
- if (!adapter) reject('RECOVERY_UNSUPPORTED');
220
- const record = local(operationId);
230
+ const record = journal.getBound(parent.record);
231
+ if (!adapter) reject('RECOVERY_UNSUPPORTED', status(record));
221
232
  if (!record) reject('RECOVERY_UNAVAILABLE');
222
- journal.prepare(parent.record); // Compare every stored identity without replacing the parent.
223
233
  if (record.state !== 'uncertain') { stopForState(record); reject('RECOVERY_UNAVAILABLE', status(record)); }
224
234
  const { invocation, request } = makeRecoveryInvocation(parent, adapter);
225
235
  try {
@@ -259,9 +269,10 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
259
269
  const observed = await authority.read(record);
260
270
  let failureCode = observed.mismatch ? 'BINDING_MISMATCH' : observed.available ? null : 'CURRENT_AUTHORITY_UNAVAILABLE';
261
271
  // Refine held-call guidance without changing durable execution state.
262
- if (!failureCode && record.state === 'held'
263
- && (['blocked', 'denied', 'expired', 'cancelled'].includes(observed.action.status)
264
- || ['denied', 'expired', 'cancelled'].includes(observed.body?.approval?.state))) failureCode = 'POLICY_DENIED';
272
+ if (!failureCode && record.state === 'held') {
273
+ const terminal = terminalReview(observed.action.status, observed.body?.approval?.state);
274
+ if (terminal) failureCode = terminalCodes[terminal];
275
+ }
265
276
  const attempt = recoveryStatus(operationId);
266
277
  return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}), remote: Object.freeze({ available: observed.available,
267
278
  status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
@@ -333,6 +333,12 @@ export class OperationJournal {
333
333
  return this.#db.prepare('SELECT * FROM operations WHERE scope=? AND operation_id=?').get(scope, operationId);
334
334
  }
335
335
 
336
+ #boundRow(value) {
337
+ const row = this.#read(value.scope, value.operationId);
338
+ if (row && Object.entries(FIELDS).some(([field, column]) => value[field] !== row[column])) fail('CONFLICT');
339
+ return row;
340
+ }
341
+
336
342
  #row(row) {
337
343
  if (!row) return null;
338
344
  return Object.freeze({
@@ -353,11 +359,8 @@ export class OperationJournal {
353
359
  return this.#run(() => {
354
360
  const value = validateRecord(record);
355
361
  return this.#transaction(() => {
356
- const prior = this.#read(value.scope, value.operationId);
357
- if (prior) {
358
- if (Object.entries(FIELDS).some(([field, column]) => value[field] !== prior[column])) fail('CONFLICT');
359
- return this.#row(prior);
360
- }
362
+ const prior = this.#boundRow(value);
363
+ if (prior) return this.#row(prior);
361
364
  if (this.#db.prepare('SELECT count(*) AS n FROM operations').get().n >= this.#maxOperations) fail('JOURNAL_CAPACITY');
362
365
  const now = Date.now();
363
366
  this.#db.prepare(`INSERT INTO operations(scope,operation_id,input_digest,context_digest,binding_digest,
@@ -378,6 +381,10 @@ export class OperationJournal {
378
381
  });
379
382
  }
380
383
 
384
+ getBound(record) {
385
+ return this.#run(() => this.#row(this.#boundRow(validateRecord(record))));
386
+ }
387
+
381
388
  claim(scope, operationId, fromStates, nextState, owner) {
382
389
  return this.#run(() => {
383
390
  identity(scope, operationId);
package/nativeDoctor.mjs CHANGED
@@ -1,8 +1,6 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
- import { statSync } from 'node:fs';
3
- import path from 'node:path';
4
2
  import { inspectCredentialFile, readCredentialFile } from './credentials.js';
5
- import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity } from './installationIdentity.js';
3
+ import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
6
4
  import { loadRuntimeConfig } from './runtime/config.mjs';
7
5
  import { createApiClient, safeId, validatedBaseUrl } from './runtime/protocol.mjs';
8
6
  import { resolveRemotePosture } from './runtime/posture.mjs';
@@ -34,10 +32,11 @@ export function loadNativeDoctorConfig({ projectRoot = process.cwd(), runtime, s
34
32
  const checks = files.map(file => inspectCredentialFile(projectRoot, file));
35
33
  if (checks.some(check => !check.safe)) fail('UNSAFE_CREDENTIALS');
36
34
  if (checks.some(check => check.exists && /\.connect\.(json|lock)$/.test(check.relativePath))) fail('CONNECTION_RECOVERY_PENDING');
37
- if (checks.at(-1).exists) fail('MCP_MIGRATION_PENDING');
38
- if (checks[0].exists && statSync(path.join(projectRoot, envPath)).size > 65536) fail('INVALID_CREDENTIAL_FILE');
35
+ if (checks.at(-1).exists) {
36
+ if (readMcpMigration(projectRoot).manifest) fail('MCP_MIGRATION_PENDING');
37
+ }
39
38
  parseInstallationIdentity(readCredentialFile(projectRoot, `${envPath}.identity.json`), runtime);
40
- const raw = readCredentialFile(projectRoot, envPath);
39
+ const raw = readCredentialFile(projectRoot, envPath, { maxBytes: 65536 });
41
40
  // Choose one complete bundle. Never borrow a missing field from another lane.
42
41
  const source = raw === null ? shellEnv : parse(raw);
43
42
  for (const [name, value] of Object.entries(source)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.14.0",
3
+ "version": "2.15.0",
4
4
  "description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -23,6 +23,9 @@
23
23
  "./governed-tools": {
24
24
  "import": "./governed-tools.mjs"
25
25
  },
26
+ "./experimental/business-evidence": {
27
+ "import": "./business-evidence.mjs"
28
+ },
26
29
  "./controlled-transfers": {
27
30
  "import": "./controlled-transfers.mjs"
28
31
  }
@@ -40,6 +43,8 @@
40
43
  "governed-tools/examples/*.mjs",
41
44
  "GOVERNED_TOOLS.md",
42
45
  "GOVERNED_RECOVERY.md",
46
+ "business-evidence.mjs",
47
+ "BUSINESS_EVIDENCE.md",
43
48
  "controlled-transfers.mjs",
44
49
  "controlled-transfers-stdio.mjs",
45
50
  "controlled-transfers/*.mjs",
@@ -47,6 +52,8 @@
47
52
  "matoiDoctor.mjs",
48
53
  "nativeDoctor.mjs",
49
54
  "projectHooks.js",
55
+ "codexTrust.mjs",
56
+ "codexExec.mjs",
50
57
  "reviewSurface.js",
51
58
  "osuite.js",
52
59
  "index.cjs",