osuite 2.14.2 → 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';
@@ -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
  }
@@ -262,9 +269,10 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
262
269
  const observed = await authority.read(record);
263
270
  let failureCode = observed.mismatch ? 'BINDING_MISMATCH' : observed.available ? null : 'CURRENT_AUTHORITY_UNAVAILABLE';
264
271
  // Refine held-call guidance without changing durable execution state.
265
- if (!failureCode && record.state === 'held'
266
- && (['blocked', 'denied', 'expired', 'cancelled'].includes(observed.action.status)
267
- || ['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
+ }
268
276
  const attempt = recoveryStatus(operationId);
269
277
  return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}), remote: Object.freeze({ available: observed.available,
270
278
  status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
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.2",
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",
package/projectHooks.js CHANGED
@@ -6,8 +6,11 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import { spawn } from 'node:child_process';
8
8
  import { fileURLToPath } from 'node:url';
9
+ import { inspectCredentialFile, readCredentialFile } from './runtime/credentials.mjs';
9
10
 
10
11
  const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop|session)\.(?:py|mjs)/;
12
+ const CODEX_RUNTIME_TAG = / --osuite-hook-version=[a-f0-9]{16}$/;
13
+ const withoutCodexTag = command => String(command || '').replace(CODEX_RUNTIME_TAG, '');
11
14
 
12
15
  export const RUNTIME_HOOKS = {
13
16
  claude: {
@@ -112,6 +115,12 @@ export function mergeHookSettings(existingText, templateText) {
112
115
  const requested = (Array.isArray(groups) ? groups : []).flatMap(group => group.hooks || []);
113
116
  const next = current.map(group => ({ ...group, hooks: (group.hooks || []).map(existing => {
114
117
  const replacement = requested.find(hook => sameHook(existing, hook));
118
+ if (replacement && CODEX_RUNTIME_TAG.test(replacement.command) && existing.command !== replacement.command
119
+ && withoutCodexTag(existing.command) === withoutCodexTag(replacement.command)
120
+ && (existing.commandWindows === undefined || withoutCodexTag(existing.commandWindows) === withoutCodexTag(replacement.commandWindows))) {
121
+ migrated.push({ event, matcher: group.matcher, command: replacement.command });
122
+ return { ...existing, command: replacement.command, commandWindows: replacement.commandWindows };
123
+ }
115
124
  if (!replacement || !hookScriptName(existing.command).endsWith('.py') || !hookScriptName(replacement.command).endsWith('.mjs')) return existing;
116
125
  const script = hookScriptName(existing.command);
117
126
  const stock = [`python3 .claude/hooks/${script}`, `python3 .codex/hooks/${script}`,
@@ -236,12 +245,19 @@ export function buildNodeRuntimeBootstrap(runtime, bootstrap = {}, { projectRoot
236
245
  const shellQuote = value => `'${String(value).replace(/'/g, "'\\''")}'`;
237
246
  const events = { PreToolUse: 'pretool', PostToolUse: 'posttool', SessionStart: 'session', Stop: 'stop' };
238
247
  const settings = { hooks: {} };
248
+ const runtimeHash = crypto.createHash('sha256').update(JSON.stringify(Object.entries(files)
249
+ .filter(([name]) => name.startsWith(`${directory}/runtime/`)))).digest('hex');
239
250
  for (const [event, script] of Object.entries(events)) {
240
251
  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`;
241
252
  const absolute = path.join(path.resolve(projectRoot), directory, `hooks/osuite_${script}.mjs`);
242
253
  const handler = { type: 'command', command: `node ${shellQuote(absolute)}`, timeout: 60 };
243
254
  if (host === 'claude' && event === 'PreToolUse') handler.onFailure = 'block';
244
- if (host === 'codex') handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"`;
255
+ if (host === 'codex') {
256
+ const hash = crypto.createHash('sha256').update(runtimeHash).update(files[`${directory}/hooks/osuite_${script}.mjs`]).digest('hex').slice(0, 16);
257
+ const tag = ` --osuite-hook-version=${hash}`;
258
+ handler.command += tag;
259
+ handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"${tag}`;
260
+ }
245
261
  settings.hooks[event] = [{ hooks: [handler] }];
246
262
  }
247
263
  if (host === 'claude') settings.hooks.PostToolUseFailure = settings.hooks.PostToolUse;
@@ -632,7 +648,7 @@ function managedFileStatus(projectRoot, relativePath, expected) {
632
648
  function isManagedHookCommand(command, projectRoot, relativePath) {
633
649
  if (typeof command !== 'string') return false;
634
650
  const executable = relativePath.endsWith('.py') ? 'python3' : 'node';
635
- const text = command.trim();
651
+ const text = (relativePath.startsWith('.codex/') ? withoutCodexTag(command) : command).trim();
636
652
  // Recognize the former stock Codex template without evaluating its substitution.
637
653
  if (relativePath.startsWith('.codex/') && executable === 'python3'
638
654
  && text === `python3 "$(git rev-parse --show-toplevel)/${relativePath}"`) return true;
@@ -825,7 +841,8 @@ export function parseDotenv(body) {
825
841
 
826
842
  /** The credentials the installed hook will use: shell values first, then its own .env. */
827
843
  export function hookCredentials(projectRoot, installation, shellEnv = process.env) {
828
- const dotenv = parseDotenv(readIfExists(path.join(projectRoot, installation.installDir, '.env')));
844
+ const relativePath = `${installation.installDir}/.env`;
845
+ const dotenv = parseDotenv(readCredentialFile(projectRoot, relativePath, { maxBytes: 65536 }));
829
846
  const env = { ...dotenv };
830
847
  Object.entries(shellEnv || {}).forEach(([key, value]) => {
831
848
  if (value !== undefined) env[key] = value;
@@ -833,7 +850,7 @@ export function hookCredentials(projectRoot, installation, shellEnv = process.en
833
850
  return {
834
851
  baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
835
852
  apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
836
- envFile: `${installation.installDir}/.env`,
853
+ envFile: inspectCredentialFile(projectRoot, relativePath).storagePath,
837
854
  hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || (installation.runtime === 'cursor' ? 'observe' : 'enforce')),
838
855
  };
839
856
  }
@@ -139,8 +139,9 @@ function installCheck(payload, context) {
139
139
  return { authorized: false, decision: payload.decision.decision, installCheck: true, reason: 'approval_not_requested', response: payload };
140
140
  }
141
141
 
142
- export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(), beforeRelease = async () => true } = {}) {
143
- const guard = await api.request('POST', '/api/guard', context);
142
+ export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(),
143
+ beforeRelease = async () => true, rememberOperation } = {}) {
144
+ const guard = await api.request('POST', '/api/guard', rememberOperation ? { ...context, hook_dispatch: 'v1' } : context);
144
145
  if (!guard.ok) {
145
146
  // Rejection, bad evidence and unknown errors are not availability failures.
146
147
  if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status });
@@ -153,27 +154,38 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
153
154
  if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
154
155
  const rollout = rolloutAuthority(guard.body, context, config);
155
156
  if (!rollout.valid) return closed('rule_rollout_binding_invalid');
156
- const finish = result => rollout.binding ? { ...result, observeOnly: false, ruleRolloutBinding: rollout.binding } : result;
157
+ const operationId = rememberOperation && /^hact_[a-f0-9]{64}$/.test(guard.body.hook_action_id || '') ? guard.body.hook_action_id : null;
158
+ if (operationId && !rememberOperation(operationId)) return closed('hook_operation_binding_changed', { actionId: operationId });
159
+ const binding = operationId ? { action_id: operationId, hook_dispatch: 'v1' } : {};
160
+ const finish = result => ({
161
+ ...result,
162
+ ...(operationId ? { hookOperationId: operationId } : {}),
163
+ ...(rollout.binding ? { observeOnly: false, ruleRolloutBinding: rollout.binding } : {}),
164
+ });
165
+ const create = fields => api.request('POST', '/api/actions', { ...context, ...binding, ...fields });
157
166
  if (requestedDecision === 'block') {
158
167
  // Observation still persists the would-block result, but never calls it authority.
159
168
  const observeOnly = config.mode === 'observe' && !rollout.binding;
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 });
169
+ let actionId = null;
170
+ if (observeOnly || operationId) {
171
+ const recorded = await create(operationId
172
+ ? { status: 'cancelled', timestamp_end: new Date().toISOString(), error_message: 'CLIENT_BLOCKED' }
173
+ : { status: 'blocked' });
174
+ if (safeId(recorded.body?.action_id) && (!operationId || recorded.body.action_id === operationId)) actionId = recorded.body.action_id;
175
+ if (!actionId && observeOnly && !recorded.ok && (!isTransientFailure(recorded) || config.guardFailureMode !== 'allow')) {
176
+ return finish(closed('admission_unconfirmed', { rejectedStatus: recorded.status, actionId: operationId }));
164
177
  }
165
178
  }
166
- return finish({ ...closed('policy_block'), observeOnly, response: guard.body });
179
+ return finish({ ...closed('policy_block'), observeOnly, response: guard.body, actionId });
167
180
  }
168
- const created = await api.request('POST', '/api/actions', {
169
- ...context, status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running',
170
- });
171
- if (!created.ok) return closed('admission_unconfirmed', { rejectedStatus: created.status });
181
+ const created = await create({ status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running' });
182
+ if (!created.ok) return finish(closed('admission_unconfirmed', { rejectedStatus: created.status, actionId: operationId }));
183
+ if (operationId && created.body?.action_id !== operationId) return finish(closed('hook_operation_binding_changed', { actionId: operationId }));
172
184
  if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
173
185
  const diagnostic = installCheck(created.body, context);
174
186
  if (diagnostic) return finish(diagnostic);
175
187
  let result = finish(actionAdmission(created.body, requestedDecision, context));
176
- if (result.authorized) return await beforeRelease(result.response) ? result : closed('action_evidence_changed');
188
+ if (result.authorized) return await beforeRelease(result.response) ? result : finish(closed('action_evidence_changed', { actionId: result.actionId }));
177
189
  if (result.decision !== 'require_approval') return result;
178
190
  if (config.mode === 'observe' && !rollout.binding) return { ...result, observeOnly: true };
179
191
 
@@ -205,11 +217,11 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
205
217
  return closed('approval_not_confirmed', { actionId: expected.actionId });
206
218
  }
207
219
  // GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
208
- const current = await api.request('POST', '/api/actions', { ...context, status: 'running' });
220
+ const current = await create({ status: 'running' });
209
221
  if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId, rejectedStatus: current.status });
210
222
  if (!rolloutAuthority(current.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
211
223
  result = finish(actionAdmission(current.body, 'allow', context, expected));
212
- if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
224
+ if (result.authorized && !await beforeRelease(result.response)) return finish(closed('action_evidence_changed', { actionId: result.actionId }));
213
225
  return result;
214
226
  }
215
227
  return result;