osuite 2.15.0 → 2.17.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.
@@ -7,6 +7,7 @@ import { OperationJournal } from './journal.mjs';
7
7
  import { createStudioAuthority } from './authority.mjs';
8
8
  import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject, scopeFor } from './contract.mjs';
9
9
  import { recoveryAdapter, recoveryScope, makeRecoveryInvocation, observeEvidence, validateEvidence, checkRecoveryAuthority } from './recovery.mjs';
10
+ import { ownerReceiptKey, verifyOwnerReceipt } from './owner-receipt.mjs';
10
11
 
11
12
  const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
12
13
  const terminalCodes = Object.freeze({ denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' });
@@ -56,8 +57,34 @@ function registrySnapshot(bindings) {
56
57
  if (!Object.hasOwn(fields.revision || {}, 'value') || !Object.hasOwn(fields.describe || {}, 'value')
57
58
  || !safeId(fields.revision.value) || fields.revision.value.length > 128
58
59
  || typeof fields.describe.value !== 'function' || types.isProxy(fields.describe.value)) reject('INVALID_MAPPING');
60
+ let amount;
61
+ if (fields.amount) {
62
+ if (!Object.hasOwn(fields.amount, 'value')) reject('NATIVE_AMOUNT_UNSUPPORTED');
63
+ try { amount = jsonSnapshot(fields.amount.value, 1024); } catch { reject('NATIVE_AMOUNT_UNSUPPORTED'); }
64
+ }
65
+ let businessKey;
66
+ if (fields.businessKey) {
67
+ if (!Object.hasOwn(fields.businessKey, 'value')) reject('NATIVE_AMOUNT_KEY_INVALID');
68
+ try { businessKey = jsonSnapshot(fields.businessKey.value, 1024); } catch { reject('NATIVE_AMOUNT_KEY_INVALID'); }
69
+ }
70
+ const receipt = fields.ownerReceipt;
71
+ const delegation = fields.delegation?.value;
72
+ if (fields.delegation && (!Object.hasOwn(fields.delegation, 'value') || typeof delegation !== 'function' || types.isProxy(delegation))) reject('INVALID_MAPPING');
73
+ let ownerReceipt;
74
+ if (receipt) {
75
+ if (!Object.hasOwn(receipt, 'value') || !receipt.value || types.isProxy(receipt.value)
76
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(receipt.value))) reject('INVALID_MAPPING');
77
+ const properties = Object.getOwnPropertyDescriptors(receipt.value);
78
+ const expected = ['resourceId', 'publicKey', 'query'];
79
+ if (Reflect.ownKeys(properties).length !== expected.length
80
+ || expected.some(key => !Object.hasOwn(properties[key] || {}, 'value'))) reject('INVALID_MAPPING');
81
+ const { resourceId, publicKey, query } = Object.fromEntries(expected.map(key => [key, properties[key].value]));
82
+ const signer = ownerReceiptKey(publicKey);
83
+ if (!signer || !safeId(resourceId) || resourceId.length > 128 || typeof query !== 'function' || types.isProxy(query)) reject('INVALID_MAPPING');
84
+ ownerReceipt = Object.freeze({ resource: Object.freeze({ resource_id: resourceId, key_id: signer.id }), publicKey, query });
85
+ }
59
86
  Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
60
- describe: fields.describe.value, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
87
+ describe: fields.describe.value, amount, businessKey, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
61
88
  }
62
89
  return Object.freeze(result);
63
90
  }
@@ -82,6 +109,24 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
82
109
  let closed = false, inFlight = 0;
83
110
  const local = operationId => journal.get(scope, operationId);
84
111
  const status = record => publicStatus(record, config.baseUrl);
