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.
@@ -0,0 +1,77 @@
1
+ # Read a refund evidence packet
2
+
3
+ `assessRefundEvidence` is an opt-in, synchronous Node examiner. It answers three historical questions: who approved this refund, what minor-unit limit covered it, and what the named resource owner observed at the specified close. It does not authorize, execute or retry a refund. It makes no callbacks, network requests, file reads or writes.
4
+
5
+ ## Connect the sources
6
+
7
+ 1. **Pin the case outside Studio.** Obtain the expected organization, action, unique refund operation, ledger, account, destination, amount, currency and immutable close ID from the buyer's independently authenticated case record. Never derive these expectations from the packet under examination. Use a stable destination alias, not bank or card details.
8
+ 2. **Pin the two issuers out of band.** Provision the approver service's verification key through the approval authority, and the ledger read service's key separately through the resource owner. Bind the pins to these roles, organization, resource and relevant historical close in your verifier configuration. Do not accept keys or a trust policy shipped with the proof, and do not use the Studio/operator key for either role.
9
+ 3. **Collect two optional facts.** The approval source signs a named authorizer and covering limit. The owner independently reads the exact operation at the exact close, then signs one posting and its reference or explicit complete absence. An incomplete read can be marked incomplete or omitted. If the source returns multiple candidates, retain the multiplicity; do not select the favorable record. Producing and authenticating these facts is integration work, separate from reading them.
10
+
11
+ ```js
12
+ import { assessRefundEvidence } from './business-evidence.mjs';
13
+
14
+ // Collection, outside the offline examiner: osuite is an already configured SDK client.
15
+ const expected = {
16
+ orgId: 'org-demo', actionId: 'act-41', operationId: 'refund-72',
17
+ resourceId: 'shop-ledger', accountId: 'acct-19', destination: 'card-alias-8',
18
+ amountMinor: 2500, currency: 'CAD', closeId: 'close-004',
19
+ };
20
+ const proofExport = await osuite.exportProof({ actionId: expected.actionId });
21
+
22
+ // Offline: verifierConfig is trusted local configuration, not part of the export.
23
+ const pins = { approver: verifierConfig.approverSpki, owner: verifierConfig.ownerSpki };
24
+ function review(locator, caseFile) {
25
+ return assessRefundEvidence({ proofExport: locator, expected: caseFile.anchor, pins,
26
+ approvalEvidence: caseFile.approval, ownerEvidence: caseFile.owner });
27
+ }
28
+ const fromReturnsDesk = ticket => review(ticket.proof, ticket.caseFile);
29
+ const fromNightlyBatch = row => review(row.exportedLocator, row.reviewFile);
30
+ const deskFacts = fromReturnsDesk({ proof: proofExport,
31
+ caseFile: { anchor: expected, approval: approvalRecordList, owner: ownerRecordList } });
32
+ // Another refund into the same ledger has its own locator, anchor and signed facts.
33
+ const batchFacts = fromNightlyBatch(batchRow);
34
+ ```
35
+
36
+ Only the export's own `export_type: "osuite.proof_export.v1"`, `org_id` and `action_id` are read. Equal amounts, entry names, Studio approval, revocation, callback success and a missing receipt establish no posting outcome. These two adapters demonstrate fixture-level portability, not native execution in any other runtime.
37
+
38
+ ## Producer wire format, v1
39
+
40
+ Each optional evidence argument is a **string**, at most 4096 UTF-8 bytes, containing compact canonical JSON for a list with **one** positional record. Omit the argument or use `"[]"` for no record. There are no JSON objects, optional tuple fields, embedded keys or algorithm selectors in the accepted wire. The tuple order below is normative:
41
+
42
+ ```text
43
+ S = [orgId, actionId, operationId, resourceId, accountId, destination, amountMinor, currency, closeId]
44
+ A = ["osuite.refund.approval.v1", S, approverId, limitMinor]
45
+ O = ["osuite.refund.owner_close.v1", S, complete, outcome, postingRef]
46
+ ```
47
+
48
+ For either unsigned tuple `body`, sign exactly the UTF-8 bytes of `JSON.stringify(["osuite.refund_evidence.signature.v1", ...body])` with pure Ed25519 (no prehash or newline). Append the standard padded base64 signature (64 decoded bytes) and transmit `JSON.stringify([[...body, signatureBase64]])`. Example at an authorized **producer**, never in the reader:
49
+
50
+ ```js
51
+ const bytes = Buffer.from(JSON.stringify(['osuite.refund_evidence.signature.v1', ...body]), 'utf8');
52
+ const signatureBase64 = sign(null, bytes, producerSigningKey).toString('base64'); // node:crypto
53
+ const oneRecordList = JSON.stringify([[...body, signatureBase64]]);
54
+ ```
55
+
56
+ - Pins are canonical standard padded base64 of the **44-byte RFC 8410 DER SubjectPublicKeyInfo** for Ed25519 (not raw keys, PEM, JWK, private keys or key IDs). Node producer spelling: `publicKey.export({format:'der', type:'spki'}).toString('base64')`. The examiner checks the algorithm and DER round trip, then compares the two pins by canonical public-key bytes. Reuse invalidates both roles. One missing/invalid pin leaves the other role independently assessable.
57
+ - All identifiers, including the authorizer and non-null posting reference, are 1 to 128 ASCII characters, start with a letter or digit, and otherwise contain only letters, digits or `._:/@+-`. Currency is exactly three uppercase ASCII letters. Amount and limit are positive safe integers, at most 9007199254740991. Limit is in the scope currency's minor units and must cover the amount. No normalization, currency conversion or close-time tolerance is applied.
58
+ - `complete` is a JSON boolean. For a known settlement it must be `true`; `"posted"` requires one non-null posting reference and `"not_posted"` requires explicit `null`. A source with multiple postings must not represent them as a single posting. Both records sign **all** of S, not just amount or account.
59
+ - Accepted wire must equal ECMAScript `JSON.stringify` of its validated tuple list: no whitespace, alternate numeric forms, escaped equivalent spellings, extra fields or noncanonical base64. The options, expected scope, pins and export are plain JavaScript data objects (same-realm or null prototype); only named own data properties are projected. Do not pass proxies, accessors, callbacks or instances. Irrelevant export fields are not traversed or size-scanned; bound the transport *before* loading an entire export.
60
+
61
+ ## Read the result
62
+
63
+ The exact top-level keys are `{ profile: "osuite.refund_evidence.v1", approver, limitMinor, settlement }`. Each fact is `{ status, source, reason, value }`. On success, `status: "known"` and `reason: "verified"`. Approval values are an authorizer ID and integer limit, each with `source: "approver"`. Settlement has `source: "resource_owner"` and value `{ outcome: "posted", postingRef: "ledger-127" }` or `{ outcome: "not_posted", postingRef: null }`. An unknown fact has `status: "unknown"`, the required source, and `value: null`.
64
+
65
+ | Unknown reason | Meaning |
66
+ | --- | --- |
67
+ | `invalid_expected_scope`, `locator_mismatch`, `shared_pin` | Global: no facts can be attributed to this case. |
68
+ | `missing_pin`, `invalid_pin` | The required issuer has no usable independently pinned verification key. |
69
+ | `missing_evidence`, `evidence_too_large`, `invalid_evidence` | Source evidence is absent, exceeds the cap, or is not the exact wire profile. |
70
+ | `ambiguous_evidence`, `scope_mismatch` | Multiple candidate records (even duplicates), or a record that does not bind this case. |
71
+ | `invalid_signature`, `verification_unavailable` | The pinned verifier rejected the signature or the local crypto provider could not verify it. |
72
+ | `insufficient_limit` | The signed limit does not cover this refund. |
73
+ | `incomplete_observation`, `contradictory_observation` | The signed read is incomplete or its outcome and reference disagree. |
74
+
75
+ Global checks precede role checks; within a role, the pin is required before reading its evidence. A usable signature authenticates an assertion, not its truth. The reader cannot discover omitted records, undisclosed key sharing, dishonest signers or subsequent changes. A matching owner observation is **not externally confirmed bank settlement**. Approval is not current authority, and revocation is not reversal.
76
+
77
+ Offline acceptance from the repository root: `node --test sdk/governed-tools/test/business-evidence.test.mjs`. The tests generate temporary signing keys in process; no private keys are persisted or shipped.
package/GOVERNED_TOOLS.md CHANGED
@@ -192,6 +192,12 @@ initial creation into a held state. Redemption/dispatch fences are not reset.
192
192
  A successful GET showing approval is not a grant to send: a fresh signed POST
