coderifts 4.4.0 → 4.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3028,7 +3028,7 @@ var require_package = __commonJS({
3028
3028
  "package.json"(exports2, module2) {
3029
3029
  module2.exports = {
3030
3030
  name: "coderifts",
3031
- version: "4.4.0",
3031
+ version: "4.4.1",
3032
3032
  description: "Detect breaking API changes from the command line. Works locally or with the CodeRifts cloud API.",
3033
3033
  author: "CodeRifts <hello@coderifts.com>",
3034
3034
  license: "MIT",
@@ -3073,7 +3073,7 @@ var require_package = __commonJS({
3073
3073
  test: "node --test test/*.test.js"
3074
3074
  },
3075
3075
  dependencies: {
3076
- "@coderifts/agent-guard": "^8.1.1",
3076
+ "@coderifts/agent-guard": "^9.0.0",
3077
3077
  chalk: "^4.1.2",
3078
3078
  "cli-table3": "^0.6.4",
3079
3079
  commander: "^12.0.0",
@@ -61936,7 +61936,7 @@ var require_axios = __commonJS({
61936
61936
  advertiseZstdAcceptEncoding: false,
61937
61937
  validateStatusUndefinedResolves: true
61938
61938
  };
61939
- var URLSearchParams = url.URLSearchParams;
61939
+ var URLSearchParams2 = url.URLSearchParams;
61940
61940
  var ALPHA = "abcdefghijklmnopqrstuvwxyz";
61941
61941
  var DIGIT = "0123456789";
61942
61942
  var ALPHABET = {
@@ -61959,7 +61959,7 @@ var require_axios = __commonJS({
61959
61959
  var platform$1 = {
61960
61960
  isNode: true,
61961
61961
  classes: {
61962
- URLSearchParams,
61962
+ URLSearchParams: URLSearchParams2,
61963
61963
  FormData: FormData$1,
61964
61964
  Blob: typeof Blob !== "undefined" && Blob || null
61965
61965
  },
@@ -65643,6 +65643,17 @@ var require_read_decision = __commonJS({
65643
65643
  }
65644
65644
  return null;
65645
65645
  }
65646
+ function isV2Response(r, envObj) {
65647
+ if (envObj)
65648
+ return true;
65649
+ if (r.preflight_mode != null && r.preflight_mode !== "")
65650
+ return true;
65651
+ const ver = r.decision_spec_version;
65652
+ return typeof ver === "string" && ver.startsWith("2.");
65653
+ }
65654
+ function allowLegacyDecisionMap(r, envObj) {
65655
+ return r.decision_spec_version === "1.0" && !isV2Response(r, envObj);
65656
+ }
65646
65657
  function readDecision(response) {
65647
65658
  if (!response || typeof response !== "object") {
65648
65659
  return { executionAction: "STOP", decision: null, reason: "UNREADABLE_DECISION" };
@@ -65696,32 +65707,34 @@ var require_read_decision = __commonJS({
65696
65707
  }
65697
65708
  return out;
65698
65709
  }
65699
- const topDecision = decisionOf(r.decision);
65700
- if (topDecision && Object.prototype.hasOwnProperty.call(DECISION_TO_ACTION, topDecision)) {
65701
- const out = {
65702
- executionAction: DECISION_TO_ACTION[topDecision],
65703
- decision: topDecision
65704
- };
65705
- if (envObj) {
65706
- out.envelope = asEnvelope(envObj);
65707
- out.receipt = receiptOf(envObj);
65710
+ if (allowLegacyDecisionMap(r, envObj)) {
65711
+ const topDecision = decisionOf(r.decision);
65712
+ if (topDecision && Object.prototype.hasOwnProperty.call(DECISION_TO_ACTION, topDecision)) {
65713
+ return {
65714
+ executionAction: DECISION_TO_ACTION[topDecision],
65715
+ decision: topDecision
65716
+ };
65717
+ }
65718
+ const envDecision = envObj ? decisionOf(envObj.decision) : null;
65719
+ if (envDecision && Object.prototype.hasOwnProperty.call(DECISION_TO_ACTION, envDecision)) {
65720
+ return {
65721
+ executionAction: DECISION_TO_ACTION[envDecision],
65722
+ decision: envDecision,
65723
+ envelope: envObj ? asEnvelope(envObj) : void 0,
65724
+ receipt: envObj ? receiptOf(envObj) : void 0
65725
+ };
65708
65726
  }
65709
- return out;
65710
- }
65711
- const envDecision = envObj ? decisionOf(envObj.decision) : null;
65712
- if (envDecision && Object.prototype.hasOwnProperty.call(DECISION_TO_ACTION, envDecision)) {
65713
- return {
65714
- executionAction: DECISION_TO_ACTION[envDecision],
65715
- decision: envDecision,
65716
- envelope: envObj ? asEnvelope(envObj) : void 0,
65717
- receipt: envObj ? receiptOf(envObj) : void 0
65718
- };
65719
65727
  }
65720
- return {
65728
+ const unreadable = {
65721
65729
  executionAction: "STOP",
65722
65730
  decision: decisionOf(r.decision, envObj?.decision),
65723
65731
  reason: "UNREADABLE_DECISION"
65724
65732
  };
65733
+ if (envObj) {
65734
+ unreadable.envelope = asEnvelope(envObj);
65735
+ unreadable.receipt = receiptOf(envObj);
65736
+ }
65737
+ return unreadable;
65725
65738
  }
65726
65739
  }
65727
65740
  });
@@ -66550,7 +66563,8 @@ var require_execution_proof = __commonJS({
66550
66563
  change_fp_is_what_was_checked_not_what_executed: true,
66551
66564
  calls_outside_guarded_path_invisible: true,
66552
66565
  execution_result_hash_is_not_artifact_match_proof: true,
66553
- conditional_write_is_host_asserted_not_cas_verified: true
66566
+ conditional_write_is_host_asserted_not_cas_verified: true,
66567
+ commit_observation_is_observed_at_t3_not_atomic: true
66554
66568
  });
66555
66569
  function assertEnforcedReceiptInvariant(input) {
66556
66570
  if (input.enforced === true) {
@@ -66658,10 +66672,31 @@ var require_execution_proof = __commonJS({
66658
66672
  }),
66659
66673
  verdict_kind: typeof input.verdict?.kind === "string" ? input.verdict.kind : "UNKNOWN",
66660
66674
  execution_result_hash: Object.freeze(executionResultHashOf(input)),
66661
- limits: LIMITS
66675
+ limits: LIMITS,
66676
+ commit_observation: freezeCommitObservation(input.commitObservation)
66662
66677
  };
66678
+ if (input.monitoringDelivery && typeof input.monitoringDelivery === "object") {
66679
+ proof.monitoring_delivery = freezeMonitoringDelivery(input.monitoringDelivery);
66680
+ }
66681
+ if (input.casEvidence && typeof input.casEvidence === "object") {
66682
+ proof.cas_evidence = Object.freeze({ ...input.casEvidence });
66683
+ }
66684
+ if (Array.isArray(input.recheckTrail) && input.recheckTrail.length > 0) {
66685
+ proof.recheck_trail = Object.freeze(input.recheckTrail.map((e) => Object.freeze({ ...e })));
66686
+ }
66663
66687
  return freezeProof(proof);
66664
66688
  }
66689
+ function freezeMonitoringDelivery(d) {
66690
+ return Object.freeze({
66691
+ status: d.status,
66692
+ ...d.reason ? { reason: d.reason } : {},
66693
+ ...d.evidence ? { evidence: Object.freeze({ ...d.evidence }) } : {}
66694
+ });
66695
+ }
66696
+ function freezeCommitObservation(obs) {
66697
+ const o = obs && typeof obs === "object" ? { ...obs, ...obs.blast ? { blast: Object.freeze({ ...obs.blast }) } : {} } : { status: "not_observed", observed_at: "", host_attestation: "absent" };
66698
+ return Object.freeze(o);
66699
+ }
66665
66700
  function freezeProof(p) {
66666
66701
  return Object.freeze(p);
66667
66702
  }
@@ -67057,20 +67092,2049 @@ var require_conditional_write = __commonJS({
67057
67092
  }
67058
67093
  throw err;
67059
67094
  }
67095
+ let observed_token = null;
67096
+ try {
67097
+ observed_token = await args.current_token();
67098
+ } catch (err) {
67099
+ if (args.detect_stale_during_commit === true)
67100
+ throw err;
67101
+ observed_token = null;
67102
+ }
67060
67103
  if (args.detect_stale_during_commit === true && typeof args.expected_after_commit === "function") {
67061
67104
  const want = await args.expected_after_commit(result);
67062
- const post = await args.current_token();
67063
- if (!tokensEqual(want, post)) {
67105
+ if (!tokensEqual(want, observed_token)) {
67064
67106
  return {
67065
67107
  status: "committed_stale_detected",
67066
67108
  reason: "stale_during_commit",
67067
67109
  result,
67068
67110
  expected_token: expected,
67069
- post_commit_token: post == null ? null : post
67111
+ post_commit_token: observed_token,
67112
+ observed_token
67113
+ };
67114
+ }
67115
+ }
67116
+ return { status: "committed", result, version_token: expected, observed_token };
67117
+ }
67118
+ }
67119
+ });
67120
+
67121
+ // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/fs.js
67122
+ var require_fs = __commonJS({
67123
+ "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/fs.js"(exports2) {
67124
+ "use strict";
67125
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
67126
+ if (k2 === void 0) k2 = k;
67127
+ var desc = Object.getOwnPropertyDescriptor(m, k);
67128
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
67129
+ desc = { enumerable: true, get: function() {
67130
+ return m[k];
67131
+ } };
67132
+ }
67133
+ Object.defineProperty(o, k2, desc);
67134
+ }) : (function(o, m, k, k2) {
67135
+ if (k2 === void 0) k2 = k;
67136
+ o[k2] = m[k];
67137
+ }));
67138
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
67139
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
67140
+ }) : function(o, v) {
67141
+ o["default"] = v;
67142
+ });
67143
+ var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
67144
+ var ownKeys = function(o) {
67145
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
67146
+ var ar = [];
67147
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
67148
+ return ar;
67149
+ };
67150
+ return ownKeys(o);
67151
+ };
67152
+ return function(mod) {
67153
+ if (mod && mod.__esModule) return mod;
67154
+ var result = {};
67155
+ if (mod != null) {
67156
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
67157
+ }
67158
+ __setModuleDefault(result, mod);
67159
+ return result;
67160
+ };
67161
+ })();
67162
+ Object.defineProperty(exports2, "__esModule", { value: true });
67163
+ exports2.tokensEqual = exports2.FS_ABSENT_TOKEN = exports2.FS_VERSION_TOKEN_PREFIX = void 0;
67164
+ exports2.fsTokenContentHash = fsTokenContentHash;
67165
+ exports2.createFsVersionToken = createFsVersionToken;
67166
+ exports2.readVersionedFile = readVersionedFile;
67167
+ exports2.writeFileIfUnchanged = writeFileIfUnchanged;
67168
+ exports2.createFsPriorContentResolver = createFsPriorContentResolver;
67169
+ var node_crypto_1 = require("node:crypto");
67170
+ var node_fs_1 = require("node:fs");
67171
+ var path = __importStar(require("node:path"));
67172
+ var conditional_write_js_1 = require_conditional_write();
67173
+ Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
67174
+ return conditional_write_js_1.tokensEqual;
67175
+ } });
67176
+ exports2.FS_VERSION_TOKEN_PREFIX = "fs:v1:";
67177
+ exports2.FS_ABSENT_TOKEN = "fs:v1:absent";
67178
+ function sha256hex(buf) {
67179
+ return (0, node_crypto_1.createHash)("sha256").update(buf).digest("hex");
67180
+ }
67181
+ function fsTokenContentHash(token) {
67182
+ if (typeof token !== "string" || !token.startsWith(exports2.FS_VERSION_TOKEN_PREFIX))
67183
+ return null;
67184
+ if (token === exports2.FS_ABSENT_TOKEN)
67185
+ return null;
67186
+ const rest = token.slice(exports2.FS_VERSION_TOKEN_PREFIX.length);
67187
+ const colon = rest.indexOf(":");
67188
+ if (colon < 0)
67189
+ return null;
67190
+ const hash = rest.slice(colon + 1);
67191
+ return /^[a-f0-9]{64}$/.test(hash) ? hash : null;
67192
+ }
67193
+ async function createFsVersionToken(filePath) {
67194
+ let st;
67195
+ try {
67196
+ st = await node_fs_1.promises.stat(filePath);
67197
+ } catch (err) {
67198
+ const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
67199
+ if (code === "ENOENT")
67200
+ return exports2.FS_ABSENT_TOKEN;
67201
+ throw err;
67202
+ }
67203
+ if (!st.isFile()) {
67204
+ throw new Error(`createFsVersionToken: not a regular file: ${filePath}`);
67205
+ }
67206
+ const buf = await node_fs_1.promises.readFile(filePath);
67207
+ const hash = sha256hex(buf);
67208
+ const mtimeMs = Math.trunc(st.mtimeMs);
67209
+ return `${exports2.FS_VERSION_TOKEN_PREFIX}${mtimeMs}:${hash}`;
67210
+ }
67211
+ async function readVersionedFile(filePath) {
67212
+ const version_token = await createFsVersionToken(filePath);
67213
+ if (version_token === exports2.FS_ABSENT_TOKEN) {
67214
+ return { content: "", version_token };
67215
+ }
67216
+ const content = await node_fs_1.promises.readFile(filePath, "utf8");
67217
+ return { content, version_token };
67218
+ }
67219
+ async function writeFileIfUnchanged(args) {
67220
+ const target = path.resolve(args.path);
67221
+ const body = typeof args.content === "string" ? Buffer.from(args.content, "utf8") : args.content;
67222
+ const writtenHash = sha256hex(body);
67223
+ return (0, conditional_write_js_1.executeIfUnchanged)({
67224
+ expected_token: args.expected_token,
67225
+ current_token: () => createFsVersionToken(target),
67226
+ detect_stale_during_commit: true,
67227
+ // Post-commit: token content-hash must equal sha256 of what we wrote (mtime may vary).
67228
+ expected_after_commit: async (result) => {
67229
+ const post = await createFsVersionToken(target);
67230
+ const postHash = fsTokenContentHash(post);
67231
+ if (postHash === result.written_content_hash)
67232
+ return post;
67233
+ return `${exports2.FS_VERSION_TOKEN_PREFIX}0:stale_during_commit_mismatch`;
67234
+ },
67235
+ write: async () => {
67236
+ const dir = path.dirname(target);
67237
+ await node_fs_1.promises.mkdir(dir, { recursive: true });
67238
+ const tmp = path.join(dir, `.coderifts-cas-${path.basename(target)}-${process.pid}-${(0, node_crypto_1.randomBytes)(6).toString("hex")}.tmp`);
67239
+ try {
67240
+ await node_fs_1.promises.writeFile(tmp, body);
67241
+ const still = await createFsVersionToken(target);
67242
+ if (!(0, conditional_write_js_1.tokensEqual)(args.expected_token, still)) {
67243
+ try {
67244
+ await node_fs_1.promises.unlink(tmp);
67245
+ } catch {
67246
+ }
67247
+ throw new conditional_write_js_1.StaleVersionTokenAbort(still);
67248
+ }
67249
+ await node_fs_1.promises.rename(tmp, target);
67250
+ } catch (err) {
67251
+ if (err instanceof conditional_write_js_1.StaleVersionTokenAbort)
67252
+ throw err;
67253
+ try {
67254
+ await node_fs_1.promises.unlink(tmp);
67255
+ } catch {
67256
+ }
67257
+ throw err;
67258
+ }
67259
+ return { path: target, bytes: body.length, written_content_hash: writtenHash };
67260
+ }
67261
+ });
67262
+ }
67263
+ function createFsPriorContentResolver(options) {
67264
+ const pathForArtifact = options?.pathForArtifact;
67265
+ return async (req) => {
67266
+ let filePath = typeof req.path === "string" && req.path.length > 0 ? req.path : void 0;
67267
+ if (!filePath && pathForArtifact) {
67268
+ const mapped = pathForArtifact(req.artifactId);
67269
+ if (typeof mapped === "string" && mapped.length > 0)
67270
+ filePath = mapped;
67271
+ }
67272
+ if (!filePath)
67273
+ return null;
67274
+ try {
67275
+ return await node_fs_1.promises.readFile(filePath, "utf8");
67276
+ } catch (err) {
67277
+ const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
67278
+ if (code === "ENOENT")
67279
+ return null;
67280
+ throw err;
67281
+ }
67282
+ };
67283
+ }
67284
+ }
67285
+ });
67286
+
67287
+ // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/api.js
67288
+ var require_api3 = __commonJS({
67289
+ "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/api.js"(exports2) {
67290
+ "use strict";
67291
+ Object.defineProperty(exports2, "__esModule", { value: true });
67292
+ exports2.tokensEqual = exports2.API_ABSENT_TOKEN = exports2.API_VERSION_TOKEN_PREFIX = void 0;
67293
+ exports2.createApiVersionToken = createApiVersionToken;
67294
+ exports2.apiTokenRaw = apiTokenRaw;
67295
+ exports2.writeApiIfUnchanged = writeApiIfUnchanged;
67296
+ var conditional_write_js_1 = require_conditional_write();
67297
+ Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
67298
+ return conditional_write_js_1.tokensEqual;
67299
+ } });
67300
+ exports2.API_VERSION_TOKEN_PREFIX = "api:v1:";
67301
+ exports2.API_ABSENT_TOKEN = "api:v1:absent";
67302
+ function createApiVersionToken(etag) {
67303
+ if (etag == null)
67304
+ return exports2.API_ABSENT_TOKEN;
67305
+ let s = String(etag).trim();
67306
+ if (s.length === 0)
67307
+ return exports2.API_ABSENT_TOKEN;
67308
+ if (s.startsWith("W/") || s.startsWith("w/"))
67309
+ s = s.slice(2).trim();
67310
+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
67311
+ s = s.slice(1, -1);
67312
+ }
67313
+ if (s.length === 0)
67314
+ return exports2.API_ABSENT_TOKEN;
67315
+ return `${exports2.API_VERSION_TOKEN_PREFIX}${s}`;
67316
+ }
67317
+ function apiTokenRaw(token) {
67318
+ if (typeof token !== "string" || !token.startsWith(exports2.API_VERSION_TOKEN_PREFIX))
67319
+ return null;
67320
+ if (token === exports2.API_ABSENT_TOKEN)
67321
+ return null;
67322
+ const raw = token.slice(exports2.API_VERSION_TOKEN_PREFIX.length);
67323
+ return raw.length > 0 ? raw : null;
67324
+ }
67325
+ async function writeApiIfUnchanged(args) {
67326
+ const detect = args.detect_stale_during_commit === true;
67327
+ return (0, conditional_write_js_1.executeIfUnchanged)({
67328
+ expected_token: args.expected_token,
67329
+ current_token: async () => createApiVersionToken(await args.current_etag()),
67330
+ detect_stale_during_commit: detect,
67331
+ expected_after_commit: detect ? async (written) => {
67332
+ if (typeof written.new_etag === "string" && written.new_etag.trim().length > 0) {
67333
+ return createApiVersionToken(written.new_etag);
67334
+ }
67335
+ return createApiVersionToken(await args.current_etag());
67336
+ } : void 0,
67337
+ write: async () => {
67338
+ const report = await args.write({
67339
+ if_match: apiTokenRaw(args.expected_token),
67340
+ expected_token: args.expected_token
67341
+ });
67342
+ if (!report || typeof report !== "object") {
67343
+ throw new Error("writeApiIfUnchanged: host write must return ApiHostWriteReport");
67344
+ }
67345
+ if (report.status === "precondition_failed") {
67346
+ const cur = report.current_etag !== void 0 ? createApiVersionToken(report.current_etag) : null;
67347
+ throw new conditional_write_js_1.StaleVersionTokenAbort(cur);
67348
+ }
67349
+ if (report.status !== "committed") {
67350
+ throw new Error(`writeApiIfUnchanged: unknown host report status ${String(report.status)}`);
67351
+ }
67352
+ const new_etag = report.new_etag === void 0 || report.new_etag === null ? null : String(report.new_etag);
67353
+ return {
67354
+ new_etag,
67355
+ result: report.result
67356
+ };
67357
+ }
67358
+ });
67359
+ }
67360
+ }
67361
+ });
67362
+
67363
+ // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/db.js
67364
+ var require_db2 = __commonJS({
67365
+ "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/db.js"(exports2) {
67366
+ "use strict";
67367
+ Object.defineProperty(exports2, "__esModule", { value: true });
67368
+ exports2.tokensEqual = exports2.DB_ABSENT_TOKEN = exports2.DB_VERSION_TOKEN_PREFIX = void 0;
67369
+ exports2.createDbVersionToken = createDbVersionToken;
67370
+ exports2.dbTokenRaw = dbTokenRaw;
67371
+ exports2.writeDbIfUnchanged = writeDbIfUnchanged;
67372
+ var conditional_write_js_1 = require_conditional_write();
67373
+ Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
67374
+ return conditional_write_js_1.tokensEqual;
67375
+ } });
67376
+ exports2.DB_VERSION_TOKEN_PREFIX = "db:v1:";
67377
+ exports2.DB_ABSENT_TOKEN = "db:v1:absent";
67378
+ function createDbVersionToken(version) {
67379
+ if (version == null)
67380
+ return exports2.DB_ABSENT_TOKEN;
67381
+ if (typeof version === "number" && !Number.isFinite(version))
67382
+ return exports2.DB_ABSENT_TOKEN;
67383
+ const s = String(version).trim();
67384
+ if (s.length === 0)
67385
+ return exports2.DB_ABSENT_TOKEN;
67386
+ return `${exports2.DB_VERSION_TOKEN_PREFIX}${s}`;
67387
+ }
67388
+ function dbTokenRaw(token) {
67389
+ if (typeof token !== "string" || !token.startsWith(exports2.DB_VERSION_TOKEN_PREFIX))
67390
+ return null;
67391
+ if (token === exports2.DB_ABSENT_TOKEN)
67392
+ return null;
67393
+ const raw = token.slice(exports2.DB_VERSION_TOKEN_PREFIX.length);
67394
+ return raw.length > 0 ? raw : null;
67395
+ }
67396
+ function normalizeDbReport(report) {
67397
+ if ("rows_affected" in report && typeof report.rows_affected === "number") {
67398
+ const r = report;
67399
+ if (r.rows_affected === 0) {
67400
+ return {
67401
+ kind: "conflict",
67402
+ new_version: void 0,
67403
+ current_version: void 0,
67404
+ rows_affected: 0
67070
67405
  };
67071
67406
  }
67407
+ return {
67408
+ kind: "committed",
67409
+ new_version: r.new_version,
67410
+ result: r.result,
67411
+ rows_affected: r.rows_affected
67412
+ };
67413
+ }
67414
+ if ("status" in report && report.status === "conflict") {
67415
+ const r = report;
67416
+ return {
67417
+ kind: "conflict",
67418
+ new_version: void 0,
67419
+ current_version: r.current_version
67420
+ };
67421
+ }
67422
+ if ("status" in report && report.status === "committed") {
67423
+ const r = report;
67424
+ return {
67425
+ kind: "committed",
67426
+ new_version: r.new_version,
67427
+ result: r.result
67428
+ };
67072
67429
  }
67073
- return { status: "committed", result, version_token: expected };
67430
+ throw new Error("writeDbIfUnchanged: host write must return DbHostWriteReport");
67431
+ }
67432
+ async function writeDbIfUnchanged(args) {
67433
+ const detect = args.detect_stale_during_commit === true;
67434
+ return (0, conditional_write_js_1.executeIfUnchanged)({
67435
+ expected_token: args.expected_token,
67436
+ current_token: async () => createDbVersionToken(await args.current_version()),
67437
+ detect_stale_during_commit: detect,
67438
+ expected_after_commit: detect ? async (written) => {
67439
+ if (typeof written.new_version === "string" && written.new_version.trim().length > 0) {
67440
+ return createDbVersionToken(written.new_version);
67441
+ }
67442
+ return createDbVersionToken(await args.current_version());
67443
+ } : void 0,
67444
+ write: async () => {
67445
+ const report = await args.write({
67446
+ expected_version: dbTokenRaw(args.expected_token),
67447
+ expected_token: args.expected_token
67448
+ });
67449
+ const norm = normalizeDbReport(report);
67450
+ if (norm.kind === "conflict") {
67451
+ const cur = norm.current_version !== void 0 ? createDbVersionToken(norm.current_version) : null;
67452
+ throw new conditional_write_js_1.StaleVersionTokenAbort(cur);
67453
+ }
67454
+ const new_version = norm.new_version === void 0 || norm.new_version === null ? null : String(norm.new_version);
67455
+ return {
67456
+ new_version,
67457
+ result: norm.result,
67458
+ rows_affected: norm.rows_affected
67459
+ };
67460
+ }
67461
+ });
67462
+ }
67463
+ }
67464
+ });
67465
+
67466
+ // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/registry.js
67467
+ var require_registry = __commonJS({
67468
+ "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/registry.js"(exports2) {
67469
+ "use strict";
67470
+ Object.defineProperty(exports2, "__esModule", { value: true });
67471
+ exports2.tokensEqual = exports2.REGISTRY_ABSENT_TOKEN = exports2.REGISTRY_VERSION_TOKEN_PREFIX = void 0;
67472
+ exports2.createRegistryVersionToken = createRegistryVersionToken;
67473
+ exports2.registryTokenRaw = registryTokenRaw;
67474
+ exports2.writeRegistryIfUnchanged = writeRegistryIfUnchanged;
67475
+ var conditional_write_js_1 = require_conditional_write();
67476
+ Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
67477
+ return conditional_write_js_1.tokensEqual;
67478
+ } });
67479
+ exports2.REGISTRY_VERSION_TOKEN_PREFIX = "registry:v1:";
67480
+ exports2.REGISTRY_ABSENT_TOKEN = "registry:v1:absent";
67481
+ function createRegistryVersionToken(token) {
67482
+ if (token == null)
67483
+ return exports2.REGISTRY_ABSENT_TOKEN;
67484
+ if (typeof token === "number" && !Number.isFinite(token))
67485
+ return exports2.REGISTRY_ABSENT_TOKEN;
67486
+ const s = String(token).trim();
67487
+ if (s.length === 0)
67488
+ return exports2.REGISTRY_ABSENT_TOKEN;
67489
+ return `${exports2.REGISTRY_VERSION_TOKEN_PREFIX}${s}`;
67490
+ }
67491
+ function registryTokenRaw(token) {
67492
+ if (typeof token !== "string" || !token.startsWith(exports2.REGISTRY_VERSION_TOKEN_PREFIX)) {
67493
+ return null;
67494
+ }
67495
+ if (token === exports2.REGISTRY_ABSENT_TOKEN)
67496
+ return null;
67497
+ const raw = token.slice(exports2.REGISTRY_VERSION_TOKEN_PREFIX.length);
67498
+ return raw.length > 0 ? raw : null;
67499
+ }
67500
+ function normalizeRegistryReport(report) {
67501
+ if (!report || typeof report !== "object") {
67502
+ throw new Error("writeRegistryIfUnchanged: host compareAndSwap must return RegistryHostCasReport");
67503
+ }
67504
+ if ("swapped" in report) {
67505
+ if (report.swapped === true) {
67506
+ return { kind: "committed", new_token: report.new_token, result: report.result };
67507
+ }
67508
+ return { kind: "conflict", current_token: report.current_token };
67509
+ }
67510
+ if (report.status === "committed") {
67511
+ return { kind: "committed", new_token: report.new_token, result: report.result };
67512
+ }
67513
+ if (report.status === "conflict") {
67514
+ return { kind: "conflict", current_token: report.current_token };
67515
+ }
67516
+ throw new Error("writeRegistryIfUnchanged: unknown host report shape");
67517
+ }
67518
+ async function writeRegistryIfUnchanged(args) {
67519
+ const detect = args.detect_stale_during_commit === true;
67520
+ return (0, conditional_write_js_1.executeIfUnchanged)({
67521
+ expected_token: args.expected_token,
67522
+ current_token: async () => createRegistryVersionToken(await args.current_token()),
67523
+ detect_stale_during_commit: detect,
67524
+ expected_after_commit: detect ? async (written) => {
67525
+ if (typeof written.new_token === "string" && written.new_token.trim().length > 0) {
67526
+ return createRegistryVersionToken(written.new_token);
67527
+ }
67528
+ return createRegistryVersionToken(await args.current_token());
67529
+ } : void 0,
67530
+ write: async () => {
67531
+ const report = await args.compareAndSwap({
67532
+ expected: registryTokenRaw(args.expected_token),
67533
+ expected_token: args.expected_token
67534
+ });
67535
+ const norm = normalizeRegistryReport(report);
67536
+ if (norm.kind === "conflict") {
67537
+ const cur = norm.current_token !== void 0 ? createRegistryVersionToken(norm.current_token) : null;
67538
+ throw new conditional_write_js_1.StaleVersionTokenAbort(cur);
67539
+ }
67540
+ const new_token = norm.new_token === void 0 || norm.new_token === null ? null : String(norm.new_token);
67541
+ return {
67542
+ new_token,
67543
+ result: norm.result
67544
+ };
67545
+ }
67546
+ });
67547
+ }
67548
+ }
67549
+ });
67550
+
67551
+ // node_modules/@coderifts/agent-guard/dist/cjs/commit-observation.js
67552
+ var require_commit_observation = __commonJS({
67553
+ "node_modules/@coderifts/agent-guard/dist/cjs/commit-observation.js"(exports2) {
67554
+ "use strict";
67555
+ Object.defineProperty(exports2, "__esModule", { value: true });
67556
+ exports2.hashObservedContent = hashObservedContent;
67557
+ exports2.observeCommit = observeCommit;
67558
+ var node_crypto_1 = require("node:crypto");
67559
+ var node_fs_1 = require("node:fs");
67560
+ var fs_js_1 = require_fs();
67561
+ var api_js_1 = require_api3();
67562
+ var db_js_1 = require_db2();
67563
+ var registry_js_1 = require_registry();
67564
+ var conditional_write_js_1 = require_conditional_write();
67565
+ function specStr(v) {
67566
+ if (v == null)
67567
+ return "";
67568
+ return typeof v === "string" ? v : JSON.stringify(v);
67569
+ }
67570
+ function hashObservedContent(v) {
67571
+ return "sha256:" + (0, node_crypto_1.createHash)("sha256").update(specStr(v), "utf8").digest("hex");
67572
+ }
67573
+ function unobserved(now, host = "absent") {
67574
+ return { status: "not_observed", observed_at: now, host_attestation: host };
67575
+ }
67576
+ function casStatus(result) {
67577
+ const s = result && typeof result === "object" ? result.status : null;
67578
+ return s === "committed" || s === "refused" || s === "committed_stale_detected" ? s : null;
67579
+ }
67580
+ function hostLabel(cas, drifted) {
67581
+ if (cas == null)
67582
+ return "absent";
67583
+ if (cas === "refused")
67584
+ return "host_attested_refused";
67585
+ if (cas === "committed" && drifted)
67586
+ return "conflict";
67587
+ if (cas === "committed_stale_detected")
67588
+ return drifted ? "conflict" : "host_attested_committed";
67589
+ return "host_attested_committed";
67590
+ }
67591
+ function casInner(result) {
67592
+ if (!result || typeof result !== "object")
67593
+ return null;
67594
+ const o = result;
67595
+ if (o.status === "committed" || o.status === "committed_stale_detected") {
67596
+ return o.result && typeof o.result === "object" ? o.result : null;
67597
+ }
67598
+ return o;
67599
+ }
67600
+ function inferPath(call, result) {
67601
+ const args = call.arguments && typeof call.arguments === "object" ? call.arguments : {};
67602
+ if (typeof args.path === "string" && args.path)
67603
+ return args.path;
67604
+ if (Array.isArray(call.filesTouched) && typeof call.filesTouched[0] === "string" && call.filesTouched[0]) {
67605
+ return call.filesTouched[0];
67606
+ }
67607
+ const inner = casInner(result);
67608
+ return inner && typeof inner.path === "string" && inner.path ? inner.path : null;
67609
+ }
67610
+ function casObservedToken(result) {
67611
+ if (!result || typeof result !== "object")
67612
+ return null;
67613
+ const o = result;
67614
+ if (typeof o.observed_token === "string" && o.observed_token)
67615
+ return o.observed_token;
67616
+ if (typeof o.post_commit_token === "string" && o.post_commit_token)
67617
+ return o.post_commit_token;
67618
+ return null;
67619
+ }
67620
+ function intendedPostToken(result) {
67621
+ const inner = casInner(result);
67622
+ if (!inner)
67623
+ return null;
67624
+ if (typeof inner.new_etag === "string" && inner.new_etag.trim())
67625
+ return (0, api_js_1.createApiVersionToken)(inner.new_etag);
67626
+ if (inner.new_version != null && String(inner.new_version).trim()) {
67627
+ return (0, db_js_1.createDbVersionToken)(inner.new_version);
67628
+ }
67629
+ if (inner.new_token != null && String(inner.new_token).trim()) {
67630
+ return (0, registry_js_1.createRegistryVersionToken)(inner.new_token);
67631
+ }
67632
+ if (typeof inner.written_content_hash === "string" && /^[a-f0-9]{64}$/.test(inner.written_content_hash)) {
67633
+ return inner.written_content_hash;
67634
+ }
67635
+ return null;
67636
+ }
67637
+ function authorizedAfter(artifacts) {
67638
+ if (!Array.isArray(artifacts))
67639
+ return void 0;
67640
+ for (const a of artifacts) {
67641
+ if (a && a.after !== void 0 && a.after !== null)
67642
+ return a.after;
67643
+ }
67644
+ return void 0;
67645
+ }
67646
+ async function observeCommit(input) {
67647
+ const cas = casStatus(input.result);
67648
+ const host0 = hostLabel(cas, false);
67649
+ if (input.enabled !== true)
67650
+ return unobserved(input.now, "absent");
67651
+ try {
67652
+ return await observeInner(input, cas, host0);
67653
+ } catch {
67654
+ return unobserved(input.now, host0);
67655
+ }
67656
+ }
67657
+ async function observeInner(input, cas, host0) {
67658
+ const now = input.now;
67659
+ const expectedAfter = authorizedAfter(input.call.artifacts);
67660
+ const filePath = inferPath(input.call, input.result);
67661
+ let observedContent = null;
67662
+ let token;
67663
+ if (filePath && expectedAfter !== void 0) {
67664
+ const fsTok = await (0, fs_js_1.createFsVersionToken)(filePath);
67665
+ token = fsTok;
67666
+ observedContent = fsTok === fs_js_1.FS_ABSENT_TOKEN ? "" : await node_fs_1.promises.readFile(filePath, "utf8");
67667
+ }
67668
+ if (observedContent !== null && expectedAfter !== void 0) {
67669
+ const observed_fp = hashObservedContent(observedContent);
67670
+ const expected_fp = hashObservedContent(expectedAfter);
67671
+ const match = observed_fp === expected_fp;
67672
+ const obs = {
67673
+ status: match ? "observed_match" : "observed_drift",
67674
+ observed_fp,
67675
+ expected_fp,
67676
+ token,
67677
+ observed_at: now,
67678
+ host_attestation: hostLabel(cas, !match)
67679
+ };
67680
+ if (!match)
67681
+ obs.blast = await contentBlast(input, observedContent);
67682
+ return obs;
67683
+ }
67684
+ const observedTok = casObservedToken(input.result);
67685
+ const intended = intendedPostToken(input.result);
67686
+ if (observedTok && intended) {
67687
+ const tokenMatch = intended.length === 64 && !intended.includes(":") ? (0, fs_js_1.fsTokenContentHash)(observedTok) === intended : (0, conditional_write_js_1.tokensEqual)(observedTok, intended);
67688
+ const obs = {
67689
+ status: tokenMatch ? "observed_token_match" : "observed_drift",
67690
+ token: observedTok,
67691
+ observed_at: now,
67692
+ host_attestation: hostLabel(cas, !tokenMatch)
67693
+ };
67694
+ if (!tokenMatch) {
67695
+ obs.observed_fp = observedTok;
67696
+ obs.expected_fp = intended;
67697
+ obs.blast = { compared: "token" };
67698
+ }
67699
+ return obs;
67700
+ }
67701
+ if (observedTok)
67702
+ return { status: "not_observed", token: observedTok, observed_at: now, host_attestation: host0 };
67703
+ return unobserved(now, host0);
67704
+ }
67705
+ async function contentBlast(input, observedContent) {
67706
+ const pf = input.preflightOnObserved;
67707
+ if (typeof pf !== "function")
67708
+ return { compared: "content" };
67709
+ const arts = Array.isArray(input.call.artifacts) ? input.call.artifacts.map((a) => ({ ...a, after: observedContent })) : [{ after: observedContent }];
67710
+ try {
67711
+ const r = await pf(arts);
67712
+ if (!r.ok)
67713
+ return { compared: "content", unavailable: true, cause: r.cause };
67714
+ const raw = r.response;
67715
+ const env = raw && typeof raw === "object" && raw.decision_result && typeof raw.decision_result === "object" ? raw.decision_result : raw && typeof raw === "object" ? raw : null;
67716
+ if (!env)
67717
+ return { compared: "content", unavailable: true };
67718
+ return {
67719
+ compared: "content",
67720
+ decision: typeof env.decision === "string" ? env.decision : void 0,
67721
+ execution_action: typeof env.execution_action === "string" ? env.execution_action : void 0,
67722
+ decision_id: typeof env.decision_id === "string" ? env.decision_id : null
67723
+ };
67724
+ } catch (err) {
67725
+ return { compared: "content", unavailable: true, cause: err instanceof Error ? err.message : "preflight_threw" };
67726
+ }
67727
+ }
67728
+ }
67729
+ });
67730
+
67731
+ // node_modules/@coderifts/sdk/dist/cjs/errors.js
67732
+ var require_errors5 = __commonJS({
67733
+ "node_modules/@coderifts/sdk/dist/cjs/errors.js"(exports2) {
67734
+ "use strict";
67735
+ Object.defineProperty(exports2, "__esModule", { value: true });
67736
+ exports2.AuthError = exports2.RateLimitError = exports2.TimeoutError = exports2.ApiError = exports2.CodeRiftsError = void 0;
67737
+ var CodeRiftsError = class extends Error {
67738
+ code;
67739
+ constructor(message, code = "unknown") {
67740
+ super(message);
67741
+ this.name = "CodeRiftsError";
67742
+ this.code = code;
67743
+ }
67744
+ };
67745
+ exports2.CodeRiftsError = CodeRiftsError;
67746
+ var ApiError = class extends CodeRiftsError {
67747
+ status;
67748
+ code;
67749
+ body;
67750
+ constructor(status, body) {
67751
+ super(`[${status}] ${body.error}: ${body.message}`);
67752
+ this.name = "ApiError";
67753
+ this.status = status;
67754
+ this.code = body.error;
67755
+ this.body = body;
67756
+ }
67757
+ };
67758
+ exports2.ApiError = ApiError;
67759
+ var TimeoutError = class extends CodeRiftsError {
67760
+ constructor(timeoutMs) {
67761
+ super(`Request timed out after ${timeoutMs}ms`);
67762
+ this.name = "TimeoutError";
67763
+ }
67764
+ };
67765
+ exports2.TimeoutError = TimeoutError;
67766
+ var RateLimitError = class extends ApiError {
67767
+ constructor(body) {
67768
+ super(429, body);
67769
+ this.name = "RateLimitError";
67770
+ }
67771
+ };
67772
+ exports2.RateLimitError = RateLimitError;
67773
+ var AuthError = class extends ApiError {
67774
+ constructor(body) {
67775
+ super(401, body);
67776
+ this.name = "AuthError";
67777
+ }
67778
+ };
67779
+ exports2.AuthError = AuthError;
67780
+ }
67781
+ });
67782
+
67783
+ // node_modules/@coderifts/sdk/dist/cjs/client.js
67784
+ var require_client = __commonJS({
67785
+ "node_modules/@coderifts/sdk/dist/cjs/client.js"(exports2) {
67786
+ "use strict";
67787
+ Object.defineProperty(exports2, "__esModule", { value: true });
67788
+ exports2.CodeRifts = void 0;
67789
+ var errors_js_1 = require_errors5();
67790
+ var DEFAULT_BASE_URL = "https://app.coderifts.com";
67791
+ var DEFAULT_TIMEOUT = 3e4;
67792
+ var CodeRifts = class {
67793
+ apiKey;
67794
+ baseUrl;
67795
+ timeout;
67796
+ constructor(options) {
67797
+ if (!options.apiKey) {
67798
+ throw new Error("apiKey is required");
67799
+ }
67800
+ this.apiKey = options.apiKey;
67801
+ this.baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
67802
+ this.timeout = options.timeout || DEFAULT_TIMEOUT;
67803
+ }
67804
+ // ─── Internal HTTP helper ──────────────────────────────────────────────
67805
+ async request(method, path, body) {
67806
+ const url = `${this.baseUrl}${path}`;
67807
+ const controller = new AbortController();
67808
+ const timer = setTimeout(() => controller.abort(), this.timeout);
67809
+ try {
67810
+ const res = await fetch(url, {
67811
+ method,
67812
+ headers: {
67813
+ "Content-Type": "application/json",
67814
+ Authorization: `Bearer ${this.apiKey}`
67815
+ },
67816
+ body: body ? JSON.stringify(body) : void 0,
67817
+ signal: controller.signal
67818
+ });
67819
+ const json = await res.json();
67820
+ if (!res.ok) {
67821
+ const errorBody = {
67822
+ error: json.error || "unknown",
67823
+ message: json.message || res.statusText
67824
+ };
67825
+ if (res.status === 401)
67826
+ throw new errors_js_1.AuthError(errorBody);
67827
+ if (res.status === 429)
67828
+ throw new errors_js_1.RateLimitError(errorBody);
67829
+ throw new errors_js_1.ApiError(res.status, errorBody);
67830
+ }
67831
+ return json;
67832
+ } catch (err) {
67833
+ if (err instanceof errors_js_1.ApiError)
67834
+ throw err;
67835
+ if (err.name === "AbortError") {
67836
+ throw new errors_js_1.TimeoutError(this.timeout);
67837
+ }
67838
+ throw err;
67839
+ } finally {
67840
+ clearTimeout(timer);
67841
+ }
67842
+ }
67843
+ // ─── 1. preflightCheck ─────────────────────────────────────────────────
67844
+ /**
67845
+ * Check whether it is safe to proceed with a tool invocation.
67846
+ *
67847
+ * Accepts `old_spec` / `new_spec` (OpenAPI YAML strings) and a `tool_name`.
67848
+ * The SDK converts the specs to MCP tool arrays and calls POST /api/v1/agent/preflight.
67849
+ */
67850
+ async preflightCheck(req) {
67851
+ const raw = await this.request("POST", "/api/v1/agent/preflight", {
67852
+ tool_name: req.tool_name,
67853
+ old_spec: req.old_spec,
67854
+ new_spec: req.new_spec
67855
+ });
67856
+ const decision = raw.decision || "ALLOW";
67857
+ return {
67858
+ decision,
67859
+ omega_api: raw.omega_api ?? 0,
67860
+ safe: decision === "ALLOW" || decision === "WARN",
67861
+ reflex_triggers: raw.reflex_triggers || [],
67862
+ affected_tools: raw.affected_tools || [],
67863
+ confidence_score: raw.confidence_score,
67864
+ reflex_override: raw.reflex_override,
67865
+ omega_components: raw.omega_components,
67866
+ breaking_changes: raw.breaking_changes,
67867
+ stats: raw.stats,
67868
+ mitigation_available: raw.mitigation_available
67869
+ };
67870
+ }
67871
+ // ─── 2. diff ───────────────────────────────────────────────────────────
67872
+ /**
67873
+ * Full analysis of two OpenAPI specs.
67874
+ */
67875
+ async diff(req) {
67876
+ return this.request("POST", "/api/v1/diff", req);
67877
+ }
67878
+ // ─── 3. explainDecision ────────────────────────────────────────────────
67879
+ /**
67880
+ * Returns a human-readable explanation of why a decision was made.
67881
+ *
67882
+ * Computed client-side from the omega components and reflex triggers.
67883
+ */
67884
+ async explainDecision(req) {
67885
+ const components = [];
67886
+ if (req.omega_components) {
67887
+ for (const [name, value] of Object.entries(req.omega_components)) {
67888
+ if (typeof value === "number") {
67889
+ components.push({
67890
+ name,
67891
+ value,
67892
+ description: describeComponent(name, value)
67893
+ });
67894
+ }
67895
+ }
67896
+ }
67897
+ const triggers = req.reflex_triggers || [];
67898
+ let summary = `Decision: ${req.decision} (\u03A9_API = ${req.omega_api}).`;
67899
+ if (triggers.length > 0) {
67900
+ summary += ` ${triggers.length} reflex rule(s) triggered.`;
67901
+ }
67902
+ if (req.decision === "BLOCK") {
67903
+ summary += " This change is blocked due to high risk.";
67904
+ } else if (req.decision === "REQUIRE_APPROVAL") {
67905
+ summary += " This change requires manual approval before merging.";
67906
+ } else if (req.decision === "WARN") {
67907
+ summary += " This change has warnings but can proceed.";
67908
+ } else {
67909
+ summary += " This change is safe to proceed.";
67910
+ }
67911
+ return { summary, components };
67912
+ }
67913
+ // ─── 4. howToUnblock ───────────────────────────────────────────────────
67914
+ /**
67915
+ * Returns actionable steps to resolve a BLOCK decision.
67916
+ *
67917
+ * Computed client-side from breaking changes and detected patterns.
67918
+ */
67919
+ async howToUnblock(req) {
67920
+ const actions = [];
67921
+ let step = 1;
67922
+ if (req.decision !== "BLOCK") {
67923
+ actions.push({
67924
+ step: step++,
67925
+ description: `Current decision is "${req.decision}" \u2014 no unblock needed.`
67926
+ });
67927
+ return { actions };
67928
+ }
67929
+ const bcs = req.breaking_changes || [];
67930
+ if (bcs.length > 0) {
67931
+ actions.push({
67932
+ step: step++,
67933
+ description: `Fix ${bcs.length} breaking change(s) in your spec.`,
67934
+ code_example: bcs.slice(0, 3).map((bc) => `# ${bc.type} at ${bc.path}: ${bc.description}`).join("\n")
67935
+ });
67936
+ }
67937
+ const triggers = req.reflex_triggers || [];
67938
+ for (const trigger of triggers) {
67939
+ actions.push({
67940
+ step: step++,
67941
+ description: `Resolve reflex rule: ${trigger.rule}`
67942
+ });
67943
+ }
67944
+ actions.push({
67945
+ step: step++,
67946
+ description: "Request a manual override via POST /api/v1/ledger/:id/override if this is an emergency."
67947
+ });
67948
+ return { actions };
67949
+ }
67950
+ // ─── 5. scoreMcp ──────────────────────────────────────────────────────
67951
+ /**
67952
+ * Score an MCP manifest for agent safety.
67953
+ */
67954
+ async scoreMcp(req) {
67955
+ return this.request("POST", "/api/v1/agent-readiness-score", {
67956
+ spec: req.manifest,
67957
+ spec_type: "mcp"
67958
+ });
67959
+ }
67960
+ // ─── 6. getLedger ─────────────────────────────────────────────────────
67961
+ /**
67962
+ * Query compliance ledger entries.
67963
+ */
67964
+ async getLedger(req = {}) {
67965
+ const params = new URLSearchParams();
67966
+ if (req.repo)
67967
+ params.set("repo", req.repo);
67968
+ if (req.decision)
67969
+ params.set("decision", req.decision);
67970
+ if (req.from)
67971
+ params.set("from", req.from);
67972
+ if (req.to)
67973
+ params.set("to", req.to);
67974
+ if (req.limit)
67975
+ params.set("limit", String(req.limit));
67976
+ const qs = params.toString();
67977
+ const path = `/api/v1/ledger${qs ? `?${qs}` : ""}`;
67978
+ return this.request("GET", path);
67979
+ }
67980
+ // ─── 7. simulatePolicy ───────────────────────────────────────────────
67981
+ /**
67982
+ * Test a YAML policy against two OpenAPI specs.
67983
+ */
67984
+ async simulatePolicy(req) {
67985
+ return this.request("POST", "/api/v1/policy-simulator", req);
67986
+ }
67987
+ // ─── 8. preflightChangeSet ─────────────────────────────────────────────
67988
+ /**
67989
+ * Preflight a multi-artifact change set (OpenAPI / GraphQL / gRPC / AsyncAPI / MCP manifest)
67990
+ * in one call. Requires top-level `preflight_mode: 'analyze' | 'authorize'` (Decision Spec v2;
67991
+ * server returns HTTP 400 if omitted). Prefer `analyzeChangeSet` / `authorizeChangeSet` so the
67992
+ * two authorization meanings cannot be mixed. POST /api/v1/preflight.
67993
+ *
67994
+ * Returns the mode-discriminated union: narrow on `preflight_mode` before reading
67995
+ * `decision` / `safe_for_agent` (authorize) or `analysis_outcome` (analyze). Call
67996
+ * `analyzeChangeSet` / `authorizeChangeSet` instead to get an already-narrowed type.
67997
+ */
67998
+ async preflightChangeSet(req) {
67999
+ return this.request("POST", "/api/v1/preflight", req);
68000
+ }
68001
+ /**
68002
+ * Risk-only preflight (`preflight_mode: 'analyze'`). Informational — not permission;
68003
+ * does not mint an operation-bound receipt. POST /api/v1/preflight.
68004
+ *
68005
+ * The mode is fixed by this method, so the analyze branch is returned directly — there is no
68006
+ * `decision` / `execution_action` / `safe_for_agent` on it, by protocol.
68007
+ */
68008
+ async analyzeChangeSet(req) {
68009
+ return this.preflightChangeSet({
68010
+ ...req,
68011
+ preflight_mode: "analyze"
68012
+ });
68013
+ }
68014
+ /**
68015
+ * Operation-bound authorize preflight (`preflight_mode: 'authorize'`).
68016
+ * Requires a non-empty `context.operation` (e.g. merge | deploy | tool_call) — the server
68017
+ * returns HTTP 400 otherwise. May mint a signed receipt. POST /api/v1/preflight.
68018
+ *
68019
+ * The mode is fixed by this method, so the authorize branch is returned directly:
68020
+ * `decision`, `execution_action` and `safe_for_agent` are present without narrowing.
68021
+ */
68022
+ async authorizeChangeSet(req) {
68023
+ return this.preflightChangeSet({
68024
+ ...req,
68025
+ preflight_mode: "authorize"
68026
+ });
68027
+ }
68028
+ // ─── 9. verifyReceipt ──────────────────────────────────────────────────
68029
+ /**
68030
+ * Verify a CodeRifts chain receipt. No API key is required — this is a public endpoint (the
68031
+ * Authorization header is sent for consistency but ignored server-side).
68032
+ * POST /api/v1/verify-receipt.
68033
+ *
68034
+ * Two questions, and which one you get depends on whether you pass `intended`:
68035
+ *
68036
+ * - `verifyReceipt(token)` — SIGNATURE only. `valid` / `status` answer authenticity and expiry
68037
+ * (30s clock-skew leeway on expiry; 0s for destructive operations in production when the
68038
+ * intended context declares them). `currently_authorized` comes back **null**, meaning not
68039
+ * evaluated. Null is not a pass.
68040
+ * - `verifyReceipt(token, { operation, environment, decision_result, … })` — AUTHORIZATION.
68041
+ * The server binds the receipt against the stated intent and `currently_authorized` becomes a
68042
+ * real `true` / `false`, with `authz_status` / `authz_reason` explaining a `false`.
68043
+ *
68044
+ * A valid signature is not authorization: only the second form can answer "does this receipt
68045
+ * authorize the action I am about to take?". Supply the context you are about to act under.
68046
+ *
68047
+ * @param token the chain-receipt token
68048
+ * @param intended optional intended context; any subset of its fields may be supplied
68049
+ */
68050
+ async verifyReceipt(token, intended) {
68051
+ const body = { token };
68052
+ if (intended && typeof intended === "object") {
68053
+ for (const [key, value] of Object.entries(intended)) {
68054
+ if (value !== void 0)
68055
+ body[key] = value;
68056
+ }
68057
+ }
68058
+ return this.request("POST", "/api/v1/verify-receipt", body);
68059
+ }
68060
+ // ─── 10. getDecisionDetails ────────────────────────────────────────────
68061
+ /**
68062
+ * Look up a stored decision by decision_id or fingerprint; returns the stored
68063
+ * decision-result.v1.1 envelope + meta. POST /api/v1/decisions/lookup.
68064
+ */
68065
+ async getDecisionDetails(req) {
68066
+ return this.request("POST", "/api/v1/decisions/lookup", req);
68067
+ }
68068
+ };
68069
+ exports2.CodeRifts = CodeRifts;
68070
+ function describeComponent(name, value) {
68071
+ const descriptions = {
68072
+ S_contract: "Contract severity score \u2014 measures how severe the breaking changes are",
68073
+ P_break: "Break probability \u2014 likelihood that downstream consumers will break",
68074
+ S_blast_eff: "Blast radius \u2014 how many consumers are affected",
68075
+ S_agent: "Agent safety score \u2014 risk to AI agent tool invocations",
68076
+ S_runtime: "Runtime impact \u2014 risk of runtime failures",
68077
+ ECI: "Ecosystem coupling index \u2014 how tightly coupled the API is",
68078
+ M_eff: "Migration effort \u2014 estimated effort to migrate consumers",
68079
+ D_contract: "Contract distance \u2014 semantic distance between old and new contracts",
68080
+ confidence_score: "Confidence in the analysis result"
68081
+ };
68082
+ return descriptions[name] || `${name} = ${value}`;
68083
+ }
68084
+ }
68085
+ });
68086
+
68087
+ // node_modules/@coderifts/sdk/dist/cjs/decision.js
68088
+ var require_decision = __commonJS({
68089
+ "node_modules/@coderifts/sdk/dist/cjs/decision.js"(exports2) {
68090
+ "use strict";
68091
+ Object.defineProperty(exports2, "__esModule", { value: true });
68092
+ exports2.readDecision = readDecision;
68093
+ var EXECUTION_ACTION = {
68094
+ ALLOW: "CONTINUE",
68095
+ WARN: "CONTINUE_WITH_MONITORING",
68096
+ REQUIRE_APPROVAL: "REQUEST_APPROVAL",
68097
+ BLOCK: "STOP"
68098
+ };
68099
+ function isExecutionAction(v) {
68100
+ return v === "CONTINUE" || v === "CONTINUE_WITH_MONITORING" || v === "REQUEST_APPROVAL" || v === "STOP";
68101
+ }
68102
+ function readDecision(response) {
68103
+ if (!response || typeof response !== "object") {
68104
+ return { executionAction: "STOP", decision: null, reason: "UNREADABLE_DECISION" };
68105
+ }
68106
+ const r = response;
68107
+ const env = r.decision_result;
68108
+ if (env && typeof env === "object" && isExecutionAction(env.execution_action)) {
68109
+ const receipt = env.receipt;
68110
+ return {
68111
+ executionAction: env.execution_action,
68112
+ decision: typeof env.decision === "string" ? env.decision : null,
68113
+ envelope: env,
68114
+ receipt: receipt && typeof receipt === "object" ? receipt : void 0
68115
+ };
68116
+ }
68117
+ if (isExecutionAction(r.execution_action)) {
68118
+ return {
68119
+ executionAction: r.execution_action,
68120
+ decision: typeof r.decision === "string" ? r.decision : null
68121
+ };
68122
+ }
68123
+ if (typeof r.decision === "string" && Object.prototype.hasOwnProperty.call(EXECUTION_ACTION, r.decision)) {
68124
+ return { executionAction: EXECUTION_ACTION[r.decision], decision: r.decision };
68125
+ }
68126
+ return {
68127
+ executionAction: "STOP",
68128
+ decision: typeof r.decision === "string" ? r.decision : null,
68129
+ reason: "UNREADABLE_DECISION"
68130
+ };
68131
+ }
68132
+ }
68133
+ });
68134
+
68135
+ // node_modules/@coderifts/sdk/dist/cjs/leeway.js
68136
+ var require_leeway = __commonJS({
68137
+ "node_modules/@coderifts/sdk/dist/cjs/leeway.js"(exports2) {
68138
+ "use strict";
68139
+ Object.defineProperty(exports2, "__esModule", { value: true });
68140
+ exports2.CLOCK_SKEW_LEEWAY_MS = void 0;
68141
+ exports2.declaresDestructiveProduction = declaresDestructiveProduction;
68142
+ exports2.expiryLeewayMs = expiryLeewayMs;
68143
+ exports2.isReceiptExpired = isReceiptExpired;
68144
+ exports2.isIssuedInFuture = isIssuedInFuture;
68145
+ exports2.CLOCK_SKEW_LEEWAY_MS = 3e4;
68146
+ function declaresDestructiveProduction(context) {
68147
+ if (!context || typeof context !== "object")
68148
+ return false;
68149
+ if (context.environment !== "production")
68150
+ return false;
68151
+ return false;
68152
+ }
68153
+ function expiryLeewayMs(context) {
68154
+ if (declaresDestructiveProduction(context))
68155
+ return 0;
68156
+ return exports2.CLOCK_SKEW_LEEWAY_MS;
68157
+ }
68158
+ function isReceiptExpired(expiresAtMs, nowMs, context) {
68159
+ if (!Number.isFinite(expiresAtMs) || !Number.isFinite(nowMs))
68160
+ return false;
68161
+ return expiresAtMs + expiryLeewayMs(context) < nowMs;
68162
+ }
68163
+ function isIssuedInFuture(issuedAtMs, nowMs, context) {
68164
+ if (!Number.isFinite(issuedAtMs) || !Number.isFinite(nowMs))
68165
+ return false;
68166
+ return issuedAtMs > nowMs + expiryLeewayMs(context);
68167
+ }
68168
+ }
68169
+ });
68170
+
68171
+ // node_modules/@coderifts/sdk/dist/cjs/execution-grant.js
68172
+ var require_execution_grant = __commonJS({
68173
+ "node_modules/@coderifts/sdk/dist/cjs/execution-grant.js"(exports2) {
68174
+ "use strict";
68175
+ Object.defineProperty(exports2, "__esModule", { value: true });
68176
+ exports2.CLOCK_SKEW_LEEWAY_MS = exports2.GRANT_SIGNING_PREFIX = exports2.GRANT_VERSION = void 0;
68177
+ exports2.afterPayloadCanonical = afterPayloadCanonical;
68178
+ exports2.computeScopeHash = computeScopeHash;
68179
+ exports2.receiptDigest = receiptDigest;
68180
+ exports2.verifyExecutionGrant = verifyExecutionGrant;
68181
+ var crypto_1 = require("crypto");
68182
+ var leeway_js_1 = require_leeway();
68183
+ Object.defineProperty(exports2, "CLOCK_SKEW_LEEWAY_MS", { enumerable: true, get: function() {
68184
+ return leeway_js_1.CLOCK_SKEW_LEEWAY_MS;
68185
+ } });
68186
+ exports2.GRANT_VERSION = "cr.exec.v1";
68187
+ exports2.GRANT_SIGNING_PREFIX = "crexec.v1";
68188
+ var NUL = "";
68189
+ var SIGNED_FIELDS = [
68190
+ "kid",
68191
+ "receipt_digest",
68192
+ "scope_hash",
68193
+ "audience",
68194
+ "operation",
68195
+ "target_id",
68196
+ "jti",
68197
+ "iat",
68198
+ "exp"
68199
+ ];
68200
+ function sha256hex(str) {
68201
+ return (0, crypto_1.createHash)("sha256").update(String(str), "utf8").digest("hex");
68202
+ }
68203
+ function specStr(v) {
68204
+ if (v == null)
68205
+ return "";
68206
+ return typeof v === "string" ? v : JSON.stringify(v);
68207
+ }
68208
+ function afterPayloadCanonical(artifacts) {
68209
+ const list = Array.isArray(artifacts) ? artifacts.slice() : [];
68210
+ list.sort((x, y) => {
68211
+ const kx = `${x?.type ?? ""}${NUL}${x?.id ?? ""}`;
68212
+ const ky = `${y?.type ?? ""}${NUL}${y?.id ?? ""}`;
68213
+ return kx < ky ? -1 : kx > ky ? 1 : 0;
68214
+ });
68215
+ return list.map((a) => specStr(a && a.after)).join(NUL);
68216
+ }
68217
+ function computeScopeHash(args) {
68218
+ const preimage = [
68219
+ args.operation == null ? "" : String(args.operation),
68220
+ args.target_id == null ? "" : String(args.target_id),
68221
+ args.after_payload == null ? "" : String(args.after_payload)
68222
+ ].join(NUL);
68223
+ return `sha256:${sha256hex(preimage)}`;
68224
+ }
68225
+ function receiptDigest(token) {
68226
+ return `sha256:${sha256hex(String(token))}`;
68227
+ }
68228
+ function scalar(v) {
68229
+ return v == null ? "" : String(v);
68230
+ }
68231
+ function hasStateNonce(body) {
68232
+ return typeof body.state_nonce === "string" && body.state_nonce.length > 0;
68233
+ }
68234
+ function signingInput(body) {
68235
+ const parts = [
68236
+ exports2.GRANT_SIGNING_PREFIX,
68237
+ scalar(body.kid),
68238
+ scalar(body.receipt_digest),
68239
+ scalar(body.scope_hash),
68240
+ scalar(body.audience),
68241
+ scalar(body.operation),
68242
+ scalar(body.target_id),
68243
+ scalar(body.jti),
68244
+ scalar(body.iat),
68245
+ scalar(body.exp)
68246
+ ];
68247
+ if (hasStateNonce(body))
68248
+ parts.push(scalar(body.state_nonce));
68249
+ return parts.join("|");
68250
+ }
68251
+ function verifyExecutionGrant(token, opts = {}) {
68252
+ if (typeof token !== "string" || token.length === 0) {
68253
+ return { valid: false, status: "MALFORMED", reason: "malformed_structure" };
68254
+ }
68255
+ const segments = token.split(".");
68256
+ if (segments.length !== 2 || segments.some((s) => !s)) {
68257
+ return { valid: false, status: "MALFORMED", reason: "malformed_structure" };
68258
+ }
68259
+ let payload;
68260
+ try {
68261
+ payload = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
68262
+ } catch {
68263
+ return { valid: false, status: "MALFORMED", reason: "bad_json" };
68264
+ }
68265
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
68266
+ return { valid: false, status: "MALFORMED", reason: "bad_json", payload };
68267
+ }
68268
+ if (payload.v !== exports2.GRANT_VERSION) {
68269
+ return { valid: false, status: "MALFORMED", reason: "unsupported_version", payload };
68270
+ }
68271
+ for (const k of SIGNED_FIELDS) {
68272
+ if (typeof payload[k] !== "string") {
68273
+ return { valid: false, status: "MALFORMED", reason: "missing_field", payload };
68274
+ }
68275
+ }
68276
+ if (payload.state_nonce != null && typeof payload.state_nonce !== "string") {
68277
+ return { valid: false, status: "MALFORMED", reason: "bad_state_nonce", payload };
68278
+ }
68279
+ const allowed = /* @__PURE__ */ new Set(["v", ...SIGNED_FIELDS, "state_nonce"]);
68280
+ for (const k of Object.keys(payload)) {
68281
+ if (!allowed.has(k)) {
68282
+ return { valid: false, status: "MALFORMED", reason: "unknown_field", payload };
68283
+ }
68284
+ }
68285
+ for (const k of SIGNED_FIELDS) {
68286
+ if (payload[k].includes("|")) {
68287
+ return { valid: false, status: "INVALID_SIGNATURE", reason: "delimiter_in_field", payload };
68288
+ }
68289
+ }
68290
+ if (hasStateNonce(payload) && payload.state_nonce.includes("|")) {
68291
+ return { valid: false, status: "INVALID_SIGNATURE", reason: "delimiter_in_field", payload };
68292
+ }
68293
+ if (!opts.publicKeyPem) {
68294
+ return { valid: false, status: "UNKNOWN_KEY", reason: "unknown_kid", payload };
68295
+ }
68296
+ let ok = false;
68297
+ try {
68298
+ const key = (0, crypto_1.createPublicKey)(opts.publicKeyPem);
68299
+ ok = (0, crypto_1.verify)(null, Buffer.from(signingInput(payload), "utf8"), key, Buffer.from(segments[1], "base64url"));
68300
+ } catch {
68301
+ return { valid: false, status: "INVALID_SIGNATURE", reason: "signature_error", payload };
68302
+ }
68303
+ if (!ok) {
68304
+ return { valid: false, status: "INVALID_SIGNATURE", reason: "signature_mismatch", payload };
68305
+ }
68306
+ const now = Number.isFinite(opts.now) ? opts.now : Date.now();
68307
+ const expMs = Date.parse(payload.exp);
68308
+ const iatMs = Date.parse(payload.iat);
68309
+ if (!Number.isFinite(expMs) || !Number.isFinite(iatMs)) {
68310
+ return { valid: false, status: "MALFORMED", reason: "bad_timestamp", payload };
68311
+ }
68312
+ if ((0, leeway_js_1.isReceiptExpired)(expMs, now, opts.intended)) {
68313
+ return { valid: false, status: "GRANT_EXPIRED", reason: "expired", payload };
68314
+ }
68315
+ if ((0, leeway_js_1.isIssuedInFuture)(iatMs, now, opts.intended)) {
68316
+ return { valid: false, status: "GRANT_EXPIRED", reason: "iat_in_future", payload };
68317
+ }
68318
+ if (!payload.receipt_digest || !payload.receipt_digest.startsWith("sha256:")) {
68319
+ return { valid: false, status: "GRANT_UNBOUND", reason: "missing_receipt_digest", payload };
68320
+ }
68321
+ const intended = opts.intended || {};
68322
+ if (intended.receipt_token) {
68323
+ if (receiptDigest(intended.receipt_token) !== payload.receipt_digest) {
68324
+ return { valid: false, status: "GRANT_UNBOUND", reason: "receipt_digest_mismatch", payload };
68325
+ }
68326
+ }
68327
+ if (intended.audience != null && intended.audience !== "" && payload.audience !== String(intended.audience)) {
68328
+ return { valid: false, status: "GRANT_WRONG_AUDIENCE", reason: "audience_mismatch", payload };
68329
+ }
68330
+ if (intended.operation != null && intended.operation !== "" && payload.operation !== String(intended.operation)) {
68331
+ return { valid: false, status: "GRANT_SCOPE_MISMATCH", reason: "operation_mismatch", payload };
68332
+ }
68333
+ if (intended.target_id != null && intended.target_id !== "" && payload.target_id !== String(intended.target_id)) {
68334
+ return { valid: false, status: "GRANT_SCOPE_MISMATCH", reason: "target_mismatch", payload };
68335
+ }
68336
+ let expectedScope = null;
68337
+ if (intended.scope_hash)
68338
+ expectedScope = String(intended.scope_hash);
68339
+ else if (intended.after_payload != null) {
68340
+ expectedScope = computeScopeHash({
68341
+ operation: intended.operation != null ? intended.operation : payload.operation,
68342
+ target_id: intended.target_id != null ? intended.target_id : payload.target_id,
68343
+ after_payload: intended.after_payload
68344
+ });
68345
+ }
68346
+ if (expectedScope != null && expectedScope !== payload.scope_hash) {
68347
+ return { valid: false, status: "GRANT_SCOPE_MISMATCH", reason: "scope_hash_mismatch", payload };
68348
+ }
68349
+ return { valid: true, status: "GRANT_CURRENT", reason: null, payload };
68350
+ }
68351
+ }
68352
+ });
68353
+
68354
+ // node_modules/@coderifts/sdk/dist/cjs/execution-attestation.js
68355
+ var require_execution_attestation = __commonJS({
68356
+ "node_modules/@coderifts/sdk/dist/cjs/execution-attestation.js"(exports2) {
68357
+ "use strict";
68358
+ Object.defineProperty(exports2, "__esModule", { value: true });
68359
+ exports2.CLOCK_SKEW_LEEWAY_MS = exports2.ATTEST_ENVELOPE_TAG = exports2.ATTEST_SIGNING_PREFIX = exports2.ATTEST_VERSION = void 0;
68360
+ exports2.attestSigningInput = attestSigningInput;
68361
+ exports2.verifyExecutionAttestation = verifyExecutionAttestation;
68362
+ var crypto_1 = require("crypto");
68363
+ var leeway_js_1 = require_leeway();
68364
+ Object.defineProperty(exports2, "CLOCK_SKEW_LEEWAY_MS", { enumerable: true, get: function() {
68365
+ return leeway_js_1.CLOCK_SKEW_LEEWAY_MS;
68366
+ } });
68367
+ exports2.ATTEST_VERSION = "cr.exec.attest.v1";
68368
+ exports2.ATTEST_SIGNING_PREFIX = "crexecattest.v1";
68369
+ exports2.ATTEST_ENVELOPE_TAG = "cr.exec.attest.v1";
68370
+ var REQUIRED_FIELDS = [
68371
+ "executor_kid",
68372
+ "grant_jti",
68373
+ "receipt_digest",
68374
+ "scope_hash",
68375
+ "committed_at"
68376
+ ];
68377
+ function scalar(v) {
68378
+ return v == null ? "" : String(v);
68379
+ }
68380
+ function canonicalMeta(meta) {
68381
+ const keys = Object.keys(meta).sort();
68382
+ const o = {};
68383
+ for (const k of keys)
68384
+ o[k] = meta[k];
68385
+ return JSON.stringify(o);
68386
+ }
68387
+ function metaOk(meta) {
68388
+ if (meta == null)
68389
+ return true;
68390
+ if (typeof meta !== "object" || Array.isArray(meta))
68391
+ return false;
68392
+ const obj = meta;
68393
+ const keys = Object.keys(obj);
68394
+ if (keys.length > 8)
68395
+ return false;
68396
+ for (const k of keys) {
68397
+ if (k.length === 0 || k.length > 64 || k.includes("|"))
68398
+ return false;
68399
+ const v = obj[k];
68400
+ const t = typeof v;
68401
+ if (t !== "string" && t !== "number" && t !== "boolean")
68402
+ return false;
68403
+ if (t === "string" && (v.length > 256 || v.includes("|")))
68404
+ return false;
68405
+ }
68406
+ return true;
68407
+ }
68408
+ function attestSigningInput(body) {
68409
+ const parts = [
68410
+ exports2.ATTEST_SIGNING_PREFIX,
68411
+ scalar(body.executor_kid),
68412
+ scalar(body.grant_jti),
68413
+ scalar(body.receipt_digest),
68414
+ scalar(body.scope_hash),
68415
+ body.state_nonce != null && String(body.state_nonce).length > 0 ? String(body.state_nonce) : "",
68416
+ scalar(body.committed_at),
68417
+ body.result_digest != null && String(body.result_digest).length > 0 ? String(body.result_digest) : ""
68418
+ ];
68419
+ if (body.meta && typeof body.meta === "object") {
68420
+ parts.push(canonicalMeta(body.meta));
68421
+ }
68422
+ return parts.join("|");
68423
+ }
68424
+ function isIssueTimeWithinKeyWindow(ts, keyMeta) {
68425
+ if (!keyMeta || keyMeta.status === "active")
68426
+ return true;
68427
+ if (keyMeta.status !== "retired")
68428
+ return false;
68429
+ if (typeof keyMeta.retired_at !== "string" || keyMeta.retired_at.length === 0)
68430
+ return false;
68431
+ if (typeof ts !== "string" || ts.length === 0)
68432
+ return false;
68433
+ const issueMs = Date.parse(ts);
68434
+ if (!Number.isFinite(issueMs))
68435
+ return false;
68436
+ if (keyMeta.valid_from) {
68437
+ const fromMs = Date.parse(keyMeta.valid_from);
68438
+ if (Number.isFinite(fromMs) && issueMs < fromMs)
68439
+ return false;
68440
+ }
68441
+ const retiredMs = Date.parse(keyMeta.retired_at);
68442
+ if (!Number.isFinite(retiredMs))
68443
+ return false;
68444
+ if (issueMs >= retiredMs)
68445
+ return false;
68446
+ return true;
68447
+ }
68448
+ function resolveExecutorKey(registry, kid) {
68449
+ if (!registry || !Array.isArray(registry.keys) || !kid)
68450
+ return null;
68451
+ const matches = registry.keys.filter((k) => k && k.kid === kid && typeof k.public_key_pem === "string");
68452
+ if (matches.length === 0)
68453
+ return null;
68454
+ const entry = matches.find((k) => k.status === "active") || matches[0];
68455
+ try {
68456
+ return {
68457
+ publicKey: (0, crypto_1.createPublicKey)(entry.public_key_pem),
68458
+ status: entry.status === "retired" ? "retired" : "active",
68459
+ valid_from: entry.valid_from || null,
68460
+ retired_at: entry.retired_at || null
68461
+ };
68462
+ } catch {
68463
+ return null;
68464
+ }
68465
+ }
68466
+ function parseGrantFields(token) {
68467
+ if (typeof token !== "string" || !token)
68468
+ return null;
68469
+ const segments = token.split(".");
68470
+ if (segments.length !== 2 || segments.some((s) => !s))
68471
+ return { unparseable: true };
68472
+ try {
68473
+ const payload = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
68474
+ if (!payload || typeof payload !== "object")
68475
+ return { unparseable: true };
68476
+ return payload;
68477
+ } catch {
68478
+ return { unparseable: true };
68479
+ }
68480
+ }
68481
+ function nonceOf(obj) {
68482
+ if (!obj)
68483
+ return "";
68484
+ return typeof obj.state_nonce === "string" && obj.state_nonce.length > 0 ? obj.state_nonce : "";
68485
+ }
68486
+ function verifyExecutionAttestation(token, opts) {
68487
+ const fail = (status, reason, payload2) => ({ valid: false, status, reason, payload: payload2 });
68488
+ if (typeof token !== "string" || token.length === 0) {
68489
+ return fail("ATTEST_MALFORMED", "malformed_structure");
68490
+ }
68491
+ const segments = token.split("|");
68492
+ if (segments.length !== 4 || segments.some((s) => !s)) {
68493
+ return fail("ATTEST_MALFORMED", "malformed_structure");
68494
+ }
68495
+ if (segments[0] !== exports2.ATTEST_ENVELOPE_TAG) {
68496
+ return fail("ATTEST_MALFORMED", "unsupported_version");
68497
+ }
68498
+ let payload;
68499
+ try {
68500
+ payload = JSON.parse(Buffer.from(segments[2], "base64url").toString("utf8"));
68501
+ } catch {
68502
+ return fail("ATTEST_MALFORMED", "bad_json");
68503
+ }
68504
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
68505
+ return fail("ATTEST_MALFORMED", "bad_json");
68506
+ }
68507
+ if (payload.v !== exports2.ATTEST_VERSION) {
68508
+ return fail("ATTEST_MALFORMED", "unsupported_version", payload);
68509
+ }
68510
+ for (const k of REQUIRED_FIELDS) {
68511
+ if (typeof payload[k] !== "string" || !payload[k].length) {
68512
+ return fail("ATTEST_MALFORMED", "missing_field", payload);
68513
+ }
68514
+ }
68515
+ if (payload.executor_kid !== segments[1]) {
68516
+ return fail("ATTEST_MALFORMED", "kid_mismatch", payload);
68517
+ }
68518
+ const allowed = /* @__PURE__ */ new Set(["v", ...REQUIRED_FIELDS, "state_nonce", "result_digest", "meta"]);
68519
+ for (const k of Object.keys(payload)) {
68520
+ if (!allowed.has(k))
68521
+ return fail("ATTEST_MALFORMED", "unknown_field", payload);
68522
+ }
68523
+ if (!metaOk(payload.meta))
68524
+ return fail("ATTEST_MALFORMED", "meta_bounds", payload);
68525
+ for (const k of [...REQUIRED_FIELDS, "state_nonce", "result_digest"]) {
68526
+ if (typeof payload[k] === "string" && payload[k].includes("|")) {
68527
+ return fail("ATTEST_INVALID_SIGNATURE", "delimiter_in_field", payload);
68528
+ }
68529
+ }
68530
+ const resolved = resolveExecutorKey(opts.registry, String(payload.executor_kid));
68531
+ if (!resolved)
68532
+ return fail("ATTEST_UNKNOWN_KEY", "unknown_kid", payload);
68533
+ let sigOk = false;
68534
+ try {
68535
+ sigOk = (0, crypto_1.verify)(null, Buffer.from(attestSigningInput(payload), "utf8"), resolved.publicKey, Buffer.from(segments[3], "base64url"));
68536
+ } catch {
68537
+ return fail("ATTEST_INVALID_SIGNATURE", "signature_error", payload);
68538
+ }
68539
+ if (!sigOk)
68540
+ return fail("ATTEST_INVALID_SIGNATURE", "signature_mismatch", payload);
68541
+ const now = Number.isFinite(opts.now) ? opts.now : Date.now();
68542
+ const committedMs = Date.parse(String(payload.committed_at));
68543
+ if (!Number.isFinite(committedMs))
68544
+ return fail("ATTEST_MALFORMED", "bad_timestamp", payload);
68545
+ if ((0, leeway_js_1.isIssuedInFuture)(committedMs, now, opts.intended)) {
68546
+ return fail("ATTEST_MALFORMED", "committed_at_in_future", payload);
68547
+ }
68548
+ let retiredHistorical = false;
68549
+ if (resolved.status === "retired") {
68550
+ if (!isIssueTimeWithinKeyWindow(String(payload.committed_at), resolved)) {
68551
+ return fail("ATTEST_UNKNOWN_KEY", "retired_key_outside_window", payload);
68552
+ }
68553
+ retiredHistorical = true;
68554
+ }
68555
+ const intended = opts.intended;
68556
+ const wantsCross = !!(intended && (intended.grant || intended.grant_fields || intended.receipt_digest));
68557
+ if (wantsCross && intended) {
68558
+ let gf = null;
68559
+ if (intended.grant_fields)
68560
+ gf = intended.grant_fields;
68561
+ else if (intended.grant)
68562
+ gf = parseGrantFields(intended.grant);
68563
+ if (gf && "unparseable" in gf && gf.unparseable) {
68564
+ return fail("ATTEST_UNBOUND", "grant_unparseable", payload);
68565
+ }
68566
+ if (gf && !("unparseable" in gf)) {
68567
+ if (String(gf.jti || "") !== payload.grant_jti) {
68568
+ return fail("ATTEST_UNBOUND", "grant_jti_mismatch", payload);
68569
+ }
68570
+ if (String(gf.scope_hash || "") !== payload.scope_hash) {
68571
+ return fail("ATTEST_UNBOUND", "scope_hash_mismatch", payload);
68572
+ }
68573
+ if (nonceOf(gf) !== nonceOf(payload)) {
68574
+ return fail("ATTEST_UNBOUND", "state_nonce_mismatch", payload);
68575
+ }
68576
+ if (gf.receipt_digest && gf.receipt_digest !== payload.receipt_digest) {
68577
+ return fail("ATTEST_UNBOUND", "receipt_digest_mismatch", payload);
68578
+ }
68579
+ }
68580
+ if (intended.receipt_digest && intended.receipt_digest !== payload.receipt_digest) {
68581
+ return fail("ATTEST_UNBOUND", "receipt_digest_mismatch", payload);
68582
+ }
68583
+ }
68584
+ if (retiredHistorical) {
68585
+ return { valid: true, status: "ATTEST_RETIRED_KEY_VALID_AT_ISSUE", reason: null, payload };
68586
+ }
68587
+ return { valid: true, status: "ATTEST_VALID", reason: null, payload };
68588
+ }
68589
+ }
68590
+ });
68591
+
68592
+ // node_modules/@coderifts/sdk/dist/cjs/index.js
68593
+ var require_cjs3 = __commonJS({
68594
+ "node_modules/@coderifts/sdk/dist/cjs/index.js"(exports2) {
68595
+ "use strict";
68596
+ Object.defineProperty(exports2, "__esModule", { value: true });
68597
+ exports2.ATTEST_ENVELOPE_TAG = exports2.ATTEST_SIGNING_PREFIX = exports2.ATTEST_VERSION = exports2.attestSigningInput = exports2.verifyExecutionAttestation = exports2.GRANT_SIGNING_PREFIX = exports2.GRANT_VERSION = exports2.receiptDigest = exports2.afterPayloadCanonical = exports2.computeScopeHash = exports2.verifyExecutionGrant = exports2.isIssuedInFuture = exports2.isReceiptExpired = exports2.declaresDestructiveProduction = exports2.expiryLeewayMs = exports2.CLOCK_SKEW_LEEWAY_MS = exports2.readDecision = exports2.AuthError = exports2.RateLimitError = exports2.TimeoutError = exports2.ApiError = exports2.CodeRiftsError = exports2.CodeRifts = void 0;
68598
+ var client_js_1 = require_client();
68599
+ Object.defineProperty(exports2, "CodeRifts", { enumerable: true, get: function() {
68600
+ return client_js_1.CodeRifts;
68601
+ } });
68602
+ var errors_js_1 = require_errors5();
68603
+ Object.defineProperty(exports2, "CodeRiftsError", { enumerable: true, get: function() {
68604
+ return errors_js_1.CodeRiftsError;
68605
+ } });
68606
+ Object.defineProperty(exports2, "ApiError", { enumerable: true, get: function() {
68607
+ return errors_js_1.ApiError;
68608
+ } });
68609
+ Object.defineProperty(exports2, "TimeoutError", { enumerable: true, get: function() {
68610
+ return errors_js_1.TimeoutError;
68611
+ } });
68612
+ Object.defineProperty(exports2, "RateLimitError", { enumerable: true, get: function() {
68613
+ return errors_js_1.RateLimitError;
68614
+ } });
68615
+ Object.defineProperty(exports2, "AuthError", { enumerable: true, get: function() {
68616
+ return errors_js_1.AuthError;
68617
+ } });
68618
+ var decision_js_1 = require_decision();
68619
+ Object.defineProperty(exports2, "readDecision", { enumerable: true, get: function() {
68620
+ return decision_js_1.readDecision;
68621
+ } });
68622
+ var leeway_js_1 = require_leeway();
68623
+ Object.defineProperty(exports2, "CLOCK_SKEW_LEEWAY_MS", { enumerable: true, get: function() {
68624
+ return leeway_js_1.CLOCK_SKEW_LEEWAY_MS;
68625
+ } });
68626
+ Object.defineProperty(exports2, "expiryLeewayMs", { enumerable: true, get: function() {
68627
+ return leeway_js_1.expiryLeewayMs;
68628
+ } });
68629
+ Object.defineProperty(exports2, "declaresDestructiveProduction", { enumerable: true, get: function() {
68630
+ return leeway_js_1.declaresDestructiveProduction;
68631
+ } });
68632
+ Object.defineProperty(exports2, "isReceiptExpired", { enumerable: true, get: function() {
68633
+ return leeway_js_1.isReceiptExpired;
68634
+ } });
68635
+ Object.defineProperty(exports2, "isIssuedInFuture", { enumerable: true, get: function() {
68636
+ return leeway_js_1.isIssuedInFuture;
68637
+ } });
68638
+ var execution_grant_js_1 = require_execution_grant();
68639
+ Object.defineProperty(exports2, "verifyExecutionGrant", { enumerable: true, get: function() {
68640
+ return execution_grant_js_1.verifyExecutionGrant;
68641
+ } });
68642
+ Object.defineProperty(exports2, "computeScopeHash", { enumerable: true, get: function() {
68643
+ return execution_grant_js_1.computeScopeHash;
68644
+ } });
68645
+ Object.defineProperty(exports2, "afterPayloadCanonical", { enumerable: true, get: function() {
68646
+ return execution_grant_js_1.afterPayloadCanonical;
68647
+ } });
68648
+ Object.defineProperty(exports2, "receiptDigest", { enumerable: true, get: function() {
68649
+ return execution_grant_js_1.receiptDigest;
68650
+ } });
68651
+ Object.defineProperty(exports2, "GRANT_VERSION", { enumerable: true, get: function() {
68652
+ return execution_grant_js_1.GRANT_VERSION;
68653
+ } });
68654
+ Object.defineProperty(exports2, "GRANT_SIGNING_PREFIX", { enumerable: true, get: function() {
68655
+ return execution_grant_js_1.GRANT_SIGNING_PREFIX;
68656
+ } });
68657
+ var execution_attestation_js_1 = require_execution_attestation();
68658
+ Object.defineProperty(exports2, "verifyExecutionAttestation", { enumerable: true, get: function() {
68659
+ return execution_attestation_js_1.verifyExecutionAttestation;
68660
+ } });
68661
+ Object.defineProperty(exports2, "attestSigningInput", { enumerable: true, get: function() {
68662
+ return execution_attestation_js_1.attestSigningInput;
68663
+ } });
68664
+ Object.defineProperty(exports2, "ATTEST_VERSION", { enumerable: true, get: function() {
68665
+ return execution_attestation_js_1.ATTEST_VERSION;
68666
+ } });
68667
+ Object.defineProperty(exports2, "ATTEST_SIGNING_PREFIX", { enumerable: true, get: function() {
68668
+ return execution_attestation_js_1.ATTEST_SIGNING_PREFIX;
68669
+ } });
68670
+ Object.defineProperty(exports2, "ATTEST_ENVELOPE_TAG", { enumerable: true, get: function() {
68671
+ return execution_attestation_js_1.ATTEST_ENVELOPE_TAG;
68672
+ } });
68673
+ }
68674
+ });
68675
+
68676
+ // node_modules/@coderifts/agent-guard/dist/cjs/cas-attestation.js
68677
+ var require_cas_attestation = __commonJS({
68678
+ "node_modules/@coderifts/agent-guard/dist/cjs/cas-attestation.js"(exports2) {
68679
+ "use strict";
68680
+ Object.defineProperty(exports2, "__esModule", { value: true });
68681
+ exports2.CAS_ATTESTATION_SPEC = void 0;
68682
+ exports2.extractExecutorAttestationToken = extractExecutorAttestationToken;
68683
+ exports2.evaluateCasEvidence = evaluateCasEvidence;
68684
+ exports2.isGuardExecutionProof = isGuardExecutionProof;
68685
+ exports2.isExecuteIfUnchangedOutcome = isExecuteIfUnchangedOutcome;
68686
+ exports2.buildCasAttestation = buildCasAttestation;
68687
+ var sdk_1 = require_cjs3();
68688
+ var execution_proof_js_1 = require_execution_proof();
68689
+ exports2.CAS_ATTESTATION_SPEC = "cas-attestation.v1";
68690
+ var LIMITS = Object.freeze({
68691
+ does_not_claim_only_write_on_host: true,
68692
+ does_not_claim_version_token_proves_change_fp_match: true,
68693
+ does_not_claim_committed_stale_is_safe: true,
68694
+ does_not_claim_execution_result_hash_equals_cas_bytes: true,
68695
+ does_not_claim_host_cannot_bypass: true,
68696
+ does_not_claim_governance_redecision: true
68697
+ });
68698
+ var ABSENT_EVIDENCE = Object.freeze({
68699
+ class: "absent",
68700
+ attest_status: null,
68701
+ executor_kid: null,
68702
+ grant_jti: null
68703
+ });
68704
+ function hostClaimed(status, kid, jti) {
68705
+ return Object.freeze({
68706
+ class: "host_claimed",
68707
+ attest_status: status,
68708
+ executor_kid: kid,
68709
+ grant_jti: jti
68710
+ });
68711
+ }
68712
+ function extractExecutorAttestationToken(outcome) {
68713
+ if (!outcome || typeof outcome !== "object")
68714
+ return null;
68715
+ const o = outcome;
68716
+ if (typeof o.executor_attestation === "string" && o.executor_attestation.length > 0) {
68717
+ return o.executor_attestation;
68718
+ }
68719
+ const r = o.result;
68720
+ if (r && typeof r === "object") {
68721
+ const tok = r.executor_attestation;
68722
+ if (typeof tok === "string" && tok.length > 0)
68723
+ return tok;
68724
+ }
68725
+ return null;
68726
+ }
68727
+ function intendedFromOutcome(outcome) {
68728
+ const intended = {};
68729
+ if (!outcome || typeof outcome !== "object")
68730
+ return intended;
68731
+ const o = outcome;
68732
+ const r = o.result && typeof o.result === "object" ? o.result : o;
68733
+ if (typeof r.grant === "string" && r.grant.length > 0)
68734
+ intended.grant = r.grant;
68735
+ else if (typeof r.execution_grant === "string" && r.execution_grant.length > 0) {
68736
+ intended.grant = r.execution_grant;
68737
+ }
68738
+ if (typeof r.receipt_digest === "string" && r.receipt_digest.length > 0) {
68739
+ intended.receipt_digest = r.receipt_digest;
68740
+ }
68741
+ return intended;
68742
+ }
68743
+ function evaluateCasEvidence(outcome, opts = {}) {
68744
+ if (!isExecuteIfUnchangedOutcome(outcome))
68745
+ return ABSENT_EVIDENCE;
68746
+ if (outcome.status === "refused")
68747
+ return ABSENT_EVIDENCE;
68748
+ const token = extractExecutorAttestationToken(outcome);
68749
+ const registry = opts.registry;
68750
+ const fromOutcome = intendedFromOutcome(outcome);
68751
+ const grant = opts.grant || fromOutcome.grant || null;
68752
+ const receipt_digest = opts.receipt_digest || fromOutcome.receipt_digest || null;
68753
+ if (!registry || !Array.isArray(registry.keys)) {
68754
+ return hostClaimed(null, null, null);
68755
+ }
68756
+ if (!token) {
68757
+ return hostClaimed(null, null, null);
68758
+ }
68759
+ const intended = {};
68760
+ if (grant)
68761
+ intended.grant = grant;
68762
+ if (receipt_digest)
68763
+ intended.receipt_digest = receipt_digest;
68764
+ const wantsIntended = Object.keys(intended).length > 0;
68765
+ let verified;
68766
+ try {
68767
+ verified = (0, sdk_1.verifyExecutionAttestation)(token, {
68768
+ registry,
68769
+ ...wantsIntended ? { intended } : {}
68770
+ });
68771
+ } catch {
68772
+ return hostClaimed("ATTEST_MALFORMED", null, null);
68773
+ }
68774
+ const payload = verified.payload && typeof verified.payload === "object" ? verified.payload : null;
68775
+ const kid = payload && typeof payload.executor_kid === "string" ? payload.executor_kid : null;
68776
+ const jti = payload && typeof payload.grant_jti === "string" ? payload.grant_jti : null;
68777
+ if (verified.valid === true && (verified.status === "ATTEST_VALID" || verified.status === "ATTEST_RETIRED_KEY_VALID_AT_ISSUE")) {
68778
+ return Object.freeze({
68779
+ class: "executor_attested",
68780
+ attest_status: verified.status,
68781
+ executor_kid: kid,
68782
+ grant_jti: jti
68783
+ });
68784
+ }
68785
+ return hostClaimed(verified.status, kid, jti);
68786
+ }
68787
+ function isGuardExecutionProof(x) {
68788
+ if (!x || typeof x !== "object")
68789
+ return false;
68790
+ const p = x;
68791
+ return p.proof_spec === execution_proof_js_1.EXECUTION_PROOF_SPEC && p.receipt != null && typeof p.receipt === "object" && p.execution_result_hash != null && typeof p.execution_result_hash === "object";
68792
+ }
68793
+ function isExecuteIfUnchangedOutcome(x) {
68794
+ if (!x || typeof x !== "object")
68795
+ return false;
68796
+ const o = x;
68797
+ if (o.status === "committed") {
68798
+ const c = x;
68799
+ return typeof c.version_token === "string";
68800
+ }
68801
+ if (o.status === "refused") {
68802
+ const r = x;
68803
+ return r.reason === "stale_version_token" && typeof r.expected_token === "string";
68804
+ }
68805
+ if (o.status === "committed_stale_detected") {
68806
+ const s = x;
68807
+ return s.reason === "stale_during_commit" && typeof s.expected_token === "string";
68808
+ }
68809
+ return false;
68810
+ }
68811
+ function freezeExecutionResultHash(h) {
68812
+ return Object.freeze({ ...h });
68813
+ }
68814
+ function projectCas(outcome) {
68815
+ if (outcome.status === "committed") {
68816
+ return Object.freeze({
68817
+ status: "committed",
68818
+ write_ran: true,
68819
+ version_token: outcome.version_token
68820
+ });
68821
+ }
68822
+ if (outcome.status === "refused") {
68823
+ return Object.freeze({
68824
+ status: "refused",
68825
+ write_ran: false,
68826
+ reason: "stale_version_token",
68827
+ expected_token: outcome.expected_token,
68828
+ current_token: outcome.current_token == null ? null : outcome.current_token
68829
+ });
68830
+ }
68831
+ return Object.freeze({
68832
+ status: "committed_stale_detected",
68833
+ write_ran: true,
68834
+ reason: "stale_during_commit",
68835
+ expected_token: outcome.expected_token,
68836
+ post_commit_token: outcome.post_commit_token == null ? null : outcome.post_commit_token
68837
+ });
68838
+ }
68839
+ function buildCasAttestation(proof, outcome, opts = {}) {
68840
+ if (!isGuardExecutionProof(proof)) {
68841
+ throw new TypeError("@coderifts/agent-guard: buildCasAttestation requires a valid guard-execution-proof.v1 object (proof_spec mismatch or missing required fields)");
68842
+ }
68843
+ if (!isExecuteIfUnchangedOutcome(outcome)) {
68844
+ throw new TypeError("@coderifts/agent-guard: buildCasAttestation requires a valid ExecuteIfUnchangedOutcome (status committed | refused | committed_stale_detected with branch fields)");
68845
+ }
68846
+ const receipt_verified = proof.receipt.verified === true;
68847
+ const cas = projectCas(outcome);
68848
+ const write_ran = cas.write_ran === true;
68849
+ const stale_during_commit = cas.status === "committed_stale_detected";
68850
+ const refused = cas.status === "refused";
68851
+ const authorized_and_committed = receipt_verified && cas.status === "committed";
68852
+ const attestation = {
68853
+ attestation_spec: exports2.CAS_ATTESTATION_SPEC,
68854
+ references: Object.freeze({
68855
+ decision_id: proof.decision_id,
68856
+ change_fp: proof.binds_to != null ? proof.binds_to.change_fp : null,
68857
+ operation: proof.binds_to != null ? proof.binds_to.operation : null,
68858
+ execution_result_hash: freezeExecutionResultHash(proof.execution_result_hash),
68859
+ receipt_verified
68860
+ }),
68861
+ cas,
68862
+ derived: Object.freeze({
68863
+ authorized_and_committed,
68864
+ write_ran,
68865
+ stale_during_commit,
68866
+ refused
68867
+ }),
68868
+ cas_evidence: evaluateCasEvidence(outcome, opts),
68869
+ limits: LIMITS
68870
+ };
68871
+ return freezeAttestation(attestation);
68872
+ }
68873
+ function freezeAttestation(a) {
68874
+ return Object.freeze(a);
68875
+ }
68876
+ }
68877
+ });
68878
+
68879
+ // node_modules/@coderifts/agent-guard/dist/cjs/monitoring-delivery.js
68880
+ var require_monitoring_delivery = __commonJS({
68881
+ "node_modules/@coderifts/agent-guard/dist/cjs/monitoring-delivery.js"(exports2) {
68882
+ "use strict";
68883
+ Object.defineProperty(exports2, "__esModule", { value: true });
68884
+ exports2.DEFAULT_MONITORING_SINK_TIMEOUT_MS = void 0;
68885
+ exports2.ackBytes = ackBytes;
68886
+ exports2.verifyAckHmac = verifyAckHmac;
68887
+ exports2.deliverMonitoring = deliverMonitoring;
68888
+ exports2.formatMonitoringDeliveryLine = formatMonitoringDeliveryLine;
68889
+ exports2.monitoringDeliveryFailClosed = monitoringDeliveryFailClosed;
68890
+ var node_crypto_1 = require("node:crypto");
68891
+ exports2.DEFAULT_MONITORING_SINK_TIMEOUT_MS = 5e3;
68892
+ var HMAC_HEADER_NAMES = [
68893
+ "x-coderifts-ack-signature",
68894
+ "x-hub-signature-256",
68895
+ "x-signature"
68896
+ ];
68897
+ function sha256Prefixed(bytes) {
68898
+ return "sha256:" + (0, node_crypto_1.createHash)("sha256").update(bytes).digest("hex");
68899
+ }
68900
+ function ackBytes(ack) {
68901
+ if (ack == null)
68902
+ return Buffer.alloc(0);
68903
+ if (typeof ack === "string")
68904
+ return Buffer.from(ack, "utf8");
68905
+ if (Buffer.isBuffer(ack))
68906
+ return ack;
68907
+ if (typeof ack === "number" || typeof ack === "boolean")
68908
+ return Buffer.from(String(ack), "utf8");
68909
+ try {
68910
+ return Buffer.from(JSON.stringify(ack), "utf8");
68911
+ } catch {
68912
+ return Buffer.from(String(ack), "utf8");
68913
+ }
68914
+ }
68915
+ function normalizeSig(raw) {
68916
+ return raw.trim().toLowerCase().replace(/^sha256=/, "");
68917
+ }
68918
+ function verifyAckHmac(ack, signature, key) {
68919
+ const expectedHex = (0, node_crypto_1.createHmac)("sha256", key).update(ack).digest("hex");
68920
+ const gotHex = normalizeSig(signature);
68921
+ if (!/^[0-9a-f]+$/.test(gotHex) || gotHex.length !== expectedHex.length)
68922
+ return false;
68923
+ try {
68924
+ return (0, node_crypto_1.timingSafeEqual)(Buffer.from(gotHex, "hex"), Buffer.from(expectedHex, "hex"));
68925
+ } catch {
68926
+ return false;
68927
+ }
68928
+ }
68929
+ function headerGet(headers, name) {
68930
+ if (!headers)
68931
+ return null;
68932
+ if (typeof headers.get === "function") {
68933
+ const v = headers.get(name);
68934
+ return v == null ? null : String(v);
68935
+ }
68936
+ const rec = headers;
68937
+ const key = Object.keys(rec).find((k) => k.toLowerCase() === name.toLowerCase());
68938
+ return key != null ? String(rec[key]) : null;
68939
+ }
68940
+ function pickSignature(hdrs) {
68941
+ if (!hdrs)
68942
+ return null;
68943
+ for (const n of HMAC_HEADER_NAMES) {
68944
+ const v = headerGet(hdrs, n);
68945
+ if (v)
68946
+ return v;
68947
+ }
68948
+ return null;
68949
+ }
68950
+ function signatureFromAckValue(ack) {
68951
+ if (!ack || typeof ack !== "object" || Array.isArray(ack))
68952
+ return null;
68953
+ const o = ack;
68954
+ for (const k of ["signature", "ack_signature", "hmac"]) {
68955
+ if (typeof o[k] === "string" && o[k])
68956
+ return o[k];
68957
+ }
68958
+ return null;
68959
+ }
68960
+ function ackMaterial(raw) {
68961
+ const signature = signatureFromAckValue(raw);
68962
+ if (raw && typeof raw === "object" && !Array.isArray(raw) && !Buffer.isBuffer(raw)) {
68963
+ const o = raw;
68964
+ if ("ack" in o)
68965
+ return { bytes: ackBytes(o.ack), signature };
68966
+ if ("body" in o)
68967
+ return { bytes: ackBytes(o.body), signature };
68968
+ const copy = { ...o };
68969
+ delete copy.signature;
68970
+ delete copy.ack_signature;
68971
+ delete copy.hmac;
68972
+ return { bytes: ackBytes(copy), signature };
68973
+ }
68974
+ return { bytes: ackBytes(raw), signature };
68975
+ }
68976
+ function withTimeout(p, ms) {
68977
+ return new Promise((resolve, reject) => {
68978
+ const timer = setTimeout(() => {
68979
+ reject(Object.assign(new Error(`monitoring sink timed out after ${ms}ms`), { name: "TimeoutError" }));
68980
+ }, Math.max(1, ms));
68981
+ p.then((v) => {
68982
+ clearTimeout(timer);
68983
+ resolve(v);
68984
+ }, (e) => {
68985
+ clearTimeout(timer);
68986
+ reject(e);
68987
+ });
68988
+ });
68989
+ }
68990
+ function hmacResult(ack, signature, key) {
68991
+ if (key == null || String(key).length === 0)
68992
+ return { ok: true };
68993
+ if (!signature)
68994
+ return { ok: false, reason: "ack_hmac_missing" };
68995
+ if (!verifyAckHmac(ack, signature, key))
68996
+ return { ok: false, reason: "ack_hmac_invalid" };
68997
+ return { ok: true, verified: true };
68998
+ }
68999
+ async function deliverCallback(sink, payload, timeoutMs, ackHmacKey, at) {
69000
+ try {
69001
+ const raw = await withTimeout(Promise.resolve(sink(payload)), timeoutMs);
69002
+ if (raw === void 0 || raw === null) {
69003
+ return {
69004
+ status: "sent_unacked",
69005
+ evidence: { at, sink_kind: "callback" }
69006
+ };
69007
+ }
69008
+ const { bytes, signature } = ackMaterial(raw);
69009
+ const hmac = hmacResult(bytes, signature, ackHmacKey);
69010
+ if (!hmac.ok) {
69011
+ return {
69012
+ status: "not_delivered",
69013
+ evidence: { at, sink_kind: "callback", ack_hash: sha256Prefixed(bytes) },
69014
+ reason: hmac.reason
69015
+ };
69016
+ }
69017
+ const evidence = {
69018
+ at,
69019
+ sink_kind: "callback",
69020
+ ack_hash: sha256Prefixed(bytes)
69021
+ };
69022
+ if (hmac.verified === true)
69023
+ evidence.ack_verified = true;
69024
+ return { status: "delivered_acked", evidence };
69025
+ } catch (err) {
69026
+ const name = err && typeof err === "object" ? err.name : "";
69027
+ const reason = name === "TimeoutError" ? "timeout" : "threw";
69028
+ return {
69029
+ status: "not_delivered",
69030
+ evidence: { at, sink_kind: "callback" },
69031
+ reason
69032
+ };
69033
+ }
69034
+ }
69035
+ async function deliverHttp(sink, payload, timeoutMs, ackHmacKey, at) {
69036
+ const fetchImpl = sink.fetchImpl || globalThis.fetch;
69037
+ if (typeof fetchImpl !== "function") {
69038
+ return {
69039
+ status: "not_delivered",
69040
+ evidence: { at, sink_kind: "http" },
69041
+ reason: "fetch_unavailable"
69042
+ };
69043
+ }
69044
+ try {
69045
+ const resp = await withTimeout(fetchImpl(sink.url, {
69046
+ method: "POST",
69047
+ headers: { "content-type": "application/json", ...sink.headers || {} },
69048
+ body: JSON.stringify(payload)
69049
+ }), timeoutMs);
69050
+ const status_code = resp.status;
69051
+ if (!resp.ok || status_code < 200 || status_code >= 300) {
69052
+ return {
69053
+ status: "not_delivered",
69054
+ evidence: { at, sink_kind: "http", status_code },
69055
+ reason: `http_${status_code}`
69056
+ };
69057
+ }
69058
+ let body = "";
69059
+ try {
69060
+ body = await resp.text();
69061
+ } catch {
69062
+ body = "";
69063
+ }
69064
+ const bytes = Buffer.from(body, "utf8");
69065
+ const key = sink.ackHmacKey != null ? sink.ackHmacKey : ackHmacKey;
69066
+ const sig = pickSignature(resp.headers);
69067
+ const hmac = hmacResult(bytes, sig, key);
69068
+ if (!hmac.ok) {
69069
+ return {
69070
+ status: "not_delivered",
69071
+ evidence: { at, sink_kind: "http", status_code, ack_hash: sha256Prefixed(bytes) },
69072
+ reason: hmac.reason
69073
+ };
69074
+ }
69075
+ const evidence = {
69076
+ at,
69077
+ sink_kind: "http",
69078
+ status_code
69079
+ };
69080
+ if (bytes.length > 0)
69081
+ evidence.ack_hash = sha256Prefixed(bytes);
69082
+ if (hmac.verified === true)
69083
+ evidence.ack_verified = true;
69084
+ return { status: "delivered_acked", evidence };
69085
+ } catch (err) {
69086
+ const name = err && typeof err === "object" ? err.name : "";
69087
+ const reason = name === "TimeoutError" ? "timeout" : "threw";
69088
+ return {
69089
+ status: "not_delivered",
69090
+ evidence: { at, sink_kind: "http" },
69091
+ reason
69092
+ };
69093
+ }
69094
+ }
69095
+ function isHttpSink(sink) {
69096
+ return typeof sink === "object" && sink != null && typeof sink.url === "string";
69097
+ }
69098
+ async function deliverMonitoring(args) {
69099
+ const at = args.now;
69100
+ const timeoutMs = args.timeoutMs ?? exports2.DEFAULT_MONITORING_SINK_TIMEOUT_MS;
69101
+ if (args.sink == null) {
69102
+ return { status: "sent_unacked", evidence: { at, sink_kind: "callback" } };
69103
+ }
69104
+ if (typeof args.sink === "function") {
69105
+ return deliverCallback(args.sink, args.payload, timeoutMs, args.ackHmacKey, at);
69106
+ }
69107
+ if (isHttpSink(args.sink)) {
69108
+ return deliverHttp(args.sink, args.payload, timeoutMs, args.ackHmacKey, at);
69109
+ }
69110
+ return {
69111
+ status: "not_delivered",
69112
+ evidence: { at, sink_kind: "callback" },
69113
+ reason: "sink_unrecognised"
69114
+ };
69115
+ }
69116
+ function formatMonitoringDeliveryLine(d) {
69117
+ if (d.status === "sent_unacked")
69118
+ return "monitoring: sent, not acked";
69119
+ if (d.status === "not_delivered") {
69120
+ return d.reason ? `monitoring: NOT delivered (${d.reason})` : "monitoring: NOT delivered";
69121
+ }
69122
+ const ev = d.evidence;
69123
+ if (ev && ev.ack_hash) {
69124
+ const short = ev.ack_hash.replace(/^sha256:/, "").slice(0, 12);
69125
+ return `monitoring: delivered (acked sha256:${short}\u2026)`;
69126
+ }
69127
+ if (ev && typeof ev.status_code === "number") {
69128
+ return `monitoring: delivered (acked HTTP ${ev.status_code})`;
69129
+ }
69130
+ return "monitoring: delivered (acked)";
69131
+ }
69132
+ function monitoringDeliveryFailClosed(config) {
69133
+ if (config.observeOnly === true)
69134
+ return false;
69135
+ if (config.failPolicy === "open")
69136
+ return false;
69137
+ return true;
67074
69138
  }
67075
69139
  }
67076
69140
  });