112
+ async function bindDelegation(invocation) {
113
+ const authorize = bindings[invocation.params.name].delegation;
114
+ if (!authorize) return invocation;
115
+ const { context, record } = invocation;
116
+ let assertion;
117
+ try {
118
+ assertion = jsonSnapshot(await authorize(Object.freeze({
119
+ actionId: record.actionId, inputDigest: record.inputDigest, sessionId: record.sessionId,
120
+ toolUseId: record.toolUseId, operationId: record.operationId, orgId: config.orgId, agentId: config.agentId,
121
+ params: invocation.params,
122
+ actionType: context.action_type, systemsTouched: context.systems_touched || Object.freeze([]),
123
+ })), 8192);
124
+ } catch { reject('DELEGATION_REQUIRED'); }
125
+ if (assertion?.claims?.schema_version !== 'osuite.business_authority.v2' || typeof assertion.signature !== 'string') reject('DELEGATION_REQUIRED');
126
+ const boundContext = jsonSnapshot({ ...context, business_authority_assertion: assertion });
127
+ return { ...invocation, context: boundContext,
128
+ record: { ...record, contextDigest: sha256(canonicalJson(boundContext)) } };
129
+ }
85
130
  const recoveryStatus = operationId => {
86
131
  const child = journal.get(recoveryScope(scope), operationId);
87
132
  return child ? Object.freeze({ ...status(child), evidenceDigest: child.errorCode?.startsWith('recovery_')
@@ -105,7 +150,9 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
105
150
  const { scope, operationId } = invocation.record;
106
151
  const local = operationId => {
107
152
  const record = journal.get(scope, operationId);
108
- return record && invocation.recovery ? { ...record, recovery: invocation.recovery } : record;
153
+ return record && { ...record, recovery: invocation.recovery, nativeAmount: invocation.context.native_amount,
154
+ delegationDigest: invocation.context.business_authority_assertion && sha256(canonicalJson(invocation.context.business_authority_assertion.claims)),
155
+ nativeResource: invocation.context.native_resource };
109
156
  };
110
157
  if (aborted()) reject('ABORTED');
111
158
  const started = performance.now(), deadline = started + waitMs, owner = randomUUID();
@@ -145,7 +192,7 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
145
192
  let admitted;
146
193
  try { admitted = await authority.admit(invocation, journal, owner, aborted); }
147
194
  catch (error) {
148
- if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)));
195
+ if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)), error.details);
149
196
  reject('OUTCOME_UNKNOWN', status(local(operationId)));
150
197
  }
151
198
  if (!admitted) { if (performance.now() >= deadline) waiting(); continue; }
@@ -162,7 +209,8 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
162
209
  // and invoking the original tool. This is not resource-side atomicity.
163
210
  const grantExpiry = admitted.phase === 'redeeming' ? Date.parse(admitted.response.action.approval_expires_at) : Infinity;
164
211
  const ruleExpiry = admitted.ruleExpiresAt == null ? Infinity : Date.parse(admitted.ruleExpiresAt);
165
- const current = () => performance.now() < admitted.dispatchDeadline && Date.now() < Math.min(grantExpiry, ruleExpiry)
212
+ const delegationExpiry = invocation.context.business_authority_assertion ? Date.parse(invocation.context.business_authority_assertion.claims.expires_at) : Infinity;
213
+ const current = () => performance.now() < admitted.dispatchDeadline && Date.now() < Math.min(grantExpiry, ruleExpiry, delegationExpiry)
166
214
  && (!recovery || recovery.fresh());