193
193
  must validate and redeem the original request.
194
194
 
195
+ When the review attached to that exact request is already denied, expired, or
196
+ cancelled, a still-pending action summary does not mean "keep waiting." Status
197
+ reads advise stopping without changing the journal. Resuming that same held
198
+ operation records the terminal reason and stops before tool dispatch; reopening
199
+ the journal preserves that reason. This is not evidence about an earlier write.
200
+
195
201
  There is no distributed transaction with an arbitrary SaaS. The journal commits
196
202
  the dispatch fence before invoking the callback. This prevents automatic local
197
203
  resend but can leave a request uncertain if the process dies between those two
package/README.md CHANGED
@@ -168,6 +168,10 @@ The v2 SDK exposes the core governance loop plus first-class PCAA, replay, proof
168
168
  - `verifyGovernanceProof(actionId)` -- Verify attestation/proof integrity and return structured checks.
169
169
  - `getComplianceEvidence({ window })` -- Pull live evidence aggregates for compliance and PCAA health.
170
170
  - `exportProof({ actionId, bundleId })` -- Export the portable verifier-facing proof package.
171
+ - The opt-in [business evidence reader](BUSINESS_EVIDENCE.md) links a refund
172
+ to independently signed approval and resource-close records. A Studio proof
173
+ on its own does not establish that a refund posted. This is an experimental
174
+ source-candidate subpath, not a feature of previously published tarballs.
171
175
  - `getPcaaHealth({ window })` -- Compute checkpoint coverage, approval trigger rate, and evidence completion.