@@ -67090,6 +69154,9 @@ var require_guard = __commonJS({
67090
69154
  var execution_proof_js_1 = require_execution_proof();
67091
69155
  var freshness_js_1 = require_freshness();
67092
69156
  var conditional_write_js_1 = require_conditional_write();
69157
+ var commit_observation_js_1 = require_commit_observation();
69158
+ var cas_attestation_js_1 = require_cas_attestation();
69159
+ var monitoring_delivery_js_1 = require_monitoring_delivery();
67093
69160
  var breakers = /* @__PURE__ */ new WeakMap();
67094
69161
  var nowMs = () => Date.now();
67095
69162
  var iso = () => (/* @__PURE__ */ new Date()).toISOString();
@@ -67215,57 +69282,105 @@ var require_guard = __commonJS({
67215
69282
  return { verified: null, cause: "RECEIPT_UNVERIFIED" };
67216
69283
  }
67217
69284
  }
67218
- async function runEnforced(config, factory, approved, redacted, freshness, conditional_write) {
69285
+ async function runEnforced(config, factory, approved, redacted, freshness, conditional_write, monitoring_delivery) {
67219
69286
  emit(config, { type: "execution_started", at: iso(), action: approved.action, decisionId: approved.envelope.decision_id });
67220
69287
  try {
67221
69288
  const result = await factory(approved.envelope, redacted);
67222
69289
  const base = { executionAttempted: true, executed: true, enforced: true, result, verdict: approved, preflighted: true };
67223
- return {
67224
- ...base,
67225
- proof: (0, execution_proof_js_1.buildExecutionProof)({ ...base, conditionalWriteBasis: conditional_write }),
67226
- freshness,
67227
- conditional_write
67228
- };
69290
+ return finishExecuted(config, base, freshness, conditional_write, redacted, result, monitoring_delivery);
67229
69291
  } catch (error) {
67230
69292
  emit(config, { type: "factory_error", at: iso(), action: approved.action });
67231
69293
  const base = { executionAttempted: true, executed: false, enforced: true, error, verdict: approved, preflighted: true };
67232
- return {
67233
- ...base,
67234
- proof: (0, execution_proof_js_1.buildExecutionProof)({ ...base, conditionalWriteBasis: conditional_write }),
67235
- freshness,
67236
- conditional_write
67237
- };
69294
+ return finishExecuted(config, base, freshness, conditional_write, redacted, void 0, monitoring_delivery);
67238
69295
  }
67239
69296
  }
67240
- async function runUnenforced(config, factory, envelope, verdict, preflighted, redacted, freshness, conditional_write) {
69297
+ async function runUnenforced(config, factory, envelope, verdict, preflighted, redacted, freshness, conditional_write, monitoring_delivery) {
67241
69298
  emit(config, { type: "execution_started", at: iso() });
67242
69299
  try {
67243
69300
  const result = await factory(envelope, redacted);
67244
69301
  const base = { executionAttempted: true, executed: true, enforced: false, result, verdict, preflighted };
67245
- return {
67246
- ...base,
67247
- proof: (0, execution_proof_js_1.buildExecutionProof)({ ...base, conditionalWriteBasis: conditional_write }),
67248
- freshness,
67249
- conditional_write
67250
- };
69302
+ return finishExecuted(config, base, freshness, conditional_write, redacted, result, monitoring_delivery);
67251
69303
  } catch (error) {
67252
69304
  emit(config, { type: "factory_error", at: iso() });
67253
69305
  const base = { executionAttempted: true, executed: false, enforced: false, error, verdict, preflighted };
67254
- return {
67255
- ...base,
67256
- proof: (0, execution_proof_js_1.buildExecutionProof)({ ...base, conditionalWriteBasis: conditional_write }),
67257
- freshness,
67258
- conditional_write
67259
- };
69306
+ return finishExecuted(config, base, freshness, conditional_write, redacted, void 0, monitoring_delivery);
67260
69307
  }
67261
69308
  }
67262
- function blocked(verdict, preflighted, freshness, conditional_write) {
69309
+ function blocked(verdict, preflighted, freshness, conditional_write, monitoring_delivery) {
69310
+ const commit_observation = {
69311
+ status: "not_observed",
69312
+ observed_at: iso(),
69313
+ host_attestation: "absent"
69314
+ };
67263
69315
  const base = { executionAttempted: false, executed: false, enforced: false, verdict, preflighted };
67264
69316
  return {
67265
69317
  ...base,
67266
- proof: (0, execution_proof_js_1.buildExecutionProof)({ ...base, conditionalWriteBasis: conditional_write }),
69318
+ proof: (0, execution_proof_js_1.buildExecutionProof)({
69319
+ ...base,
69320
+ conditionalWriteBasis: conditional_write,
69321
+ commitObservation: commit_observation,
69322
+ monitoringDelivery: monitoring_delivery
69323
+ }),
69324
+ freshness,
69325
+ conditional_write,
69326
+ commit_observation,
69327
+ ...monitoring_delivery ? { monitoring_delivery } : {}
69328
+ };
69329
+ }
69330
+ async function finishExecuted(config, base, freshness, conditional_write, redacted, result, monitoring_delivery) {
69331
+ const enabled = config.requireCommitObservation !== false;
69332
+ const commit_observation = await (0, commit_observation_js_1.observeCommit)({
69333
+ enabled,
69334
+ call: redacted,
69335
+ result,
69336
+ now: iso(),
69337
+ preflightOnObserved: (artifacts) => preflightWithRetry(config, {
69338
+ artifacts,
69339
+ context: { operation: config.operation ?? "tool_call", environment: config.environment, audience: config.audience },
69340
+ previous_receipt: resolvePreviousReceipt(config)
69341
+ })
69342
+ });
69343
+ if (!enabled) {
69344
+ emit(config, {
69345
+ type: "commit_observation_check_disabled",
69346
+ at: iso(),
69347
+ cause: "requireCommitObservation_false"
69348
+ });
69349
+ } else if (commit_observation.status === "observed_drift") {
69350
+ emit(config, {
69351
+ type: "commit_observed_drift",
69352
+ at: iso(),
69353
+ observed_fp: commit_observation.observed_fp,
69354
+ expected_fp: commit_observation.expected_fp,
69355
+ token: commit_observation.token
69356
+ });
69357
+ }
69358
+ const cas_evidence = result !== void 0 ? (0, cas_attestation_js_1.evaluateCasEvidence)(result, {
69359
+ registry: config.executorAttestation && config.executorAttestation.registry
69360
+ }) : void 0;
69361
+ const proof = (0, execution_proof_js_1.buildExecutionProof)({
69362
+ ...base,
69363
+ conditionalWriteBasis: conditional_write,
69364
+ commitObservation: commit_observation,
69365
+ monitoringDelivery: monitoring_delivery,
69366
+ ...cas_evidence ? { casEvidence: cas_evidence } : {}
69367
+ });
69368
+ if (result !== void 0 && (0, cas_attestation_js_1.isExecuteIfUnchangedOutcome)(result)) {
69369
+ try {
69370
+ (0, cas_attestation_js_1.buildCasAttestation)(proof, result, {
69371
+ registry: config.executorAttestation && config.executorAttestation.registry
69372
+ });
69373
+ } catch {
69374
+ }
69375
+ }
69376
+ return {
69377
+ ...base,
69378
+ proof,
67267
69379
  freshness,
67268
- conditional_write
69380
+ conditional_write,
69381
+ commit_observation,
69382
+ ...monitoring_delivery ? { monitoring_delivery } : {},
69383
+ ...cas_evidence ? { cas_evidence } : {}
67269
69384
  };
67270
69385
  }
67271
69386
  function preflightBeforeByIdFrom(arts) {
@@ -67427,7 +69542,11 @@ var require_guard = __commonJS({
67427
69542
  breakerRecord(config);
67428
69543
  return closedIntegrity(config, "EXECUTION_ACTION_UNRECOGNISED", failPolicy, fctx, cwctx, redacted, detection.artifacts);
67429
69544
  }
67430
- if (rd.reason === "UNREADABLE_DECISION" || !rd.envelope) {
69545
+ if (rd.reason === "UNREADABLE_DECISION") {
69546
+ breakerRecord(config);
69547
+ return closedIntegrity(config, "UNREADABLE_DECISION", failPolicy, fctx, cwctx, redacted, detection.artifacts);
69548
+ }
69549
+ if (!rd.envelope) {
67431
69550
  breakerRecord(config);
67432
69551
  return closedIntegrity(config, "SCHEMA_INVALID", failPolicy, fctx, cwctx, redacted, detection.artifacts);
67433
69552
  }
@@ -67470,6 +69589,41 @@ var require_guard = __commonJS({
67470
69589
  else
67471
69590
  emit(config, { type: "monitoring_unwired", at: iso(), decisionId: envelope.decision_id });
67472
69591
  }
69592
+ let monitoringDelivery;
69593
+ if (kind === "MONITOR") {
69594
+ if (!sinkWired) {
69595
+ monitoringDelivery = {
69596
+ status: "not_delivered",
69597
+ evidence: { at: iso(), sink_kind: "callback" },
69598
+ reason: "sink_not_wired"
69599
+ };
69600
+ } else {
69601
+ monitoringDelivery = await (0, monitoring_delivery_js_1.deliverMonitoring)({
69602
+ sink: config.monitoringSink,
69603
+ timeoutMs: config.monitoringSinkTimeoutMs,
69604
+ ackHmacKey: config.ackHmacKey,
69605
+ payload: {
69606
+ at: iso(),
69607
+ decision_id: typeof envelope.decision_id === "string" ? envelope.decision_id : void 0,
69608
+ action: "CONTINUE_WITH_MONITORING",
69609
+ kind: "MONITOR"
69610
+ },
69611
+ now: iso()
69612
+ });
69613
+ if (monitoringDelivery.status === "not_delivered") {
69614
+ emit(config, {
69615
+ type: "monitoring_not_delivered",
69616
+ at: iso(),
69617
+ decisionId: envelope.decision_id,
69618
+ cause: monitoringDelivery.reason
69619
+ });
69620
+ if ((0, monitoring_delivery_js_1.monitoringDeliveryFailClosed)(config)) {
69621
+ breakerRecord(config);
69622
+ return closedIntegrity(config, "MONITORING_UNWIRED", failPolicy, fctx, cwctx, redacted, detection.artifacts, monitoringDelivery);
69623
+ }
69624
+ }
69625
+ }
69626
+ }
67473
69627
  const { basis: freshBasis, blockCause: freshBlock } = freshnessFor(config, redacted, fctx, detection.artifacts);
67474
69628
  if (freshBlock === "FRESHNESS_REQUIRED" || freshBlock === "FRESHNESS_FAILED") {
67475
69629
  breakerRecord(config);
@@ -67483,7 +69637,11 @@ var require_guard = __commonJS({
67483
69637
  if (config.observeOnly) {
67484
69638
  emit(config, { type: "observe_only_passthrough", at: iso(), action: closedAction });
67485
69639
  const verdict = kind === "ALLOW" ? { kind: "ALLOW", action: "CONTINUE", envelope, receiptVerified } : { kind: "MONITOR", action: "CONTINUE_WITH_MONITORING", envelope, receiptVerified };
67486
- return runUnenforced(config, executeFactory, envelope, verdict, true, redacted, freshBasis, cwBasis);
69640
+ return runUnenforced(config, executeFactory, envelope, verdict, true, redacted, freshBasis, cwBasis, monitoringDelivery);
69641
+ }
69642
+ if (kind === "MONITOR" && sinkWired && monitoringDelivery && monitoringDelivery.status === "not_delivered") {
69643
+ const degraded = { kind: "MONITOR", action: "CONTINUE_WITH_MONITORING", envelope, receiptVerified };
69644
+ return runUnenforced(config, executeFactory, envelope, degraded, true, redacted, freshBasis, cwBasis, monitoringDelivery);
67487
69645
  }
67488
69646
  const enforceable = receiptVerified && (kind === "ALLOW" || sinkWired);
67489
69647
  if (enforceable) {
@@ -67496,7 +69654,7 @@ var require_guard = __commonJS({
67496
69654
  cause: "requireExecutionStateMatch_false"
67497
69655
  });
67498
69656
  const offVerdict = kind === "ALLOW" ? { kind: "ALLOW", action: "CONTINUE", envelope, receiptVerified } : { kind: "MONITOR", action: "CONTINUE_WITH_MONITORING", envelope, receiptVerified };
67499
- return runUnenforced(config, executeFactory, envelope, offVerdict, true, redacted, freshBasis, cwBasis);
69657
+ return runUnenforced(config, executeFactory, envelope, offVerdict, true, redacted, freshBasis, cwBasis, monitoringDelivery);
67500
69658
  }
67501
69659
  const et = (0, execution_time_fingerprint_js_1.checkExecutionTimeFingerprint)({
67502
69660
  artifacts: detection.artifacts,
@@ -67533,21 +69691,21 @@ var require_guard = __commonJS({
67533
69691
  });
67534
69692
  }
67535
69693
  const warnVerdict = kind === "ALLOW" ? { kind: "ALLOW", action: "CONTINUE", envelope, receiptVerified } : { kind: "MONITOR", action: "CONTINUE_WITH_MONITORING", envelope, receiptVerified };
67536
- return runUnenforced(config, executeFactory, envelope, warnVerdict, true, redacted, freshBasis, cwBasis);
69694
+ return runUnenforced(config, executeFactory, envelope, warnVerdict, true, redacted, freshBasis, cwBasis, monitoringDelivery);
67537
69695
  }
67538
69696
  const approved = kind === "ALLOW" ? { kind: "ALLOW", action: "CONTINUE", envelope, receiptVerified: true } : { kind: "MONITOR", action: "CONTINUE_WITH_MONITORING", envelope, receiptVerified: true };
67539
- return runEnforced(config, executeFactory, approved, redacted, freshBasis, cwBasis);
69697
+ return runEnforced(config, executeFactory, approved, redacted, freshBasis, cwBasis, monitoringDelivery);
67540
69698
  }
67541
69699
  breakerRecord(config);
67542
- return closedIntegrity(config, receiptVerified ? "MONITORING_UNWIRED" : "RECEIPT_MISSING", failPolicy, fctx, cwctx, redacted, detection.artifacts);
69700
+ return closedIntegrity(config, receiptVerified ? "MONITORING_UNWIRED" : "RECEIPT_MISSING", failPolicy, fctx, cwctx, redacted, detection.artifacts, monitoringDelivery);
67543
69701
  }
67544
- function closedIntegrity(config, cause, failPolicy, fctx, cwctx, redacted, arts) {
69702
+ function closedIntegrity(config, cause, failPolicy, fctx, cwctx, redacted, arts, monitoring_delivery) {
67545
69703
  const count = breakers.get(config)?.fails.length ?? 1;
67546
69704
  emit(config, { type: "breaker_tripped", at: iso(), cause });
67547
69705
  const v = unavailableVerdict({ cause, failPolicy, resolution: "CLOSED", action: "STOP" }, count);
67548
69706
  const { basis } = freshnessFor(config, redacted, fctx, arts);
67549
69707
  const { basis: cw } = conditionalWriteFor(config, redacted, cwctx);
67550
- return blocked(v, false, basis, cw);
69708
+ return blocked(v, false, basis, cw, monitoring_delivery);
67551
69709
  }
67552
69710
  function isExpired(envelope) {
67553
69711
  const exp = envelope.expires_at;
@@ -67984,6 +70142,7 @@ var require_final_answer_proof = __commonJS({
67984
70142
  exports2.renderFinalAnswerProof = renderFinalAnswerProof;
67985
70143
  exports2.attachProofToAgentResponse = attachProofToAgentResponse;
67986
70144
  var execution_proof_js_1 = require_execution_proof();
70145
+ var monitoring_delivery_js_1 = require_monitoring_delivery();
67987
70146
  function deriveProofBanner(proof) {
67988
70147
  if (!proof || typeof proof !== "object")
67989
70148
  return "NO_PREFLIGHT";
@@ -68042,6 +70201,7 @@ var require_final_answer_proof = __commonJS({
68042
70201
  "Calls outside the guarded path are invisible to this proof.",
68043
70202
  "execution_result_hash is NOT proof that applied artifacts match change_fp.",
68044
70203
  "conditional_write:true is host-asserted (the host says it conditioned on a version token); it is NOT independently CAS-verified by the guard.",
70204
+ ...L.commit_observation_is_observed_at_t3_not_atomic === true ? ["commit_observation is observed at T3, not atomic: another writer may act between write and observation; token-only adapters compare version token not content; host attestation is a host claim layered on the measurement"] : [],
68045
70205
  // Machine keys for greppability (still honest if someone only reads keys).
68046
70206
  `limits.does_not_claim_host_cannot_bypass=${L.does_not_claim_host_cannot_bypass === true}`,
68047
70207
  `limits.calls_outside_guarded_path_invisible=${L.calls_outside_guarded_path_invisible === true}`,
@@ -68079,6 +70239,12 @@ var require_final_answer_proof = __commonJS({
68079
70239
  lines.push(bullet(`receipt.verified: ${yn(proof.receipt.verified === true)}`));
68080
70240
  lines.push(bullet(`receipt.status: ${proof.receipt.status != null ? proof.receipt.status : "null (not verified / no receipt path)"}`));
68081
70241
  lines.push(bullet(`receipt.expires_at: ${proof.receipt.expires_at != null ? proof.receipt.expires_at : "(none)"}`));
70242
+ const trail = proof.recheck_trail;
70243
+ if (Array.isArray(trail) && trail.length > 1) {
70244
+ const n = trail.length - 1;
70245
+ const id = proof.decision_id != null ? proof.decision_id : "(none)";
70246
+ lines.push(bullet(`re-preflighted ${n}\xD7 after remediation; final decision ${id}`));
70247
+ }
68082
70248
  lines.push("");
68083
70249
  lines.push(h2("Authorization"));
68084
70250
  lines.push(bullet(`currently_authorized: ${formatAuthz(proof.currently_authorized)}`));
@@ -68106,6 +70272,40 @@ var require_final_answer_proof = __commonJS({
68106
70272
  lines.push(bullet(`enforced: ${yn(proof.execution.enforced === true)}`));
68107
70273
  lines.push(bullet(`execution_result_hash: ${formatResultHash(proof.execution_result_hash)}`));
68108
70274
  lines.push("");
70275
+ const co = proof.commit_observation;
70276
+ if (co && typeof co === "object") {
70277
+ lines.push(h2("Commit observation (T3)"));
70278
+ lines.push(bullet(`status: ${co.status}`));
70279
+ lines.push(bullet(`observed_at: ${co.observed_at || "(none)"}`));
70280
+ if (co.host_attestation)
70281
+ lines.push(bullet(`host_attestation: ${co.host_attestation}`));
70282
+ if (co.observed_fp)
70283
+ lines.push(bullet(`observed_fp: ${co.observed_fp}`));
70284
+ if (co.expected_fp)
70285
+ lines.push(bullet(`expected_fp: ${co.expected_fp}`));
70286
+ if (co.token)
70287
+ lines.push(bullet(`token: ${co.token}`));
70288
+ const ce = proof.cas_evidence;
70289
+ if (ce && ce.class === "executor_attested") {
70290
+ const kid = ce.executor_kid != null ? ce.executor_kid : "\u2026";
70291
+ const st = ce.attest_status != null ? ce.attest_status : "ATTEST_VALID";
70292
+ lines.push(bullet(`committed \u2014 executor-attested (${st}, kid ${kid})`));
70293
+ lines.push(bullet("Observed at T3, not atomic: another writer may act between write and observation; token-only adapters compare version token not content."));
70294
+ } else if (ce && ce.class === "host_claimed" && ce.attest_status) {
70295
+ lines.push(bullet(`committed \u2014 host-claimed (attest_status ${ce.attest_status})`));
70296
+ lines.push(bullet("Observed at T3, not atomic: another writer may act between write and observation; token-only adapters compare version token not content; host attestation is a host claim layered on the measurement."));
70297
+ } else {
70298
+ lines.push(bullet("Observed at T3, not atomic: another writer may act between write and observation; token-only adapters compare version token not content; host attestation is a host claim layered on the measurement."));
70299
+ }
70300
+ lines.push("");
70301
+ }
70302
+ const mdv = proof.monitoring_delivery;
70303
+ if (mdv && typeof mdv === "object" && typeof mdv.status === "string") {
70304
+ lines.push(h2("Monitoring delivery"));
70305
+ lines.push(bullet((0, monitoring_delivery_js_1.formatMonitoringDeliveryLine)(mdv)));
70306
+ lines.push(bullet("delivered_acked means the sink returned an ack \u2014 it does NOT mean a human saw the event."));
70307
+ lines.push("");
70308
+ }
68109
70309
  lines.push(h2("Limits (non-claims \u2014 always true on this proof)"));
68110
70310
  for (const L of limitLines(proof)) {
68111
70311
  lines.push(bullet(L));
@@ -68152,546 +70352,6 @@ var require_final_answer_proof = __commonJS({
68152
70352
  }
68153
70353
  });
68154
70354
 
68155
- // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/fs.js
68156
- var require_fs = __commonJS({
68157
- "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/fs.js"(exports2) {
68158
- "use strict";
68159
- var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
68160
- if (k2 === void 0) k2 = k;
68161
- var desc = Object.getOwnPropertyDescriptor(m, k);
68162
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
68163
- desc = { enumerable: true, get: function() {
68164
- return m[k];
68165
- } };
68166
- }
68167
- Object.defineProperty(o, k2, desc);
68168
- }) : (function(o, m, k, k2) {
68169
- if (k2 === void 0) k2 = k;
68170
- o[k2] = m[k];
68171
- }));
68172
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
68173
- Object.defineProperty(o, "default", { enumerable: true, value: v });
68174
- }) : function(o, v) {
68175
- o["default"] = v;
68176
- });
68177
- var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
68178
- var ownKeys = function(o) {
68179
- ownKeys = Object.getOwnPropertyNames || function(o2) {
68180
- var ar = [];
68181
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
68182
- return ar;
68183
- };
68184
- return ownKeys(o);
68185
- };
68186
- return function(mod) {
68187
- if (mod && mod.__esModule) return mod;
68188
- var result = {};
68189
- if (mod != null) {
68190
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
68191
- }
68192
- __setModuleDefault(result, mod);
68193
- return result;
68194
- };
68195
- })();
68196
- Object.defineProperty(exports2, "__esModule", { value: true });
68197
- exports2.tokensEqual = exports2.FS_ABSENT_TOKEN = exports2.FS_VERSION_TOKEN_PREFIX = void 0;
68198
- exports2.fsTokenContentHash = fsTokenContentHash;
68199
- exports2.createFsVersionToken = createFsVersionToken;
68200
- exports2.readVersionedFile = readVersionedFile;
68201
- exports2.writeFileIfUnchanged = writeFileIfUnchanged;
68202
- exports2.createFsPriorContentResolver = createFsPriorContentResolver;
68203
- var node_crypto_1 = require("node:crypto");
68204
- var node_fs_1 = require("node:fs");
68205
- var path = __importStar(require("node:path"));
68206
- var conditional_write_js_1 = require_conditional_write();
68207
- Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
68208
- return conditional_write_js_1.tokensEqual;
68209
- } });
68210
- exports2.FS_VERSION_TOKEN_PREFIX = "fs:v1:";
68211
- exports2.FS_ABSENT_TOKEN = "fs:v1:absent";
68212
- function sha256hex(buf) {
68213
- return (0, node_crypto_1.createHash)("sha256").update(buf).digest("hex");
68214
- }
68215
- function fsTokenContentHash(token) {
68216
- if (typeof token !== "string" || !token.startsWith(exports2.FS_VERSION_TOKEN_PREFIX))
68217
- return null;
68218
- if (token === exports2.FS_ABSENT_TOKEN)
68219
- return null;
68220
- const rest = token.slice(exports2.FS_VERSION_TOKEN_PREFIX.length);
68221
- const colon = rest.indexOf(":");
68222
- if (colon < 0)
68223
- return null;
68224
- const hash = rest.slice(colon + 1);
68225
- return /^[a-f0-9]{64}$/.test(hash) ? hash : null;
68226
- }
68227
- async function createFsVersionToken(filePath) {
68228
- let st;
68229
- try {
68230
- st = await node_fs_1.promises.stat(filePath);
68231
- } catch (err) {
68232
- const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
68233
- if (code === "ENOENT")
68234
- return exports2.FS_ABSENT_TOKEN;
68235
- throw err;
68236
- }
68237
- if (!st.isFile()) {
68238
- throw new Error(`createFsVersionToken: not a regular file: ${filePath}`);
68239
- }
68240
- const buf = await node_fs_1.promises.readFile(filePath);
68241
- const hash = sha256hex(buf);
68242
- const mtimeMs = Math.trunc(st.mtimeMs);
68243
- return `${exports2.FS_VERSION_TOKEN_PREFIX}${mtimeMs}:${hash}`;
68244
- }
68245
- async function readVersionedFile(filePath) {
68246
- const version_token = await createFsVersionToken(filePath);
68247
- if (version_token === exports2.FS_ABSENT_TOKEN) {
68248
- return { content: "", version_token };
68249
- }
68250
- const content = await node_fs_1.promises.readFile(filePath, "utf8");
68251
- return { content, version_token };
68252
- }
68253
- async function writeFileIfUnchanged(args) {
68254
- const target = path.resolve(args.path);
68255
- const body = typeof args.content === "string" ? Buffer.from(args.content, "utf8") : args.content;
68256
- const writtenHash = sha256hex(body);
68257
- return (0, conditional_write_js_1.executeIfUnchanged)({
68258
- expected_token: args.expected_token,
68259
- current_token: () => createFsVersionToken(target),
68260
- detect_stale_during_commit: true,
68261
- // Post-commit: token content-hash must equal sha256 of what we wrote (mtime may vary).
68262
- expected_after_commit: async (result) => {
68263
- const post = await createFsVersionToken(target);
68264
- const postHash = fsTokenContentHash(post);
68265
- if (postHash === result.written_content_hash)
68266
- return post;
68267
- return `${exports2.FS_VERSION_TOKEN_PREFIX}0:stale_during_commit_mismatch`;
68268
- },
68269
- write: async () => {
68270
- const dir = path.dirname(target);
68271
- await node_fs_1.promises.mkdir(dir, { recursive: true });
68272
- const tmp = path.join(dir, `.coderifts-cas-${path.basename(target)}-${process.pid}-${(0, node_crypto_1.randomBytes)(6).toString("hex")}.tmp`);
68273
- try {
68274
- await node_fs_1.promises.writeFile(tmp, body);
68275
- const still = await createFsVersionToken(target);
68276
- if (!(0, conditional_write_js_1.tokensEqual)(args.expected_token, still)) {
68277
- try {
68278
- await node_fs_1.promises.unlink(tmp);
68279
- } catch {
68280
- }
68281
- throw new conditional_write_js_1.StaleVersionTokenAbort(still);
68282
- }
68283
- await node_fs_1.promises.rename(tmp, target);
68284
- } catch (err) {
68285
- if (err instanceof conditional_write_js_1.StaleVersionTokenAbort)
68286
- throw err;
68287
- try {
68288
- await node_fs_1.promises.unlink(tmp);
68289
- } catch {
68290
- }
68291
- throw err;
68292
- }
68293
- return { path: target, bytes: body.length, written_content_hash: writtenHash };
68294
- }
68295
- });
68296
- }
68297
- function createFsPriorContentResolver(options) {
68298
- const pathForArtifact = options?.pathForArtifact;
68299
- return async (req) => {
68300
- let filePath = typeof req.path === "string" && req.path.length > 0 ? req.path : void 0;
68301
- if (!filePath && pathForArtifact) {
68302
- const mapped = pathForArtifact(req.artifactId);
68303
- if (typeof mapped === "string" && mapped.length > 0)
68304
- filePath = mapped;
68305
- }
68306
- if (!filePath)
68307
- return null;
68308
- try {
68309
- return await node_fs_1.promises.readFile(filePath, "utf8");
68310
- } catch (err) {
68311
- const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
68312
- if (code === "ENOENT")
68313
- return null;
68314
- throw err;
68315
- }
68316
- };
68317
- }
68318
- }
68319
- });
68320
-
68321
- // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/api.js
68322
- var require_api3 = __commonJS({
68323
- "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/api.js"(exports2) {
68324
- "use strict";
68325
- Object.defineProperty(exports2, "__esModule", { value: true });
68326
- exports2.tokensEqual = exports2.API_ABSENT_TOKEN = exports2.API_VERSION_TOKEN_PREFIX = void 0;
68327
- exports2.createApiVersionToken = createApiVersionToken;
68328
- exports2.apiTokenRaw = apiTokenRaw;
68329
- exports2.writeApiIfUnchanged = writeApiIfUnchanged;
68330
- var conditional_write_js_1 = require_conditional_write();
68331
- Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
68332
- return conditional_write_js_1.tokensEqual;
68333
- } });
68334
- exports2.API_VERSION_TOKEN_PREFIX = "api:v1:";
68335
- exports2.API_ABSENT_TOKEN = "api:v1:absent";
68336
- function createApiVersionToken(etag) {
68337
- if (etag == null)
68338
- return exports2.API_ABSENT_TOKEN;
68339
- let s = String(etag).trim();
68340
- if (s.length === 0)
68341
- return exports2.API_ABSENT_TOKEN;
68342
- if (s.startsWith("W/") || s.startsWith("w/"))
68343
- s = s.slice(2).trim();
68344
- if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
68345
- s = s.slice(1, -1);
68346
- }
68347
- if (s.length === 0)
68348
- return exports2.API_ABSENT_TOKEN;
68349
- return `${exports2.API_VERSION_TOKEN_PREFIX}${s}`;
68350
- }
68351
- function apiTokenRaw(token) {
68352
- if (typeof token !== "string" || !token.startsWith(exports2.API_VERSION_TOKEN_PREFIX))
68353
- return null;
68354
- if (token === exports2.API_ABSENT_TOKEN)
68355
- return null;
68356
- const raw = token.slice(exports2.API_VERSION_TOKEN_PREFIX.length);
68357
- return raw.length > 0 ? raw : null;
68358
- }
68359
- async function writeApiIfUnchanged(args) {
68360
- const detect = args.detect_stale_during_commit === true;
68361
- return (0, conditional_write_js_1.executeIfUnchanged)({
68362
- expected_token: args.expected_token,
68363
- current_token: async () => createApiVersionToken(await args.current_etag()),
68364
- detect_stale_during_commit: detect,
68365
- expected_after_commit: detect ? async (written) => {
68366
- if (typeof written.new_etag === "string" && written.new_etag.trim().length > 0) {
68367
- return createApiVersionToken(written.new_etag);
68368
- }
68369
- return createApiVersionToken(await args.current_etag());
68370
- } : void 0,
68371
- write: async () => {
68372
- const report = await args.write({
68373
- if_match: apiTokenRaw(args.expected_token),
68374
- expected_token: args.expected_token
68375
- });
68376
- if (!report || typeof report !== "object") {
68377
- throw new Error("writeApiIfUnchanged: host write must return ApiHostWriteReport");
68378
- }
68379
- if (report.status === "precondition_failed") {
68380
- const cur = report.current_etag !== void 0 ? createApiVersionToken(report.current_etag) : null;
68381
- throw new conditional_write_js_1.StaleVersionTokenAbort(cur);
68382
- }
68383
- if (report.status !== "committed") {
68384
- throw new Error(`writeApiIfUnchanged: unknown host report status ${String(report.status)}`);
68385
- }
68386
- const new_etag = report.new_etag === void 0 || report.new_etag === null ? null : String(report.new_etag);
68387
- return {
68388
- new_etag,
68389
- result: report.result
68390
- };
68391
- }
68392
- });
68393
- }
68394
- }
68395
- });
68396
-
68397
- // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/db.js
68398
- var require_db2 = __commonJS({
68399
- "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/db.js"(exports2) {
68400
- "use strict";
68401
- Object.defineProperty(exports2, "__esModule", { value: true });
68402
- exports2.tokensEqual = exports2.DB_ABSENT_TOKEN = exports2.DB_VERSION_TOKEN_PREFIX = void 0;
68403
- exports2.createDbVersionToken = createDbVersionToken;
68404
- exports2.dbTokenRaw = dbTokenRaw;
68405
- exports2.writeDbIfUnchanged = writeDbIfUnchanged;
68406
- var conditional_write_js_1 = require_conditional_write();
68407
- Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
68408
- return conditional_write_js_1.tokensEqual;
68409
- } });
68410
- exports2.DB_VERSION_TOKEN_PREFIX = "db:v1:";
68411
- exports2.DB_ABSENT_TOKEN = "db:v1:absent";
68412
- function createDbVersionToken(version) {
68413
- if (version == null)
68414
- return exports2.DB_ABSENT_TOKEN;
68415
- if (typeof version === "number" && !Number.isFinite(version))
68416
- return exports2.DB_ABSENT_TOKEN;
68417
- const s = String(version).trim();
68418
- if (s.length === 0)
68419
- return exports2.DB_ABSENT_TOKEN;
68420
- return `${exports2.DB_VERSION_TOKEN_PREFIX}${s}`;
68421
- }
68422
- function dbTokenRaw(token) {
68423
- if (typeof token !== "string" || !token.startsWith(exports2.DB_VERSION_TOKEN_PREFIX))
68424
- return null;
68425
- if (token === exports2.DB_ABSENT_TOKEN)
68426
- return null;
68427
- const raw = token.slice(exports2.DB_VERSION_TOKEN_PREFIX.length);
68428
- return raw.length > 0 ? raw : null;
68429
- }
68430
- function normalizeDbReport(report) {
68431
- if ("rows_affected" in report && typeof report.rows_affected === "number") {
68432
- const r = report;
68433
- if (r.rows_affected === 0) {
68434
- return {
68435
- kind: "conflict",
68436
- new_version: void 0,
68437
- current_version: void 0,
68438
- rows_affected: 0
68439
- };
68440
- }
68441
- return {
68442
- kind: "committed",
68443
- new_version: r.new_version,
68444
- result: r.result,
68445
- rows_affected: r.rows_affected
68446
- };
68447
- }
68448
- if ("status" in report && report.status === "conflict") {
68449
- const r = report;
68450
- return {
68451
- kind: "conflict",
68452
- new_version: void 0,
68453
- current_version: r.current_version
68454
- };
68455
- }
68456
- if ("status" in report && report.status === "committed") {
68457
- const r = report;
68458
- return {
68459
- kind: "committed",
68460
- new_version: r.new_version,
68461
- result: r.result
68462
- };
68463
- }
68464
- throw new Error("writeDbIfUnchanged: host write must return DbHostWriteReport");
68465
- }
68466
- async function writeDbIfUnchanged(args) {
68467
- const detect = args.detect_stale_during_commit === true;
68468
- return (0, conditional_write_js_1.executeIfUnchanged)({
68469
- expected_token: args.expected_token,
68470
- current_token: async () => createDbVersionToken(await args.current_version()),
68471
- detect_stale_during_commit: detect,
68472
- expected_after_commit: detect ? async (written) => {
68473
- if (typeof written.new_version === "string" && written.new_version.trim().length > 0) {
68474
- return createDbVersionToken(written.new_version);
68475
- }
68476
- return createDbVersionToken(await args.current_version());
68477
- } : void 0,
68478
- write: async () => {
68479
- const report = await args.write({
68480
- expected_version: dbTokenRaw(args.expected_token),
68481
- expected_token: args.expected_token
68482
- });
68483
- const norm = normalizeDbReport(report);
68484
- if (norm.kind === "conflict") {
68485
- const cur = norm.current_version !== void 0 ? createDbVersionToken(norm.current_version) : null;
68486
- throw new conditional_write_js_1.StaleVersionTokenAbort(cur);
68487
- }
68488
- const new_version = norm.new_version === void 0 || norm.new_version === null ? null : String(norm.new_version);
68489
- return {
68490
- new_version,
68491
- result: norm.result,
68492
- rows_affected: norm.rows_affected
68493
- };
68494
- }
68495
- });
68496
- }
68497
- }
68498
- });
68499
-
68500
- // node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/registry.js
68501
- var require_registry = __commonJS({
68502
- "node_modules/@coderifts/agent-guard/dist/cjs/cas-adapters/registry.js"(exports2) {
68503
- "use strict";
68504
- Object.defineProperty(exports2, "__esModule", { value: true });
68505
- exports2.tokensEqual = exports2.REGISTRY_ABSENT_TOKEN = exports2.REGISTRY_VERSION_TOKEN_PREFIX = void 0;
68506
- exports2.createRegistryVersionToken = createRegistryVersionToken;
68507
- exports2.registryTokenRaw = registryTokenRaw;
68508
- exports2.writeRegistryIfUnchanged = writeRegistryIfUnchanged;
68509
- var conditional_write_js_1 = require_conditional_write();
68510
- Object.defineProperty(exports2, "tokensEqual", { enumerable: true, get: function() {
68511
- return conditional_write_js_1.tokensEqual;
68512
- } });
68513
- exports2.REGISTRY_VERSION_TOKEN_PREFIX = "registry:v1:";
68514
- exports2.REGISTRY_ABSENT_TOKEN = "registry:v1:absent";
68515
- function createRegistryVersionToken(token) {
68516
- if (token == null)
68517
- return exports2.REGISTRY_ABSENT_TOKEN;
68518
- if (typeof token === "number" && !Number.isFinite(token))
68519
- return exports2.REGISTRY_ABSENT_TOKEN;
68520
- const s = String(token).trim();
68521
- if (s.length === 0)
68522
- return exports2.REGISTRY_ABSENT_TOKEN;
68523
- return `${exports2.REGISTRY_VERSION_TOKEN_PREFIX}${s}`;
68524
- }
68525
- function registryTokenRaw(token) {
68526
- if (typeof token !== "string" || !token.startsWith(exports2.REGISTRY_VERSION_TOKEN_PREFIX)) {
68527
- return null;
68528
- }
68529
- if (token === exports2.REGISTRY_ABSENT_TOKEN)
68530
- return null;
68531
- const raw = token.slice(exports2.REGISTRY_VERSION_TOKEN_PREFIX.length);
68532
- return raw.length > 0 ? raw : null;
68533
- }
68534
- function normalizeRegistryReport(report) {
68535
- if (!report || typeof report !== "object") {
68536
- throw new Error("writeRegistryIfUnchanged: host compareAndSwap must return RegistryHostCasReport");
68537
- }
68538
- if ("swapped" in report) {
68539
- if (report.swapped === true) {
68540
- return { kind: "committed", new_token: report.new_token, result: report.result };
68541
- }
68542
- return { kind: "conflict", current_token: report.current_token };
68543
- }
68544
- if (report.status === "committed") {
68545
- return { kind: "committed", new_token: report.new_token, result: report.result };
68546
- }
68547
- if (report.status === "conflict") {
68548
- return { kind: "conflict", current_token: report.current_token };
68549
- }
68550
- throw new Error("writeRegistryIfUnchanged: unknown host report shape");
68551
- }
68552
- async function writeRegistryIfUnchanged(args) {
68553
- const detect = args.detect_stale_during_commit === true;
68554
- return (0, conditional_write_js_1.executeIfUnchanged)({
68555
- expected_token: args.expected_token,
68556
- current_token: async () => createRegistryVersionToken(await args.current_token()),
68557
- detect_stale_during_commit: detect,
68558
- expected_after_commit: detect ? async (written) => {
68559
- if (typeof written.new_token === "string" && written.new_token.trim().length > 0) {
68560
- return createRegistryVersionToken(written.new_token);
68561
- }
68562
- return createRegistryVersionToken(await args.current_token());
68563
- } : void 0,
68564
- write: async () => {
68565
- const report = await args.compareAndSwap({
68566
- expected: registryTokenRaw(args.expected_token),
68567
- expected_token: args.expected_token
68568
- });
68569
- const norm = normalizeRegistryReport(report);
68570
- if (norm.kind === "conflict") {
68571
- const cur = norm.current_token !== void 0 ? createRegistryVersionToken(norm.current_token) : null;
68572
- throw new conditional_write_js_1.StaleVersionTokenAbort(cur);
68573
- }
68574
- const new_token = norm.new_token === void 0 || norm.new_token === null ? null : String(norm.new_token);
68575
- return {
68576
- new_token,
68577
- result: norm.result
68578
- };
68579
- }
68580
- });
68581
- }
68582
- }
68583
- });
68584
-
68585
- // node_modules/@coderifts/agent-guard/dist/cjs/cas-attestation.js
68586
- var require_cas_attestation = __commonJS({
68587
- "node_modules/@coderifts/agent-guard/dist/cjs/cas-attestation.js"(exports2) {
68588
- "use strict";
68589
- Object.defineProperty(exports2, "__esModule", { value: true });
68590
- exports2.CAS_ATTESTATION_SPEC = void 0;
68591
- exports2.isGuardExecutionProof = isGuardExecutionProof;
68592
- exports2.isExecuteIfUnchangedOutcome = isExecuteIfUnchangedOutcome;
68593
- exports2.buildCasAttestation = buildCasAttestation;
68594
- var execution_proof_js_1 = require_execution_proof();
68595
- exports2.CAS_ATTESTATION_SPEC = "cas-attestation.v1";
68596
- var LIMITS = Object.freeze({
68597
- does_not_claim_only_write_on_host: true,
68598
- does_not_claim_version_token_proves_change_fp_match: true,
68599
- does_not_claim_committed_stale_is_safe: true,
68600
- does_not_claim_execution_result_hash_equals_cas_bytes: true,
68601
- does_not_claim_host_cannot_bypass: true,
68602
- does_not_claim_governance_redecision: true
68603
- });
68604
- function isGuardExecutionProof(x) {
68605
- if (!x || typeof x !== "object")
68606
- return false;
68607
- const p = x;
68608
- return p.proof_spec === execution_proof_js_1.EXECUTION_PROOF_SPEC && p.receipt != null && typeof p.receipt === "object" && p.execution_result_hash != null && typeof p.execution_result_hash === "object";
68609
- }
68610
- function isExecuteIfUnchangedOutcome(x) {
68611
- if (!x || typeof x !== "object")
68612
- return false;
68613
- const o = x;
68614
- if (o.status === "committed") {
68615
- const c = x;
68616
- return typeof c.version_token === "string";
68617
- }
68618
- if (o.status === "refused") {
68619
- const r = x;
68620
- return r.reason === "stale_version_token" && typeof r.expected_token === "string";
68621
- }
68622
- if (o.status === "committed_stale_detected") {
68623
- const s = x;
68624
- return s.reason === "stale_during_commit" && typeof s.expected_token === "string";
68625
- }
68626
- return false;
68627
- }
68628
- function freezeExecutionResultHash(h) {
68629
- return Object.freeze({ ...h });
68630
- }
68631
- function projectCas(outcome) {
68632
- if (outcome.status === "committed") {
68633
- return Object.freeze({
68634
- status: "committed",
68635
- write_ran: true,
68636
- version_token: outcome.version_token
68637
- });
68638
- }
68639
- if (outcome.status === "refused") {
68640
- return Object.freeze({
68641
- status: "refused",
68642
- write_ran: false,
68643
- reason: "stale_version_token",
68644
- expected_token: outcome.expected_token,
68645
- current_token: outcome.current_token == null ? null : outcome.current_token
68646
- });
68647
- }
68648
- return Object.freeze({
68649
- status: "committed_stale_detected",
68650
- write_ran: true,
68651
- reason: "stale_during_commit",
68652
- expected_token: outcome.expected_token,
68653
- post_commit_token: outcome.post_commit_token == null ? null : outcome.post_commit_token
68654
- });
68655
- }
68656
- function buildCasAttestation(proof, outcome) {
68657
- if (!isGuardExecutionProof(proof)) {
68658
- throw new TypeError("@coderifts/agent-guard: buildCasAttestation requires a valid guard-execution-proof.v1 object (proof_spec mismatch or missing required fields)");
68659
- }
68660
- if (!isExecuteIfUnchangedOutcome(outcome)) {
68661
- throw new TypeError("@coderifts/agent-guard: buildCasAttestation requires a valid ExecuteIfUnchangedOutcome (status committed | refused | committed_stale_detected with branch fields)");
68662
- }
68663
- const receipt_verified = proof.receipt.verified === true;
68664
- const cas = projectCas(outcome);
68665
- const write_ran = cas.write_ran === true;
68666
- const stale_during_commit = cas.status === "committed_stale_detected";
68667
- const refused = cas.status === "refused";
68668
- const authorized_and_committed = receipt_verified && cas.status === "committed";
68669
- const attestation = {
68670
- attestation_spec: exports2.CAS_ATTESTATION_SPEC,
68671
- references: Object.freeze({
68672
- decision_id: proof.decision_id,
68673
- change_fp: proof.binds_to != null ? proof.binds_to.change_fp : null,
68674
- operation: proof.binds_to != null ? proof.binds_to.operation : null,
68675
- execution_result_hash: freezeExecutionResultHash(proof.execution_result_hash),
68676
- receipt_verified
68677
- }),
68678
- cas,
68679
- derived: Object.freeze({
68680
- authorized_and_committed,
68681
- write_ran,
68682
- stale_during_commit,
68683
- refused
68684
- }),
68685
- limits: LIMITS
68686
- };
68687
- return freezeAttestation(attestation);
68688
- }
68689
- function freezeAttestation(a) {
68690
- return Object.freeze(a);
68691
- }
68692
- }
68693
- });
68694
-
68695
70355
  // node_modules/@coderifts/agent-guard/dist/cjs/remediation-loop-attestation.js
68696
70356
  var require_remediation_loop_attestation = __commonJS({
68697
70357
  "node_modules/@coderifts/agent-guard/dist/cjs/remediation-loop-attestation.js"(exports2) {
@@ -69512,6 +71172,459 @@ var require_artifact_resolver = __commonJS({
69512
71172
  }
69513
71173
  });
69514
71174
 
71175
+ // node_modules/@coderifts/agent-guard/dist/cjs/auto-recheck.js
71176
+ var require_auto_recheck = __commonJS({
71177
+ "node_modules/@coderifts/agent-guard/dist/cjs/auto-recheck.js"(exports2) {
71178
+ "use strict";
71179
+ Object.defineProperty(exports2, "__esModule", { value: true });
71180
+ exports2.AUTO_RECHECK_MAX_CAP = void 0;
71181
+ exports2.clampMaxAttempts = clampMaxAttempts;
71182
+ exports2.normalizeAutoRecheck = normalizeAutoRecheck;
71183
+ exports2.runAutoRecheckLoop = runAutoRecheckLoop;
71184
+ var guard_js_1 = require_guard();
71185
+ var remediation_loop_attestation_js_1 = require_remediation_loop_attestation();
71186
+ var artifact_resolver_js_1 = require_artifact_resolver();
71187
+ exports2.AUTO_RECHECK_MAX_CAP = 3;
71188
+ function iso() {
71189
+ return (/* @__PURE__ */ new Date()).toISOString();
71190
+ }
71191
+ function emit(config, e) {
71192
+ if (config.onEvent) {
71193
+ try {
71194
+ config.onEvent(e);
71195
+ } catch {
71196
+ }
71197
+ }
71198
+ }
71199
+ function clampMaxAttempts(n) {
71200
+ const v = typeof n === "number" ? n : Number(n);
71201
+ if (!Number.isFinite(v))
71202
+ return 0;
71203
+ const i = Math.floor(v);
71204
+ if (i < 1)
71205
+ return 0;
71206
+ return i > exports2.AUTO_RECHECK_MAX_CAP ? exports2.AUTO_RECHECK_MAX_CAP : i;
71207
+ }
71208
+ function normalizeAutoRecheck(raw) {
71209
+ if (!raw || typeof raw !== "object")
71210
+ return null;
71211
+ const o = raw;
71212
+ if (typeof o.applyFix !== "function")
71213
+ return null;
71214
+ const maxAttempts = clampMaxAttempts(o.maxAttempts);
71215
+ if (maxAttempts < 1)
71216
+ return null;
71217
+ const cfg = { maxAttempts, applyFix: o.applyFix };
71218
+ if (typeof o.resolveInput === "function")
71219
+ cfg.resolveInput = o.resolveInput;
71220
+ if (o.resolveConfig && typeof o.resolveConfig === "object")
71221
+ cfg.resolveConfig = o.resolveConfig;
71222
+ return cfg;
71223
+ }
71224
+ function envelopeOf(outcome) {
71225
+ const v = outcome.verdict;
71226
+ if (v && "envelope" in v && v.envelope && typeof v.envelope === "object") {
71227
+ return v.envelope;
71228
+ }
71229
+ return null;
71230
+ }
71231
+ function fingerprintOf(outcome) {
71232
+ const env = envelopeOf(outcome);
71233
+ if (env && typeof env.fingerprint === "string" && env.fingerprint)
71234
+ return env.fingerprint;
71235
+ const fp = outcome.proof && outcome.proof.binds_to && outcome.proof.binds_to.change_fp;
71236
+ return typeof fp === "string" && fp ? fp : null;
71237
+ }
71238
+ function decisionIdOf(outcome) {
71239
+ const env = envelopeOf(outcome);
71240
+ if (env && typeof env.decision_id === "string" && env.decision_id)
71241
+ return env.decision_id;
71242
+ const id = outcome.proof && outcome.proof.decision_id;
71243
+ return typeof id === "string" && id ? id : null;
71244
+ }
71245
+ function executionActionOf(outcome) {
71246
+ const v = outcome.verdict;
71247
+ if (v && "action" in v && typeof v.action === "string")
71248
+ return v.action;
71249
+ return null;
71250
+ }
71251
+ function isAllowClass(outcome) {
71252
+ const v = outcome.verdict;
71253
+ if (!v || typeof v !== "object")
71254
+ return false;
71255
+ return v.kind === "ALLOW" || v.kind === "MONITOR";
71256
+ }
71257
+ function isBlockWithRemediation(outcome) {
71258
+ const v = outcome.verdict;
71259
+ if (!v || v.kind !== "BLOCK")
71260
+ return null;
71261
+ return (0, remediation_loop_attestation_js_1.readRemediationTransaction)(envelopeOf(outcome));
71262
+ }
71263
+ function trailEntry(outcome, attempt) {
71264
+ return Object.freeze({
71265
+ attempt,
71266
+ decision_id: decisionIdOf(outcome),
71267
+ fingerprint: fingerprintOf(outcome),
71268
+ execution_action: executionActionOf(outcome)
71269
+ });
71270
+ }
71271
+ function attachObservation(outcome, trail, extras) {
71272
+ const frozenTrail = Object.freeze(trail.map((e) => Object.freeze({ ...e })));
71273
+ const proof = Object.freeze({
71274
+ ...outcome.proof,
71275
+ recheck_trail: frozenTrail
71276
+ });
71277
+ const obs = { recheck_trail: frozenTrail };
71278
+ if (extras.stop)
71279
+ obs.recheck_stop_reason = extras.stop;
71280
+ const recheckCount = Math.max(0, trail.length - 1);
71281
+ if (extras.fixed === true) {
71282
+ obs.fixed_after_block = { value: true, attempt_count: recheckCount };
71283
+ } else if (trail.length > 0) {
71284
+ obs.fixed_after_block = { value: null, attempt_count: recheckCount > 0 ? recheckCount : null };
71285
+ }
71286
+ return { ...outcome, proof, ...obs };
71287
+ }
71288
+ function withFreshArtifacts(call, artifacts) {
71289
+ const next = { ...call, artifacts };
71290
+ const args = next.arguments;
71291
+ if (args && typeof args === "object" && !Array.isArray(args)) {
71292
+ next.arguments = { ...args, artifacts };
71293
+ }
71294
+ return next;
71295
+ }
71296
+ async function freshCall(cfg, current, rebind, artifactsBeforeFix) {
71297
+ let next = { ...current };
71298
+ if (typeof cfg.resolveInput === "function") {
71299
+ const input = await cfg.resolveInput();
71300
+ const resolved = (0, artifact_resolver_js_1.resolve)(input, cfg.resolveConfig);
71301
+ if (resolved.artifacts && resolved.artifacts.length > 0) {
71302
+ return withFreshArtifacts(next, resolved.artifacts);
71303
+ }
71304
+ }
71305
+ const hostReplacedArtifacts = Array.isArray(current.artifacts) && current.artifacts !== artifactsBeforeFix;
71306
+ if (hostReplacedArtifacts) {
71307
+ return withFreshArtifacts(next, current.artifacts);
71308
+ }
71309
+ const rebound = await Promise.resolve(rebind());
71310
+ if (Array.isArray(rebound.artifacts) && rebound.artifacts.length > 0) {
71311
+ return withFreshArtifacts(next, rebound.artifacts);
71312
+ }
71313
+ return next;
71314
+ }
71315
+ async function runAutoRecheckLoop(args) {
71316
+ const cfg = normalizeAutoRecheck(args.config.autoRecheck);
71317
+ const first = await (0, guard_js_1.guardToolCall)(args.call, args.factory, args.config, args.callContext);
71318
+ if (!cfg)
71319
+ return first;
71320
+ const remediation0 = isBlockWithRemediation(first);
71321
+ if (!remediation0)
71322
+ return first;
71323
+ const trail = [trailEntry(first, 0)];
71324
+ let currentCall = args.call;
71325
+ let previous = first;
71326
+ let previousFp = fingerprintOf(first);
71327
+ let remediation = remediation0;
71328
+ for (let i = 1; i <= cfg.maxAttempts; i++) {
71329
+ const artifactsBeforeFix = currentCall.artifacts;
71330
+ const ctx = {
71331
+ call: currentCall,
71332
+ attempt: i,
71333
+ outcome: previous
71334
+ };
71335
+ let applied = false;
71336
+ try {
71337
+ applied = await cfg.applyFix(remediation, ctx) === true;
71338
+ } catch {
71339
+ emit(args.config, {
71340
+ type: "recheck_attempt",
71341
+ at: iso(),
71342
+ attempt: i,
71343
+ decisionId: decisionIdOf(previous) ?? void 0,
71344
+ from_fp: previousFp,
71345
+ to_fp: previousFp,
71346
+ cause: "apply_fix_threw"
71347
+ });
71348
+ return attachObservation(first, trail, { stop: "apply_fix_threw" });
71349
+ }
71350
+ if (!applied) {
71351
+ return attachObservation(first, trail, { stop: "apply_fix_declined" });
71352
+ }
71353
+ currentCall = await freshCall(cfg, ctx.call, args.rebind, artifactsBeforeFix);
71354
+ const nextCtx = args.refreshContext ? await args.refreshContext(currentCall) : args.callContext;
71355
+ const next = await (0, guard_js_1.guardToolCall)(currentCall, args.factory, args.config, nextCtx);
71356
+ const toFp = fingerprintOf(next);
71357
+ trail.push(trailEntry(next, i));
71358
+ emit(args.config, {
71359
+ type: "recheck_attempt",
71360
+ at: iso(),
71361
+ attempt: i,
71362
+ decisionId: decisionIdOf(next) ?? void 0,
71363
+ from_fp: previousFp,
71364
+ to_fp: toFp
71365
+ });
71366
+ if (previousFp != null && toFp != null && previousFp === toFp) {
71367
+ return attachObservation(next, trail, { stop: "no_progress" });
71368
+ }
71369
+ if (isAllowClass(next)) {
71370
+ return attachObservation(next, trail, { fixed: true });
71371
+ }
71372
+ const remNext = isBlockWithRemediation(next);
71373
+ if (!remNext) {
71374
+ return attachObservation(next, trail, {});
71375
+ }
71376
+ previous = next;
71377
+ previousFp = toFp;
71378
+ remediation = remNext;
71379
+ }
71380
+ return attachObservation(previous, trail, { stop: "exhausted" });
71381
+ }
71382
+ }
71383
+ });
71384
+
71385
+ // node_modules/@coderifts/agent-guard/dist/cjs/auto-derive.js
71386
+ var require_auto_derive = __commonJS({
71387
+ "node_modules/@coderifts/agent-guard/dist/cjs/auto-derive.js"(exports2) {
71388
+ "use strict";
71389
+ Object.defineProperty(exports2, "__esModule", { value: true });
71390
+ exports2.AUTO_DERIVE_READ_TIMEOUT_MS = exports2.AUTO_DERIVE_SOURCE = void 0;
71391
+ exports2.defaultFsReader = defaultFsReader;
71392
+ exports2.normalizeAutoDerive = normalizeAutoDerive;
71393
+ exports2.runAutoDerive = runAutoDerive;
71394
+ exports2.attachDerivation = attachDerivation;
71395
+ var node_fs_1 = require("node:fs");
71396
+ var artifact_resolver_js_1 = require_artifact_resolver();
71397
+ exports2.AUTO_DERIVE_SOURCE = "guard_auto_derived";
71398
+ exports2.AUTO_DERIVE_READ_TIMEOUT_MS = 2e3;
71399
+ function iso() {
71400
+ return (/* @__PURE__ */ new Date()).toISOString();
71401
+ }
71402
+ function emit(config, e) {
71403
+ if (config.onEvent) {
71404
+ try {
71405
+ config.onEvent(e);
71406
+ } catch {
71407
+ }
71408
+ }
71409
+ }
71410
+ async function defaultFsReader(filePath) {
71411
+ try {
71412
+ return await node_fs_1.promises.readFile(filePath, "utf8");
71413
+ } catch (err) {
71414
+ const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
71415
+ if (code === "ENOENT")
71416
+ return null;
71417
+ throw err;
71418
+ }
71419
+ }
71420
+ function looksLikeResolveConfig(o) {
71421
+ return "ssotPrefer" in o || "generatedGlobs" in o || "pathTypeHints" in o || "openApiAssembly" in o || "maxRefDepth" in o;
71422
+ }
71423
+ function looksLikeReaders(o) {
71424
+ const r = o;
71425
+ return typeof r.fs === "function" || typeof r.api === "function" || typeof r.db === "function" || typeof r.registry === "function";
71426
+ }
71427
+ function normalizeAutoDerive(raw) {
71428
+ if (raw === true)
71429
+ return { readers: { fs: defaultFsReader } };
71430
+ if (!raw || raw === false || typeof raw !== "object")
71431
+ return null;
71432
+ const o = raw;
71433
+ const cfg = {};
71434
+ if (o.resolveConfig && typeof o.resolveConfig === "object")
71435
+ cfg.resolveConfig = o.resolveConfig;
71436
+ if (o.readers && typeof o.readers === "object") {
71437
+ if (looksLikeReaders(o.readers)) {
71438
+ cfg.readers = { ...o.readers };
71439
+ } else if (looksLikeResolveConfig(o.readers)) {
71440
+ cfg.resolveConfig = o.readers;
71441
+ }
71442
+ }
71443
+ if (!cfg.readers)
71444
+ cfg.readers = {};
71445
+ if (typeof cfg.readers.fs !== "function")
71446
+ cfg.readers.fs = defaultFsReader;
71447
+ return cfg;
71448
+ }
71449
+ function rawRecord(args) {
71450
+ if (!args || typeof args !== "object" || Array.isArray(args))
71451
+ return null;
71452
+ return args;
71453
+ }
71454
+ function hostSuppliedArtifacts(args) {
71455
+ const a = rawRecord(args);
71456
+ return !!(a && Array.isArray(a.artifacts));
71457
+ }
71458
+ function targetFromArgs(a) {
71459
+ if (typeof a.path === "string" && a.path.length > 0)
71460
+ return { kind: "fs", key: a.path };
71461
+ if (typeof a.url === "string" && a.url.length > 0)
71462
+ return { kind: "api", key: a.url };
71463
+ if (typeof a.endpoint === "string" && a.endpoint.length > 0)
71464
+ return { kind: "api", key: a.endpoint };
71465
+ if (typeof a.table === "string" && a.table.length > 0) {
71466
+ const id = a.id != null ? String(a.id) : "";
71467
+ return { kind: "db", key: id ? `${a.table}/${id}` : a.table };
71468
+ }
71469
+ if (typeof a.key === "string" && a.key.length > 0)
71470
+ return { kind: "registry", key: a.key };
71471
+ return null;
71472
+ }
71473
+ function intendedAfter(a, before) {
71474
+ for (const k of ["contents", "content", "new_content", "new_contents"]) {
71475
+ if (typeof a[k] === "string")
71476
+ return a[k];
71477
+ }
71478
+ const oldS = typeof a.old_string === "string" ? a.old_string : null;
71479
+ const newS = typeof a.new_string === "string" ? a.new_string : null;
71480
+ if (newS == null)
71481
+ return null;
71482
+ if (typeof before === "string" && oldS && oldS.length > 0 && before.includes(oldS)) {
71483
+ return before.replace(oldS, newS);
71484
+ }
71485
+ if (newS.length > 0)
71486
+ return newS;
71487
+ return null;
71488
+ }
71489
+ function typeForTarget(target, a, resolveConfig) {
71490
+ if (typeof a.type === "string" && a.type) {
71491
+ const t = a.type;
71492
+ if (t === "openapi" || t === "graphql" || t === "grpc" || t === "asyncapi" || t === "mcp_manifest") {
71493
+ return t;
71494
+ }
71495
+ }
71496
+ if (target.kind === "fs") {
71497
+ const hinted = resolveConfig && resolveConfig.pathTypeHints ? resolveConfig.pathTypeHints[target.key] : void 0;
71498
+ if (hinted)
71499
+ return hinted;
71500
+ return (0, artifact_resolver_js_1.classifyByName)(target.key);
71501
+ }
71502
+ return null;
71503
+ }
71504
+ async function withTimeout(p, ms) {
71505
+ let timer;
71506
+ try {
71507
+ return await Promise.race([
71508
+ p,
71509
+ new Promise((_, reject) => {
71510
+ timer = setTimeout(() => {
71511
+ const e = new Error(`autoDerive reader timed out after ${ms}ms`);
71512
+ e.name = "TimeoutError";
71513
+ reject(e);
71514
+ }, Math.max(1, ms));
71515
+ })
71516
+ ]);
71517
+ } finally {
71518
+ if (timer)
71519
+ clearTimeout(timer);
71520
+ }
71521
+ }
71522
+ async function readCurrent(readers, target) {
71523
+ const fn = readers[target.kind];
71524
+ if (typeof fn !== "function") {
71525
+ const err = new Error(`autoDerive: no ${target.kind} reader`);
71526
+ err.code = "NO_READER";
71527
+ throw err;
71528
+ }
71529
+ return withTimeout(Promise.resolve(fn(target.key)), exports2.AUTO_DERIVE_READ_TIMEOUT_MS);
71530
+ }
71531
+ async function runAutoDerive(args) {
71532
+ const bound = args.bound;
71533
+ if (hostSuppliedArtifacts(args.rawArgs)) {
71534
+ return {
71535
+ call: bound,
71536
+ derivation: { mode: "host_supplied", targets: [] }
71537
+ };
71538
+ }
71539
+ const a = rawRecord(args.rawArgs) || rawRecord(bound.arguments);
71540
+ if (!a) {
71541
+ return { call: bound, derivation: { mode: "fragment_only", targets: [] } };
71542
+ }
71543
+ const target = targetFromArgs(a);
71544
+ if (!target) {
71545
+ return { call: bound, derivation: { mode: "fragment_only", targets: [] } };
71546
+ }
71547
+ const type = typeForTarget(target, a, args.cfg.resolveConfig);
71548
+ if (!type) {
71549
+ return {
71550
+ call: bound,
71551
+ derivation: {
71552
+ mode: "fragment_only",
71553
+ targets: [target],
71554
+ notes: [{ target: target.key, note: "not_contract_path" }]
71555
+ }
71556
+ };
71557
+ }
71558
+ const readers = args.cfg.readers || { fs: defaultFsReader };
71559
+ let before;
71560
+ try {
71561
+ before = await readCurrent(readers, target);
71562
+ } catch (err) {
71563
+ const name = err && typeof err === "object" && "name" in err ? String(err.name) : "";
71564
+ const cause = name === "TimeoutError" ? "reader_timeout" : "reader_threw";
71565
+ emit(args.config, { type: "derive_failed", at: iso(), cause });
71566
+ return {
71567
+ call: bound,
71568
+ derivation: {
71569
+ mode: "fragment_only",
71570
+ targets: [target],
71571
+ notes: [{
71572
+ target: target.key,
71573
+ note: cause === "reader_timeout" ? "reader_timeout" : "reader_threw"
71574
+ }]
71575
+ },
71576
+ failed: { cause }
71577
+ };
71578
+ }
71579
+ const after = intendedAfter(a, before);
71580
+ if (after == null) {
71581
+ return {
71582
+ call: bound,
71583
+ derivation: { mode: "fragment_only", targets: [target] }
71584
+ };
71585
+ }
71586
+ const notes = [];
71587
+ if (before === null) {
71588
+ notes.push({ target: target.key, note: "before_unavailable" });
71589
+ if (Array.isArray(bound.artifacts) && bound.artifacts.length > 0) {
71590
+ return {
71591
+ call: bound,
71592
+ derivation: {
71593
+ mode: "fragment_only",
71594
+ targets: [target],
71595
+ notes
71596
+ }
71597
+ };
71598
+ }
71599
+ }
71600
+ const derived = {
71601
+ id: `${type}:${target.key}`,
71602
+ type,
71603
+ before,
71604
+ after,
71605
+ source: exports2.AUTO_DERIVE_SOURCE
71606
+ };
71607
+ const call = {
71608
+ ...bound,
71609
+ artifacts: [derived]
71610
+ };
71611
+ return {
71612
+ call,
71613
+ derivation: {
71614
+ mode: "auto_derived",
71615
+ targets: [target],
71616
+ ...notes.length ? { notes } : {}
71617
+ }
71618
+ };
71619
+ }
71620
+ function attachDerivation(outcome, derivation) {
71621
+ if (!derivation)
71622
+ return outcome;
71623
+ return { ...outcome, derivation };
71624
+ }
71625
+ }
71626
+ });
71627
+
69515
71628
  // node_modules/@coderifts/agent-guard/dist/cjs/tool-registry.js
69516
71629
  var require_tool_registry = __commonJS({
69517
71630
  "node_modules/@coderifts/agent-guard/dist/cjs/tool-registry.js"(exports2) {
@@ -69522,6 +71635,8 @@ var require_tool_registry = __commonJS({
69522
71635
  var guard_js_1 = require_guard();
69523
71636
  var artifact_resolver_js_1 = require_artifact_resolver();
69524
71637
  var freshness_js_1 = require_freshness();
71638
+ var auto_recheck_js_1 = require_auto_recheck();
71639
+ var auto_derive_js_1 = require_auto_derive();
69525
71640
  var RegistryConstructionError = class extends Error {
69526
71641
  code;
69527
71642
  toolName;
@@ -69674,16 +71789,42 @@ var require_tool_registry = __commonJS({
69674
71789
  inputSchema: tool.inputSchema,
69675
71790
  meta: tool.meta,
69676
71791
  execute: async (args) => {
69677
- const call = binder(tool, args, cls);
69678
- const fctx = await (0, freshness_js_1.collectFreshnessCallContext)({
71792
+ const deriveCfg = (0, auto_derive_js_1.normalizeAutoDerive)(guardCfg.autoDerive);
71793
+ const rebindRaw = () => binder(tool, args, cls);
71794
+ let lastDerivation = null;
71795
+ const rebind = async () => {
71796
+ const c = rebindRaw();
71797
+ if (!deriveCfg)
71798
+ return c;
71799
+ const d = await (0, auto_derive_js_1.runAutoDerive)({
71800
+ bound: c,
71801
+ rawArgs: args,
71802
+ cfg: deriveCfg,
71803
+ config: guardCfg
71804
+ });
71805
+ lastDerivation = d.derivation;
71806
+ return d.call;
71807
+ };
71808
+ const call = await rebind();
71809
+ const refreshContext = async (c) => (0, freshness_js_1.collectFreshnessCallContext)({
69679
71810
  call: {
69680
- toolName: call.toolName,
69681
- artifacts: call.artifacts,
69682
- arguments: call.arguments
71811
+ toolName: c.toolName,
71812
+ artifacts: c.artifacts,
71813
+ arguments: c.arguments
69683
71814
  },
69684
71815
  resolvePriorContent: guardCfg.resolvePriorContent
69685
71816
  });
69686
- return (0, guard_js_1.guardToolCall)(call, async (_envelope, redacted) => rawExecute(redacted ? redacted.arguments : args), guardCfg, fctx);
71817
+ const fctx = await refreshContext(call);
71818
+ const factory = async (_envelope, redacted) => rawExecute(redacted ? redacted.arguments : args);
71819
+ const outcome = (0, auto_recheck_js_1.normalizeAutoRecheck)(guardCfg.autoRecheck) ? await (0, auto_recheck_js_1.runAutoRecheckLoop)({
71820
+ call,
71821
+ factory,
71822
+ config: guardCfg,
71823
+ callContext: fctx,
71824
+ rebind,
71825
+ refreshContext
71826
+ }) : await (0, guard_js_1.guardToolCall)(call, factory, guardCfg, fctx);
71827
+ return (0, auto_derive_js_1.attachDerivation)(outcome, lastDerivation);
69687
71828
  },
69688
71829
  _coderifts: { guarded: true, mutationClass: cls, operation }
69689
71830
  };
@@ -69929,12 +72070,247 @@ var require_merge_gate = __commonJS({
69929
72070
  }
69930
72071
  });
69931
72072
 
72073
+ // node_modules/@coderifts/agent-guard/dist/cjs/deploy-receipt-token.js
72074
+ var require_deploy_receipt_token = __commonJS({
72075
+ "node_modules/@coderifts/agent-guard/dist/cjs/deploy-receipt-token.js"(exports2) {
72076
+ "use strict";
72077
+ Object.defineProperty(exports2, "__esModule", { value: true });
72078
+ exports2.CHAIN_SIGNING_PREFIX = void 0;
72079
+ exports2.verifyDeployReceiptToken = verifyDeployReceiptToken;
72080
+ var node_crypto_1 = require("node:crypto");
72081
+ var sdk_1 = require_cjs3();
72082
+ var receipt_binding_js_1 = require_receipt_binding();
72083
+ exports2.CHAIN_SIGNING_PREFIX = "crchain.v1";
72084
+ function scalar(v) {
72085
+ return v == null ? "" : String(v);
72086
+ }
72087
+ function reconstructInput(payload) {
72088
+ const v1 = `${exports2.CHAIN_SIGNING_PREFIX}|${scalar(payload.kid)}|${scalar(payload.fp)}|${scalar(payload.prev)}|${scalar(payload.caller)}|${scalar(payload.ts)}`;
72089
+ if (payload.v === 4) {
72090
+ return `${v1}|${scalar(payload.reg)}|${scalar(payload.ir)}|${scalar(payload.expires_at)}|${scalar(payload.bh)}`;
72091
+ }
72092
+ if (payload.v === 3) {
72093
+ return `${v1}|${scalar(payload.reg)}|${scalar(payload.ir)}`;
72094
+ }
72095
+ if (payload.v === 2) {
72096
+ return `${v1}|${scalar(payload.reg)}`;
72097
+ }
72098
+ return v1;
72099
+ }
72100
+ function isIssueTimeWithinKeyWindow(ts, keyMeta) {
72101
+ if (!keyMeta || keyMeta.status === "active")
72102
+ return true;
72103
+ if (keyMeta.status !== "retired")
72104
+ return false;
72105
+ if (typeof keyMeta.retired_at !== "string" || keyMeta.retired_at.length === 0)
72106
+ return false;
72107
+ if (typeof ts !== "string" || ts.length === 0)
72108
+ return false;
72109
+ const issueMs = Date.parse(ts);
72110
+ if (!Number.isFinite(issueMs))
72111
+ return false;
72112
+ if (keyMeta.valid_from) {
72113
+ const fromMs = Date.parse(keyMeta.valid_from);
72114
+ if (Number.isFinite(fromMs) && issueMs < fromMs)
72115
+ return false;
72116
+ }
72117
+ const retiredMs = Date.parse(keyMeta.retired_at);
72118
+ if (!Number.isFinite(retiredMs))
72119
+ return false;
72120
+ if (issueMs >= retiredMs)
72121
+ return false;
72122
+ return true;
72123
+ }
72124
+ function resolveKey(kid, registry, pinnedKeyPem) {
72125
+ if (typeof pinnedKeyPem === "string" && pinnedKeyPem.trim().length > 0) {
72126
+ try {
72127
+ return {
72128
+ publicKey: (0, node_crypto_1.createPublicKey)(pinnedKeyPem),
72129
+ status: "active",
72130
+ valid_from: null,
72131
+ retired_at: null
72132
+ };
72133
+ } catch {
72134
+ return null;
72135
+ }
72136
+ }
72137
+ if (!registry || !Array.isArray(registry.keys) || !kid)
72138
+ return null;
72139
+ const matches = registry.keys.filter((k) => k && k.kid === kid && typeof k.public_key_pem === "string");
72140
+ if (matches.length === 0)
72141
+ return null;
72142
+ const entry = matches.find((k) => k.status === "active") || matches[0];
72143
+ try {
72144
+ return {
72145
+ publicKey: (0, node_crypto_1.createPublicKey)(entry.public_key_pem),
72146
+ status: entry.status === "retired" ? "retired" : "active",
72147
+ valid_from: entry.valid_from || null,
72148
+ retired_at: entry.retired_at || null
72149
+ };
72150
+ } catch {
72151
+ return null;
72152
+ }
72153
+ }
72154
+ function fail(status, denyReason, extra = {}) {
72155
+ return {
72156
+ valid: false,
72157
+ status,
72158
+ currently_authorized: false,
72159
+ authz_reason: extra.authz_reason ?? denyReason,
72160
+ denyReason,
72161
+ view: null,
72162
+ key_status: extra.key_status ?? null,
72163
+ payload: extra.payload
72164
+ };
72165
+ }
72166
+ function viewFromEnvelope(envelope, payload, currently_authorized) {
72167
+ const artifact = envelope.target_id ?? envelope.artifact_digest ?? envelope.bound_artifact_id;
72168
+ return {
72169
+ currently_authorized,
72170
+ decision: typeof envelope.decision === "string" ? envelope.decision : "",
72171
+ execution_action: typeof envelope.execution_action === "string" ? envelope.execution_action : void 0,
72172
+ operation: typeof envelope.operation === "string" ? envelope.operation : void 0,
72173
+ bound_environment: typeof envelope.environment === "string" ? envelope.environment : null,
72174
+ bound_artifact_id: artifact == null ? null : String(artifact),
72175
+ verdict_fingerprint: typeof envelope.fingerprint === "string" ? envelope.fingerprint : typeof payload.fp === "string" ? payload.fp : void 0,
72176
+ body_hash: typeof payload.bh === "string" ? payload.bh : void 0,
72177
+ target_id: envelope.target_id == null ? void 0 : String(envelope.target_id)
72178
+ };
72179
+ }
72180
+ function verifyDeployReceiptToken(input, _intended = {}, nowMs) {
72181
+ const token = input && input.token;
72182
+ if (typeof token !== "string" || token.length === 0) {
72183
+ return fail("MALFORMED", "unverified_receipt_view");
72184
+ }
72185
+ const hasKeys = input.pinnedKeyPem && String(input.pinnedKeyPem).trim().length > 0 || input.registry && Array.isArray(input.registry.keys) && input.registry.keys.length > 0;
72186
+ if (!hasKeys) {
72187
+ return fail("MALFORMED", "inputs_incomplete", { authz_reason: "keys_missing" });
72188
+ }
72189
+ const segments = token.split(".");
72190
+ if (segments.length !== 2 || segments.some((s) => !s)) {
72191
+ return fail("MALFORMED", "unverified_receipt_view");
72192
+ }
72193
+ let payload;
72194
+ try {
72195
+ payload = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
72196
+ } catch {
72197
+ return fail("MALFORMED", "unverified_receipt_view");
72198
+ }
72199
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
72200
+ return fail("MALFORMED", "unverified_receipt_view");
72201
+ }
72202
+ if (typeof payload.v === "number" && payload.v > 4) {
72203
+ return fail("UNSUPPORTED_VERSION", "unverified_receipt_view", { payload });
72204
+ }
72205
+ const kid = typeof payload.kid === "string" ? payload.kid : "";
72206
+ const resolved = resolveKey(kid, input.registry, input.pinnedKeyPem);
72207
+ if (!resolved)
72208
+ return fail("UNKNOWN_KEY", "unknown_key", { payload });
72209
+ let sigOk = false;
72210
+ try {
72211
+ sigOk = (0, node_crypto_1.verify)(null, Buffer.from(reconstructInput(payload), "utf8"), resolved.publicKey, Buffer.from(segments[1], "base64url"));
72212
+ } catch {
72213
+ return fail("INVALID_SIGNATURE", "invalid_signature", { payload });
72214
+ }
72215
+ if (!sigOk)
72216
+ return fail("INVALID_SIGNATURE", "invalid_signature", { payload });
72217
+ for (const k of ["kid", "fp", "prev", "caller", "ts", "reg", "ir", "expires_at", "bh"]) {
72218
+ if (typeof payload[k] === "string" && payload[k].includes("|")) {
72219
+ return fail("INVALID_SIGNATURE", "invalid_signature", { payload, authz_reason: "delimiter_in_field" });
72220
+ }
72221
+ }
72222
+ if (resolved.status === "retired") {
72223
+ if (!isIssueTimeWithinKeyWindow(typeof payload.ts === "string" ? payload.ts : void 0, resolved)) {
72224
+ return fail("INVALID_SIGNATURE", "invalid_signature", { payload, authz_reason: "retired_key_outside_window" });
72225
+ }
72226
+ const envelope2 = input.decision_result && typeof input.decision_result === "object" ? input.decision_result : void 0;
72227
+ const view = envelope2 ? viewFromEnvelope(envelope2, payload, false) : null;
72228
+ return {
72229
+ valid: true,
72230
+ status: "RETIRED_KEY_VALID_AT_ISSUE",
72231
+ currently_authorized: false,
72232
+ authz_reason: "retired_key",
72233
+ denyReason: "retired_key",
72234
+ payload,
72235
+ view,
72236
+ key_status: "retired"
72237
+ };
72238
+ }
72239
+ if (payload.v === 4 && typeof payload.expires_at === "string") {
72240
+ const exp = Date.parse(payload.expires_at);
72241
+ const now = Number.isFinite(nowMs) ? nowMs : Date.now();
72242
+ if ((0, sdk_1.isReceiptExpired)(exp, now, { environment: _intended.environment, operation: _intended.operation })) {
72243
+ const envelope2 = input.decision_result && typeof input.decision_result === "object" ? input.decision_result : void 0;
72244
+ return {
72245
+ valid: true,
72246
+ status: "VERIFIED_EXPIRED",
72247
+ currently_authorized: false,
72248
+ authz_reason: "expired",
72249
+ denyReason: "expired",
72250
+ payload,
72251
+ view: envelope2 ? viewFromEnvelope(envelope2, payload, false) : null,
72252
+ key_status: "active"
72253
+ };
72254
+ }
72255
+ }
72256
+ const envelope = input.decision_result && typeof input.decision_result === "object" ? input.decision_result : void 0;
72257
+ if (!envelope) {
72258
+ return {
72259
+ valid: true,
72260
+ status: "VERIFIED_CURRENT",
72261
+ currently_authorized: false,
72262
+ authz_reason: "receipt_context_required",
72263
+ denyReason: "receipt_not_authorized",
72264
+ payload,
72265
+ view: null,
72266
+ key_status: "active"
72267
+ };
72268
+ }
72269
+ let localBh = null;
72270
+ try {
72271
+ localBh = (0, receipt_binding_js_1.computeBodyHash)(envelope);
72272
+ } catch {
72273
+ localBh = null;
72274
+ }
72275
+ if (typeof payload.bh !== "string" || payload.bh !== localBh) {
72276
+ return fail("INVALID_SIGNATURE", "body_hash_mismatch", { payload, authz_reason: "body_hash_mismatch" });
72277
+ }
72278
+ return {
72279
+ valid: true,
72280
+ status: "VERIFIED_CURRENT",
72281
+ currently_authorized: true,
72282
+ authz_reason: "ok",
72283
+ denyReason: null,
72284
+ payload,
72285
+ view: viewFromEnvelope(envelope, payload, true),
72286
+ key_status: "active"
72287
+ };
72288
+ }
72289
+ }
72290
+ });
72291
+
69932
72292
  // node_modules/@coderifts/agent-guard/dist/cjs/deploy-gate.js
69933
72293
  var require_deploy_gate = __commonJS({
69934
72294
  "node_modules/@coderifts/agent-guard/dist/cjs/deploy-gate.js"(exports2) {
69935
72295
  "use strict";
69936
72296
  Object.defineProperty(exports2, "__esModule", { value: true });
72297
+ exports2.DEPLOY_RECEIPT_VIEW_SPEC = void 0;
72298
+ exports2.asVerifiedDeployReceiptView = asVerifiedDeployReceiptView;
72299
+ exports2.isVerifiedDeployReceiptView = isVerifiedDeployReceiptView;
69937
72300
  exports2.deployGate = deployGate;
72301
+ var deploy_receipt_token_js_1 = require_deploy_receipt_token();
72302
+ exports2.DEPLOY_RECEIPT_VIEW_SPEC = "deploy-receipt-view.v1";
72303
+ function asVerifiedDeployReceiptView(view, verify_status = "VERIFIED_CURRENT") {
72304
+ return {
72305
+ ...view,
72306
+ view_spec: exports2.DEPLOY_RECEIPT_VIEW_SPEC,
72307
+ verified: true,
72308
+ verify_status
72309
+ };
72310
+ }
72311
+ function isVerifiedDeployReceiptView(r) {
72312
+ return !!r && r.view_spec === exports2.DEPLOY_RECEIPT_VIEW_SPEC && r.verified === true;
72313
+ }
69938
72314
  function norm(s) {
69939
72315
  return String(s == null ? "" : s).trim().toLowerCase();
69940
72316
  }
@@ -69975,14 +72351,15 @@ var require_deploy_gate = __commonJS({
69975
72351
  const allowPending = input.allowPending ?? rc.allowPending ?? false;
69976
72352
  const allowWarnDeploy = input.allowWarnDeploy ?? rc.allowWarnDeploy ?? false;
69977
72353
  const allowPrefix = input.allowPrefixCompare ?? rc.allowPrefixCompare ?? false;
69978
- const receipt = input.receipt;
69979
- const detail = {
72354
+ let verification = { mode: "none", verify_status: null };
72355
+ let receipt = input.receipt;
72356
+ const detailOf = (r) => ({
69980
72357
  environment: norm(target.environment),
69981
72358
  artifact_id: norm(target.artifact_id),
69982
- bound_environment: receipt && receipt.bound_environment != null ? norm(receipt.bound_environment) : null,
69983
- bound_artifact_id: receipt && receipt.bound_artifact_id != null ? norm(receipt.bound_artifact_id) : null,
69984
- operation: receipt && receipt.operation != null ? String(receipt.operation) : null
69985
- };
72359
+ bound_environment: r && r.bound_environment != null ? norm(r.bound_environment) : null,
72360
+ bound_artifact_id: r && r.bound_artifact_id != null ? norm(r.bound_artifact_id) : null,
72361
+ operation: r && r.operation != null ? String(r.operation) : null
72362
+ });
69986
72363
  const deny = (state, reason) => ({
69987
72364
  deploy_allowed: false,
69988
72365
  state,
@@ -69990,11 +72367,36 @@ var require_deploy_gate = __commonJS({
69990
72367
  enforcement_state,
69991
72368
  inescapable_deploy: false,
69992
72369
  residuals: [],
69993
- detail
72370
+ detail: detailOf(receipt),
72371
+ verification
69994
72372
  });
69995
72373
  if (!target.environment || String(target.environment).trim() === "" || !target.artifact_id || String(target.artifact_id).trim() === "") {
69996
72374
  return deny(allowPending ? "pending" : "failure", "inputs_incomplete");
69997
72375
  }
72376
+ const tokenInput = input.token;
72377
+ if (tokenInput && typeof tokenInput.token === "string" && tokenInput.token.length > 0) {
72378
+ const tv = (0, deploy_receipt_token_js_1.verifyDeployReceiptToken)(tokenInput, {
72379
+ operation: opRequired,
72380
+ environment: target.environment,
72381
+ artifact_id: target.artifact_id
72382
+ });
72383
+ verification = { mode: "token", verify_status: tv.status };
72384
+ if (tv.denyReason) {
72385
+ receipt = tv.view;
72386
+ return deny("failure", tv.denyReason);
72387
+ }
72388
+ receipt = tv.view;
72389
+ } else if (receipt === null || receipt === void 0) {
72390
+ return deny(allowPending ? "pending" : "failure", "no_receipt");
72391
+ } else if (isVerifiedDeployReceiptView(receipt)) {
72392
+ verification = {
72393
+ mode: "verified_view",
72394
+ verify_status: typeof receipt.verify_status === "string" ? receipt.verify_status : null
72395
+ };
72396
+ } else {
72397
+ verification = { mode: "unverified", verify_status: null };
72398
+ return deny("failure", "unverified_receipt_view");
72399
+ }
69998
72400
  if (receipt === null || receipt === void 0) {
69999
72401
  return deny(allowPending ? "pending" : "failure", "no_receipt");
70000
72402
  }
@@ -70056,7 +72458,8 @@ var require_deploy_gate = __commonJS({
70056
72458
  inescapable_deploy,
70057
72459
  residuals,
70058
72460
  ...residual ? { residual } : {},
70059
- detail
72461
+ detail: detailOf(receipt),
72462
+ verification
70060
72463
  };
70061
72464
  }
70062
72465
  }
@@ -70078,7 +72481,12 @@ var require_deploy_bind = __commonJS({
70078
72481
  "fingerprint_mismatch",
70079
72482
  "body_hash_mismatch",
70080
72483
  "no_receipt",
70081
- "inputs_incomplete"
72484
+ "inputs_incomplete",
72485
+ "unverified_receipt_view",
72486
+ "invalid_signature",
72487
+ "expired",
72488
+ "unknown_key",
72489
+ "retired_key"
70082
72490
  ]);
70083
72491
  exports2.DEPLOY_REPAIRABLE_REASONS = REPAIRABLE;
70084
72492
  function asHostAssertedEnvironment(env) {
@@ -70111,6 +72519,7 @@ var require_deploy_bind = __commonJS({
70111
72519
  const gate = (0, deploy_gate_js_1.deployGate)({
70112
72520
  deployTarget,
70113
72521
  receipt: input.receipt,
72522
+ token: input.token,
70114
72523
  requiredContext,
70115
72524
  ...input.allowPending != null ? { allowPending: input.allowPending } : {},
70116
72525
  ...input.allowWarnDeploy != null ? { allowWarnDeploy: input.allowWarnDeploy } : {},
@@ -70362,6 +72771,8 @@ var require_with_coderifts = __commonJS({
70362
72771
  }
70363
72772
  if (input.requireConditionalWrite === false)
70364
72773
  flags.push("requireConditionalWrite");
72774
+ if (input.requireCommitObservation === false)
72775
+ flags.push("requireCommitObservation");
70365
72776
  const reg = input.registry ?? {};
70366
72777
  if (reg.failOnUnguardedMutator === false)
70367
72778
  flags.push("failOnUnguardedMutator");
@@ -70582,6 +72993,18 @@ var require_with_coderifts = __commonJS({
70582
72993
  if (input.monitoringSinkWired !== void 0) {
70583
72994
  guard.monitoringSinkWired = input.monitoringSinkWired;
70584
72995
  }
72996
+ if (input.monitoringSink !== void 0) {
72997
+ guard.monitoringSink = input.monitoringSink;
72998
+ }
72999
+ if (input.monitoringSinkTimeoutMs !== void 0) {
73000
+ guard.monitoringSinkTimeoutMs = input.monitoringSinkTimeoutMs;
73001
+ }
73002
+ if (input.ackHmacKey !== void 0) {
73003
+ guard.ackHmacKey = input.ackHmacKey;
73004
+ }
73005
+ if (input.profile === "ENFORCING_STRICT") {
73006
+ guard.profile = "ENFORCING_STRICT";
73007
+ }
70585
73008
  if (hostPreviousReceipt !== void 0 || threadReceipts) {
70586
73009
  guard.previousReceipt = () => {
70587
73010
  if (hostPreviousReceipt !== void 0) {
@@ -70605,11 +73028,24 @@ var require_with_coderifts = __commonJS({
70605
73028
  if (input.requireExecutionStateMatch !== void 0) {
70606
73029
  guard.requireExecutionStateMatch = input.requireExecutionStateMatch;
70607
73030
  }
73031
+ if (input.requireCommitObservation !== void 0) {
73032
+ guard.requireCommitObservation = input.requireCommitObservation;
73033
+ }
73034
+ if (input.autoRecheck !== void 0) {
73035
+ guard.autoRecheck = input.autoRecheck;
73036
+ }
73037
+ if (input.autoDerive !== void 0) {
73038
+ guard.autoDerive = input.autoDerive;
73039
+ }
73040
+ if (input.executorAttestation !== void 0) {
73041
+ guard.executorAttestation = input.executorAttestation;
73042
+ }
70608
73043
  const strict = isEnforcingStrict(input);
70609
73044
  if (strict) {
70610
73045
  guard.requireFreshness = true;
70611
73046
  guard.requireConditionalWrite = true;
70612
73047
  guard.requireExecutionStateMatch = true;
73048
+ guard.requireCommitObservation = true;
70613
73049
  }
70614
73050
  const config = {
70615
73051
  guard,
@@ -70753,7 +73189,7 @@ var require_openai = __commonJS({
70753
73189
  const kind = outcome.verdict && typeof outcome.verdict === "object" && "kind" in outcome.verdict ? String(outcome.verdict.kind) : "UNKNOWN";
70754
73190
  body = `Tool execution failed after gate decision (verdict: ${kind}): ${errText}`;
70755
73191
  }
70756
- const content = (0, final_answer_proof_js_1.attachProofToAgentResponse)(body, outcome.proof);
73192
+ const content = args.attachProof === false ? body : (0, final_answer_proof_js_1.attachProofToAgentResponse)(body, outcome.proof);
70757
73193
  const msg = {
70758
73194
  role: "tool",
70759
73195
  tool_call_id,
@@ -70851,7 +73287,7 @@ var require_anthropic = __commonJS({
70851
73287
  const kind = verdictKind(outcome);
70852
73288
  body = `Tool execution failed after gate decision (verdict: ${kind}): ${formatGuardError(err)}`;
70853
73289
  }
70854
- const content = (0, final_answer_proof_js_1.attachProofToAgentResponse)(body, outcome.proof);
73290
+ const content = args.attachProof === false ? body : (0, final_answer_proof_js_1.attachProofToAgentResponse)(body, outcome.proof);
70855
73291
  const block = {
70856
73292
  type: "tool_result",
70857
73293
  tool_use_id,
@@ -70955,7 +73391,7 @@ var require_langgraph = __commonJS({
70955
73391
  const kind = verdictKind(outcome);
70956
73392
  body = `Tool execution failed after gate decision (verdict: ${kind}): ${formatGuardError(err)}`;
70957
73393
  }
70958
- const content = (0, final_answer_proof_js_1.attachProofToAgentResponse)(body, outcome.proof);
73394
+ const content = args.attachProof === false ? body : (0, final_answer_proof_js_1.attachProofToAgentResponse)(body, outcome.proof);
70959
73395
  const msg = {
70960
73396
  content,
70961
73397
  tool_call_id
@@ -71070,7 +73506,7 @@ var require_gemini = __commonJS({
71070
73506
  gate_message: `Tool execution failed after gate decision (verdict: ${kind}): ${formatGuardError(err)}`
71071
73507
  };
71072
73508
  }
71073
- const bound = (0, final_answer_proof_js_1.attachProofToAgentResponse)(base, outcome.proof);
73509
+ const bound = args.attachProof === false ? base : (0, final_answer_proof_js_1.attachProofToAgentResponse)(base, outcome.proof);
71074
73510
  const part = {
71075
73511
  functionResponse: {
71076
73512
  name,
@@ -71149,6 +73585,13 @@ var require_execute_tool_call = __commonJS({
71149
73585
  require_conditional_write: false,
71150
73586
  write_style: false
71151
73587
  });
73588
+ function notObserved() {
73589
+ return {
73590
+ status: "not_observed",
73591
+ observed_at: (/* @__PURE__ */ new Date()).toISOString(),
73592
+ host_attestation: "absent"
73593
+ };
73594
+ }
71152
73595
  function unknownToolOutcome(toolName) {
71153
73596
  const verdict = {
71154
73597
  kind: "UNAVAILABLE",
@@ -71159,12 +73602,14 @@ var require_execute_tool_call = __commonJS({
71159
73602
  decisionMissing: true,
71160
73603
  unavailableCount: 1
71161
73604
  };
73605
+ const commit_observation = notObserved();
71162
73606
  const proof = (0, execution_proof_js_1.buildExecutionProof)({
71163
73607
  preflighted: false,
71164
73608
  executionAttempted: false,
71165
73609
  executed: false,
71166
73610
  enforced: false,
71167
- verdict
73611
+ verdict,
73612
+ commitObservation: commit_observation
71168
73613
  });
71169
73614
  void toolName;
71170
73615
  return {
@@ -71175,7 +73620,8 @@ var require_execute_tool_call = __commonJS({
71175
73620
  preflighted: false,
71176
73621
  proof,
71177
73622
  freshness: FRESHNESS_NOT_CONFIGURED,
71178
- conditional_write: CW_NOT_REPORTED
73623
+ conditional_write: CW_NOT_REPORTED,
73624
+ commit_observation
71179
73625
  };
71180
73626
  }
71181
73627
  function wrapRawAsOutcome(result) {
@@ -71185,13 +73631,15 @@ var require_execute_tool_call = __commonJS({
71185
73631
  signals: ["dispatcher_passthrough"],
71186
73632
  detectorVersion: "execute-tool-call"
71187
73633
  };
73634
+ const commit_observation = notObserved();
71188
73635
  const proof = (0, execution_proof_js_1.buildExecutionProof)({
71189
73636
  preflighted: false,
71190
73637
  executionAttempted: true,
71191
73638
  executed: true,
71192
73639
  enforced: false,
71193
73640
  verdict,
71194
- result
73641
+ result,
73642
+ commitObservation: commit_observation
71195
73643
  });
71196
73644
  return {
71197
73645
  executionAttempted: true,
@@ -71202,7 +73650,8 @@ var require_execute_tool_call = __commonJS({
71202
73650
  preflighted: false,
71203
73651
  proof,
71204
73652
  freshness: FRESHNESS_NOT_CONFIGURED,
71205
- conditional_write: CW_NOT_REPORTED
73653
+ conditional_write: CW_NOT_REPORTED,
73654
+ commit_observation
71206
73655
  };
71207
73656
  }
71208
73657
  function wrapThrownAsOutcome(error) {
@@ -71212,13 +73661,15 @@ var require_execute_tool_call = __commonJS({
71212
73661
  signals: ["dispatcher_passthrough_throw"],
71213
73662
  detectorVersion: "execute-tool-call"
71214
73663
  };
73664
+ const commit_observation = notObserved();
71215
73665
  const proof = (0, execution_proof_js_1.buildExecutionProof)({
71216
73666
  preflighted: false,
71217
73667
  executionAttempted: true,
71218
73668
  executed: false,
71219
73669
  enforced: false,
71220
73670
  verdict,
71221
- error
73671
+ error,
73672
+ commitObservation: commit_observation
71222
73673
  });
71223
73674
  return {
71224
73675
  executionAttempted: true,
@@ -71229,7 +73680,8 @@ var require_execute_tool_call = __commonJS({
71229
73680
  preflighted: false,
71230
73681
  proof,
71231
73682
  freshness: FRESHNESS_NOT_CONFIGURED,
71232
- conditional_write: CW_NOT_REPORTED
73683
+ conditional_write: CW_NOT_REPORTED,
73684
+ commit_observation
71233
73685
  };
71234
73686
  }
71235
73687
  async function executeProtectedTool(table, toolName, args) {
@@ -71373,13 +73825,14 @@ var require_execute_tool_call = __commonJS({
71373
73825
  });
71374
73826
 
71375
73827
  // node_modules/@coderifts/agent-guard/dist/cjs/index.js
71376
- var require_cjs3 = __commonJS({
73828
+ var require_cjs4 = __commonJS({
71377
73829
  "node_modules/@coderifts/agent-guard/dist/cjs/index.js"(exports2) {
71378
73830
  "use strict";
71379
73831
  Object.defineProperty(exports2, "__esModule", { value: true });
71380
- exports2.RESIDUAL_UNCONDITIONAL_WRITE = exports2.conditionalWriteResidual = exports2.tokensEqual = exports2.buildConditionalWriteBasis = exports2.buildFreshnessBasis = exports2.collectFreshnessCallContext = exports2.artifactIdsForResolve = exports2.isWriteStyleCall = exports2.freshnessAllowsEnforce = exports2.computePathSetTreeHash = exports2.contentByteIdentical = exports2.assessWriteStylePrior = exports2.assessFreshness = exports2.deriveProofBanner = exports2.attachProofToAgentResponse = exports2.renderFinalAnswerProof = exports2.EXECUTION_PROOF_SPEC = exports2.assertEnforcedReceiptInvariant = exports2.hashExecutionResult = exports2.buildExecutionProof = exports2.deriveKeySignal = exports2.pathClass = exports2.classifyCommand = exports2.projectState = exports2.emptySessionState = exports2.computeTainted = exports2.evaluate = exports2.updateSession = exports2.SESSION_TAINT_VERSION = exports2.SessionTaintTracker = exports2.readDecision = exports2.EXECUTION_TIME_FP_REASONS = exports2.EXECUTION_STATE_UNMEASURABLE_NOTE = exports2.isUnmeasurableExecutionStateReason = exports2.computeCanonicalBundleFingerprint = exports2.authorizedFingerprintFromEnvelope = exports2.checkExecutionTimeFingerprint = exports2.computeBundleFingerprint = exports2.computeArtifactDigest = exports2.evaluateEnvelope = exports2.RECEIPT_PREV_NULL = exports2.decodeReceiptBodyPrev = exports2.previousReceiptCommitment = exports2.verifyReceiptChainLinkage = exports2.canonicalJson = exports2.computeBodyHash = exports2.bindReceiptToEnvelope = exports2.DETECTOR_VERSION = exports2.builtinDetector = exports2.guardToolCall = void 0;
71381
- exports2.openAIToolAdapter = exports2.withCodeRiftsOpenAI = exports2.guardedFractionAmongRoutes = exports2.foldTableSettledCalls = exports2.withCodeRifts = exports2.coverageReport = exports2.DEPLOY_REPAIRABLE_REASONS = exports2.bindDeploy = exports2.deployGate = exports2.gateDecision = exports2.RegistryConstructionError = exports2.guardToolRegistry = exports2.globToRegExp = exports2.matchGlob = exports2.blobMapKey = exports2.classifyByName = exports2.resolveArtifacts = exports2.REMEDIATION_LOOP_ATTESTATION_SPEC = exports2.isCasAttestation = exports2.readPriorBlockRemediation = exports2.readRemediationTransaction = exports2.buildRemediationLoopAttestation = exports2.CAS_ATTESTATION_SPEC = exports2.isExecuteIfUnchangedOutcome = exports2.isGuardExecutionProof = exports2.buildCasAttestation = exports2.REGISTRY_ABSENT_TOKEN = exports2.REGISTRY_VERSION_TOKEN_PREFIX = exports2.registryTokenRaw = exports2.writeRegistryIfUnchanged = exports2.createRegistryVersionToken = exports2.DB_ABSENT_TOKEN = exports2.DB_VERSION_TOKEN_PREFIX = exports2.dbTokenRaw = exports2.writeDbIfUnchanged = exports2.createDbVersionToken = exports2.API_ABSENT_TOKEN = exports2.API_VERSION_TOKEN_PREFIX = exports2.apiTokenRaw = exports2.writeApiIfUnchanged = exports2.createApiVersionToken = exports2.FS_ABSENT_TOKEN = exports2.FS_VERSION_TOKEN_PREFIX = exports2.fsTokenContentHash = exports2.createFsPriorContentResolver = exports2.writeFileIfUnchanged = exports2.readVersionedFile = exports2.createFsVersionToken = exports2.StaleVersionTokenAbort = exports2.executeIfUnchanged = void 0;
71382
- exports2.surfaceEnvelopeFields = exports2.isGuardOutcome = exports2.executeLangGraphToolCall = exports2.executeGeminiToolCall = exports2.executeAnthropicToolCall = exports2.executeOpenAIToolCall = exports2.executeProtectedTool = exports2.defaultSerializeGeminiToolResult = exports2.bindGeminiGuardOutcome = exports2.protectedToolToFunctionDeclaration = exports2.toGeminiTools = exports2.geminiToolAdapter = exports2.withCodeRiftsGemini = exports2.defaultSerializeLangGraphToolResult = exports2.bindLangGraphGuardOutcome = exports2.protectedToolToLangGraph = exports2.toLangGraphTools = exports2.langGraphToolAdapter = exports2.withCodeRiftsLangGraph = exports2.defaultSerializeAnthropicToolResult = exports2.bindAnthropicGuardOutcome = exports2.protectedToolToAnthropic = exports2.toAnthropicTools = exports2.anthropicToolAdapter = exports2.withCodeRiftsAnthropic = exports2.defaultSerializeOpenAIToolResult = exports2.bindOpenAIGuardOutcome = exports2.protectedToolToOpenAI = exports2.toOpenAITools = void 0;
73832
+ exports2.freshnessAllowsEnforce = exports2.computePathSetTreeHash = exports2.contentByteIdentical = exports2.assessWriteStylePrior = exports2.assessFreshness = exports2.deriveProofBanner = exports2.attachProofToAgentResponse = exports2.renderFinalAnswerProof = exports2.EXECUTION_PROOF_SPEC = exports2.assertEnforcedReceiptInvariant = exports2.hashExecutionResult = exports2.buildExecutionProof = exports2.DEFAULT_MONITORING_SINK_TIMEOUT_MS = exports2.ackBytes = exports2.verifyAckHmac = exports2.monitoringDeliveryFailClosed = exports2.formatMonitoringDeliveryLine = exports2.deliverMonitoring = exports2.hashObservedContent = exports2.observeCommit = exports2.deriveKeySignal = exports2.pathClass = exports2.classifyCommand = exports2.projectState = exports2.emptySessionState = exports2.computeTainted = exports2.evaluate = exports2.updateSession = exports2.SESSION_TAINT_VERSION = exports2.SessionTaintTracker = exports2.readDecision = exports2.EXECUTION_TIME_FP_REASONS = exports2.EXECUTION_STATE_UNMEASURABLE_NOTE = exports2.isUnmeasurableExecutionStateReason = exports2.computeCanonicalBundleFingerprint = exports2.authorizedFingerprintFromEnvelope = exports2.checkExecutionTimeFingerprint = exports2.computeBundleFingerprint = exports2.computeArtifactDigest = exports2.evaluateEnvelope = exports2.RECEIPT_PREV_NULL = exports2.decodeReceiptBodyPrev = exports2.previousReceiptCommitment = exports2.verifyReceiptChainLinkage = exports2.canonicalJson = exports2.computeBodyHash = exports2.bindReceiptToEnvelope = exports2.DETECTOR_VERSION = exports2.builtinDetector = exports2.guardToolCall = void 0;
73833
+ exports2.RegistryConstructionError = exports2.guardToolRegistry = exports2.globToRegExp = exports2.matchGlob = exports2.blobMapKey = exports2.classifyByName = exports2.resolveArtifacts = exports2.REMEDIATION_LOOP_ATTESTATION_SPEC = exports2.isCasAttestation = exports2.readPriorBlockRemediation = exports2.readRemediationTransaction = exports2.buildRemediationLoopAttestation = exports2.CAS_ATTESTATION_SPEC = exports2.extractExecutorAttestationToken = exports2.evaluateCasEvidence = exports2.isExecuteIfUnchangedOutcome = exports2.isGuardExecutionProof = exports2.buildCasAttestation = exports2.REGISTRY_ABSENT_TOKEN = exports2.REGISTRY_VERSION_TOKEN_PREFIX = exports2.registryTokenRaw = exports2.writeRegistryIfUnchanged = exports2.createRegistryVersionToken = exports2.DB_ABSENT_TOKEN = exports2.DB_VERSION_TOKEN_PREFIX = exports2.dbTokenRaw = exports2.writeDbIfUnchanged = exports2.createDbVersionToken = exports2.API_ABSENT_TOKEN = exports2.API_VERSION_TOKEN_PREFIX = exports2.apiTokenRaw = exports2.writeApiIfUnchanged = exports2.createApiVersionToken = exports2.FS_ABSENT_TOKEN = exports2.FS_VERSION_TOKEN_PREFIX = exports2.fsTokenContentHash = exports2.createFsPriorContentResolver = exports2.writeFileIfUnchanged = exports2.readVersionedFile = exports2.createFsVersionToken = exports2.StaleVersionTokenAbort = exports2.executeIfUnchanged = exports2.RESIDUAL_UNCONDITIONAL_WRITE = exports2.conditionalWriteResidual = exports2.tokensEqual = exports2.buildConditionalWriteBasis = exports2.buildFreshnessBasis = exports2.collectFreshnessCallContext = exports2.artifactIdsForResolve = exports2.isWriteStyleCall = void 0;
73834
+ exports2.executeLangGraphToolCall = exports2.executeGeminiToolCall = exports2.executeAnthropicToolCall = exports2.executeOpenAIToolCall = exports2.executeProtectedTool = exports2.defaultSerializeGeminiToolResult = exports2.bindGeminiGuardOutcome = exports2.protectedToolToFunctionDeclaration = exports2.toGeminiTools = exports2.geminiToolAdapter = exports2.withCodeRiftsGemini = exports2.defaultSerializeLangGraphToolResult = exports2.bindLangGraphGuardOutcome = exports2.protectedToolToLangGraph = exports2.toLangGraphTools = exports2.langGraphToolAdapter = exports2.withCodeRiftsLangGraph = exports2.defaultSerializeAnthropicToolResult = exports2.bindAnthropicGuardOutcome = exports2.protectedToolToAnthropic = exports2.toAnthropicTools = exports2.anthropicToolAdapter = exports2.withCodeRiftsAnthropic = exports2.defaultSerializeOpenAIToolResult = exports2.bindOpenAIGuardOutcome = exports2.protectedToolToOpenAI = exports2.toOpenAITools = exports2.openAIToolAdapter = exports2.withCodeRiftsOpenAI = exports2.guardedFractionAmongRoutes = exports2.foldTableSettledCalls = exports2.withCodeRifts = exports2.AUTO_DERIVE_READ_TIMEOUT_MS = exports2.AUTO_DERIVE_SOURCE = exports2.defaultFsReader = exports2.normalizeAutoDerive = exports2.runAutoDerive = exports2.AUTO_RECHECK_MAX_CAP = exports2.clampMaxAttempts = exports2.normalizeAutoRecheck = exports2.runAutoRecheckLoop = exports2.coverageReport = exports2.DEPLOY_REPAIRABLE_REASONS = exports2.bindDeploy = exports2.verifyDeployReceiptToken = exports2.DEPLOY_RECEIPT_VIEW_SPEC = exports2.isVerifiedDeployReceiptView = exports2.asVerifiedDeployReceiptView = exports2.deployGate = exports2.gateDecision = void 0;
73835
+ exports2.surfaceEnvelopeFields = exports2.isGuardOutcome = void 0;
71383
73836
  var guard_js_1 = require_guard();
71384
73837
  Object.defineProperty(exports2, "guardToolCall", { enumerable: true, get: function() {
71385
73838
  return guard_js_1.guardToolCall;
@@ -71478,6 +73931,32 @@ var require_cjs3 = __commonJS({
71478
73931
  Object.defineProperty(exports2, "deriveKeySignal", { enumerable: true, get: function() {
71479
73932
  return session_taint_js_1.deriveKeySignal;
71480
73933
  } });
73934
+ var commit_observation_js_1 = require_commit_observation();
73935
+ Object.defineProperty(exports2, "observeCommit", { enumerable: true, get: function() {
73936
+ return commit_observation_js_1.observeCommit;
73937
+ } });
73938
+ Object.defineProperty(exports2, "hashObservedContent", { enumerable: true, get: function() {
73939
+ return commit_observation_js_1.hashObservedContent;
73940
+ } });
73941
+ var monitoring_delivery_js_1 = require_monitoring_delivery();
73942
+ Object.defineProperty(exports2, "deliverMonitoring", { enumerable: true, get: function() {
73943
+ return monitoring_delivery_js_1.deliverMonitoring;
73944
+ } });
73945
+ Object.defineProperty(exports2, "formatMonitoringDeliveryLine", { enumerable: true, get: function() {
73946
+ return monitoring_delivery_js_1.formatMonitoringDeliveryLine;
73947
+ } });
73948
+ Object.defineProperty(exports2, "monitoringDeliveryFailClosed", { enumerable: true, get: function() {
73949
+ return monitoring_delivery_js_1.monitoringDeliveryFailClosed;
73950
+ } });
73951
+ Object.defineProperty(exports2, "verifyAckHmac", { enumerable: true, get: function() {
73952
+ return monitoring_delivery_js_1.verifyAckHmac;
73953
+ } });
73954
+ Object.defineProperty(exports2, "ackBytes", { enumerable: true, get: function() {
73955
+ return monitoring_delivery_js_1.ackBytes;
73956
+ } });
73957
+ Object.defineProperty(exports2, "DEFAULT_MONITORING_SINK_TIMEOUT_MS", { enumerable: true, get: function() {
73958
+ return monitoring_delivery_js_1.DEFAULT_MONITORING_SINK_TIMEOUT_MS;
73959
+ } });
71481
73960
  var execution_proof_js_1 = require_execution_proof();
71482
73961
  Object.defineProperty(exports2, "buildExecutionProof", { enumerable: true, get: function() {
71483
73962
  return execution_proof_js_1.buildExecutionProof;
@@ -71628,6 +74107,12 @@ var require_cjs3 = __commonJS({
71628
74107
  Object.defineProperty(exports2, "isExecuteIfUnchangedOutcome", { enumerable: true, get: function() {
71629
74108
  return cas_attestation_js_1.isExecuteIfUnchangedOutcome;
71630
74109
  } });
74110
+ Object.defineProperty(exports2, "evaluateCasEvidence", { enumerable: true, get: function() {
74111
+ return cas_attestation_js_1.evaluateCasEvidence;
74112
+ } });
74113
+ Object.defineProperty(exports2, "extractExecutorAttestationToken", { enumerable: true, get: function() {
74114
+ return cas_attestation_js_1.extractExecutorAttestationToken;
74115
+ } });
71631
74116
  Object.defineProperty(exports2, "CAS_ATTESTATION_SPEC", { enumerable: true, get: function() {
71632
74117
  return cas_attestation_js_1.CAS_ATTESTATION_SPEC;
71633
74118
  } });
@@ -71679,6 +74164,19 @@ var require_cjs3 = __commonJS({
71679
74164
  Object.defineProperty(exports2, "deployGate", { enumerable: true, get: function() {
71680
74165
  return deploy_gate_js_1.deployGate;
71681
74166
  } });
74167
+ Object.defineProperty(exports2, "asVerifiedDeployReceiptView", { enumerable: true, get: function() {
74168
+ return deploy_gate_js_1.asVerifiedDeployReceiptView;
74169
+ } });
74170
+ Object.defineProperty(exports2, "isVerifiedDeployReceiptView", { enumerable: true, get: function() {
74171
+ return deploy_gate_js_1.isVerifiedDeployReceiptView;
74172
+ } });
74173
+ Object.defineProperty(exports2, "DEPLOY_RECEIPT_VIEW_SPEC", { enumerable: true, get: function() {
74174
+ return deploy_gate_js_1.DEPLOY_RECEIPT_VIEW_SPEC;
74175
+ } });
74176
+ var deploy_receipt_token_js_1 = require_deploy_receipt_token();
74177
+ Object.defineProperty(exports2, "verifyDeployReceiptToken", { enumerable: true, get: function() {
74178
+ return deploy_receipt_token_js_1.verifyDeployReceiptToken;
74179
+ } });
71682
74180
  var deploy_bind_js_1 = require_deploy_bind();
71683
74181
  Object.defineProperty(exports2, "bindDeploy", { enumerable: true, get: function() {
71684
74182
  return deploy_bind_js_1.bindDeploy;
@@ -71690,6 +74188,35 @@ var require_cjs3 = __commonJS({
71690
74188
  Object.defineProperty(exports2, "coverageReport", { enumerable: true, get: function() {
71691
74189
  return coverage_report_js_1.coverageReport;
71692
74190
  } });
74191
+ var auto_recheck_js_1 = require_auto_recheck();
74192
+ Object.defineProperty(exports2, "runAutoRecheckLoop", { enumerable: true, get: function() {
74193
+ return auto_recheck_js_1.runAutoRecheckLoop;
74194
+ } });
74195
+ Object.defineProperty(exports2, "normalizeAutoRecheck", { enumerable: true, get: function() {
74196
+ return auto_recheck_js_1.normalizeAutoRecheck;
74197
+ } });
74198
+ Object.defineProperty(exports2, "clampMaxAttempts", { enumerable: true, get: function() {
74199
+ return auto_recheck_js_1.clampMaxAttempts;
74200
+ } });
74201
+ Object.defineProperty(exports2, "AUTO_RECHECK_MAX_CAP", { enumerable: true, get: function() {
74202
+ return auto_recheck_js_1.AUTO_RECHECK_MAX_CAP;
74203
+ } });
74204
+ var auto_derive_js_1 = require_auto_derive();
74205
+ Object.defineProperty(exports2, "runAutoDerive", { enumerable: true, get: function() {
74206
+ return auto_derive_js_1.runAutoDerive;
74207
+ } });
74208
+ Object.defineProperty(exports2, "normalizeAutoDerive", { enumerable: true, get: function() {
74209
+ return auto_derive_js_1.normalizeAutoDerive;
74210
+ } });
74211
+ Object.defineProperty(exports2, "defaultFsReader", { enumerable: true, get: function() {
74212
+ return auto_derive_js_1.defaultFsReader;
74213
+ } });
74214
+ Object.defineProperty(exports2, "AUTO_DERIVE_SOURCE", { enumerable: true, get: function() {
74215
+ return auto_derive_js_1.AUTO_DERIVE_SOURCE;
74216
+ } });
74217
+ Object.defineProperty(exports2, "AUTO_DERIVE_READ_TIMEOUT_MS", { enumerable: true, get: function() {
74218
+ return auto_derive_js_1.AUTO_DERIVE_READ_TIMEOUT_MS;
74219
+ } });
71693
74220
  var with_coderifts_js_1 = require_with_coderifts();
71694
74221
  Object.defineProperty(exports2, "withCodeRifts", { enumerable: true, get: function() {
71695
74222
  return with_coderifts_js_1.withCodeRifts;
@@ -74681,7 +77208,7 @@ var require_names2 = __commonJS({
74681
77208
  });
74682
77209
 
74683
77210
  // ../../node_modules/ajv/dist/compile/errors.js
74684
- var require_errors5 = __commonJS({
77211
+ var require_errors6 = __commonJS({
74685
77212
  "../../node_modules/ajv/dist/compile/errors.js"(exports2) {
74686
77213
  "use strict";
74687
77214
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -74808,7 +77335,7 @@ var require_boolSchema2 = __commonJS({
74808
77335
  "use strict";
74809
77336
  Object.defineProperty(exports2, "__esModule", { value: true });
74810
77337
  exports2.boolOrEmptySchema = exports2.topBoolOrEmptySchema = void 0;
74811
- var errors_1 = require_errors5();
77338
+ var errors_1 = require_errors6();
74812
77339
  var codegen_1 = require_codegen2();
74813
77340
  var names_1 = require_names2();
74814
77341
  var boolError = {
@@ -74915,7 +77442,7 @@ var require_dataType2 = __commonJS({
74915
77442
  exports2.reportTypeError = exports2.checkDataTypes = exports2.checkDataType = exports2.coerceAndCheckDataType = exports2.getJSONTypes = exports2.getSchemaTypes = exports2.DataType = void 0;
74916
77443
  var rules_1 = require_rules2();
74917
77444
  var applicability_1 = require_applicability2();
74918
- var errors_1 = require_errors5();
77445
+ var errors_1 = require_errors6();
74919
77446
  var codegen_1 = require_codegen2();
74920
77447
  var util_1 = require_util5();
74921
77448
  var DataType;
@@ -75270,7 +77797,7 @@ var require_keyword2 = __commonJS({
75270
77797
  var codegen_1 = require_codegen2();
75271
77798
  var names_1 = require_names2();
75272
77799
  var code_1 = require_code4();
75273
- var errors_1 = require_errors5();
77800
+ var errors_1 = require_errors6();
75274
77801
  function macroKeywordCode(cxt, def) {
75275
77802
  const { gen, keyword, schema, parentSchema, it } = cxt;
75276
77803
  const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
@@ -75758,7 +78285,7 @@ var require_validate2 = __commonJS({
75758
78285
  var names_1 = require_names2();
75759
78286
  var resolve_1 = require_resolve2();
75760
78287
  var util_1 = require_util5();
75761
- var errors_1 = require_errors5();
78288
+ var errors_1 = require_errors6();
75762
78289
  function validateFunctionCode(it) {
75763
78290
  if (isSchemaObj(it)) {
75764
78291
  checkKeywords(it);
@@ -87820,7 +90347,7 @@ var require_lib6 = __commonJS({
87820
90347
  });
87821
90348
 
87822
90349
  // ../../node_modules/pg/lib/client.js
87823
- var require_client = __commonJS({
90350
+ var require_client2 = __commonJS({
87824
90351
  "../../node_modules/pg/lib/client.js"(exports2, module2) {
87825
90352
  var EventEmitter = require("events").EventEmitter;
87826
90353
  var utils = require_utils4();
@@ -89005,7 +91532,7 @@ var require_query2 = __commonJS({
89005
91532
  });
89006
91533
 
89007
91534
  // ../../node_modules/pg/lib/native/client.js
89008
- var require_client2 = __commonJS({
91535
+ var require_client3 = __commonJS({
89009
91536
  "../../node_modules/pg/lib/native/client.js"(exports2, module2) {
89010
91537
  var nodeUtils = require("util");
89011
91538
  var Native;
@@ -89261,7 +91788,7 @@ var require_client2 = __commonJS({
89261
91788
  var require_native = __commonJS({
89262
91789
  "../../node_modules/pg/lib/native/index.js"(exports2, module2) {
89263
91790
  "use strict";
89264
- module2.exports = require_client2();
91791
+ module2.exports = require_client3();
89265
91792
  }
89266
91793
  });
89267
91794
 
@@ -89269,7 +91796,7 @@ var require_native = __commonJS({
89269
91796
  var require_lib7 = __commonJS({
89270
91797
  "../../node_modules/pg/lib/index.js"(exports2, module2) {
89271
91798
  "use strict";
89272
- var Client = require_client();
91799
+ var Client = require_client2();
89273
91800
  var defaults = require_defaults4();
89274
91801
  var Connection = require_connection();
89275
91802
  var Result = require_result();
@@ -89349,7 +91876,7 @@ var require_verbatim_string = __commonJS({
89349
91876
  });
89350
91877
 
89351
91878
  // ../../node_modules/@redis/client/dist/lib/errors.js
89352
- var require_errors6 = __commonJS({
91879
+ var require_errors7 = __commonJS({
89353
91880
  "../../node_modules/@redis/client/dist/lib/errors.js"(exports2) {
89354
91881
  "use strict";
89355
91882
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -89468,7 +91995,7 @@ var require_decoder = __commonJS({
89468
91995
  Object.defineProperty(exports2, "__esModule", { value: true });
89469
91996
  exports2.Decoder = exports2.PUSH_TYPE_MAPPING = exports2.RESP_TYPES = void 0;
89470
91997
  var verbatim_string_1 = require_verbatim_string();
89471
- var errors_1 = require_errors6();
91998
+ var errors_1 = require_errors7();
89472
91999
  exports2.RESP_TYPES = {
89473
92000
  NULL: 95,
89474
92001
  // _
@@ -103679,7 +106206,7 @@ var require_socket = __commonJS({
103679
106206
  var node_events_1 = require("node:events");
103680
106207
  var node_net_1 = __importDefault(require("node:net"));
103681
106208
  var node_tls_1 = __importDefault(require("node:tls"));
103682
- var errors_1 = require_errors6();
106209
+ var errors_1 = require_errors7();
103683
106210
  var promises_1 = require("node:timers/promises");
103684
106211
  var enterprise_maintenance_manager_1 = require_enterprise_maintenance_manager();
103685
106212
  var RedisSocket = class extends node_events_1.EventEmitter {
@@ -105124,7 +107651,7 @@ var require_commands_queue = __commonJS({
105124
107651
  var encoder_1 = __importDefault(require_encoder());
105125
107652
  var decoder_1 = require_decoder();
105126
107653
  var pub_sub_1 = require_pub_sub();
105127
- var errors_1 = require_errors6();
107654
+ var errors_1 = require_errors7();
105128
107655
  var enterprise_maintenance_manager_1 = require_enterprise_maintenance_manager();
105129
107656
  var PONG = Buffer.from("pong");
105130
107657
  var RESET = Buffer.from("RESET");
@@ -105673,7 +108200,7 @@ var require_multi_command = __commonJS({
105673
108200
  "../../node_modules/@redis/client/dist/lib/multi-command.js"(exports2) {
105674
108201
  "use strict";
105675
108202
  Object.defineProperty(exports2, "__esModule", { value: true });
105676
- var errors_1 = require_errors6();
108203
+ var errors_1 = require_errors7();
105677
108204
  var RedisMultiCommand = class {
105678
108205
  typeMapping;
105679
108206
  constructor(typeMapping) {
@@ -106562,10 +109089,10 @@ var require_pool = __commonJS({
106562
109089
  Object.defineProperty(exports2, "__esModule", { value: true });
106563
109090
  exports2.RedisClientPool = void 0;
106564
109091
  var commands_1 = require_commands();
106565
- var _1 = __importDefault(require_client3());
109092
+ var _1 = __importDefault(require_client4());
106566
109093
  var node_events_1 = require("node:events");
106567
109094
  var linked_list_1 = require_linked_list();
106568
- var errors_1 = require_errors6();
109095
+ var errors_1 = require_errors7();
106569
109096
  var commander_1 = require_commander2();
106570
109097
  var multi_command_1 = __importDefault(require_multi_command2());
106571
109098
  var cache_1 = require_cache();
@@ -106924,7 +109451,7 @@ var require_package2 = __commonJS({
106924
109451
  });
106925
109452
 
106926
109453
  // ../../node_modules/@redis/client/dist/lib/client/index.js
106927
- var require_client3 = __commonJS({
109454
+ var require_client4 = __commonJS({
106928
109455
  "../../node_modules/@redis/client/dist/lib/client/index.js"(exports2) {
106929
109456
  "use strict";
106930
109457
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
@@ -106965,7 +109492,7 @@ var require_client3 = __commonJS({
106965
109492
  var commands_queue_1 = __importDefault(require_commands_queue());
106966
109493
  var node_events_1 = require("node:events");
106967
109494
  var commander_1 = require_commander2();
106968
- var errors_1 = require_errors6();
109495
+ var errors_1 = require_errors7();
106969
109496
  var node_url_1 = require("node:url");
106970
109497
  var pub_sub_1 = require_pub_sub();
106971
109498
  var multi_command_1 = __importDefault(require_multi_command2());
@@ -107895,8 +110422,8 @@ var require_cluster_slots = __commonJS({
107895
110422
  var _a;
107896
110423
  Object.defineProperty(exports2, "__esModule", { value: true });
107897
110424
  exports2.RESUBSCRIBE_LISTENERS_EVENT = void 0;
107898
- var errors_1 = require_errors6();
107899
- var client_1 = __importDefault(require_client3());
110425
+ var errors_1 = require_errors7();
110426
+ var client_1 = __importDefault(require_client4());
107900
110427
  var pub_sub_1 = require_pub_sub();
107901
110428
  var cluster_key_slot_1 = __importDefault(require_lib8());
107902
110429
  var cache_1 = require_cache();
@@ -108633,7 +111160,7 @@ var require_cluster = __commonJS({
108633
111160
  var commander_1 = require_commander2();
108634
111161
  var cluster_slots_1 = __importStar(require_cluster_slots());
108635
111162
  var multi_command_1 = __importDefault(require_multi_command3());
108636
- var errors_1 = require_errors6();
111163
+ var errors_1 = require_errors7();
108637
111164
  var parser_1 = require_parser2();
108638
111165
  var ASKING_1 = require_ASKING();
108639
111166
  var single_entry_cache_1 = __importDefault(require_single_entry_cache());
@@ -109192,7 +111719,7 @@ var require_pub_sub_proxy = __commonJS({
109192
111719
  exports2.PubSubProxy = void 0;
109193
111720
  var node_events_1 = __importDefault(require("node:events"));
109194
111721
  var pub_sub_1 = require_pub_sub();
109195
- var client_1 = __importDefault(require_client3());
111722
+ var client_1 = __importDefault(require_client4());
109196
111723
  var PubSubProxy = class extends node_events_1.default {
109197
111724
  #clientOptions;
109198
111725
  #onError;
@@ -109527,7 +112054,7 @@ var require_sentinel = __commonJS({
109527
112054
  Object.defineProperty(exports2, "__esModule", { value: true });
109528
112055
  exports2.RedisSentinelFactory = exports2.RedisSentinelClient = void 0;
109529
112056
  var node_events_1 = require("node:events");
109530
- var client_1 = __importDefault(require_client3());
112057
+ var client_1 = __importDefault(require_client4());
109531
112058
  var commander_1 = require_commander2();
109532
112059
  var commands_1 = require_commands();
109533
112060
  var utils_1 = require_utils6();
@@ -110702,8 +113229,8 @@ var require_dist3 = __commonJS({
110702
113229
  Object.defineProperty(exports2, "digest", { enumerable: true, get: function() {
110703
113230
  return digest_1.digest;
110704
113231
  } });
110705
- __exportStar(require_errors6(), exports2);
110706
- var client_1 = __importDefault(require_client3());
113232
+ __exportStar(require_errors7(), exports2);
113233
+ var client_1 = __importDefault(require_client4());
110707
113234
  exports2.createClient = client_1.default.create;
110708
113235
  var pool_1 = require_pool();
110709
113236
  exports2.createClientPool = pool_1.RedisClientPool.create;
@@ -141040,7 +143567,7 @@ var require_util6 = __commonJS({
141040
143567
  });
141041
143568
 
141042
143569
  // ../../node_modules/zod/v4/core/errors.cjs
141043
- var require_errors7 = __commonJS({
143570
+ var require_errors8 = __commonJS({
141044
143571
  "../../node_modules/zod/v4/core/errors.cjs"(exports2) {
141045
143572
  "use strict";
141046
143573
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
@@ -141250,7 +143777,7 @@ var require_parse4 = __commonJS({
141250
143777
  Object.defineProperty(exports2, "__esModule", { value: true });
141251
143778
  exports2.safeDecodeAsync = exports2._safeDecodeAsync = exports2.safeEncodeAsync = exports2._safeEncodeAsync = exports2.safeDecode = exports2._safeDecode = exports2.safeEncode = exports2._safeEncode = exports2.decodeAsync = exports2._decodeAsync = exports2.encodeAsync = exports2._encodeAsync = exports2.decode = exports2._decode = exports2.encode = exports2._encode = exports2.safeParseAsync = exports2._safeParseAsync = exports2.safeParse = exports2._safeParse = exports2.parseAsync = exports2._parseAsync = exports2.parse = exports2._parse = void 0;
141252
143779
  var core = __importStar(require_core7());
141253
- var errors = __importStar(require_errors7());
143780
+ var errors = __importStar(require_errors8());
141254
143781
  var util = __importStar(require_util6());
141255
143782
  var _parse = (_Err) => (schema, value, _ctx, _params) => {
141256
143783
  const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
@@ -153956,7 +156483,7 @@ var require_core8 = __commonJS({
153956
156483
  exports2.JSONSchema = exports2.JSONSchemaGenerator = exports2.toJSONSchema = exports2.locales = exports2.regexes = exports2.util = void 0;
153957
156484
  __exportStar(require_core7(), exports2);
153958
156485
  __exportStar(require_parse4(), exports2);
153959
- __exportStar(require_errors7(), exports2);
156486
+ __exportStar(require_errors8(), exports2);
153960
156487
  __exportStar(require_schemas(), exports2);
153961
156488
  __exportStar(require_checks(), exports2);
153962
156489
  __exportStar(require_versions(), exports2);
@@ -154147,7 +156674,7 @@ var require_iso = __commonJS({
154147
156674
  });
154148
156675
 
154149
156676
  // ../../node_modules/zod/v4/classic/errors.cjs
154150
- var require_errors8 = __commonJS({
156677
+ var require_errors9 = __commonJS({
154151
156678
  "../../node_modules/zod/v4/classic/errors.cjs"(exports2) {
154152
156679
  "use strict";
154153
156680
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
@@ -154257,7 +156784,7 @@ var require_parse5 = __commonJS({
154257
156784
  Object.defineProperty(exports2, "__esModule", { value: true });
154258
156785
  exports2.safeDecodeAsync = exports2.safeEncodeAsync = exports2.safeDecode = exports2.safeEncode = exports2.decodeAsync = exports2.encodeAsync = exports2.decode = exports2.encode = exports2.safeParseAsync = exports2.safeParse = exports2.parseAsync = exports2.parse = void 0;
154259
156786
  var core = __importStar(require_core8());
154260
- var errors_js_1 = require_errors8();
156787
+ var errors_js_1 = require_errors9();
154261
156788
  exports2.parse = core._parse(errors_js_1.ZodRealError);
154262
156789
  exports2.parseAsync = core._parseAsync(errors_js_1.ZodRealError);
154263
156790
  exports2.safeParse = core._safeParse(errors_js_1.ZodRealError);
@@ -156170,7 +158697,7 @@ var require_external = __commonJS({
156170
158697
  exports2.core = __importStar(require_core8());
156171
158698
  __exportStar(require_schemas2(), exports2);
156172
158699
  __exportStar(require_checks2(), exports2);
156173
- __exportStar(require_errors8(), exports2);
158700
+ __exportStar(require_errors9(), exports2);
156174
158701
  __exportStar(require_parse5(), exports2);
156175
158702
  __exportStar(require_compat(), exports2);
156176
158703
  var index_js_1 = require_core8();
@@ -199750,7 +202277,7 @@ var require_clock_skew_leeway = __commonJS({
199750
202277
  });
199751
202278
 
199752
202279
  // ../../src/verdict-core/execution-grant.js
199753
- var require_execution_grant = __commonJS({
202280
+ var require_execution_grant2 = __commonJS({
199754
202281
  "../../src/verdict-core/execution-grant.js"(exports2, module2) {
199755
202282
  "use strict";
199756
202283
  var crypto = require("node:crypto");
@@ -201021,7 +203548,7 @@ var require_change_set = __commonJS({
201021
203548
  const {
201022
203549
  issueExecutionGrant,
201023
203550
  afterPayloadCanonical
201024
- } = require_execution_grant();
203551
+ } = require_execution_grant2();
201025
203552
  const grantTarget = nonEmptyStr(context.target_id) || artifactDigest;
201026
203553
  const stateNonce = typeof input.state_nonce === "string" && input.state_nonce.length > 0 ? input.state_nonce : null;
201027
203554
  executionGrant = issueExecutionGrant({
@@ -204890,7 +207417,11 @@ var require_deploy_gate2 = __commonJS({
204890
207417
  var fs = require("fs");
204891
207418
  var path = require("path");
204892
207419
  var chalk = require_source();
204893
- var { deployGate } = require_cjs3();
207420
+ var {
207421
+ deployGate,
207422
+ asVerifiedDeployReceiptView,
207423
+ DEPLOY_RECEIPT_VIEW_SPEC
207424
+ } = require_cjs4();
204894
207425
  var { renderJson } = require_json2();
204895
207426
  var { renderDecisionWhy, isEnvFlag } = require_claude_hook();
204896
207427
  function loadVerifierKernel() {
@@ -204916,7 +207447,8 @@ var require_deploy_gate2 = __commonJS({
204916
207447
  "retired_key",
204917
207448
  "unknown_key",
204918
207449
  "receipt_context_required",
204919
- "target_mismatch"
207450
+ "target_mismatch",
207451
+ "unverified_receipt_view"
204920
207452
  ]);
204921
207453
  var DEFAULT_KEYS_URL = "https://app.coderifts.com/.well-known/coderifts-keys.json";
204922
207454
  var KEYS_FETCH_TIMEOUT_MS = 1e4;
@@ -204959,9 +207491,24 @@ var require_deploy_gate2 = __commonJS({
204959
207491
  function deployCoverageInput(enforcement_state, inescapable_deploy) {
204960
207492
  return { enforcement_state, inescapable_deploy: inescapable_deploy === true, applicability_attested: true };
204961
207493
  }
204962
- function deployBind({ environment, artifact_id, receipt, observed_cd_enforcement, expected_fingerprint, expected_body_hash }) {
207494
+ function stampVerifiedView(receipt) {
207495
+ if (!receipt || typeof receipt !== "object") return receipt;
207496
+ if (receipt.view_spec === DEPLOY_RECEIPT_VIEW_SPEC && receipt.verified === true) return receipt;
207497
+ const status = typeof receipt.verify_status === "string" ? receipt.verify_status : receipt.currently_authorized === true ? "VERIFIED_CURRENT" : "VERIFIED_EXPIRED";
207498
+ return asVerifiedDeployReceiptView(receipt, status);
207499
+ }
207500
+ function deployBind({
207501
+ environment,
207502
+ artifact_id,
207503
+ receipt,
207504
+ token,
207505
+ observed_cd_enforcement,
207506
+ expected_fingerprint,
207507
+ expected_body_hash
207508
+ }) {
204963
207509
  const attested_enforcement = observed_cd_enforcement && observed_cd_enforcement.enforcement || "UNKNOWN";
204964
- if (!receipt) {
207510
+ const hasToken = !!(token && typeof token.token === "string" && token.token.length > 0);
207511
+ if (!hasToken && !receipt) {
204965
207512
  return {
204966
207513
  deploy_check_status: "pending",
204967
207514
  reason: "no_receipt",
@@ -204969,7 +207516,8 @@ var require_deploy_gate2 = __commonJS({
204969
207516
  attested_enforcement,
204970
207517
  gate: null,
204971
207518
  report_residuals: [],
204972
- coverage_deploy_input: deployCoverageInput(attested_enforcement, false)
207519
+ coverage_deploy_input: deployCoverageInput(attested_enforcement, false),
207520
+ verification: { mode: "none", verify_status: null }
204973
207521
  };
204974
207522
  }
204975
207523
  const requiredContext = {
@@ -204981,16 +207529,17 @@ var require_deploy_gate2 = __commonJS({
204981
207529
  }
204982
207530
  };
204983
207531
  let change_set_rebound = false;
204984
- if (attested_enforcement === "ENFORCING") {
204985
- if (expected_fingerprint != null) {
204986
- requiredContext.expected_fingerprint = expected_fingerprint;
204987
- change_set_rebound = true;
204988
- }
204989
- if (expected_body_hash != null) requiredContext.expected_body_hash = expected_body_hash;
207532
+ if (expected_fingerprint != null) {
207533
+ requiredContext.expected_fingerprint = expected_fingerprint;
207534
+ if (attested_enforcement === "ENFORCING") change_set_rebound = true;
207535
+ }
207536
+ if (attested_enforcement === "ENFORCING" && expected_body_hash != null) {
207537
+ requiredContext.expected_body_hash = expected_body_hash;
204990
207538
  }
204991
- const gate = deployGate({ deployTarget: { environment, artifact_id }, receipt, requiredContext });
207539
+ const gate = hasToken ? deployGate({ deployTarget: { environment, artifact_id }, token, requiredContext }) : deployGate({ deployTarget: { environment, artifact_id }, receipt: stampVerifiedView(receipt), requiredContext });
204992
207540
  const enforcement_inescapable = attested_enforcement === "ENFORCING" && !!(observed_cd_enforcement && observed_cd_enforcement.bypass_possible === false);
204993
207541
  const inescapable_deploy = gate.inescapable_deploy === true && change_set_rebound === true;
207542
+ const verification = gate.verification || { mode: hasToken ? "token" : "verified_view", verify_status: null };
204994
207543
  return {
204995
207544
  deploy_check_status: gate.state,
204996
207545
  reason: gate.reason,
@@ -204998,7 +207547,8 @@ var require_deploy_gate2 = __commonJS({
204998
207547
  attested_enforcement,
204999
207548
  gate: { deploy_allowed: gate.deploy_allowed, reason: gate.reason, inescapable_deploy },
205000
207549
  report_residuals: deployReportResiduals(gate.state, enforcement_inescapable, attested_enforcement, change_set_rebound),
205001
- coverage_deploy_input: deployCoverageInput(attested_enforcement, inescapable_deploy)
207550
+ coverage_deploy_input: deployCoverageInput(attested_enforcement, inescapable_deploy),
207551
+ verification
205002
207552
  };
205003
207553
  }
205004
207554
  function clampExit(deployCheckStatus, advisory) {
@@ -205157,6 +207707,22 @@ var require_deploy_gate2 = __commonJS({
205157
207707
  authz = applyRetiredKeyLiveRule(status, authz, intended);
205158
207708
  return { result, status, authz };
205159
207709
  }
207710
+ function overlayTokenWhy(bind, kernel, untrusted, keysSource) {
207711
+ const v = bind && bind.verification || {};
207712
+ bind.verification_mode = v.mode || "token";
207713
+ bind.verify_status = v.verify_status || kernel && kernel.status || null;
207714
+ bind.currently_authorized = bind.deploy_check_status === "success";
207715
+ bind.authz_reason = bind.reason;
207716
+ bind.untrusted_currently_authorized_input = untrusted === true;
207717
+ bind.keys_source = keysSource || null;
207718
+ bind.kernel_verify_status = kernel && kernel.status ? kernel.status : null;
207719
+ return bind;
207720
+ }
207721
+ function causesAgree(gateReason, kernelReason) {
207722
+ if (gateReason === "allow_current_deploy") return kernelReason == null;
207723
+ if (kernelReason == null) return false;
207724
+ return gateReason === kernelReason;
207725
+ }
205160
207726
  function reasonFromVerify({ status, authz, hasToken, hasEnvelope }) {
205161
207727
  if (!hasToken) return "unsigned_receipt";
205162
207728
  if (status === "INVALID_SIGNATURE") return "invalid_signature";
@@ -205176,21 +207742,6 @@ var require_deploy_gate2 = __commonJS({
205176
207742
  if (ar === "target_mismatch") return "stale_artifact";
205177
207743
  return ar;
205178
207744
  }
205179
- function verifiedReceiptView(envelope, payload, currentlyAuthorized) {
205180
- const artifact = envelope && (envelope.target_id || envelope.artifact_digest || envelope.bound_artifact_id);
205181
- return {
205182
- currently_authorized: currentlyAuthorized === true,
205183
- decision: envelope && envelope.decision,
205184
- execution_action: envelope && envelope.execution_action,
205185
- operation: envelope && envelope.operation,
205186
- bound_environment: envelope && envelope.environment,
205187
- bound_artifact_id: artifact,
205188
- decision_id: envelope && envelope.decision_id,
205189
- blocking_reasons: envelope && envelope.blocking_reasons,
205190
- decision_result: envelope,
205191
- fingerprint: envelope && envelope.fingerprint || payload && payload.fp || null
205192
- };
205193
- }
205194
207745
  function policyBlockBind({
205195
207746
  reason,
205196
207747
  verify_status,
@@ -205359,48 +207910,40 @@ var require_deploy_gate2 = __commonJS({
205359
207910
  target_id: artifactId,
205360
207911
  fingerprint: options.fingerprint || void 0
205361
207912
  };
205362
- const verified = verifyDeployReceipt({
207913
+ const bind = deployBind({
207914
+ environment,
207915
+ artifact_id: artifactId,
207916
+ token: {
207917
+ token,
207918
+ decision_result: envelope || void 0,
207919
+ registry: keys.registry,
207920
+ pinnedKeyPem: keys.pinnedKeyPem
207921
+ },
207922
+ observed_cd_enforcement: observed,
207923
+ expected_fingerprint: options.fingerprint || void 0
207924
+ });
207925
+ const kernel = verifyDeployReceipt({
205363
207926
  token,
205364
207927
  envelope,
205365
207928
  intended,
205366
207929
  registry: keys.registry,
205367
207930
  pinnedKeyPem: keys.pinnedKeyPem
205368
207931
  });
205369
- const reason = reasonFromVerify({
205370
- status: verified.status,
205371
- authz: verified.authz,
205372
- hasToken: true,
205373
- hasEnvelope: !!envelope
205374
- });
205375
- const computedAuthorized = verified.authz && verified.authz.currently_authorized === true && verified.status === "VERIFIED_CURRENT";
205376
- if (reason || !computedAuthorized) {
205377
- const bind2 = policyBlockBind({
205378
- reason: reason || "receipt_not_authorized",
205379
- verify_status: verified.status,
205380
- currently_authorized: false,
205381
- authz_reason: verified.authz && verified.authz.authz_reason || reason || "receipt_not_authorized",
205382
- untrusted,
205383
- attested_enforcement: attested
205384
- });
205385
- return finish(bind2, {
205386
- failureClass: "policy",
205387
- retryable: false,
205388
- receiptForWhy: envelope ? { ...parsed, decision_result: envelope } : parsed
205389
- });
205390
- }
205391
- const view = verifiedReceiptView(envelope, verified.result.payload, true);
205392
- const bind = deployBind({
205393
- environment,
205394
- artifact_id: artifactId,
205395
- receipt: view,
205396
- observed_cd_enforcement: observed
207932
+ overlayTokenWhy(bind, kernel, untrusted, keys.source);
207933
+ bind.causes_agree = causesAgree(
207934
+ bind.reason,
207935
+ reasonFromVerify({
207936
+ status: kernel.status,
207937
+ authz: kernel.authz,
207938
+ hasToken: true,
207939
+ hasEnvelope: !!envelope
207940
+ })
207941
+ );
207942
+ return finish(bind, {
207943
+ failureClass: bind.deploy_check_status === "success" ? null : "policy",
207944
+ retryable: false,
207945
+ receiptForWhy: envelope ? { ...parsed, decision_result: envelope } : parsed
205397
207946
  });
205398
- bind.verify_status = verified.status;
205399
- bind.currently_authorized = true;
205400
- bind.authz_reason = verified.authz && verified.authz.authz_reason;
205401
- bind.untrusted_currently_authorized_input = untrusted;
205402
- bind.keys_source = keys.source || null;
205403
- return finish(bind, { failureClass: bind.deploy_check_status === "success" ? null : "policy", retryable: false, receiptForWhy: view });
205404
207947
  }
205405
207948
  module2.exports = {
205406
207949
  runDeployGate,
@@ -205413,6 +207956,10 @@ var require_deploy_gate2 = __commonJS({
205413
207956
  extractDecisionEnvelope,
205414
207957
  loadKeysMaterial,
205415
207958
  verifyDeployReceipt,
207959
+ stampVerifiedView,
207960
+ overlayTokenWhy,
207961
+ causesAgree,
207962
+ reasonFromVerify,
205416
207963
  extractDecisionIdFromReceipt,
205417
207964
  formatOutcomeReportHint,
205418
207965
  renderDeployGateTerminal,
@@ -206153,7 +208700,7 @@ var require_registry_gate = __commonJS({
206153
208700
  var fs = require("fs");
206154
208701
  var path = require("path");
206155
208702
  var chalk = require_source();
206156
- var { matchGlob } = require_cjs3();
208703
+ var { matchGlob } = require_cjs4();
206157
208704
  var {
206158
208705
  validateRegistry,
206159
208706
  safeParse,
@@ -217173,7 +219720,7 @@ var require_zipWith = __commonJS({
217173
219720
  });
217174
219721
 
217175
219722
  // node_modules/rxjs/dist/cjs/index.js
217176
- var require_cjs4 = __commonJS({
219723
+ var require_cjs5 = __commonJS({
217177
219724
  "node_modules/rxjs/dist/cjs/index.js"(exports2) {
217178
219725
  "use strict";
217179
219726
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
@@ -218490,7 +221037,7 @@ var require_run_async = __commonJS({
218490
221037
  var require_utils11 = __commonJS({
218491
221038
  "node_modules/inquirer/lib/utils/utils.js"(exports2) {
218492
221039
  "use strict";
218493
- var { from, of } = require_cjs4();
221040
+ var { from, of } = require_cjs5();
218494
221041
  var runAsync = require_run_async();
218495
221042
  exports2.fetchAsyncQuestionProperty = function(question, prop, answers) {
218496
221043
  if (typeof question[prop] !== "function") {
@@ -218515,7 +221062,7 @@ var require_prompt = __commonJS({
218515
221062
  get: require_get3(),
218516
221063
  set: require_set4()
218517
221064
  };
218518
- var { defer, empty, from, of } = require_cjs4();
221065
+ var { defer, empty, from, of } = require_cjs5();
218519
221066
  var { concatMap, filter, publish, reduce } = require_operators();
218520
221067
  var runAsync = require_run_async();
218521
221068
  var utils = require_utils11();
@@ -221229,7 +223776,7 @@ var require_base = __commonJS({
221229
223776
  var require_events = __commonJS({
221230
223777
  "node_modules/inquirer/lib/utils/events.js"(exports2, module2) {
221231
223778
  "use strict";
221232
- var { fromEvent } = require_cjs4();
223779
+ var { fromEvent } = require_cjs5();
221233
223780
  var { filter, map, share, takeUntil } = require_operators();
221234
223781
  function normalizeKeypressEvents(value, key) {
221235
223782
  return { value, key: key || {} };
@@ -232027,7 +234574,7 @@ var require_editor = __commonJS({
232027
234574
  var { editAsync } = require_commonjs();
232028
234575
  var Base = require_base();
232029
234576
  var observe = require_events();
232030
- var { Subject } = require_cjs4();
234577
+ var { Subject } = require_cjs5();
232031
234578
  var EditorPrompt = class extends Base {
232032
234579
  /**
232033
234580
  * Start the Inquiry session