167
215
  if (aborted() || closed || !current()) {
168
216
  journal.settle(scope, operationId, owner, admitted.phase,
@@ -215,10 +263,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
215
263
 
216
264
  return Object.freeze({
217
265
  async run(operationId, params, execute, options = {}) {
218
- return work(() => {
266
+ return work(async () => {
219
267
  const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
220
268
  if (typeof execute !== 'function' || types.isProxy(execute)) reject('INVALID_EXECUTOR');
221
- return perform(invocation, execute, runOptions(options));
269
+ const settings = runOptions(options);
270
+ if (settings.aborted()) reject('ABORTED');
271
+ return perform(await bindDelegation(invocation), execute, settings);
222
272
  });
223
273
  },
224
274
  async recover(operationId, params, options = {}) {
@@ -227,11 +277,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
227
277
  const settings = runOptions(options);
228
278
  if (settings.aborted()) reject('ABORTED');
229
279
  const adapter = bindings[parent.params.name].recovery;
230
- const record = journal.getBound(parent.record);
280
+ const record = journal.getBound((await bindDelegation(parent)).record);
231
281
  if (!adapter) reject('RECOVERY_UNSUPPORTED', status(record));
232
282
  if (!record) reject('RECOVERY_UNAVAILABLE');
233
283
  if (record.state !== 'uncertain') { stopForState(record); reject('RECOVERY_UNAVAILABLE', status(record)); }
234
- const { invocation, request } = makeRecoveryInvocation(parent, adapter);
284
+ const { invocation: childInvocation, request } = makeRecoveryInvocation(parent, adapter);
285
+ const invocation = await bindDelegation(childInvocation);
235
286
  try {
236
287
  const child = journal.get(invocation.record.scope, operationId);
237
288
  if (child) {
@@ -274,10 +325,42 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
274
325
  if (terminal) failureCode = terminalCodes[terminal];
275
326
  }
276
327
  const attempt = recoveryStatus(operationId);
277
- return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}), remote: Object.freeze({ available: observed.available,
328
+ return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}),
329
+ ...(observed.body?.owner_receipt ? { ownerReceipt: observed.body.owner_receipt } : {}), remote: Object.freeze({ available: observed.available,
278
330
  status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
279
331
  });
280
332
  },
333
+ async reconcile(operationId, params, options = {}) {
334
+ return work(async () => {
335
+ const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
336
+ const adapter = bindings[invocation.params.name].ownerReceipt;
337
+ const localRecord = local(operationId);
338
+ if (localRecord && ['inputDigest', 'bindingDigest', 'actionId'].some(key => localRecord[key] !== invocation.record[key])) reject('CONFLICT');
339
+ if (!adapter || !localRecord) reject('OWNER_RECONCILIATION_UNAVAILABLE', status(localRecord));
340
+ const settings = runOptions(options);
341
+ const unknown = { ...status(localRecord), outcome: 'unknown' };
342
+ if (settings.aborted()) reject('ABORTED', status(localRecord));
343
+ if (!['dispatching', 'uncertain', 'completed'].includes(localRecord.state)) return unknown;
344
+ const nativeResource = invocation.context.native_resource;
345
+ const record = { ...localRecord, nativeResource, nativeAmount: invocation.context.native_amount };
346
+ const expected = Object.freeze({ ...nativeResource, org_id: config.orgId, action_id: record.actionId });
347
+ const observed = await authority.read(record);
348
+ if (!observed.available) return unknown;
349
+ const valid = receipt => verifyOwnerReceipt(receipt, expected, adapter.publicKey, { startedAt: observed.action.timestamp_start });
350
+ let receipt = observed.body.owner_receipt;
351
+ if (!valid(receipt)) {
352
+ const timeout = AbortSignal.timeout(5000);
353
+ const signal = settings.signal ? AbortSignal.any([timeout, settings.signal]) : timeout;
354
+ try { receipt = jsonSnapshot(await adapter.query({ ...expected, operationId, signal }), 8192); }
355
+ catch { return unknown; }
356
+ if (signal.aborted || !valid(receipt)) return unknown;
357
+ const submitted = receipt;
358
+ receipt = await authority.closeOwnerOutcome(record, submitted);
359
+ if (!valid(receipt) || receipt.claims.outcome !== submitted.claims.outcome) return unknown;
360
+ }
361
+ return Object.freeze({ ...status(localRecord), outcome: receipt.claims.outcome, ownerReceipt: receipt });
362
+ });
363
+ },
281
364
  close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
282
365
  });
283
366
  }
@@ -0,0 +1,40 @@
1
+ import { createPublicKey, verify } from 'node:crypto';
2
+ import { canonicalJson, isObject, safeId, sha256 } from '../runtime/protocol.mjs';
3
+
4
+ export const OWNER_RECEIPT_SCHEMA = 'osuite.native_owner_receipt.v1';
5
+ const digest = /^[a-f0-9]{64}$/;
6
+ const timestamp = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/;
7
+
8
+ function bytes(value, size) {
9
+ if (typeof value !== 'string' || value.length !== Math.ceil(size / 3) * 4) return null;
10
+ const buffer = Buffer.from(value, 'base64');
11
+ return buffer.length === size && buffer.toString('base64') === value ? buffer : null;
12
+ }
13
+
14
+ export function ownerReceiptKey(value) {
15
+ const spki = bytes(value, 44);
16
+ if (!spki) return null;
17
+ try {
18
+ const key = createPublicKey({ key: spki, format: 'der', type: 'spki' });
19
+ return key.asymmetricKeyType === 'ed25519' ? { key, id: sha256(spki) } : null;
20
+ } catch { return null; }
21
+ }
22
+
23
+ export function ownerReceiptPayload(claims) {
24
+ return Buffer.from(`${OWNER_RECEIPT_SCHEMA}\n${canonicalJson(claims)}`);
25
+ }
26
+
27
+ export function verifyOwnerReceipt(receipt, expected, publicKey, { startedAt, now = Date.now() } = {}) {
28
+ const { claims, signature } = receipt || {};
29
+ if (!isObject(receipt) || Object.keys(receipt).length !== 2 || !isObject(claims) || Object.keys(claims).length !== 11
30
+ || claims.schema_version !== OWNER_RECEIPT_SCHEMA || claims.complete !== true || claims.final !== true
31
+ || !['committed', 'absent'].includes(claims.outcome) || !safeId(claims.receipt_id)
32
+ || !['org_id', 'action_id', 'resource_id'].every(key => safeId(claims[key]) && claims[key] === expected[key])
33
+ || !['input_digest', 'key_id'].every(key => digest.test(claims[key] || '') && claims[key] === expected[key])
34
+ || !timestamp.test(claims.observed_at || '')) return false;
35
+ const date = Date.parse(claims.observed_at);
36
+ if (!Number.isFinite(date) || date > now + 30000 || (startedAt !== undefined && !(date >= Date.parse(startedAt)))) return false;
37
+ const signer = ownerReceiptKey(publicKey);
38
+ const sig = bytes(signature, 64);
39
+ return Boolean(signer?.id === claims.key_id && sig && verify(null, ownerReceiptPayload(claims), signer.key, sig));
40
+ }
@@ -46,6 +46,7 @@ export function makeRecoveryInvocation(parent, adapter) {
46
46
  const inputSummary = JSON.stringify(summary);
47
47
  if (inputSummary.length > 4000) reject('INVALID_MAPPING');
48
48
  const context = jsonSnapshot({ ...parent.context, input_summary: inputSummary,
49
+ ...(parent.context.native_amount ? { native_amount: { ...parent.context.native_amount, binding_digest: bindingDigest } } : {}),
49
50
  action_id: actionId, runtime_session_id: sessionId, tool_use_id: toolUseId });
50
51
  const invocation = Object.freeze({ params: parent.params, context, marker, recovery: linkage,
51
52
  record: Object.freeze({ ...original, scope, actionId, sessionId, toolUseId, bindingDigest,
@@ -6,6 +6,7 @@ import { prepareCredentialFile, readCredentialFile, removeCredentialFile, writeC
6
6
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
7
7
  const PREFIX = { codex: 'codex-runtime', claude: 'claude-code-runtime', cursor: 'cursor-runtime', mcp: 'mcp-runtime', sdk: 'sdk-runtime' };
8
8
  export const SDK_ENV_PATH = '.osuite/.env';
9
+ export const TERMINAL_ENV_PATH = '.osuite/terminal/.env';
9
10
  export const MCP_ENV_PATH = '.osuite/mcp/.env';
10
11
  export const MCP_MIGRATION_PATH = '.osuite/.env.migrate-mcp.json';
11
12
  const BUNDLE_FILES = { env: '', identity: '.identity.json', journal: '.connect.json' };
@@ -0,0 +1,109 @@
1
+ import { sign, verify } from 'node:crypto';
2
+ import { canonicalJson, isObject, sha256 } from './runtime/protocol.mjs';
3
+ import { ownerReceiptKey, verifyOwnerReceipt } from './governed-tools/owner-receipt.mjs';
4
+
5
+ export const NATIVE_PROOF_TYPE = 'application/vnd.in-toto+json';
6
+ export const NATIVE_CHECKPOINT_TYPE = 'application/vnd.osuite.native-checkpoint+json';
7
+ export const NATIVE_CHECKPOINT_SCOPE = 'registered_native_tools';
8
+ const hex = /^[0-9a-f]{64}$/;
9
+ const actionId = /^act_[0-9a-f]{64}$/;
10
+
11
+ function pae(type, data) {
12
+ return Buffer.concat([Buffer.from(`DSSEv1 ${Buffer.byteLength(type)} ${type} ${data.length} `), data]);
13
+ }
14
+
15
+ export function signNativeEvidence(payloadType, value, signer) {
16
+ const payload = Buffer.from(canonicalJson(value));
17
+ return { payloadType, payload: payload.toString('base64'),
18
+ signatures: [{ keyid: signer.id, sig: sign(null, pae(payloadType, payload), signer.key).toString('base64') }] };
19
+ }
20
+
21
+ function open(envelope, payloadType, pin) {
22
+ if (envelope?.payloadType !== payloadType || typeof envelope.payload !== 'string' || envelope.payload.length > 1500000
23
+ || !Array.isArray(envelope.signatures) || envelope.signatures.length !== 1) return null;
24
+ if (!isObject(envelope.signatures[0])) return null;
25
+ const { keyid, sig } = envelope.signatures[0];
26
+ if (!pin || keyid !== pin.id || typeof sig !== 'string' || sig.length !== 88) return null;
27
+ try {
28
+ const data = Buffer.from(envelope.payload, 'base64'), signature = Buffer.from(sig, 'base64');
29
+ if (data.toString('base64') !== envelope.payload || signature.length !== 64 || signature.toString('base64') !== sig
30
+ || !verify(null, pae(payloadType, data), pin.key, signature)) return null;
31
+ const value = JSON.parse(data);
32
+ if (!isObject(value) || !Buffer.from(canonicalJson(value)).equals(data)) return null;
33
+ return { value, digest: sha256(data) };
34
+ } catch { return null; }
35
+ }
36
+
37
+ export function nativeProofRoot(entries) {
38
+ const ordered = [...entries].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
39
+ return sha256(canonicalJson([NATIVE_CHECKPOINT_SCOPE, ordered]));
40
+ }
41
+
42
+ function validDelegation(predicate, issuers) {
43
+ const authority = predicate.business_authority;
44
+ if (authority?.schema_version !== 'osuite.business_authority.v2') return true;
45
+ const assertion = authority.delegation_assertion;
46
+ const claims = assertion?.claims;
47
+ if (claims?.schema_version !== authority.schema_version || claims.kind !== 'delegated'
48
+ || claims.org_id !== predicate.org_id || claims.principal_org_id !== predicate.org_id
49
+ || claims.agent_id !== predicate.agent_id || claims.action_id !== predicate.action_id || claims.input_digest !== predicate.input_digest
50
+ || !Array.isArray(claims.reviewer_roles) || !Array.isArray(predicate.approval_receipts)
51
+ || !(Date.parse(claims.not_before) <= Date.parse(predicate.timestamp_start) && Date.parse(predicate.timestamp_start) < Date.parse(claims.expires_at))) return false;
52
+ const pin = Array.isArray(issuers) && issuers.filter(root => root?.id === claims.issuer_id && root?.org_id === claims.org_id);
53
+ const issuer = pin?.length === 1 ? ownerReceiptKey(pin[0].public_key) : null;
54
+ if (!issuer || issuer.id !== authority.issuer_key_fingerprint || sha256(canonicalJson(claims)) !== authority.assertion_digest
55
+ || typeof assertion.signature !== 'string' || assertion.signature.length !== 88) return false;
56
+ const signature = Buffer.from(assertion.signature, 'base64');
57
+ if (signature.length !== 64 || signature.toString('base64') !== assertion.signature
58
+ || !verify(null, Buffer.from(`${claims.schema_version}\n${canonicalJson(claims)}`), issuer.key, signature)) return false;
59
+ const { credential_id, ...projected } = claims;
60
+ if (Object.entries(projected).some(([name, value]) => canonicalJson(authority[name]) !== canonicalJson(value))) return false;
61
+ return predicate.approval_receipts.filter(receipt => receipt?.source === 'workspace').every(receipt => {
62
+ const review = receipt.reviewer_authority;
63
+ return review?.org_id === predicate.org_id && review.grant_id === claims.grant_id && review.input_digest === predicate.input_digest
64
+ && review.executor_agent_id === predicate.agent_id && review.assertion_digest === authority.assertion_digest
65
+ && claims.reviewer_roles.includes(review.role) && receipt.action_id === predicate.action_id;
66
+ });
67
+ }
68
+
69
+ export function verifyNativeProofCohort(records, roots, checkpoint) {
70
+ const fail = code => ({ verified: false, code });
71
+ const proofKey = ownerReceiptKey(roots?.proof), checkpointKey = ownerReceiptKey(roots?.checkpoint);
72
+ if (!proofKey || !checkpointKey || proofKey.id === checkpointKey.id || !Array.isArray(roots.owners)) return fail('INVALID_TRUST_ROOTS');
73
+ const opened = open(checkpoint, NATIVE_CHECKPOINT_TYPE, checkpointKey);
74
+ const scope = opened?.value;
75
+ const from = Date.parse(scope?.from), to = Date.parse(scope?.to);
76
+ if (scope?.schema_version !== 'osuite.native_checkpoint.v1' || scope.scope !== NATIVE_CHECKPOINT_SCOPE
77
+ || typeof scope.org_id !== 'string' || !scope.org_id || !(from < to) || !hex.test(scope.root || '')
78
+ || !Number.isSafeInteger(scope.count) || scope.count < 0 || scope.count > 1000) return fail('INVALID_CHECKPOINT');
79
+ if (!Array.isArray(records) || records.length !== scope.count) return fail('INCOMPLETE_COHORT');
80
+
81
+ const seen = new Map();
82
+ const outcomes = { committed: 0, absent: 0, unknown: 0 };
83
+ for (const record of records) {
84
+ const decoded = open(record?.dsse_envelope, NATIVE_PROOF_TYPE, proofKey);
85
+ const statement = decoded?.value, p = statement?.predicate, subject = statement?.subject;
86
+ const created = Date.parse(p?.created_at);
87
+ if (!decoded || record.schema_version !== 'osuite.native_proof.v1' || decoded.digest !== record.payload_sha256
88
+ || statement._type !== 'https://in-toto.io/Statement/v1' || statement.predicateType !== 'https://osuite.ai/attestations/native-tool/v1'
89
+ || !Array.isArray(subject) || subject.length !== 1 || subject[0]?.name !== p?.action_id || !hex.test(subject[0]?.digest?.sha256 || '')
90
+ || !actionId.test(p?.action_id || '') || p.org_id !== scope.org_id || !(created >= from && created < to)
91
+ || !hex.test(p.input_digest || '') || !hex.test(p.binding_digest || '') || !['committed', 'absent', 'unknown'].includes(p.outcome)) return fail('INVALID_RECORD');
92
+ if (seen.has(p.action_id)) return fail('DUPLICATE_RECORD');
93
+ if (!validDelegation(p, roots.issuers)) return fail('INVALID_DELEGATION');
94
+ if (p.outcome === 'unknown') {
95
+ if (p.owner_receipt !== null) return fail('INVALID_OWNER_RECEIPT');
96
+ } else {
97
+ const resource = p.native_resource;
98
+ const pins = roots.owners.filter(root => root && resource && root.resource_id === resource.resource_id
99
+ && ownerReceiptKey(root.public_key)?.id === resource.key_id);
100
+ if (!resource || resource.input_digest !== p.input_digest || pins.length !== 1 || [proofKey.id, checkpointKey.id].includes(resource.key_id)
101
+ || p.owner_receipt?.claims?.outcome !== p.outcome || !verifyOwnerReceipt(p.owner_receipt,
102
+ { ...resource, org_id: p.org_id, action_id: p.action_id }, pins[0].public_key, { startedAt: p.timestamp_start })) return fail('INVALID_OWNER_RECEIPT');
103
+ }
104
+ seen.set(p.action_id, decoded.digest);
105
+ outcomes[p.outcome]++;
106
+ }
107
+ if (nativeProofRoot(seen) !== scope.root) return fail('CHECKPOINT_MISMATCH');
108
+ return { verified: true, count: seen.size, outcomes };
109
+ }
package/nativeDoctor.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
2
  import { inspectCredentialFile, readCredentialFile } from './credentials.js';
3
- import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
3
+ import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, TERMINAL_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
4
4
  import { loadRuntimeConfig } from './runtime/config.mjs';
5
5
  import { createApiClient, safeId, validatedBaseUrl } from './runtime/protocol.mjs';
6
6
  import { resolveRemotePosture } from './runtime/posture.mjs';
@@ -26,8 +26,10 @@ function parse(raw) {
26
26
 
27
27
  export function loadNativeDoctorConfig({ projectRoot = process.cwd(), runtime, shellEnv = process.env }) {
28
28
  if (!['sdk', 'mcp'].includes(runtime)) fail('INVALID_RUNTIME_OPTIONS');
29
- const envPath = runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
30
29
  try {
30
+ const legacy = runtime === 'sdk' ? inspectCredentialFile(projectRoot, SDK_ENV_PATH) : null;
31
+ const envPath = runtime === 'mcp' ? MCP_ENV_PATH : !legacy.safe || legacy.exists
32
+ || !inspectCredentialFile(projectRoot, TERMINAL_ENV_PATH).exists ? SDK_ENV_PATH : TERMINAL_ENV_PATH;
31
33
  const files = [envPath, `${envPath}.identity.json`, `${envPath}.connect.json`, `${envPath}.connect.lock`, MCP_MIGRATION_PATH];
32
34
  const checks = files.map(file => inspectCredentialFile(projectRoot, file));
33
35
  if (checks.some(check => !check.safe)) fail('UNSAFE_CREDENTIALS');