172
176
  - `getPcaaAction(actionId)` -- Fetch one action's replay/proof/export bundle and derive checkpoint states.
173
177
  - `events()` -- Subscribe to live approval and governance events over SSE.
@@ -0,0 +1,139 @@
1
+ import { createPublicKey, verify } from 'node:crypto';
2
+ import { types } from 'node:util';
3
+
4
+ const PROFILE = 'osuite.refund_evidence.v1';
5
+ const DOMAIN = 'osuite.refund_evidence.signature.v1';
6
+ const APPROVAL = 'osuite.refund.approval.v1';
7
+ const OWNER = 'osuite.refund.owner_close.v1';
8
+ const MAX_WIRE_BYTES = 4096;
9
+ const SCOPE = ['orgId', 'actionId', 'operationId', 'resourceId', 'accountId', 'destination',
10
+ 'amountMinor', 'currency', 'closeId'];
11
+ const INVALID = Symbol('not an own data field');
12
+
13
+ // Project only named fields. Never enumerate, clone, stringify or coerce the caller's objects.
14
+ function field(object, key) {
15
+ if (object === null || typeof object !== 'object' || types.isProxy(object)) return INVALID;
16
+ const proto = Object.getPrototypeOf(object);
17
+ if (proto !== Object.prototype && proto !== null) return INVALID;
18
+ const d = Object.getOwnPropertyDescriptor(object, key);
19
+ return d === undefined ? undefined : Object.hasOwn(d, 'value') ? d.value : INVALID;
20
+ }
21
+
22
+ function id(value) {
23
+ return typeof value === 'string' && value.length >= 1 && value.length <= 128 &&
24
+ /^[a-zA-Z0-9]/.test(value) && !/[^a-zA-Z0-9._:/@+-]/.test(value);
25
+ }
26
+
27
+ function minor(value) {
28
+ return Number.isSafeInteger(value) && value > 0;
29
+ }
30
+
31
+ function validScope(tuple) {
32
+ return tuple.every((value, i) => {
33
+ if (SCOPE[i] === 'amountMinor') return minor(value);
34
+ if (SCOPE[i] === 'currency') return typeof value === 'string' && value.length === 3 && !/[^A-Z]/.test(value);
35
+ return id(value);
36
+ });
37
+ }
38
+
39
+ function fact(source, reason, value = null) {
40
+ return { status: reason === 'verified' ? 'known' : 'unknown', source, reason, value };
41
+ }
42
+
43
+ function unknown(reason) {
44
+ return {
45
+ profile: PROFILE,
46
+ approver: fact('approver', reason),
47
+ limitMinor: fact('approver', reason),
48
+ settlement: fact('resource_owner', reason),
49
+ };
50
+ }
51
+
52
+ function base64Bytes(text, size) {
53
+ if (typeof text !== 'string' || text.length !== 4 * Math.ceil(size / 3)) return null;
54
+ const bytes = Buffer.from(text, 'base64');
55
+ return bytes.length === size && bytes.toString('base64') === text ? bytes : null;
56
+ }
57
+
58
+ function pin(text) {
59
+ if (text === undefined) return { reason: 'missing_pin' };
60
+ const bytes = base64Bytes(text, 44);
61
+ if (bytes) {
62
+ try {
63
+ const key = createPublicKey({ key: bytes, format: 'der', type: 'spki' });
64
+ const spki = key.export({ format: 'der', type: 'spki' });
65
+ if (key.asymmetricKeyType === 'ed25519' && spki.equals(bytes)) return { key, spki };
66
+ } catch {
67
+ // Incorrect SPKI or unsupported algorithm: never fall back to an envelope key.
68
+ }
69
+ }
70
+ return { reason: 'invalid_pin' };
71
+ }
72
+
73
+ function checkRecord(text, issuer, type, scope) {
74
+ if (issuer.reason) return { reason: issuer.reason };
75
+ if (text === undefined || text === '[]') return { reason: 'missing_evidence' };
76
+ if (typeof text !== 'string') return { reason: 'invalid_evidence' };
77
+ if (text.length > MAX_WIRE_BYTES || Buffer.byteLength(text) > MAX_WIRE_BYTES) {
78
+ return { reason: 'evidence_too_large' };
79
+ }
80
+
81
+ let list;
82
+ try {
83
+ list = JSON.parse(text);
84
+ } catch {
85
+ return { reason: 'invalid_evidence' };
86
+ }
87
+ if (Array.isArray(list) && list.length > 1) return { reason: 'ambiguous_evidence' };
88
+ if (!Array.isArray(list) || list.length !== 1) return { reason: 'invalid_evidence' };
89
+ const [r] = list;
90
+ const approval = type === APPROVAL;
91
+ if (!Array.isArray(r) || r.length !== (approval ? 5 : 6) || r[0] !== type) {
92
+ return { reason: 'invalid_evidence' };
93
+ }
94
+ if (!Array.isArray(r[1]) || r[1].length !== scope.length || !scope.every((v, i) => v === r[1][i])) {
95
+ return { reason: 'scope_mismatch' };
96
+ }
97
+ const validFields = approval ? id(r[2]) && minor(r[3]) :
98
+ typeof r[2] === 'boolean' && (r[3] === 'posted' || r[3] === 'not_posted') && (r[4] === null || id(r[4]));
99
+ if (!validFields) return { reason: 'invalid_evidence' };
100
+ const signature = base64Bytes(r.at(-1), 64);
101
+ // Only flat, shape-checked tuples of bounded primitives reach serialization here.
102
+ if (!signature || JSON.stringify(list) !== text) return { reason: 'invalid_evidence' };
103
+ const signed = Buffer.from(JSON.stringify([DOMAIN, ...r.slice(0, -1)]), 'utf8');
104
+ try {
105
+ if (!verify(null, signed, issuer.key, signature)) return { reason: 'invalid_signature' };
106
+ } catch {
107
+ return { reason: 'verification_unavailable' };
108
+ }
109
+ if (approval && r[3] < scope[SCOPE.indexOf('amountMinor')]) return { reason: 'insufficient_limit' };
110
+ if (!approval && !r[2]) return { reason: 'incomplete_observation' };
111
+ if (!approval && (r[3] === 'posted') !== (r[4] !== null)) {
112
+ return { reason: 'contradictory_observation' };
113
+ }
114
+ return { reason: 'verified', record: r };
115
+ }
116
+
117
+ export function assessRefundEvidence(input) {
118
+ const expected = field(input, 'expected');
119
+ const scope = SCOPE.map(key => field(expected, key));
120
+ if (!validScope(scope)) return unknown('invalid_expected_scope');
121
+ const proof = field(input, 'proofExport');
122
+ if (field(proof, 'export_type') !== 'osuite.proof_export.v1' ||
123
+ field(proof, 'org_id') !== scope[0] || field(proof, 'action_id') !== scope[1]) {
124
+ return unknown('locator_mismatch');
125
+ }
126
+ const pins = field(input, 'pins');
127
+ const approver = pin(pins === undefined ? undefined : field(pins, 'approver'));
128
+ const owner = pin(pins === undefined ? undefined : field(pins, 'owner'));
129
+ if (approver.spki && owner.spki && approver.spki.equals(owner.spki)) return unknown('shared_pin');
130
+
131
+ const a = checkRecord(field(input, 'approvalEvidence'), approver, APPROVAL, scope);
132
+ const o = checkRecord(field(input, 'ownerEvidence'), owner, OWNER, scope);
133
+ return {
134
+ profile: PROFILE,
135
+ approver: fact('approver', a.reason, a.record?.[2]),
136
+ limitMinor: fact('approver', a.reason, a.record?.[3]),
137
+ settlement: fact('resource_owner', o.reason, o.record ? { outcome: o.record[3], postingRef: o.record[4] } : null),
138
+ };
139
+ }
package/cli.js CHANGED
@@ -8,6 +8,8 @@ import { fileURLToPath } from 'node:url';
8
8
  import { OSuite, buildReviewSurface } from './osuite.js';
9
9
  import { runTryFlow } from './tryFlow.js';
10
10
  import { runDoctorWithMeasurement } from './activationMetrics.js';
11
+ import { auditCodexTrust, codexExecArguments, inspectCodexTrust } from './codexTrust.mjs';
12
+ import { runCodexExec } from './codexExec.mjs';
11
13
  import {
12
14
  credentialDigest, getInstallationIdentity, migrateMcpInstallation, parseInstallationIdentity,
13
15
  readInstallationBundle, readInstallationIdentity, readMcpMigration,
@@ -64,7 +66,7 @@ const PROJECT_BOOTSTRAPS = {
64
66
  endpoint: '/api/runtimes/codex/bootstrap',
65
67
  envPath: '.codex/.env.example',
66
68
  readmePath: '.codex/README.osuite.md',
67
- runLine: 'Run Codex from this project root so .codex/hooks.json can govern Bash/Edit/Write actions.',
69
+ runLine: 'After reviewing Codex hook trust, run osuite codex exec from this project root.',
68
70
  smokeLine: 'Try: osuite explain "git push origin main", then ask Codex to run a low-risk command such as git status.',
69
71
  },
70
72
  claude: {
@@ -135,21 +137,17 @@ function parseEnvBody(body = '') {
135
137
  return env;
136
138
  }
137
139
 
138
- function loadDotenvFile(relativePath) {
139
- const absolute = path.join(process.cwd(), relativePath);
140
- if (!fs.existsSync(absolute)) return;
141
- for (const [key, value] of Object.entries(parseEnvBody(fs.readFileSync(absolute, 'utf8')))) {
142
- if (!process.env[key]) process.env[key] = value;
143
- }
144
- }
145
-
146
140
  function loadProjectEnvironment() {
147
141
  // Enrollment selects one whole runtime bundle, never a merged global env.
148
- if (process.argv[2] === 'connect' || CONTROLLED_TRANSFER_CLI || NATIVE_RUNTIME_DOCTOR) return;
149
- [...CLI_CREDENTIAL_PATHS, '.env'].forEach((relativePath) => {
150
- if (process.argv[2] === 'doctor' && !inspectCredentialFile(process.cwd(), relativePath).safe) return;
151
- loadDotenvFile(relativePath);
152
- });
142
+ if (['connect', 'codex'].includes(process.argv[2]) || CONTROLLED_TRANSFER_CLI || NATIVE_RUNTIME_DOCTOR) return;
143
+ for (const relativePath of [...CLI_CREDENTIAL_PATHS, '.env']) {
144
+ let body;
145
+ try { body = readCredentialFile(process.cwd(), relativePath, { maxBytes: 65536 }); }
146
+ catch { continue; } // Doctor and connect provide the repair details.
147
+ for (const [key, value] of Object.entries(parseEnvBody(body || ''))) {
148
+ if (!process.env[key]) process.env[key] = value;
149
+ }
150
+ }
153
151
  }
154
152
 
155
153
  function parseArgs(argv) {
@@ -687,6 +685,40 @@ async function installRuntimeProjectBootstrap(target, args = {}, { nextSteps = t
687
685
  return { ok: blockers.length === 0, results, blockers };
688
686
  }
689
687
 
688
+ async function codexTrustCheck(installation) {
689
+ const projectRoot = process.cwd();
690
+ const trust = await inspectCodexTrust({ projectRoot, installation, env: SHELL_ENV });
691
+ writeCheckLine(trust.status === 'trusted' ? 'ok' : 'warn', 'Codex hook trust', `${trust.status}${trust.guidance ? ` — ${trust.guidance}` : ''}`);
692
+ if (installation?.hostEnabled) await auditCodexTrust(projectRoot, SHELL_ENV, trust);
693
+ return trust;
694
+ }
695
+
696
+ async function managedCodexExec(raw) {
697
+ const [command, ...rest] = raw;
698
+ const strict = rest[0] !== '--osuite-observe';
699
+ const args = ['--strict', '--osuite-observe'].includes(rest[0]) ? rest.slice(1) : rest;
700
+ if (command !== 'exec' || !codexExecArguments(args)) {
701
+ throw new Error('Usage: osuite codex exec [--strict|--osuite-observe] [--json] [--model NAME] [--sandbox read-only|workspace-write] PROMPT');
702
+ }
703
+ const projectRoot = process.cwd();
704
+ const [installation] = findHookInstallations(projectRoot, ['codex'], { diagnose: true });
705
+ const trust = await inspectCodexTrust({ projectRoot, installation, env: SHELL_ENV });
706
+ const blocked = strict && trust.status !== 'trusted';
707
+ process.stderr.write(`${JSON.stringify({
708
+ type: 'osuite.governance_status', host: 'codex', hook_trust: trust.status,
709
+ mode: strict ? 'strict' : 'observe', status: blocked ? 'blocked' : trust.status === 'trusted' ? 'hooks_trusted' : 'ungoverned',
710
+ ...(trust.guidance ? { message: trust.guidance } : {}),
711
+ })}\n`);
712
+ await auditCodexTrust(projectRoot, SHELL_ENV, trust);
713
+ if (blocked) { process.exitCode = 2; return; }
714
+ if (trust.status === 'trusted') { process.exitCode = await runCodexExec(projectRoot, args, SHELL_ENV, installation, { strict }); return; }
715
+ process.exitCode = await new Promise((resolve, reject) => {
716
+ const child = spawn('codex', ['exec', ...args], { cwd: projectRoot, env: SHELL_ENV, stdio: 'inherit' });
717
+ child.on('error', reject);
718
+ child.on('close', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 130 : 1)));
719
+ });
720
+ }
721
+
690
722
  function writeCheckLine(status, label, detail) {
691
723
  const tags = {
692
724
  ok: c('OK ', ANSI.green),
@@ -707,6 +739,7 @@ async function verifyProjectHooks(runtimes) {
707
739
  ? 'managed Node runtime and launcher bytes match this CLI; not a registry/latest-version or native-host verification'
708
740
  : 'Not verified against this CLI\'s packaged Node runtime; probe success cannot establish installation freshness'}`);
709
741
  diagnostics.warnings.forEach(warning => writeCheckLine('warn', 'Install warning', `${installation.label}: ${warning}`));
742
+ if (installation.runtime === 'codex') await codexTrustCheck(installation);
710
743
  if (diagnostics.status !== 'current') {
711
744
  writeCheckLine('warn', 'Install next step', `Upgrade the OSuite CLI, then run osuite connect ${installation.runtime}; review preserved custom differences before replacing files. Disabled hooks remain disabled.`);
712
745
  }
@@ -753,6 +786,7 @@ function printHelp() {
753
786
  write(' osuite connect [auto|codex|claude|cursor|sdk|mcp] Detect runtime and start browser handoff');
754
787
  write(' --no-browser prints the link instead of opening it');
755
788
  write(' osuite connect mcp --migrate-legacy Move legacy MCP state locally; no enrollment or ACK');
789
+ write(' osuite codex exec PROMPT Check native hook trust before running Codex');
756
790
  write(' osuite init [sdk|codex|claude|cursor|mcp] Prepare a runtime lane');
757
791
  write('');
758
792
  write(c('Environment', ANSI.bold));
@@ -1233,16 +1267,21 @@ async function doctor() {
1233
1267
 
1234
1268
  const credentialChecks = [...CLI_CREDENTIAL_PATHS.flatMap((file) => [file, `${file}.identity.json`, `${file}.connect.json`, `${file}.connect.lock`]), MCP_MIGRATION_PATH, '.env']
1235
1269
  .map((relativePath) => inspectCredentialFile(process.cwd(), relativePath));
1236
- const unsafeCredentials = credentialChecks.filter((check) => check.exists && !check.safe);
1237
- for (const check of credentialChecks.filter((item) => item.exists)) {
1238
- writeCheckLine(check.safe ? 'ok' : 'fail', 'Credential file', `${check.relativePath}: ${check.safe ? check.mode ? `${check.mode}; owner-only` : 'review platform ACLs; POSIX mode unavailable' : `unsafe; ${check.problems.join('; ')}`}`);
1270
+ const unsafeCredentials = credentialChecks.filter((check) => !check.safe);
1271
+ const reported = new Set();
1272
+ for (const check of credentialChecks.filter((item) => item.exists || !item.safe)) {
1273
+ const problem = check.problems.join('; ');
1274
+ if (problem && reported.has(problem)) continue;
1275
+ reported.add(problem);
1276
+ writeCheckLine(check.safe ? 'ok' : 'fail', 'Credential file', `${check.storagePath}: ${check.safe ? check.mode ? `${check.mode}; owner-only` : 'review platform ACLs; POSIX mode unavailable' : `unsafe; ${problem}`}`);
1239
1277
  }
1240
1278
  if (unsafeCredentials.length) {
1241
1279
  write('Repair credential protection before running hooks. Reconnect to rotate any possibly exposed key; chmod alone cannot undo disclosure.');
1242
1280
  process.exitCode = 1;
1243
1281
  return false;
1244
1282
  }
1245
- if (credentialChecks.some((check) => check.exists && check.relativePath === MCP_MIGRATION_PATH)) {
1283
+ if (credentialChecks.some((check) => check.exists && check.relativePath === MCP_MIGRATION_PATH)
1284
+ && readMcpMigration(process.cwd()).manifest) {
1246
1285
  writeCheckLine('warn', 'MCP migration', 'resume osuite connect mcp --migrate-legacy before using either SDK or MCP.');
1247
1286
  process.exitCode = 1;
1248
1287
  return false;
@@ -1320,13 +1359,16 @@ async function tryWalkthrough(args) {
1320
1359
  if (args._.length || Object.keys(args).some((key) => !['_', 'timeout-ms'].includes(key))) {
1321
1360
  throw new Error('osuite try accepts no command arguments: its output is fixed. Only --timeout-ms may be set.');
1322
1361
  }
1323
- if (inspectCredentialFile(process.cwd(), MCP_MIGRATION_PATH).exists) {
1362
+ const migration = inspectCredentialFile(process.cwd(), MCP_MIGRATION_PATH);
1363
+ if (!migration.safe) throw new Error('Credential storage needs attention. Run osuite doctor before starting the walkthrough.');
1364
+ if (migration.exists && readMcpMigration(process.cwd()).manifest) {
1324
1365
  throw new Error('Resume osuite connect mcp --migrate-legacy before starting the walkthrough.');
1325
1366
  }
1326
1367
  for (const file of [...CLI_CREDENTIAL_PATHS, '.env']) {
1327
1368
  const check = inspectCredentialFile(process.cwd(), file);
1328
- if (check.exists && !check.safe) throw new Error('Credential storage needs attention. Run osuite doctor before starting the walkthrough.');
1329
- if (inspectCredentialFile(process.cwd(), `${file}.connect.json`).exists) {
1369
+ const recovery = inspectCredentialFile(process.cwd(), `${file}.connect.json`);
1370
+ if (!check.safe || !recovery.safe) throw new Error('Credential storage needs attention. Run osuite doctor before starting the walkthrough.');
1371
+ if (recovery.exists) {
1330
1372
  throw new Error('Resume the saved osuite connect operation before starting the walkthrough.');
1331
1373
  }
1332
1374
  }
@@ -1608,7 +1650,7 @@ async function connectProject(target = 'auto', args = {}) {
1608
1650
  }
1609
1651
  saveJournal();
1610
1652
  } else {
1611
- if (hasApiKey && fs.existsSync(projectFilePath(envPath))) {
1653
+ if (hasApiKey && liveEnv !== null) {
1612
1654
  throw new Error('This Studio does not support acknowledged reconnect. Upgrade Studio before replacing existing credentials; they were left unchanged.');
1613
1655
  }
1614
1656
  write(c('Legacy Studio protocol: secure file storage is available, but delivery has no acknowledgement or interruption recovery. Upgrade Studio for safe reconnect.', ANSI.yellow));
@@ -1641,8 +1683,13 @@ async function connectProject(target = 'auto', args = {}) {
1641
1683
  if (PROJECT_BOOTSTRAPS[runtime]) {
1642
1684
  if (args['dry-run']) {
1643
1685
  write(`Dry run: would install project hook files for ${runtime}.`);
1686
+ if (runtime === 'codex') writeCheckLine('warn', 'Codex hook trust', 'review the installed OSuite entries with /hooks in Codex after connecting.');
1644
1687
  } else {
1645
1688
  install = await installRuntimeProjectBootstrap(runtime, { ...args, 'base-url': baseUrl }, { nextSteps: false });
1689
+ if (runtime === 'codex') {
1690
+ const [installation] = findHookInstallations(process.cwd(), ['codex'], { diagnose: true });
1691
+ await codexTrustCheck(installation);
1692
+ }
1646
1693
  }
1647
1694
  } else {
1648
1695
  write(c('Runtime setup', ANSI.bold));
@@ -1763,7 +1810,7 @@ async function connect(target = 'auto', args = {}) {
1763
1810
  releases.push(acquireCredentialLock(process.cwd(), envPathForRuntime(runtime)));
1764
1811
  if (args['migrate-legacy']) return migrateLegacyMcp(args);
1765
1812
  if (runtime === 'sdk' || runtime === 'mcp') {
1766
- if (readCredentialFile(process.cwd(), MCP_MIGRATION_PATH) !== null) {
1813
+ if (readCredentialFile(process.cwd(), MCP_MIGRATION_PATH) !== null && readMcpMigration(process.cwd()).manifest) {
1767
1814
  throw new Error('MCP migration is incomplete. Resume osuite connect mcp --migrate-legacy before using either runtime.');
1768
1815
  }
1769
1816
  const legacy = readInstallationBundle(process.cwd(), SDK_ENV_PATH);
@@ -1820,6 +1867,7 @@ function migrateLegacyMcp(args) {
1820
1867
  async function main() {
1821
1868
  const { command, args } = parseArgs(process.argv.slice(2));
1822
1869
 
1870
+ if (command === 'codex') return managedCodexExec(process.argv.slice(3));
1823
1871
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1824
1872
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1825
1873
  if (CONTROLLED_TRANSFER_CLI) return controlledTransferCommand(command, args);
package/codexExec.mjs ADDED
@@ -0,0 +1,120 @@
1
+ import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import { createInterface } from 'node:readline';
4
+ import { loadRuntimeConfig } from './runtime/config.mjs';
5
+ import { createApiClient, safeId } from './runtime/protocol.mjs';
6
+ import { createStateStore } from './runtime/state.mjs';
7
+ import { recordOutcome } from './runtime/outcome.mjs';
8
+ import { resolveRemotePosture } from './runtime/posture.mjs';
9
+ import { inspectCodexTrust } from './codexTrust.mjs';
10
+
11
+ export function nativeCodexResult(item) {
12
+ if (!safeId(item?.id) || !['commandExecution', 'mcpToolCall', 'fileChange'].includes(item.type)) return null;
13
+ if (item.status === 'declined' || item.status === 'cancelled') {
14
+ return { status: 'cancelled', summary: 'Codex reported that execution was declined or cancelled.' };
15
+ }
16
+ if (item.type === 'commandExecution' && Number.isSafeInteger(item.exitCode)) {
17
+ return { status: item.exitCode === 0 && item.status === 'completed' ? 'completed' : 'failed',
18
+ summary: `Codex reported process exit code ${item.exitCode}.` };
19
+ }
20
+ if (item.status === 'failed') {
21
+ return { status: 'failed', summary: 'Codex reported a failed tool result without a process exit code.' };
22
+ }
23
+ if (item.status === 'completed' && item.type !== 'commandExecution') {
24
+ return { status: 'completed', summary: 'Codex reported a terminal tool result.' };
25
+ }
26
+ return null;
27
+ }
28
+
29
+ export async function runCodexExec(projectRoot, args, env, installation, { strict = true } = {}) {
30
+ const options = { sandbox: 'read-only', ephemeral: false };
31
+ const json = args.includes('--json');
32
+ let prompt;
33
+ for (let index = 0; index < args.length; index += 1) {
34
+ const arg = args[index];
35
+ if (arg === '--model') options.model = args[++index];
36
+ else if (arg === '--sandbox') options.sandbox = args[++index];
37
+ else if (arg === '--ephemeral') options.ephemeral = true;
38
+ else if (arg === '--') { prompt = args[index + 1]; break; }
39
+ else if (!arg.startsWith('-')) prompt = arg;
40
+ }
41
+ const config = loadRuntimeConfig({ host: 'codex', installDir: path.join(projectRoot, '.codex'), env });
42
+ const store = createStateStore(config);
43
+ const api = createApiClient(config);
44
+ if (strict) {
45
+ const remote = await resolveRemotePosture(config, { api, store });
46
+ if (!remote.available || remote.blocked || !['enforce', 'strict'].includes(remote.posture.mode)
47
+ || remote.posture.on_guard_unavailable !== 'block') {
48
+ process.stderr.write(JSON.stringify({
49
+ type: 'osuite.governance_status', host: 'codex', status: 'blocked', mode: 'strict', hook_trust: 'trusted',
50
+ reason: 'runtime_posture_not_enforcing', message: 'Set Codex to enforce with guard failures blocked in Studio, then run osuite doctor.',
51
+ }) + '\n');
52
+ return 2;
53
+ }
54
+ }
55
+ const child = spawn('codex', ['app-server', '--listen', 'stdio://'], {
56
+ cwd: projectRoot, env, stdio: ['pipe', 'pipe', 'inherit'],
57
+ });
58
+ const exited = new Promise(resolve => {
59
+ child.on('error', () => resolve(1));
60
+ child.on('close', code => resolve(code ?? 1));
61
+ });
62
+ const send = value => child.stdin.write(JSON.stringify(value) + '\n');
63
+ const messages = createInterface({ input: child.stdout });
64
+ child.stdin.on('error', () => {});
65
+ let threadId;
66
+ let turnId;
67
+ const startup = setTimeout(() => child.kill(), 12000);
68
+ try {
69
+ send({ id: 1, method: 'initialize', params: { clientInfo: { name: 'osuite', version: '1' }, capabilities: { experimentalApi: true } } });
70
+ for await (const line of messages) {
71
+ let message;
72
+ try { message = JSON.parse(line); } catch { continue; }
73
+ if (message.id !== undefined && message.error) {
74
+ process.stderr.write(`[OSuite] Codex request failed (${message.error.code}).\n`);
75
+ return 1;
76
+ }
77
+ if (message.id === 1) {
78
+ send({ method: 'initialized' });
79
+ send({ id: 2, method: 'thread/start', params: { cwd: projectRoot, approvalPolicy: 'never', ...options } });
80
+ } else if (message.id === 2 && safeId(message.result?.thread?.id)) {
81
+ threadId = message.result.thread.id;
82
+ send({ id: 3, method: 'hooks/list', params: { cwds: [projectRoot] } });
83
+ } else if (message.id === 3) {
84
+ const trust = await inspectCodexTrust({ projectRoot, installation, env,
85
+ listHooks: ({ projectRoot: root }) => message.result?.data?.find(entry => entry.cwd === root) });
86
+ if (trust.status !== 'trusted') {
87
+ process.stderr.write(JSON.stringify({ type: 'osuite.governance_status', host: 'codex', status: 'blocked',
88
+ hook_trust: trust.status, message: trust.guidance }) + '\n');
89
+ return 2;
90
+ }
91
+ send({ id: 4, method: 'turn/start', params: { threadId, input: [{ type: 'text', text: prompt, text_elements: [] }] } });
92
+ } else if (message.id === 4 && safeId(message.result?.turn?.id)) {
93
+ turnId = message.result.turn.id;
94
+ clearTimeout(startup);
95
+ } else if (message.method && Object.hasOwn(message, 'id')) {
96
+ send({ id: message.id, error: { code: -32601, message: 'Interactive requests require a Codex terminal session' } });
97
+ } else if (message.method && message.params?.threadId === threadId) {
98
+ if (message.method === 'turn/started' && safeId(message.params.turn?.id)) turnId = message.params.turn.id;
99
+ if (json) process.stdout.write(line + '\n');
100
+ const { item } = message.params;
101
+ if (message.method === 'item/completed' && message.params.turnId === turnId) {
102
+ const nativeOutcome = nativeCodexResult(item);
103
+ if (nativeOutcome) await recordOutcome(config, { session_id: threadId, tool_use_id: item.id }, { api, store, nativeOutcome });
104
+ if (!json && item?.type === 'agentMessage') process.stdout.write(`${item.text}\n`);
105
+ }
106
+ if (message.method === 'turn/completed' && message.params.turn?.id === turnId) {
107
+ return message.params.turn.status === 'completed' ? 0 : 1;
108
+ }
109
+ }
110
+ }
111
+ await exited;
112
+ return 1;
113
+ } finally {
114
+ clearTimeout(startup);
115
+ messages.close();
116
+ child.stdin.destroy();
117
+ child.kill();
118
+ await exited;
119
+ }
120
+ }