coderifts 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3007,7 +3007,7 @@ var require_package = __commonJS({
3007
3007
  "package.json"(exports2, module2) {
3008
3008
  module2.exports = {
3009
3009
  name: "coderifts",
3010
- version: "2.0.0",
3010
+ version: "3.0.0",
3011
3011
  description: "Detect breaking API changes from the command line. Works locally or with the CodeRifts cloud API.",
3012
3012
  author: "CodeRifts <hello@coderifts.com>",
3013
3013
  license: "MIT",
@@ -13493,33 +13493,39 @@ var require_cloud = __commonJS({
13493
13493
  "src/cloud.js"(exports2, module2) {
13494
13494
  "use strict";
13495
13495
  var https = require("https");
13496
- var API_BASE = "https://app.coderifts.com";
13497
- function cloudDiff(oldSpec, newSpec, apiKey) {
13496
+ var API_BASE = process.env.CODERIFTS_API_BASE || "https://app.coderifts.com";
13497
+ function cloudRequest(method, pathname, apiKey, bodyObj = null) {
13498
13498
  return new Promise((resolve, reject) => {
13499
- const body = JSON.stringify({ old_spec: oldSpec, new_spec: newSpec });
13500
- const url = new URL("/api/v1/diff", API_BASE);
13499
+ const body = bodyObj != null ? JSON.stringify(bodyObj) : null;
13500
+ const base = API_BASE.replace(/\/$/, "");
13501
+ const url = new URL(pathname.startsWith("http") ? pathname : base + pathname);
13501
13502
  const options = {
13502
13503
  hostname: url.hostname,
13503
- port: 443,
13504
- path: url.pathname,
13505
- method: "POST",
13504
+ port: url.port || (url.protocol === "http:" ? 80 : 443),
13505
+ path: url.pathname + url.search,
13506
+ method,
13506
13507
  headers: {
13507
- "Content-Type": "application/json",
13508
- "Content-Length": Buffer.byteLength(body),
13509
- "Authorization": `Bearer ${apiKey}`,
13510
- "User-Agent": "@coderifts/cli"
13508
+ Accept: "application/json",
13509
+ Authorization: `Bearer ${apiKey}`,
13510
+ "User-Agent": "@coderifts/cli",
13511
+ ...body ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) } : {}
13511
13512
  }
13512
13513
  };
13513
- const req = https.request(options, (res) => {
13514
+ const transport = url.protocol === "http:" ? require("http") : https;
13515
+ const req = transport.request(options, (res) => {
13514
13516
  let data = "";
13515
13517
  res.on("data", (chunk) => {
13516
13518
  data += chunk;
13517
13519
  });
13518
13520
  res.on("end", () => {
13519
13521
  try {
13520
- const parsed = JSON.parse(data);
13522
+ const parsed = data ? JSON.parse(data) : {};
13521
13523
  if (res.statusCode >= 400) {
13522
- reject(new Error(parsed.message || parsed.error || `HTTP ${res.statusCode}`));
13524
+ const err = new Error(parsed.message || parsed.error || `HTTP ${res.statusCode}`);
13525
+ err.statusCode = res.statusCode;
13526
+ err.code = parsed.error || null;
13527
+ err.body = parsed;
13528
+ reject(err);
13523
13529
  } else {
13524
13530
  resolve(parsed);
13525
13531
  }
@@ -13529,11 +13535,26 @@ var require_cloud = __commonJS({
13529
13535
  });
13530
13536
  });
13531
13537
  req.on("error", reject);
13532
- req.write(body);
13538
+ if (body) req.write(body);
13533
13539
  req.end();
13534
13540
  });
13535
13541
  }
13536
- module2.exports = { cloudDiff };
13542
+ function cloudDiff(oldSpec, newSpec, apiKey) {
13543
+ return cloudRequest("POST", "/api/v1/diff", apiKey, {
13544
+ old_spec: oldSpec,
13545
+ new_spec: newSpec
13546
+ });
13547
+ }
13548
+ function cloudGetEnforcementStatus(repo, apiKey) {
13549
+ const q = encodeURIComponent(String(repo || ""));
13550
+ return cloudRequest("GET", `/api/v1/enforcement-status?repo=${q}`, apiKey);
13551
+ }
13552
+ module2.exports = {
13553
+ cloudDiff,
13554
+ cloudRequest,
13555
+ cloudGetEnforcementStatus,
13556
+ API_BASE
13557
+ };
13537
13558
  }
13538
13559
  });
13539
13560
 
@@ -68958,12 +68979,15 @@ var require_deploy_gate2 = __commonJS({
68958
68979
  attestation_source: "cli_flag"
68959
68980
  };
68960
68981
  }
68961
- function deployReportResiduals(state, inescapable, enforcement) {
68982
+ function deployReportResiduals(state, enforcement_inescapable, enforcement, change_set_rebound) {
68962
68983
  const out = [];
68963
- if (state === "success" && inescapable !== true) {
68984
+ if (state !== "success") return out;
68985
+ if (enforcement_inescapable !== true) {
68964
68986
  if (enforcement === "ENFORCING") out.push("bypass_open");
68965
68987
  else if (enforcement === "ADVISORY") out.push("deploy_gate_advisory");
68966
68988
  else if (enforcement === "ABSENT") out.push("deploy_path_ungated");
68989
+ } else if (change_set_rebound !== true) {
68990
+ out.push("change_set_not_rebound");
68967
68991
  }
68968
68992
  return out;
68969
68993
  }
@@ -68991,19 +69015,24 @@ var require_deploy_gate2 = __commonJS({
68991
69015
  bypass_possible: !(observed_cd_enforcement && observed_cd_enforcement.bypass_possible === false)
68992
69016
  }
68993
69017
  };
69018
+ let change_set_rebound = false;
68994
69019
  if (attested_enforcement === "ENFORCING") {
68995
- if (expected_fingerprint != null) requiredContext.expected_fingerprint = expected_fingerprint;
69020
+ if (expected_fingerprint != null) {
69021
+ requiredContext.expected_fingerprint = expected_fingerprint;
69022
+ change_set_rebound = true;
69023
+ }
68996
69024
  if (expected_body_hash != null) requiredContext.expected_body_hash = expected_body_hash;
68997
69025
  }
68998
69026
  const gate = deployGate({ deployTarget: { environment, artifact_id }, receipt, requiredContext });
68999
- const inescapable_deploy = gate.inescapable_deploy === true;
69027
+ const enforcement_inescapable = gate.inescapable_deploy === true;
69028
+ const inescapable_deploy = enforcement_inescapable && change_set_rebound === true;
69000
69029
  return {
69001
69030
  deploy_check_status: gate.state,
69002
69031
  reason: gate.reason,
69003
69032
  must_re_preflight: REPAIRABLE.has(gate.reason),
69004
69033
  attested_enforcement,
69005
69034
  gate: { deploy_allowed: gate.deploy_allowed, reason: gate.reason, inescapable_deploy },
69006
- report_residuals: deployReportResiduals(gate.state, inescapable_deploy, attested_enforcement),
69035
+ report_residuals: deployReportResiduals(gate.state, enforcement_inescapable, attested_enforcement, change_set_rebound),
69007
69036
  coverage_deploy_input: deployCoverageInput(attested_enforcement, inescapable_deploy)
69008
69037
  };
69009
69038
  }
@@ -69513,6 +69542,560 @@ var require_publish_gate = __commonJS({
69513
69542
  }
69514
69543
  });
69515
69544
 
69545
+ // src/registry-validation-core.js
69546
+ var require_registry_validation_core = __commonJS({
69547
+ "src/registry-validation-core.js"(exports2, module2) {
69548
+ "use strict";
69549
+ var yaml = require_js_yaml();
69550
+ function safeParse(content) {
69551
+ if (!content) return null;
69552
+ try {
69553
+ const trimmed = content.trim();
69554
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
69555
+ return JSON.parse(trimmed);
69556
+ }
69557
+ return yaml.load(trimmed);
69558
+ } catch (_) {
69559
+ return null;
69560
+ }
69561
+ }
69562
+ function validateOpenApiSpec(parsed) {
69563
+ if (!parsed || typeof parsed !== "object") {
69564
+ return { valid: false, error: "Not a valid YAML or JSON object" };
69565
+ }
69566
+ if (parsed.openapi) {
69567
+ const ver = String(parsed.openapi);
69568
+ if (ver.startsWith("3.")) {
69569
+ return { valid: true, version: ver };
69570
+ }
69571
+ return { valid: false, error: `Unsupported OpenAPI version: ${ver}` };
69572
+ }
69573
+ if (parsed.swagger) {
69574
+ const ver = String(parsed.swagger);
69575
+ if (ver.startsWith("2.")) {
69576
+ return { valid: true, version: ver };
69577
+ }
69578
+ return { valid: false, error: `Unsupported Swagger version: ${ver}` };
69579
+ }
69580
+ return { valid: false, error: "Missing required field: 'openapi' or 'swagger'" };
69581
+ }
69582
+ function extractEndpoints(parsed) {
69583
+ const endpoints = [];
69584
+ const paths = parsed.paths || {};
69585
+ const httpMethods = ["get", "post", "put", "patch", "delete", "head", "options"];
69586
+ for (const [path, pathItem] of Object.entries(paths)) {
69587
+ if (!pathItem || typeof pathItem !== "object") continue;
69588
+ for (const method of httpMethods) {
69589
+ if (pathItem[method]) {
69590
+ endpoints.push({
69591
+ path,
69592
+ method: method.toUpperCase(),
69593
+ operationId: pathItem[method].operationId || ""
69594
+ });
69595
+ }
69596
+ }
69597
+ }
69598
+ return endpoints;
69599
+ }
69600
+ function extractSchemaNames(parsed) {
69601
+ const schemas = [];
69602
+ const components = parsed.components?.schemas || {};
69603
+ for (const [name, schema] of Object.entries(components)) {
69604
+ const hash = JSON.stringify(schema);
69605
+ schemas.push({ name, hash });
69606
+ }
69607
+ return schemas;
69608
+ }
69609
+ function extractDefinedScopes(parsed) {
69610
+ const scopes = /* @__PURE__ */ new Set();
69611
+ const schemes = parsed.components?.securitySchemes || {};
69612
+ for (const scheme of Object.values(schemes)) {
69613
+ if (scheme.type === "oauth2" && scheme.flows) {
69614
+ for (const flow of Object.values(scheme.flows)) {
69615
+ if (flow.scopes) {
69616
+ for (const scope of Object.keys(flow.scopes)) {
69617
+ scopes.add(scope);
69618
+ }
69619
+ }
69620
+ }
69621
+ }
69622
+ }
69623
+ return scopes;
69624
+ }
69625
+ function extractUsedScopes(parsed) {
69626
+ const scopes = /* @__PURE__ */ new Set();
69627
+ if (Array.isArray(parsed.security)) {
69628
+ for (const req of parsed.security) {
69629
+ for (const scopeList of Object.values(req)) {
69630
+ if (Array.isArray(scopeList)) {
69631
+ for (const s of scopeList) scopes.add(s);
69632
+ }
69633
+ }
69634
+ }
69635
+ }
69636
+ const paths = parsed.paths || {};
69637
+ const httpMethods = ["get", "post", "put", "patch", "delete", "head", "options"];
69638
+ for (const pathItem of Object.values(paths)) {
69639
+ if (!pathItem || typeof pathItem !== "object") continue;
69640
+ for (const method of httpMethods) {
69641
+ const op = pathItem[method];
69642
+ if (op?.security && Array.isArray(op.security)) {
69643
+ for (const req of op.security) {
69644
+ for (const scopeList of Object.values(req)) {
69645
+ if (Array.isArray(scopeList)) {
69646
+ for (const s of scopeList) scopes.add(s);
69647
+ }
69648
+ }
69649
+ }
69650
+ }
69651
+ }
69652
+ }
69653
+ return scopes;
69654
+ }
69655
+ function extractRefs(obj, refs = /* @__PURE__ */ new Set()) {
69656
+ if (!obj || typeof obj !== "object") return refs;
69657
+ if (Array.isArray(obj)) {
69658
+ for (const item of obj) extractRefs(item, refs);
69659
+ return refs;
69660
+ }
69661
+ for (const [key, value] of Object.entries(obj)) {
69662
+ if (key === "$ref" && typeof value === "string") {
69663
+ refs.add(value);
69664
+ } else {
69665
+ extractRefs(value, refs);
69666
+ }
69667
+ }
69668
+ return refs;
69669
+ }
69670
+ function refResolves(parsed, ref) {
69671
+ if (!ref.startsWith("#/")) return true;
69672
+ const parts = ref.replace("#/", "").split("/");
69673
+ let current = parsed;
69674
+ for (const part of parts) {
69675
+ if (!current || typeof current !== "object") return false;
69676
+ current = current[part];
69677
+ }
69678
+ return current !== void 0;
69679
+ }
69680
+ function validateRegistry(specs) {
69681
+ if (!Array.isArray(specs) || specs.length === 0) {
69682
+ return { valid: true, issues: [], stats: { specs_count: 0, endpoints_count: 0, schemas_count: 0 } };
69683
+ }
69684
+ const issues = [];
69685
+ const parsedSpecs = [];
69686
+ for (const { name, spec } of specs) {
69687
+ const parsed = safeParse(spec);
69688
+ if (!parsed) {
69689
+ issues.push({
69690
+ severity: "error",
69691
+ type: "parse_error",
69692
+ message: `Could not parse spec '${name}' as valid YAML or JSON`,
69693
+ specs: [name]
69694
+ });
69695
+ continue;
69696
+ }
69697
+ const validation = validateOpenApiSpec(parsed);
69698
+ if (!validation.valid) {
69699
+ issues.push({
69700
+ severity: "error",
69701
+ type: "invalid_spec",
69702
+ message: `Spec '${name}' is not a valid OpenAPI document: ${validation.error}`,
69703
+ specs: [name]
69704
+ });
69705
+ continue;
69706
+ }
69707
+ parsedSpecs.push({ name, parsed });
69708
+ }
69709
+ const endpointMap = /* @__PURE__ */ new Map();
69710
+ for (const { name, parsed } of parsedSpecs) {
69711
+ const endpoints = extractEndpoints(parsed);
69712
+ for (const ep of endpoints) {
69713
+ const key = `${ep.method} ${ep.path}`;
69714
+ if (!endpointMap.has(key)) endpointMap.set(key, []);
69715
+ endpointMap.get(key).push({ spec: name, operationId: ep.operationId });
69716
+ }
69717
+ }
69718
+ for (const [endpoint, owners] of endpointMap) {
69719
+ if (owners.length > 1) {
69720
+ const specNames = owners.map((o) => o.spec);
69721
+ issues.push({
69722
+ severity: "warning",
69723
+ type: "endpoint_collision",
69724
+ message: `Endpoint '${endpoint}' is defined in multiple specs: ${specNames.join(", ")}`,
69725
+ specs: specNames
69726
+ });
69727
+ }
69728
+ }
69729
+ const schemaMap = /* @__PURE__ */ new Map();
69730
+ for (const { name, parsed } of parsedSpecs) {
69731
+ const schemas = extractSchemaNames(parsed);
69732
+ for (const s of schemas) {
69733
+ if (!schemaMap.has(s.name)) schemaMap.set(s.name, []);
69734
+ schemaMap.get(s.name).push({ spec: name, hash: s.hash });
69735
+ }
69736
+ }
69737
+ for (const [schemaName, definitions] of schemaMap) {
69738
+ if (definitions.length > 1) {
69739
+ const uniqueHashes = new Set(definitions.map((d) => d.hash));
69740
+ if (uniqueHashes.size > 1) {
69741
+ const specNames = definitions.map((d) => d.spec);
69742
+ issues.push({
69743
+ severity: "warning",
69744
+ type: "schema_conflict",
69745
+ message: `Schema '${schemaName}' has conflicting definitions across specs: ${specNames.join(", ")}`,
69746
+ specs: specNames
69747
+ });
69748
+ }
69749
+ }
69750
+ }
69751
+ for (const { name, parsed } of parsedSpecs) {
69752
+ const defined = extractDefinedScopes(parsed);
69753
+ const used = extractUsedScopes(parsed);
69754
+ for (const scope of used) {
69755
+ if (!defined.has(scope)) {
69756
+ issues.push({
69757
+ severity: "warning",
69758
+ type: "undefined_scope",
69759
+ message: `Scope '${scope}' is used in '${name}' but not defined in securitySchemes`,
69760
+ specs: [name]
69761
+ });
69762
+ }
69763
+ }
69764
+ for (const scope of defined) {
69765
+ if (!used.has(scope)) {
69766
+ issues.push({
69767
+ severity: "info",
69768
+ type: "unused_scope",
69769
+ message: `Scope '${scope}' is defined in '${name}' but never used in any operation`,
69770
+ specs: [name]
69771
+ });
69772
+ }
69773
+ }
69774
+ }
69775
+ for (const { name, parsed } of parsedSpecs) {
69776
+ const refs = extractRefs(parsed);
69777
+ for (const ref of refs) {
69778
+ if (!refResolves(parsed, ref)) {
69779
+ issues.push({
69780
+ severity: "error",
69781
+ type: "unresolved_ref",
69782
+ message: `$ref '${ref}' in '${name}' does not resolve`,
69783
+ specs: [name]
69784
+ });
69785
+ }
69786
+ }
69787
+ }
69788
+ let totalEndpoints = 0;
69789
+ let totalSchemas = 0;
69790
+ for (const { parsed } of parsedSpecs) {
69791
+ totalEndpoints += extractEndpoints(parsed).length;
69792
+ totalSchemas += extractSchemaNames(parsed).length;
69793
+ }
69794
+ const hasErrors = issues.some((i) => i.severity === "error");
69795
+ return {
69796
+ valid: !hasErrors,
69797
+ issues,
69798
+ stats: {
69799
+ specs_count: parsedSpecs.length,
69800
+ endpoints_count: totalEndpoints,
69801
+ schemas_count: totalSchemas
69802
+ }
69803
+ };
69804
+ }
69805
+ module2.exports = {
69806
+ validateRegistry,
69807
+ safeParse,
69808
+ validateOpenApiSpec,
69809
+ // Exported for testing
69810
+ extractEndpoints,
69811
+ extractSchemaNames,
69812
+ extractDefinedScopes,
69813
+ extractUsedScopes,
69814
+ extractRefs,
69815
+ refResolves
69816
+ };
69817
+ }
69818
+ });
69819
+
69820
+ // src/commands/registry-gate.js
69821
+ var require_registry_gate = __commonJS({
69822
+ "src/commands/registry-gate.js"(exports2, module2) {
69823
+ "use strict";
69824
+ var fs = require("fs");
69825
+ var path = require("path");
69826
+ var chalk = require_source();
69827
+ var { matchGlob } = require_cjs4();
69828
+ var {
69829
+ validateRegistry,
69830
+ safeParse,
69831
+ validateOpenApiSpec
69832
+ } = require_registry_validation_core();
69833
+ if (process.env.NO_COLOR) chalk.level = 0;
69834
+ var SPEC_EXT = /* @__PURE__ */ new Set([".yaml", ".yml", ".json"]);
69835
+ function walkSpecCandidates(rootDir, {
69836
+ readdirSync = fs.readdirSync.bind(fs),
69837
+ statSync = fs.statSync.bind(fs)
69838
+ } = {}) {
69839
+ const out = [];
69840
+ function walk(absDir) {
69841
+ let entries;
69842
+ try {
69843
+ entries = readdirSync(absDir, { withFileTypes: true });
69844
+ } catch (err) {
69845
+ const e = new Error(`Cannot read directory ${absDir}: ${err && err.message}`);
69846
+ e.code = "GATE_ERROR";
69847
+ e.path = absDir;
69848
+ throw e;
69849
+ }
69850
+ for (const ent of entries) {
69851
+ const name = ent.name;
69852
+ if (name === "node_modules" || name.startsWith(".")) continue;
69853
+ const abs = path.join(absDir, name);
69854
+ let isDir = ent.isDirectory && ent.isDirectory();
69855
+ let isFile = ent.isFile && ent.isFile();
69856
+ if (!isDir && !isFile) {
69857
+ try {
69858
+ const st = statSync(abs);
69859
+ isDir = st.isDirectory();
69860
+ isFile = st.isFile();
69861
+ } catch (err) {
69862
+ const e = new Error(`Cannot stat ${abs}: ${err && err.message}`);
69863
+ e.code = "GATE_ERROR";
69864
+ e.path = abs;
69865
+ throw e;
69866
+ }
69867
+ }
69868
+ if (isDir) {
69869
+ walk(abs);
69870
+ continue;
69871
+ }
69872
+ if (isFile) {
69873
+ const ext = path.extname(name).toLowerCase();
69874
+ if (SPEC_EXT.has(ext)) out.push(abs);
69875
+ }
69876
+ }
69877
+ }
69878
+ walk(rootDir);
69879
+ return out.sort();
69880
+ }
69881
+ function relPosix(rootDir, absPath) {
69882
+ let rel = path.relative(rootDir, absPath);
69883
+ if (path.sep !== "/") rel = rel.split(path.sep).join("/");
69884
+ return rel;
69885
+ }
69886
+ function readFileThreeState(absPath, readFileSync = fs.readFileSync.bind(fs)) {
69887
+ try {
69888
+ const content = readFileSync(absPath, "utf8");
69889
+ return { ok: true, content: content == null ? "" : String(content) };
69890
+ } catch (err) {
69891
+ const msg = err && err.message ? String(err.message) : String(err);
69892
+ return {
69893
+ ok: false,
69894
+ code: "GATE_ERROR",
69895
+ message: `unreadable file: ${absPath} (${msg.slice(0, 200)})`,
69896
+ path: absPath
69897
+ };
69898
+ }
69899
+ }
69900
+ function discoverRegistrySpecs(dir, {
69901
+ glob = null,
69902
+ readdirSync = fs.readdirSync.bind(fs),
69903
+ readFileSync = fs.readFileSync.bind(fs),
69904
+ statSync = fs.statSync.bind(fs)
69905
+ } = {}) {
69906
+ const rootDir = path.resolve(dir);
69907
+ let candidates;
69908
+ try {
69909
+ candidates = walkSpecCandidates(rootDir, { readdirSync, statSync });
69910
+ } catch (err) {
69911
+ return {
69912
+ ok: false,
69913
+ code: err.code || "GATE_ERROR",
69914
+ message: err.message || String(err),
69915
+ path: err.path
69916
+ };
69917
+ }
69918
+ if (glob) {
69919
+ candidates = candidates.filter((abs) => matchGlob(glob, relPosix(rootDir, abs)));
69920
+ }
69921
+ const specs = [];
69922
+ let skippedNonSpec = 0;
69923
+ for (const abs of candidates) {
69924
+ const read = readFileThreeState(abs, readFileSync);
69925
+ if (!read.ok) {
69926
+ return {
69927
+ ok: false,
69928
+ code: "GATE_ERROR",
69929
+ message: read.message,
69930
+ path: read.path || abs
69931
+ };
69932
+ }
69933
+ const name = relPosix(rootDir, abs);
69934
+ const parsed = safeParse(read.content);
69935
+ if (!parsed || typeof parsed !== "object") {
69936
+ specs.push({ name, spec: read.content });
69937
+ continue;
69938
+ }
69939
+ const shape = validateOpenApiSpec(parsed);
69940
+ if (!shape.valid) {
69941
+ if (shape.error && shape.error.includes("Missing required field: 'openapi' or 'swagger'")) {
69942
+ skippedNonSpec += 1;
69943
+ continue;
69944
+ }
69945
+ specs.push({ name, spec: read.content });
69946
+ continue;
69947
+ }
69948
+ specs.push({ name, spec: read.content });
69949
+ }
69950
+ return {
69951
+ ok: true,
69952
+ specs,
69953
+ skippedNonSpec,
69954
+ candidates: candidates.length,
69955
+ rootDir
69956
+ };
69957
+ }
69958
+ function findingsFailGate(issues, { warnOnly = false, errorsOnly = false } = {}) {
69959
+ if (warnOnly) return false;
69960
+ for (const i of issues || []) {
69961
+ if (i.severity === "error") return true;
69962
+ if (i.severity === "warning" && !errorsOnly) return true;
69963
+ }
69964
+ return false;
69965
+ }
69966
+ function countBySeverity(issues) {
69967
+ const c = { error: 0, warning: 0, info: 0 };
69968
+ for (const i of issues || []) {
69969
+ if (i.severity === "error") c.error += 1;
69970
+ else if (i.severity === "warning") c.warning += 1;
69971
+ else if (i.severity === "info") c.info += 1;
69972
+ }
69973
+ return c;
69974
+ }
69975
+ function severityColor(sev) {
69976
+ if (sev === "error") return chalk.red;
69977
+ if (sev === "warning") return chalk.yellow;
69978
+ return chalk.cyan;
69979
+ }
69980
+ function printFindings(issues, log) {
69981
+ for (const i of issues || []) {
69982
+ const color = severityColor(i.severity);
69983
+ const files = Array.isArray(i.specs) ? i.specs.join(", ") : "";
69984
+ log(color(`[${i.severity}] ${i.type}`) + (files ? chalk.dim(` ${files}`) : ""));
69985
+ log(` ${i.message}`);
69986
+ }
69987
+ }
69988
+ function runRegistryGate(options = {}, deps = {}) {
69989
+ const log = deps.log || console.log.bind(console);
69990
+ const logErr = deps.logErr || console.error.bind(console);
69991
+ const cwd = deps.cwd || process.cwd();
69992
+ const dirArg = options.dir != null && options.dir !== "" ? options.dir : ".";
69993
+ const rootDir = path.isAbsolute(dirArg) ? dirArg : path.resolve(cwd, dirArg);
69994
+ const readdirSync = deps.readdirSync || fs.readdirSync.bind(fs);
69995
+ const readFileSync = deps.readFileSync || fs.readFileSync.bind(fs);
69996
+ const statSync = deps.statSync || fs.statSync.bind(fs);
69997
+ const existsSync = deps.existsSync || fs.existsSync.bind(fs);
69998
+ if (!existsSync(rootDir)) {
69999
+ const msg = `CodeRifts registry-gate: GATE_ERROR \u2014 directory not found: ${rootDir}`;
70000
+ logErr(chalk.red(msg));
70001
+ return { ok: false, exitCode: 1, code: "GATE_ERROR", message: msg };
70002
+ }
70003
+ let st;
70004
+ try {
70005
+ st = statSync(rootDir);
70006
+ } catch (err) {
70007
+ const msg = `CodeRifts registry-gate: GATE_ERROR \u2014 cannot access ${rootDir}: ${err && err.message}`;
70008
+ logErr(chalk.red(msg));
70009
+ return { ok: false, exitCode: 1, code: "GATE_ERROR", message: msg };
70010
+ }
70011
+ if (!st.isDirectory()) {
70012
+ const msg = `CodeRifts registry-gate: GATE_ERROR \u2014 not a directory: ${rootDir}`;
70013
+ logErr(chalk.red(msg));
70014
+ return { ok: false, exitCode: 1, code: "GATE_ERROR", message: msg };
70015
+ }
70016
+ const discovered = discoverRegistrySpecs(rootDir, {
70017
+ glob: options.glob || null,
70018
+ readdirSync,
70019
+ readFileSync,
70020
+ statSync
70021
+ });
70022
+ if (!discovered.ok) {
70023
+ const msg = `CodeRifts registry-gate: ${discovered.code} \u2014 ${discovered.message}`;
70024
+ logErr(chalk.red(msg));
70025
+ return {
70026
+ ok: false,
70027
+ exitCode: 1,
70028
+ code: discovered.code || "GATE_ERROR",
70029
+ message: discovered.message,
70030
+ path: discovered.path
70031
+ };
70032
+ }
70033
+ if (discovered.specs.length === 0) {
70034
+ const msg = `CodeRifts registry-gate: REGISTRY_EMPTY \u2014 no OpenAPI/Swagger specs discovered (scanned ${discovered.candidates} yaml/json file(s), skipped non-spec: ${discovered.skippedNonSpec}). An admission gate guarding nothing must fail, not pass.`;
70035
+ logErr(chalk.red(msg));
70036
+ return {
70037
+ ok: false,
70038
+ exitCode: 1,
70039
+ code: "REGISTRY_EMPTY",
70040
+ message: msg,
70041
+ skippedNonSpec: discovered.skippedNonSpec,
70042
+ candidates: discovered.candidates
70043
+ };
70044
+ }
70045
+ const result = validateRegistry(discovered.specs);
70046
+ const counts = countBySeverity(result.issues);
70047
+ const mode = {
70048
+ warnOnly: !!options.warnOnly,
70049
+ errorsOnly: !!options.errorsOnly
70050
+ };
70051
+ const fail = findingsFailGate(result.issues, mode);
70052
+ if (result.issues.length > 0) {
70053
+ printFindings(result.issues, log);
70054
+ }
70055
+ const summary = [
70056
+ `specs=${result.stats.specs_count}`,
70057
+ `endpoints=${result.stats.endpoints_count}`,
70058
+ `schemas=${result.stats.schemas_count}`,
70059
+ `errors=${counts.error}`,
70060
+ `warnings=${counts.warning}`,
70061
+ `info=${counts.info}`,
70062
+ discovered.skippedNonSpec ? `skipped_non_spec=${discovered.skippedNonSpec}` : null,
70063
+ mode.warnOnly ? "mode=warn-only" : mode.errorsOnly ? "mode=errors-only" : "mode=default",
70064
+ fail ? "FAIL" : "PASS"
70065
+ ].filter(Boolean).join(" ");
70066
+ if (fail) {
70067
+ log(chalk.red(`CodeRifts registry-gate: ${summary}`));
70068
+ } else {
70069
+ log(chalk.green(`CodeRifts registry-gate: ${summary}`));
70070
+ }
70071
+ if (counts.error === 0 && counts.warning === 0 && counts.info === 0) {
70072
+ log(chalk.dim(" checks: endpoint_collision, schema_conflict, scopes, unresolved_ref \u2014 no findings"));
70073
+ }
70074
+ return {
70075
+ ok: !fail,
70076
+ exitCode: fail ? 1 : 0,
70077
+ code: fail ? "REGISTRY_FINDINGS" : "REGISTRY_OK",
70078
+ issues: result.issues,
70079
+ stats: result.stats,
70080
+ counts,
70081
+ skippedNonSpec: discovered.skippedNonSpec,
70082
+ candidates: discovered.candidates,
70083
+ warnOnly: mode.warnOnly,
70084
+ errorsOnly: mode.errorsOnly
70085
+ };
70086
+ }
70087
+ module2.exports = {
70088
+ runRegistryGate,
70089
+ discoverRegistrySpecs,
70090
+ walkSpecCandidates,
70091
+ findingsFailGate,
70092
+ countBySeverity,
70093
+ readFileThreeState,
70094
+ relPosix
70095
+ };
70096
+ }
70097
+ });
70098
+
69516
70099
  // src/commands/init.js
69517
70100
  var require_init = __commonJS({
69518
70101
  "src/commands/init.js"(exports2, module2) {
@@ -69772,6 +70355,63 @@ notifications:
69772
70355
  on_breaking: true
69773
70356
  on_risk_above: 60
69774
70357
 
70358
+ overlap_detection: true
70359
+ generator_detection: true
70360
+ `
70361
+ },
70362
+ "ai-agent-platform": {
70363
+ aliases: ["ai-agent-platform", "ai-agent", "agent", "mcp"],
70364
+ label: "AI Agent Platform",
70365
+ description: "Zero-tolerance removals for agent/MCP-consumed APIs",
70366
+ yaml: `# CodeRifts Policy: AI Agent Platform
70367
+ # For APIs consumed by AI agents and MCP tool surfaces.
70368
+ # Agent consumers cannot renegotiate contracts at runtime \u2014 a removed field
70369
+ # or endpoint is a hard break for automated callers (no human can "adapt").
70370
+ # Portable policy vocabulary only (same keys as other templates).
70371
+
70372
+ failOnBreaking: true
70373
+
70374
+ policy:
70375
+ # Zero tolerance: any breaking change blocks the check.
70376
+ max_breaking_changes: 0
70377
+ # Removals that break tool schemas / agent bindings are never silent.
70378
+ no_delete_endpoints: true
70379
+ no_delete_required_fields: true
70380
+ require_deprecation_before_removal: true
70381
+ require_version_bump_on_breaking: true
70382
+ # Freeze merges when risk is elevated (agents amplify blast radius).
70383
+ freeze_on_risk_score: 55
70384
+
70385
+ # Who must approve high-impact contract changes for agent-facing surfaces.
70386
+ approval_matrix:
70387
+ endpoint_removal:
70388
+ - agent-platform-owners
70389
+ - api-governance
70390
+ field_removal:
70391
+ - agent-platform-owners
70392
+ auth_change:
70393
+ - security-team
70394
+ - agent-platform-owners
70395
+ type_change:
70396
+ - agent-platform-owners
70397
+
70398
+ freeze_periods: []
70399
+
70400
+ risk_scoring:
70401
+ # dimension_weights is the key the engine reads (0-100 scale, relative weights)
70402
+ dimension_weights:
70403
+ revenue_impact: 20
70404
+ blast_radius: 35
70405
+ app_compatibility: 30
70406
+ security: 15
70407
+
70408
+ linting:
70409
+ enabled: true
70410
+ rules:
70411
+ naming_convention: true
70412
+ consistent_errors: true
70413
+ pagination_pattern: true
70414
+
69775
70415
  overlap_detection: true
69776
70416
  generator_detection: true
69777
70417
  `
@@ -69793,7 +70433,8 @@ generator_detection: true
69793
70433
  ["growth", "Balanced between speed and safety"],
69794
70434
  ["fintech", "Maximum governance for regulated industries"],
69795
70435
  ["public-api", "Backward compatibility for external consumers"],
69796
- ["microservices", "Internal service-to-service with blast radius focus"]
70436
+ ["microservices", "Internal service-to-service with blast radius focus"],
70437
+ ["ai-agent", "Zero-tolerance removals for agent/MCP-consumed APIs"]
69797
70438
  ];
69798
70439
  for (const [name, desc] of entries) {
69799
70440
  console.log(` ${chalk.cyan(name.padEnd(16))}${chalk.dim(desc)}`);
@@ -69829,9 +70470,10 @@ generator_detection: true
69829
70470
  console.log("");
69830
70471
  console.log(chalk.green(` Created .coderifts.yml with ${tmpl.label} policy template.`));
69831
70472
  console.log(chalk.dim(` Edit the file to customize approval teams, freeze periods, and domain mappings.`));
70473
+ console.log(chalk.dim(` Agent-using repo? Run: coderifts agent-setup`));
69832
70474
  console.log("");
69833
70475
  }
69834
- module2.exports = { init, TEMPLATES };
70476
+ module2.exports = { init, TEMPLATES, resolveTemplate };
69835
70477
  }
69836
70478
  });
69837
70479
 
@@ -95188,6 +95830,679 @@ var require_login = __commonJS({
95188
95830
  }
95189
95831
  });
95190
95832
 
95833
+ // src/commands/setup-required-check.js
95834
+ var require_setup_required_check = __commonJS({
95835
+ "src/commands/setup-required-check.js"(exports2, module2) {
95836
+ "use strict";
95837
+ var { execFileSync } = require("child_process");
95838
+ var chalk = require_source();
95839
+ if (process.env.NO_COLOR) chalk.level = 0;
95840
+ var CHECK_NAME = "CodeRifts / contract-gate";
95841
+ var EXIT = {
95842
+ OK: 0,
95843
+ /** Target already required or dry-run printed successfully. */
95844
+ NEEDS_APPLY: 0,
95845
+ /** Unknown / permission / gh missing / verify failed. */
95846
+ ERROR: 1,
95847
+ PERMISSION: 2
95848
+ };
95849
+ function extractRequiredContexts(protection) {
95850
+ if (!protection || typeof protection !== "object") return [];
95851
+ const rsc = protection.required_status_checks;
95852
+ if (!rsc || typeof rsc !== "object") return [];
95853
+ if (Array.isArray(rsc.contexts) && rsc.contexts.length) {
95854
+ return rsc.contexts.map((c) => String(c));
95855
+ }
95856
+ if (Array.isArray(rsc.checks)) {
95857
+ return rsc.checks.map((c) => c && c.context != null ? String(c.context) : "").filter(Boolean);
95858
+ }
95859
+ return [];
95860
+ }
95861
+ function classifyObservation(read, contextName = CHECK_NAME) {
95862
+ const status = read && read.status != null ? Number(read.status) : null;
95863
+ if (status === 404) {
95864
+ return {
95865
+ state: "ABSENT",
95866
+ context_is_required: false,
95867
+ required_contexts: [],
95868
+ protection: null,
95869
+ observation_error: null
95870
+ };
95871
+ }
95872
+ if (status === 403) {
95873
+ return {
95874
+ state: "UNKNOWN",
95875
+ context_is_required: false,
95876
+ required_contexts: [],
95877
+ protection: null,
95878
+ observation_error: "403",
95879
+ permission_hint: "administration:read (or repo admin) required to read branch protection"
95880
+ };
95881
+ }
95882
+ if (status != null && status >= 400) {
95883
+ return {
95884
+ state: "UNKNOWN",
95885
+ context_is_required: false,
95886
+ required_contexts: [],
95887
+ protection: null,
95888
+ observation_error: String(status),
95889
+ permission_hint: read.errorMessage || `GitHub API returned HTTP ${status}`
95890
+ };
95891
+ }
95892
+ const protection = read && read.body && typeof read.body === "object" ? read.body : null;
95893
+ if (!protection) {
95894
+ return {
95895
+ state: "ABSENT",
95896
+ context_is_required: false,
95897
+ required_contexts: [],
95898
+ protection: null,
95899
+ observation_error: null
95900
+ };
95901
+ }
95902
+ const required_contexts = extractRequiredContexts(protection);
95903
+ const context_is_required = required_contexts.some((c) => c === contextName);
95904
+ if (context_is_required) {
95905
+ return {
95906
+ state: "REQUIRED",
95907
+ context_is_required: true,
95908
+ required_contexts,
95909
+ protection,
95910
+ observation_error: null
95911
+ };
95912
+ }
95913
+ return {
95914
+ state: "PRESENT_NOT_REQUIRED",
95915
+ context_is_required: false,
95916
+ required_contexts,
95917
+ protection,
95918
+ observation_error: null
95919
+ };
95920
+ }
95921
+ function buildProtectionUpdatePayload(protection, contextName = CHECK_NAME) {
95922
+ const p = protection && typeof protection === "object" ? protection : {};
95923
+ const prev = p.required_status_checks && typeof p.required_status_checks === "object" ? p.required_status_checks : {};
95924
+ const contexts = extractRequiredContexts(p);
95925
+ const nextContexts = contexts.includes(contextName) ? contexts.slice() : contexts.concat([contextName]);
95926
+ const body = {
95927
+ required_status_checks: {
95928
+ strict: prev.strict === true,
95929
+ contexts: nextContexts,
95930
+ // Prefer also sending checks[] when the API used that shape so app ids survive when present.
95931
+ ...Array.isArray(prev.checks) && prev.checks.length ? {
95932
+ checks: nextContexts.map((ctx) => {
95933
+ const existing = prev.checks.find((c) => c && c.context === ctx);
95934
+ return existing && existing.app_id != null ? { context: ctx, app_id: existing.app_id } : { context: ctx };
95935
+ })
95936
+ } : {}
95937
+ },
95938
+ enforce_admins: !!(p.enforce_admins && p.enforce_admins.enabled),
95939
+ required_pull_request_reviews: p.required_pull_request_reviews ? serializePrReviews(p.required_pull_request_reviews) : null,
95940
+ restrictions: p.restrictions ? {
95941
+ users: (p.restrictions.users || []).map((u) => u.login || u).filter(Boolean),
95942
+ teams: (p.restrictions.teams || []).map((t) => t.slug || t).filter(Boolean),
95943
+ apps: (p.restrictions.apps || []).map((a) => a.slug || a).filter(Boolean)
95944
+ } : null
95945
+ };
95946
+ if (typeof p.required_linear_history === "boolean") {
95947
+ body.required_linear_history = p.required_linear_history;
95948
+ } else if (p.required_linear_history && typeof p.required_linear_history.enabled === "boolean") {
95949
+ body.required_linear_history = p.required_linear_history.enabled;
95950
+ }
95951
+ if (typeof p.allow_force_pushes === "boolean") {
95952
+ body.allow_force_pushes = p.allow_force_pushes;
95953
+ } else if (p.allow_force_pushes && typeof p.allow_force_pushes.enabled === "boolean") {
95954
+ body.allow_force_pushes = p.allow_force_pushes.enabled;
95955
+ }
95956
+ if (typeof p.allow_deletions === "boolean") {
95957
+ body.allow_deletions = p.allow_deletions;
95958
+ } else if (p.allow_deletions && typeof p.allow_deletions.enabled === "boolean") {
95959
+ body.allow_deletions = p.allow_deletions.enabled;
95960
+ }
95961
+ if (typeof p.block_creations === "boolean") {
95962
+ body.block_creations = p.block_creations;
95963
+ } else if (p.block_creations && typeof p.block_creations.enabled === "boolean") {
95964
+ body.block_creations = p.block_creations.enabled;
95965
+ }
95966
+ if (typeof p.required_conversation_resolution === "boolean") {
95967
+ body.required_conversation_resolution = p.required_conversation_resolution;
95968
+ } else if (p.required_conversation_resolution && typeof p.required_conversation_resolution.enabled === "boolean") {
95969
+ body.required_conversation_resolution = p.required_conversation_resolution.enabled;
95970
+ }
95971
+ return body;
95972
+ }
95973
+ function serializePrReviews(rpr) {
95974
+ if (!rpr || typeof rpr !== "object") return null;
95975
+ return {
95976
+ dismiss_stale_reviews: !!rpr.dismiss_stale_reviews,
95977
+ require_code_owner_reviews: !!rpr.require_code_owner_reviews,
95978
+ required_approving_review_count: Number(rpr.required_approving_review_count) || 0,
95979
+ require_last_push_approval: !!rpr.require_last_push_approval,
95980
+ ...Array.isArray(rpr.bypass_pull_request_allowances?.users) ? {
95981
+ bypass_pull_request_allowances: {
95982
+ users: (rpr.bypass_pull_request_allowances.users || []).map((u) => u.login || u).filter(Boolean),
95983
+ teams: (rpr.bypass_pull_request_allowances.teams || []).map((t) => t.slug || t).filter(Boolean),
95984
+ apps: (rpr.bypass_pull_request_allowances.apps || []).map((a) => a.slug || a).filter(Boolean)
95985
+ }
95986
+ } : {}
95987
+ };
95988
+ }
95989
+ function detectRulesetRequiredCheck(rulesets, contextName = CHECK_NAME) {
95990
+ const names = [];
95991
+ const list = Array.isArray(rulesets) ? rulesets : [];
95992
+ for (const rs of list) {
95993
+ if (!rs || typeof rs !== "object") continue;
95994
+ const rules = Array.isArray(rs.rules) ? rs.rules : [];
95995
+ for (const rule of rules) {
95996
+ if (!rule || rule.type !== "required_status_checks") continue;
95997
+ const params = rule.parameters || {};
95998
+ const checks = Array.isArray(params.required_status_checks) ? params.required_status_checks : Array.isArray(params.contexts) ? params.contexts.map((c) => ({ context: c })) : [];
95999
+ for (const c of checks) {
96000
+ const ctx = typeof c === "string" ? c : c && c.context;
96001
+ if (ctx === contextName) {
96002
+ names.push(String(rs.name || rs.id || "ruleset"));
96003
+ }
96004
+ }
96005
+ }
96006
+ }
96007
+ return { enforced: names.length > 0, ruleset_names: [...new Set(names)] };
96008
+ }
96009
+ function defaultGit(args, cwd) {
96010
+ return execFileSync("git", args, {
96011
+ cwd: cwd || process.cwd(),
96012
+ encoding: "utf8",
96013
+ maxBuffer: 4 * 1024 * 1024,
96014
+ stdio: ["ignore", "pipe", "pipe"]
96015
+ }).trim();
96016
+ }
96017
+ function parseGitHubRemote(remoteUrl) {
96018
+ const s = String(remoteUrl || "").trim();
96019
+ let m = s.match(/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/i);
96020
+ if (m) return { owner: m[1], repo: m[2].replace(/\.git$/i, "") };
96021
+ m = s.match(/^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i);
96022
+ if (m) return { owner: m[1], repo: m[2].replace(/\.git$/i, "") };
96023
+ m = s.match(/^ssh:\/\/git@github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i);
96024
+ if (m) return { owner: m[1], repo: m[2].replace(/\.git$/i, "") };
96025
+ return null;
96026
+ }
96027
+ function resolveOwnerRepo(cwd, gitImpl = defaultGit) {
96028
+ let url;
96029
+ try {
96030
+ url = gitImpl(["remote", "get-url", "origin"], cwd);
96031
+ } catch {
96032
+ try {
96033
+ url = gitImpl(["config", "--get", "remote.origin.url"], cwd);
96034
+ } catch {
96035
+ return null;
96036
+ }
96037
+ }
96038
+ return parseGitHubRemote(url);
96039
+ }
96040
+ function resolveDefaultBranch(cwd, gitImpl = defaultGit) {
96041
+ try {
96042
+ const ref = gitImpl(["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
96043
+ const m = ref.match(/refs\/remotes\/origin\/(.+)$/);
96044
+ if (m) return m[1];
96045
+ } catch {
96046
+ }
96047
+ for (const b of ["main", "master"]) {
96048
+ try {
96049
+ gitImpl(["rev-parse", "--verify", `origin/${b}`], cwd);
96050
+ return b;
96051
+ } catch {
96052
+ }
96053
+ }
96054
+ try {
96055
+ return gitImpl(["branch", "--show-current"], cwd) || "main";
96056
+ } catch {
96057
+ return "main";
96058
+ }
96059
+ }
96060
+ function defaultGhAvailable() {
96061
+ try {
96062
+ execFileSync("gh", ["--version"], { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8" });
96063
+ return true;
96064
+ } catch {
96065
+ return false;
96066
+ }
96067
+ }
96068
+ function runGhApi(args, { cwd, ghRunner } = {}) {
96069
+ const runner = ghRunner || ((a, c) => execFileSync("gh", a, {
96070
+ cwd: c || process.cwd(),
96071
+ encoding: "utf8",
96072
+ maxBuffer: 8 * 1024 * 1024,
96073
+ stdio: ["ignore", "pipe", "pipe"]
96074
+ }));
96075
+ try {
96076
+ const raw = runner(["api", ...args], cwd);
96077
+ let body = null;
96078
+ try {
96079
+ body = JSON.parse(raw);
96080
+ } catch {
96081
+ body = raw;
96082
+ }
96083
+ return { ok: true, status: 200, body, raw: String(raw) };
96084
+ } catch (err) {
96085
+ const stderr = err && err.stderr ? String(err.stderr) : "";
96086
+ const stdout = err && err.stdout ? String(err.stdout) : "";
96087
+ const msg = stderr || err && err.message || String(err);
96088
+ const m = msg.match(/HTTP\s+(\d{3})/i) || stdout.match(/"status"\s*:\s*"(\d{3})"/);
96089
+ const status = m ? Number(m[1]) : err && err.status === 1 ? null : null;
96090
+ let body = null;
96091
+ try {
96092
+ body = JSON.parse(stdout);
96093
+ } catch {
96094
+ }
96095
+ let httpStatus = status;
96096
+ if (httpStatus == null) {
96097
+ if (/403|Forbidden|Resource not accessible/i.test(msg)) httpStatus = 403;
96098
+ else if (/404|Not Found/i.test(msg)) httpStatus = 404;
96099
+ else httpStatus = 500;
96100
+ }
96101
+ return {
96102
+ ok: false,
96103
+ status: httpStatus,
96104
+ body,
96105
+ raw: stdout || msg,
96106
+ errorMessage: msg.slice(0, 400)
96107
+ };
96108
+ }
96109
+ }
96110
+ function protectionGetPath(owner, repo, branch) {
96111
+ return `repos/${owner}/${repo}/branches/${encodeURIComponent(branch)}/protection`;
96112
+ }
96113
+ function protectionPutArgs(owner, repo, branch, payload) {
96114
+ return {
96115
+ args: [
96116
+ "--method",
96117
+ "PUT",
96118
+ protectionGetPath(owner, repo, branch),
96119
+ "--input",
96120
+ "-"
96121
+ ],
96122
+ input: JSON.stringify(payload)
96123
+ };
96124
+ }
96125
+ function printApplyCommand(owner, repo, branch, payload) {
96126
+ const path = protectionGetPath(owner, repo, branch);
96127
+ const json = JSON.stringify(payload, null, 2);
96128
+ return [
96129
+ `# Read-modify-write: add '${CHECK_NAME}' to required status checks (preserves other settings)`,
96130
+ `gh api --method PUT ${path} --input - <<'EOF'`,
96131
+ json,
96132
+ "EOF"
96133
+ ].join("\n");
96134
+ }
96135
+ async function runSetupRequiredCheck(options = {}, deps = {}) {
96136
+ const cwd = deps.cwd || process.cwd();
96137
+ const gitImpl = deps.gitImpl || defaultGit;
96138
+ const log = deps.log || console.log.bind(console);
96139
+ const logErr = deps.logErr || console.error.bind(console);
96140
+ const ghAvailable = deps.ghAvailable != null ? deps.ghAvailable : defaultGhAvailable;
96141
+ const ghRunner = deps.ghRunner;
96142
+ const runApi = deps.runGhApi || ((args, o) => runGhApi(args, { ...o, ghRunner }));
96143
+ const doExit = deps.exit !== false;
96144
+ const finish = (code, payload2) => {
96145
+ if (options.json) log(JSON.stringify(payload2, null, 2));
96146
+ if (doExit) process.exit(code);
96147
+ return { exitCode: code, ...payload2 };
96148
+ };
96149
+ const ownerRepo = options.repo ? (() => {
96150
+ const m = String(options.repo).match(/^([^/]+)\/([^/]+)$/);
96151
+ return m ? { owner: m[1], repo: m[2] } : null;
96152
+ })() : resolveOwnerRepo(cwd, gitImpl);
96153
+ if (!ownerRepo) {
96154
+ logErr(chalk.red("Could not resolve owner/repo from git remote origin (or --repo OWNER/REPO)."));
96155
+ return finish(EXIT.ERROR, { ok: false, code: "REPO_UNRESOLVED" });
96156
+ }
96157
+ const { owner, repo } = ownerRepo;
96158
+ const branch = options.branch || resolveDefaultBranch(cwd, gitImpl);
96159
+ if (!ghAvailable()) {
96160
+ logErr(chalk.yellow("GitHub CLI (`gh`) not found on PATH."));
96161
+ logErr("Install: https://cli.github.com/ then: gh auth login");
96162
+ logErr("");
96163
+ logErr("Manual check (your credentials, not a CodeRifts key):");
96164
+ logErr(` gh api ${protectionGetPath(owner, repo, branch)}`);
96165
+ logErr("");
96166
+ logErr(`Required check name: ${CHECK_NAME}`);
96167
+ logErr("The CodeRifts App never writes branch protection (needs administration:write).");
96168
+ return finish(EXIT.ERROR, { ok: false, code: "GH_MISSING", owner, repo, branch, check: CHECK_NAME });
96169
+ }
96170
+ const getPath = protectionGetPath(owner, repo, branch);
96171
+ const read = runApi([getPath], { cwd });
96172
+ const obs = classifyObservation(read, CHECK_NAME);
96173
+ let ruleset = { enforced: false, ruleset_names: [] };
96174
+ try {
96175
+ const rsList = runApi([`repos/${owner}/${repo}/rulesets`], { cwd });
96176
+ if (rsList.ok && Array.isArray(rsList.body)) {
96177
+ const detailed = [];
96178
+ for (const rs of rsList.body) {
96179
+ if (!rs || rs.id == null) continue;
96180
+ const one = runApi([`repos/${owner}/${repo}/rulesets/${rs.id}`], { cwd });
96181
+ if (one.ok && one.body) detailed.push(one.body);
96182
+ else detailed.push(rs);
96183
+ }
96184
+ ruleset = detectRulesetRequiredCheck(detailed.length ? detailed : rsList.body, CHECK_NAME);
96185
+ }
96186
+ } catch {
96187
+ }
96188
+ const basePayload = {
96189
+ ok: true,
96190
+ owner,
96191
+ repo,
96192
+ branch,
96193
+ check: CHECK_NAME,
96194
+ classic: obs.state,
96195
+ context_is_required: obs.context_is_required,
96196
+ required_contexts: obs.required_contexts,
96197
+ ruleset_enforced: ruleset.enforced,
96198
+ ruleset_names: ruleset.ruleset_names
96199
+ };
96200
+ if (ruleset.enforced) {
96201
+ if (!options.json) {
96202
+ log(chalk.green(`Required via repository ruleset: ${CHECK_NAME}`));
96203
+ log(` repo: ${owner}/${repo}`);
96204
+ log(` branch: ${branch}`);
96205
+ log(` rulesets: ${ruleset.ruleset_names.join(", ") || "(named)"}`);
96206
+ log(" Classic branch protection may still be ABSENT \u2014 rulesets enforce separately.");
96207
+ }
96208
+ return finish(EXIT.OK, { ...basePayload, code: "RULESET_REQUIRED" });
96209
+ }
96210
+ if (obs.state === "REQUIRED") {
96211
+ if (!options.json) {
96212
+ log(chalk.green(`Already required: '${CHECK_NAME}'`));
96213
+ log(` repo: ${owner}/${repo}`);
96214
+ log(` branch: ${branch}`);
96215
+ log(" (classic branch protection \u2014 idempotent; nothing to do)");
96216
+ }
96217
+ return finish(EXIT.OK, { ...basePayload, code: "ALREADY_REQUIRED" });
96218
+ }
96219
+ if (obs.state === "UNKNOWN") {
96220
+ if (!options.json) {
96221
+ logErr(chalk.red("Cannot observe branch protection (UNKNOWN)."));
96222
+ logErr(` HTTP: ${obs.observation_error || "unknown"}`);
96223
+ logErr(` ${obs.permission_hint || "An admin with administration:read must run this command."}`);
96224
+ logErr(" The CodeRifts App never writes protection; an admin must grant or run this.");
96225
+ }
96226
+ return finish(EXIT.PERMISSION, { ...basePayload, ok: false, code: "PERMISSION", observation_error: obs.observation_error });
96227
+ }
96228
+ let payload;
96229
+ if (obs.state === "ABSENT" || !obs.protection) {
96230
+ payload = {
96231
+ required_status_checks: {
96232
+ strict: false,
96233
+ contexts: [CHECK_NAME]
96234
+ },
96235
+ enforce_admins: false,
96236
+ required_pull_request_reviews: null,
96237
+ restrictions: null
96238
+ };
96239
+ } else {
96240
+ payload = buildProtectionUpdatePayload(obs.protection, CHECK_NAME);
96241
+ }
96242
+ const cmdText = printApplyCommand(owner, repo, branch, payload);
96243
+ if (!options.apply) {
96244
+ if (!options.json) {
96245
+ log(chalk.yellow(`Status: ${obs.state} \u2014 '${CHECK_NAME}' is not a required check.`));
96246
+ log(` repo: ${owner}/${repo}`);
96247
+ log(` branch: ${branch}`);
96248
+ log("");
96249
+ log("Dry-run (default). Exact command to add the required check with your credentials:");
96250
+ log("");
96251
+ log(cmdText);
96252
+ log("");
96253
+ log("Re-run with --apply to execute that PUT and re-verify.");
96254
+ log("Why the App never writes this: administration:write is a trust jump we refuse (audit 3.4/1, 3.5).");
96255
+ }
96256
+ return finish(EXIT.NEEDS_APPLY, {
96257
+ ...basePayload,
96258
+ code: "NEEDS_APPLY",
96259
+ apply_command: cmdText,
96260
+ apply_payload: payload
96261
+ });
96262
+ }
96263
+ const put = protectionPutArgs(owner, repo, branch, payload);
96264
+ let putResult;
96265
+ if (deps.ghApply) {
96266
+ putResult = deps.ghApply(put, { cwd });
96267
+ } else {
96268
+ try {
96269
+ const raw = execFileSync("gh", ["api", ...put.args], {
96270
+ cwd,
96271
+ encoding: "utf8",
96272
+ input: put.input,
96273
+ maxBuffer: 8 * 1024 * 1024,
96274
+ stdio: ["pipe", "pipe", "pipe"]
96275
+ });
96276
+ putResult = { ok: true, status: 200, body: JSON.parse(raw || "{}"), raw };
96277
+ } catch (err) {
96278
+ const msg = err && err.stderr ? String(err.stderr) : err && err.message || String(err);
96279
+ const m = msg.match(/HTTP\s+(\d{3})/i);
96280
+ putResult = {
96281
+ ok: false,
96282
+ status: m ? Number(m[1]) : 500,
96283
+ errorMessage: msg.slice(0, 400),
96284
+ raw: msg
96285
+ };
96286
+ }
96287
+ }
96288
+ if (!putResult.ok) {
96289
+ if (!options.json) {
96290
+ logErr(chalk.red("Apply failed."));
96291
+ logErr(` ${putResult.errorMessage || putResult.status}`);
96292
+ if (putResult.status === 403) {
96293
+ logErr(" Need administration:write on the repository (admin).");
96294
+ }
96295
+ }
96296
+ return finish(
96297
+ putResult.status === 403 ? EXIT.PERMISSION : EXIT.ERROR,
96298
+ { ...basePayload, ok: false, code: "APPLY_FAILED", apply_status: putResult.status }
96299
+ );
96300
+ }
96301
+ const reRead = runApi([getPath], { cwd });
96302
+ const reObs = classifyObservation(reRead, CHECK_NAME);
96303
+ if (reObs.state !== "REQUIRED") {
96304
+ if (!options.json) {
96305
+ logErr(chalk.red("Apply returned success but re-read did not show the check as required."));
96306
+ logErr(` classic state after apply: ${reObs.state}`);
96307
+ logErr(" Unverified apply is not success.");
96308
+ }
96309
+ return finish(EXIT.ERROR, {
96310
+ ...basePayload,
96311
+ ok: false,
96312
+ code: "VERIFY_FAILED",
96313
+ classic_after: reObs.state
96314
+ });
96315
+ }
96316
+ if (!options.json) {
96317
+ log(chalk.green(`Success: '${CHECK_NAME}' is now required.`));
96318
+ log(` repo: ${owner}/${repo}`);
96319
+ log(` branch: ${branch}`);
96320
+ }
96321
+ return finish(EXIT.OK, {
96322
+ ...basePayload,
96323
+ code: "APPLIED",
96324
+ classic: "REQUIRED",
96325
+ context_is_required: true
96326
+ });
96327
+ }
96328
+ module2.exports = {
96329
+ runSetupRequiredCheck,
96330
+ CHECK_NAME,
96331
+ EXIT,
96332
+ extractRequiredContexts,
96333
+ classifyObservation,
96334
+ buildProtectionUpdatePayload,
96335
+ detectRulesetRequiredCheck,
96336
+ parseGitHubRemote,
96337
+ resolveOwnerRepo,
96338
+ resolveDefaultBranch,
96339
+ printApplyCommand,
96340
+ protectionGetPath,
96341
+ protectionPutArgs,
96342
+ runGhApi
96343
+ };
96344
+ }
96345
+ });
96346
+
96347
+ // src/commands/status.js
96348
+ var require_status = __commonJS({
96349
+ "src/commands/status.js"(exports2, module2) {
96350
+ "use strict";
96351
+ var chalk = require_source();
96352
+ var { getApiKey } = require_config();
96353
+ var { cloudGetEnforcementStatus } = require_cloud();
96354
+ var { renderJson } = require_json2();
96355
+ if (process.env.NO_COLOR) chalk.level = 0;
96356
+ var USAGE = [
96357
+ "Usage: coderifts status --repo owner/repo",
96358
+ " or: coderifts status owner/repo",
96359
+ "",
96360
+ "Read-only: prints the cross-layer enforcement report from the CodeRifts API.",
96361
+ "Requires a cloud API key (coderifts login or CODERIFTS_API_KEY)."
96362
+ ].join("\n");
96363
+ function isValidRepo(full) {
96364
+ const parts = String(full || "").split("/");
96365
+ if (parts.length !== 2) return false;
96366
+ const [owner, repo] = parts.map((p) => p.trim());
96367
+ return !!(owner && repo);
96368
+ }
96369
+ function colorStatus(status) {
96370
+ const s = String(status == null ? "" : status);
96371
+ const upper = s.toUpperCase();
96372
+ if (upper === "ENFORCING") return chalk.green(s);
96373
+ if (upper === "ADVISORY" || s === "declared_required" || s === "declared_optional") {
96374
+ return chalk.yellow(s);
96375
+ }
96376
+ if (upper === "ABSENT" || s === "no_config" || s === "not_observable_from_server") {
96377
+ return chalk.dim(s);
96378
+ }
96379
+ if (upper === "UNKNOWN" || s === "unknown") return chalk.red(s);
96380
+ if (upper === "PARTIAL") return chalk.yellow(s);
96381
+ return chalk.white(s);
96382
+ }
96383
+ function residualsFromReport(report) {
96384
+ const residuals = [];
96385
+ const legs = report && report.legs || {};
96386
+ const merge = legs.merge;
96387
+ if (merge) {
96388
+ if (merge.enforcing !== true) {
96389
+ residuals.push(`merge:${merge.status || "UNKNOWN"}`);
96390
+ }
96391
+ } else {
96392
+ residuals.push("merge:missing");
96393
+ }
96394
+ const deploy = legs.deploy;
96395
+ if (deploy) {
96396
+ residuals.push(`deploy:${deploy.status || "unknown"}`);
96397
+ } else {
96398
+ residuals.push("deploy:missing");
96399
+ }
96400
+ const runtime = legs.runtime;
96401
+ if (runtime) {
96402
+ residuals.push(`runtime:${runtime.status || "not_observable_from_server"}`);
96403
+ }
96404
+ const content = legs.content;
96405
+ if (content) {
96406
+ residuals.push(`content:${content.status || "not_observable_from_server"}`);
96407
+ }
96408
+ return residuals;
96409
+ }
96410
+ function renderStatusReport(report) {
96411
+ const lines = [];
96412
+ const repo = report && report.repo || "(unknown repo)";
96413
+ const legs = report && report.legs || {};
96414
+ const summary = report && report.summary || {};
96415
+ lines.push(chalk.bold(`CodeRifts enforcement \u2014 ${repo}`));
96416
+ if (report && report.timestamp) {
96417
+ lines.push(chalk.dim(` as of ${report.timestamp}`));
96418
+ }
96419
+ lines.push("");
96420
+ const order = [
96421
+ ["Runtime", legs.runtime],
96422
+ ["Merge", legs.merge],
96423
+ ["Deploy", legs.deploy],
96424
+ ["Content", legs.content]
96425
+ ];
96426
+ for (const [label, leg] of order) {
96427
+ if (!leg) {
96428
+ lines.push(` ${label.padEnd(10)} ${chalk.dim("\u2014")}`);
96429
+ continue;
96430
+ }
96431
+ const statusStr = colorStatus(leg.status);
96432
+ const enforcing = leg.enforcing === true ? chalk.green("enforcing=true") : chalk.dim("enforcing=false");
96433
+ const epi = leg.epistemic_status ? chalk.dim(` [${leg.epistemic_status}]`) : "";
96434
+ lines.push(` ${label.padEnd(10)} ${statusStr} ${enforcing}${epi}`);
96435
+ if (leg.note) {
96436
+ lines.push(chalk.dim(` ${leg.note.slice(0, 100)}${leg.note.length > 100 ? "\u2026" : ""}`));
96437
+ }
96438
+ if (leg.epistemic_note && leg.leg === "deploy") {
96439
+ lines.push(chalk.dim(` ${leg.epistemic_note.slice(0, 100)}\u2026`));
96440
+ }
96441
+ }
96442
+ const residuals = residualsFromReport(report);
96443
+ lines.push("");
96444
+ lines.push(` Residuals: ${residuals.length ? residuals.map((r) => chalk.yellow(r)).join(", ") : chalk.green("(none \u2014 merge enforcing; other legs still not server-observable)")}`);
96445
+ if (summary.status) {
96446
+ lines.push("");
96447
+ lines.push(chalk.dim(` summary.status: ${summary.status}`));
96448
+ if (summary.can_claim_fully_enforced === false) {
96449
+ lines.push(chalk.dim(" can_claim_fully_enforced: false (server ceiling)"));
96450
+ }
96451
+ }
96452
+ lines.push("");
96453
+ lines.push(chalk.dim(" Read-only report. To close gaps:"));
96454
+ lines.push(chalk.dim(" merge \u2192 coderifts setup-required-check"));
96455
+ lines.push(chalk.dim(" deploy \u2192 coderifts deploy-gate --enforce (CD step)"));
96456
+ lines.push(chalk.dim(" runtime/content \u2192 wire @coderifts/agent-guard in the agent host"));
96457
+ return lines.join("\n");
96458
+ }
96459
+ async function runStatus(options = {}, deps = {}) {
96460
+ const getKey = deps.getApiKey || getApiKey;
96461
+ const fetchStatus = deps.cloudGetEnforcementStatus || cloudGetEnforcementStatus;
96462
+ const log = deps.log || console.log;
96463
+ const errLog = deps.errLog || console.error;
96464
+ const repo = options.repo != null && String(options.repo).trim() ? String(options.repo).trim() : null;
96465
+ if (!repo) {
96466
+ errLog(chalk.red("Error: missing repo"));
96467
+ errLog(USAGE);
96468
+ return { exitCode: 1, error: "missing_repo" };
96469
+ }
96470
+ if (!isValidRepo(repo)) {
96471
+ errLog(chalk.red("Error: repo must be in owner/repo form (e.g. coderifts/app)"));
96472
+ return { exitCode: 1, error: "invalid_repo" };
96473
+ }
96474
+ const apiKey = getKey();
96475
+ if (!apiKey) {
96476
+ errLog(chalk.red("Error: no API key. Run `coderifts login` or set CODERIFTS_API_KEY."));
96477
+ return { exitCode: 1, error: "missing_api_key" };
96478
+ }
96479
+ let report;
96480
+ try {
96481
+ report = await fetchStatus(repo, apiKey);
96482
+ } catch (e) {
96483
+ const msg = e && e.message ? String(e.message) : "request failed";
96484
+ errLog(chalk.red(`Error: ${msg}`));
96485
+ if (e && e.code) errLog(chalk.dim(` (${e.code})`));
96486
+ return { exitCode: 1, error: msg };
96487
+ }
96488
+ if (options.json) {
96489
+ log(renderJson(report));
96490
+ } else {
96491
+ log(renderStatusReport(report));
96492
+ }
96493
+ return { exitCode: 0, report };
96494
+ }
96495
+ module2.exports = {
96496
+ runStatus,
96497
+ renderStatusReport,
96498
+ residualsFromReport,
96499
+ colorStatus,
96500
+ isValidRepo,
96501
+ USAGE
96502
+ };
96503
+ }
96504
+ });
96505
+
95191
96506
  // src/commands/hook.js
95192
96507
  var require_hook = __commonJS({
95193
96508
  "src/commands/hook.js"(exports2, module2) {
@@ -95425,6 +96740,8 @@ exit 0
95425
96740
  console.log("After upgrading the coderifts CLI, re-run this command so the installed");
95426
96741
  console.log("hook matches the package (already-installed hooks are not auto-updated):");
95427
96742
  console.log(" coderifts hook install");
96743
+ console.log("");
96744
+ console.log("Agent-using repo? Run: coderifts agent-setup");
95428
96745
  }
95429
96746
  function uninstall() {
95430
96747
  const gitDir = findGitDir();
@@ -95481,6 +96798,437 @@ exit 0
95481
96798
  }
95482
96799
  });
95483
96800
 
96801
+ // src/commands/enforce.js
96802
+ var require_enforce = __commonJS({
96803
+ "src/commands/enforce.js"(exports2, module2) {
96804
+ "use strict";
96805
+ var chalk = require_source();
96806
+ var { getApiKey } = require_config();
96807
+ var { cloudGetEnforcementStatus } = require_cloud();
96808
+ var {
96809
+ renderStatusReport,
96810
+ isValidRepo
96811
+ } = require_status();
96812
+ var { runSetupRequiredCheck } = require_setup_required_check();
96813
+ var path = require("path");
96814
+ var hookMod = require_hook();
96815
+ var hookInstall = hookMod.install;
96816
+ var isCodeRiftsHook = hookMod.isCodeRiftsHook;
96817
+ var findGitDir = hookMod.findGitDir;
96818
+ var getHookPath = typeof hookMod.getHookPath === "function" ? hookMod.getHookPath : (gitDir) => path.join(gitDir, "hooks", "pre-push");
96819
+ if (process.env.NO_COLOR) chalk.level = 0;
96820
+ var USAGE = [
96821
+ "Usage: coderifts enforce --repo owner/repo [--apply]",
96822
+ " or: coderifts enforce owner/repo [--apply]",
96823
+ "",
96824
+ "Cross-layer orchestrator: reads enforcement-status, then closes gaps by calling existing",
96825
+ "setup commands (setup-required-check, hook install, deploy-gate guidance).",
96826
+ "",
96827
+ "DRY-RUN BY DEFAULT \u2014 without --apply, prints what WOULD run and mutates NOTHING.",
96828
+ "With --apply, threads apply into each underlying command (their own safety still applies).",
96829
+ "",
96830
+ "Requires a cloud API key for the status read (coderifts login / CODERIFTS_API_KEY).",
96831
+ "Merge apply uses your local `gh` credentials, not the CodeRifts API key."
96832
+ ].join("\n");
96833
+ var AGENT_GUARD_GUIDANCE = [
96834
+ "Runtime is not_observable_from_server \u2014 wire @coderifts/agent-guard in the agent host:",
96835
+ " - wrap mutating tools with guardToolCall / withCodeRifts",
96836
+ " - see: https://coderifts.com/docs (agent-guard) and `coderifts agent-setup`",
96837
+ " Local pre-push hook is complementary (git path), not a substitute for agent-guard."
96838
+ ].join("\n");
96839
+ var DEPLOY_GUIDANCE = [
96840
+ "Deploy is declared-only on the server (never server-observed ENFORCING).",
96841
+ "Add a CD step that runs: coderifts deploy-gate --env <env> --artifact <id> --receipt <file> --enforce",
96842
+ " (phase-1 default is advisory; --enforce attests ENFORCING for the pipeline).",
96843
+ "Also set policy.require_source_binding: true in .coderifts.yml for the deploy declaration leg."
96844
+ ].join("\n");
96845
+ var CONTENT_GUIDANCE = [
96846
+ "Content/freshness is not_observable_from_server (registry path at resolve time).",
96847
+ "No server-side enforce action is available \u2014 configure registry/freshness in the agent host."
96848
+ ].join("\n");
96849
+ function isMergeEnforcing(leg) {
96850
+ return !!(leg && leg.enforcing === true && String(leg.status).toUpperCase() === "ENFORCING");
96851
+ }
96852
+ function runHookInstall(installFn) {
96853
+ const prev = process.exitCode;
96854
+ process.exitCode = 0;
96855
+ try {
96856
+ installFn();
96857
+ const code = typeof process.exitCode === "number" ? process.exitCode : 0;
96858
+ return {
96859
+ ok: code === 0,
96860
+ detail: code === 0 ? "hook.install completed" : `hook.install set exitCode=${code}`
96861
+ };
96862
+ } catch (e) {
96863
+ return { ok: false, detail: e && e.message || String(e) };
96864
+ } finally {
96865
+ process.exitCode = prev;
96866
+ }
96867
+ }
96868
+ async function runEnforce(options = {}, deps = {}) {
96869
+ const apply = options.apply === true;
96870
+ const getKey = deps.getApiKey || getApiKey;
96871
+ const fetchStatus = deps.cloudGetEnforcementStatus || cloudGetEnforcementStatus;
96872
+ const setupCheck = deps.runSetupRequiredCheck || runSetupRequiredCheck;
96873
+ const installHook = deps.hookInstall || hookInstall;
96874
+ const isHookInstalled = deps.isCodeRiftsHook || isCodeRiftsHook;
96875
+ const findGit = deps.findGitDir || findGitDir;
96876
+ const hookPathOf = deps.getHookPath || getHookPath;
96877
+ const log = deps.log || console.log.bind(console);
96878
+ const errLog = deps.errLog || console.error.bind(console);
96879
+ const repo = options.repo != null && String(options.repo).trim() ? String(options.repo).trim() : null;
96880
+ if (!repo) {
96881
+ errLog(chalk.red("Error: missing repo"));
96882
+ errLog(USAGE);
96883
+ return { exitCode: 1, error: "missing_repo", outcomes: [] };
96884
+ }
96885
+ if (!isValidRepo(repo)) {
96886
+ errLog(chalk.red("Error: repo must be in owner/repo form (e.g. coderifts/app)"));
96887
+ return { exitCode: 1, error: "invalid_repo", outcomes: [] };
96888
+ }
96889
+ const apiKey = getKey();
96890
+ if (!apiKey) {
96891
+ errLog(chalk.red("Error: no API key. Run `coderifts login` or set CODERIFTS_API_KEY."));
96892
+ return { exitCode: 1, error: "missing_api_key", outcomes: [] };
96893
+ }
96894
+ log(chalk.bold(`CodeRifts enforce \u2014 ${repo}`));
96895
+ log(chalk.dim(apply ? " Mode: --apply (will mutate via underlying commands where applicable)" : " Mode: dry-run (default) \u2014 no mutations; showing what WOULD run"));
96896
+ log("");
96897
+ let report;
96898
+ try {
96899
+ report = await fetchStatus(repo, apiKey);
96900
+ } catch (e) {
96901
+ const msg = e && e.message ? String(e.message) : "status request failed";
96902
+ errLog(chalk.red(`Error: ${msg}`));
96903
+ return { exitCode: 1, error: msg, outcomes: [] };
96904
+ }
96905
+ const legs = report && report.legs || {};
96906
+ const outcomes = [];
96907
+ if (isMergeEnforcing(legs.merge)) {
96908
+ outcomes.push({
96909
+ layer: "merge",
96910
+ action: "skip",
96911
+ apply,
96912
+ ok: true,
96913
+ detail: `already ENFORCING (status=${legs.merge.status})`
96914
+ });
96915
+ log(chalk.green(" Merge skip \u2014 already ENFORCING"));
96916
+ } else {
96917
+ const mergeStatus = legs.merge && legs.merge.status || "UNKNOWN";
96918
+ log(chalk.yellow(` Merge ${apply ? "apply" : "dry-run"} \u2014 setup-required-check (current: ${mergeStatus})`));
96919
+ try {
96920
+ const r = await setupCheck(
96921
+ { repo, apply: apply === true },
96922
+ {
96923
+ exit: false,
96924
+ log: deps.setupLog || log,
96925
+ logErr: deps.setupLogErr || errLog,
96926
+ ...deps.setupDeps || {}
96927
+ }
96928
+ );
96929
+ const code = r && typeof r.exitCode === "number" ? r.exitCode : 1;
96930
+ outcomes.push({
96931
+ layer: "merge",
96932
+ action: "setup-required-check",
96933
+ apply,
96934
+ ok: code === 0,
96935
+ exitCode: code,
96936
+ detail: r && r.code ? String(r.code) : `exit ${code}`
96937
+ });
96938
+ if (code !== 0) {
96939
+ errLog(chalk.red(` Merge failed (exit ${code}${r && r.code ? `, ${r.code}` : ""})`));
96940
+ }
96941
+ } catch (e) {
96942
+ outcomes.push({
96943
+ layer: "merge",
96944
+ action: "setup-required-check",
96945
+ apply,
96946
+ ok: false,
96947
+ detail: e && e.message || String(e)
96948
+ });
96949
+ errLog(chalk.red(` Merge error: ${e && e.message || e}`));
96950
+ }
96951
+ }
96952
+ {
96953
+ const gitDir = findGit && findGit();
96954
+ let alreadyHook = false;
96955
+ try {
96956
+ if (gitDir) {
96957
+ const hp = hookPathOf(gitDir);
96958
+ alreadyHook = !!(isHookInstalled && isHookInstalled(hp));
96959
+ }
96960
+ } catch {
96961
+ }
96962
+ if (alreadyHook && apply) {
96963
+ outcomes.push({
96964
+ layer: "runtime",
96965
+ action: "hook.install",
96966
+ apply: true,
96967
+ ok: true,
96968
+ detail: "hook already installed (idempotent skip); not server-observable ENFORCING",
96969
+ server_enforcing: false
96970
+ });
96971
+ log(chalk.green(" Runtime skip \u2014 CodeRifts hook already installed (local)"));
96972
+ } else if (apply) {
96973
+ log(chalk.yellow(" Runtime apply \u2014 hook.install (local; not server ENFORCING)"));
96974
+ const r = runHookInstall(installHook);
96975
+ outcomes.push({
96976
+ layer: "runtime",
96977
+ action: "hook.install",
96978
+ apply: true,
96979
+ ok: r.ok,
96980
+ detail: `${r.detail}; not server-observable ENFORCING`,
96981
+ server_enforcing: false
96982
+ });
96983
+ if (!r.ok) errLog(chalk.red(` Runtime hook install failed: ${r.detail}`));
96984
+ } else {
96985
+ outcomes.push({
96986
+ layer: "runtime",
96987
+ action: "hook.install",
96988
+ apply: false,
96989
+ ok: true,
96990
+ detail: alreadyHook ? "dry-run: hook already present; would re-run install (idempotent)" : "dry-run: would run coderifts hook install",
96991
+ server_enforcing: false
96992
+ });
96993
+ log(chalk.dim(` Runtime dry-run \u2014 would ${alreadyHook ? "re-run" : "run"} hook install (local)`));
96994
+ }
96995
+ log(chalk.dim(AGENT_GUARD_GUIDANCE.split("\n").map((l) => ` ${l}`).join("\n")));
96996
+ }
96997
+ {
96998
+ const st = legs.deploy && legs.deploy.status || "unknown";
96999
+ outcomes.push({
97000
+ layer: "deploy",
97001
+ action: "guidance",
97002
+ apply: false,
97003
+ // never mutates GitHub here
97004
+ ok: true,
97005
+ detail: `server status=${st} (declared-only); print CD step instruction`,
97006
+ server_enforcing: false
97007
+ });
97008
+ log(chalk.dim(` Deploy guidance \u2014 current: ${st} (not server-enforcing)`));
97009
+ log(chalk.dim(DEPLOY_GUIDANCE.split("\n").map((l) => ` ${l}`).join("\n")));
97010
+ }
97011
+ {
97012
+ outcomes.push({
97013
+ layer: "content",
97014
+ action: "guidance",
97015
+ apply: false,
97016
+ ok: true,
97017
+ detail: "not_observable_from_server; guidance only",
97018
+ server_enforcing: false
97019
+ });
97020
+ log(chalk.dim(" Content guidance \u2014 not_observable_from_server"));
97021
+ log(chalk.dim(CONTENT_GUIDANCE.split("\n").map((l) => ` ${l}`).join("\n")));
97022
+ }
97023
+ log("");
97024
+ log(chalk.bold(" Per-layer outcomes"));
97025
+ for (const o of outcomes) {
97026
+ const mark = o.ok ? chalk.green("ok") : chalk.red("FAIL");
97027
+ const mode = o.apply === true ? "apply" : o.action === "skip" ? "skip" : "dry-run";
97028
+ log(` ${String(o.layer).padEnd(8)} ${mark} ${mode.padEnd(7)} ${o.action} ${chalk.dim(o.detail || "")}`);
97029
+ }
97030
+ log("");
97031
+ log(chalk.bold(" Cross-layer report" + (apply ? " (after actions)" : " (current / dry-run)")));
97032
+ let finalReport = report;
97033
+ if (apply) {
97034
+ try {
97035
+ finalReport = await fetchStatus(repo, apiKey);
97036
+ } catch (e) {
97037
+ errLog(chalk.yellow(` Warning: re-fetch status failed: ${e && e.message || e}`));
97038
+ }
97039
+ }
97040
+ if (options.json) {
97041
+ log(JSON.stringify({ command: "enforce", apply, repo, outcomes, report: finalReport }, null, 2));
97042
+ } else {
97043
+ log(renderStatusReport(finalReport));
97044
+ }
97045
+ const anyFail = outcomes.some((o) => o.ok === false);
97046
+ return {
97047
+ exitCode: anyFail ? 1 : 0,
97048
+ apply,
97049
+ outcomes,
97050
+ report: finalReport
97051
+ };
97052
+ }
97053
+ module2.exports = {
97054
+ runEnforce,
97055
+ isMergeEnforcing,
97056
+ USAGE,
97057
+ AGENT_GUARD_GUIDANCE,
97058
+ DEPLOY_GUIDANCE,
97059
+ CONTENT_GUIDANCE
97060
+ };
97061
+ }
97062
+ });
97063
+
97064
+ // src/agent-host-files.embedded.js
97065
+ var require_agent_host_files_embedded = __commonJS({
97066
+ "src/agent-host-files.embedded.js"(exports2, module2) {
97067
+ "use strict";
97068
+ var AGENT_HOST_PATHS = Object.freeze([
97069
+ "AGENTS.md",
97070
+ "CLAUDE.md",
97071
+ ".cursor/rules/coderifts.mdc",
97072
+ ".github/copilot-instructions.md",
97073
+ "coderifts-langgraph-policy.js",
97074
+ "openai-agent-instructions.md"
97075
+ ]);
97076
+ var AGENT_HOST_FILES = Object.freeze({
97077
+ "AGENTS.md": '<!-- GENERATED from CodeRifts agent-host-rule (single source). Do not edit rule sentences by hand; run: node scripts/generate-agent-host-files.js -->\n\n# CodeRifts agent rules\n\nCall `preflight_change_set` before merge, deploy, publish, or tool registration when a contract artifact changed (OpenAPI/Swagger, GraphQL, gRPC/protobuf, AsyncAPI, MCP manifest, or agent tool schemas).\n\nSend the complete base-to-head change set: every changed contract artifact with full before and after content. Do not send a single-file subset when other contract files also change.\n\nBranch on `execution_action` only. Do not branch on `decision` and do not branch on `safe_for_agent` (not_for_control_flow_use_execution_action). Canonical `execution_action` values: CONTINUE, CONTINUE_WITH_MONITORING, REQUEST_APPROVAL, STOP.\n\nAn unrecognised `execution_action` is not permission: fail closed (halt or re-preflight). Well-known code: `not_permission_fail_closed`.\n\n`CONTINUE_WITH_MONITORING` requires a wired monitoring sink (`monitoringSinkWired`). It is not "proceed with caution" without monitoring.\n\nDo not call CodeRifts tools for a documentation-only change (README, guides, comments) with no contract artifact content change.\n\nIf you already hold a chain receipt and only need authenticity/lifecycle: `verify_receipt`. If you need a past decision by id: `get_decision_details`. Neither replaces preflight for a new change set.\n\nFor mutating tools, put only the guarded version in the agent\'s tool table; keep the raw handler host-only and unreachable from that table. How you name tools is yours \u2014 this is a reachability property, not a product rename of host tools. CodeRifts cannot see or stop a raw call the host makes outside the table it returns; adopt this as a host convention, not as a guarantee from the package.\n\nCodeRifts reports a governance decision and `execution_action`; it does not by itself block merges. Blocking requires separate repository configuration (required status checks, enforcement) that this rule file does not set.\n',
97078
+ "CLAUDE.md": '<!-- GENERATED from CodeRifts agent-host-rule (single source). Do not edit rule sentences by hand; run: node scripts/generate-agent-host-files.js -->\n\n# CodeRifts\n\nCall `preflight_change_set` before merge, deploy, publish, or tool registration when a contract artifact changed (OpenAPI/Swagger, GraphQL, gRPC/protobuf, AsyncAPI, MCP manifest, or agent tool schemas).\n\nSend the complete base-to-head change set: every changed contract artifact with full before and after content. Do not send a single-file subset when other contract files also change.\n\nBranch on `execution_action` only. Do not branch on `decision` and do not branch on `safe_for_agent` (not_for_control_flow_use_execution_action). Canonical `execution_action` values: CONTINUE, CONTINUE_WITH_MONITORING, REQUEST_APPROVAL, STOP.\n\nAn unrecognised `execution_action` is not permission: fail closed (halt or re-preflight). Well-known code: `not_permission_fail_closed`.\n\n`CONTINUE_WITH_MONITORING` requires a wired monitoring sink (`monitoringSinkWired`). It is not "proceed with caution" without monitoring.\n\nDo not call CodeRifts tools for a documentation-only change (README, guides, comments) with no contract artifact content change.\n\nIf you already hold a chain receipt and only need authenticity/lifecycle: `verify_receipt`. If you need a past decision by id: `get_decision_details`. Neither replaces preflight for a new change set.\n\nFor mutating tools, put only the guarded version in the agent\'s tool table; keep the raw handler host-only and unreachable from that table. How you name tools is yours \u2014 this is a reachability property, not a product rename of host tools. CodeRifts cannot see or stop a raw call the host makes outside the table it returns; adopt this as a host convention, not as a guarantee from the package.\n\nCodeRifts reports a governance decision and `execution_action`; it does not by itself block merges. Blocking requires separate repository configuration (required status checks, enforcement) that this rule file does not set.\n',
97079
+ ".cursor/rules/coderifts.mdc": '---\ndescription: CodeRifts API governance \u2014 when to preflight and how to branch\nglobs:\nalwaysApply: true\n---\n\n<!-- GENERATED from CodeRifts agent-host-rule (single source). Do not edit rule sentences by hand; run: node scripts/generate-agent-host-files.js -->\n\n# CodeRifts\n\nCall `preflight_change_set` before merge, deploy, publish, or tool registration when a contract artifact changed (OpenAPI/Swagger, GraphQL, gRPC/protobuf, AsyncAPI, MCP manifest, or agent tool schemas).\n\nSend the complete base-to-head change set: every changed contract artifact with full before and after content. Do not send a single-file subset when other contract files also change.\n\nBranch on `execution_action` only. Do not branch on `decision` and do not branch on `safe_for_agent` (not_for_control_flow_use_execution_action). Canonical `execution_action` values: CONTINUE, CONTINUE_WITH_MONITORING, REQUEST_APPROVAL, STOP.\n\nAn unrecognised `execution_action` is not permission: fail closed (halt or re-preflight). Well-known code: `not_permission_fail_closed`.\n\n`CONTINUE_WITH_MONITORING` requires a wired monitoring sink (`monitoringSinkWired`). It is not "proceed with caution" without monitoring.\n\nDo not call CodeRifts tools for a documentation-only change (README, guides, comments) with no contract artifact content change.\n\nIf you already hold a chain receipt and only need authenticity/lifecycle: `verify_receipt`. If you need a past decision by id: `get_decision_details`. Neither replaces preflight for a new change set.\n\nFor mutating tools, put only the guarded version in the agent\'s tool table; keep the raw handler host-only and unreachable from that table. How you name tools is yours \u2014 this is a reachability property, not a product rename of host tools. CodeRifts cannot see or stop a raw call the host makes outside the table it returns; adopt this as a host convention, not as a guarantee from the package.\n\nCodeRifts reports a governance decision and `execution_action`; it does not by itself block merges. Blocking requires separate repository configuration (required status checks, enforcement) that this rule file does not set.\n',
97080
+ ".github/copilot-instructions.md": '<!-- GENERATED from CodeRifts agent-host-rule (single source). Do not edit rule sentences by hand; run: node scripts/generate-agent-host-files.js -->\n\n# CodeRifts instructions for GitHub Copilot\n\nCall `preflight_change_set` before merge, deploy, publish, or tool registration when a contract artifact changed (OpenAPI/Swagger, GraphQL, gRPC/protobuf, AsyncAPI, MCP manifest, or agent tool schemas).\n\nSend the complete base-to-head change set: every changed contract artifact with full before and after content. Do not send a single-file subset when other contract files also change.\n\nBranch on `execution_action` only. Do not branch on `decision` and do not branch on `safe_for_agent` (not_for_control_flow_use_execution_action). Canonical `execution_action` values: CONTINUE, CONTINUE_WITH_MONITORING, REQUEST_APPROVAL, STOP.\n\nAn unrecognised `execution_action` is not permission: fail closed (halt or re-preflight). Well-known code: `not_permission_fail_closed`.\n\n`CONTINUE_WITH_MONITORING` requires a wired monitoring sink (`monitoringSinkWired`). It is not "proceed with caution" without monitoring.\n\nDo not call CodeRifts tools for a documentation-only change (README, guides, comments) with no contract artifact content change.\n\nIf you already hold a chain receipt and only need authenticity/lifecycle: `verify_receipt`. If you need a past decision by id: `get_decision_details`. Neither replaces preflight for a new change set.\n\nFor mutating tools, put only the guarded version in the agent\'s tool table; keep the raw handler host-only and unreachable from that table. How you name tools is yours \u2014 this is a reachability property, not a product rename of host tools. CodeRifts cannot see or stop a raw call the host makes outside the table it returns; adopt this as a host convention, not as a guarantee from the package.\n\nCodeRifts reports a governance decision and `execution_action`; it does not by itself block merges. Blocking requires separate repository configuration (required status checks, enforcement) that this rule file does not set.\n',
97081
+ "coderifts-langgraph-policy.js": '// GENERATED from CodeRifts agent-host-rule (single source). Do not edit rule sentences by hand; run: node scripts/generate-agent-host-files.js\n// System policy string for a LangGraph (or similar) agent. Content is generated;\n// identical rule sentences to AGENTS.md / other formats.\n\'use strict\';\n\nmodule.exports = "Call `preflight_change_set` before merge, deploy, publish, or tool registration when a contract artifact changed (OpenAPI/Swagger, GraphQL, gRPC/protobuf, AsyncAPI, MCP manifest, or agent tool schemas).\\n\\nSend the complete base-to-head change set: every changed contract artifact with full before and after content. Do not send a single-file subset when other contract files also change.\\n\\nBranch on `execution_action` only. Do not branch on `decision` and do not branch on `safe_for_agent` (not_for_control_flow_use_execution_action). Canonical `execution_action` values: CONTINUE, CONTINUE_WITH_MONITORING, REQUEST_APPROVAL, STOP.\\n\\nAn unrecognised `execution_action` is not permission: fail closed (halt or re-preflight). Well-known code: `not_permission_fail_closed`.\\n\\n`CONTINUE_WITH_MONITORING` requires a wired monitoring sink (`monitoringSinkWired`). It is not \\"proceed with caution\\" without monitoring.\\n\\nDo not call CodeRifts tools for a documentation-only change (README, guides, comments) with no contract artifact content change.\\n\\nIf you already hold a chain receipt and only need authenticity/lifecycle: `verify_receipt`. If you need a past decision by id: `get_decision_details`. Neither replaces preflight for a new change set.\\n\\nFor mutating tools, put only the guarded version in the agent\'s tool table; keep the raw handler host-only and unreachable from that table. How you name tools is yours \u2014 this is a reachability property, not a product rename of host tools. CodeRifts cannot see or stop a raw call the host makes outside the table it returns; adopt this as a host convention, not as a guarantee from the package.\\n\\nCodeRifts reports a governance decision and `execution_action`; it does not by itself block merges. Blocking requires separate repository configuration (required status checks, enforcement) that this rule file does not set.";\n',
97082
+ "openai-agent-instructions.md": '<!-- GENERATED from CodeRifts agent-host-rule (single source). Do not edit rule sentences by hand; run: node scripts/generate-agent-host-files.js -->\n\n# CodeRifts agent instructions\n\nCall `preflight_change_set` before merge, deploy, publish, or tool registration when a contract artifact changed (OpenAPI/Swagger, GraphQL, gRPC/protobuf, AsyncAPI, MCP manifest, or agent tool schemas).\n\nSend the complete base-to-head change set: every changed contract artifact with full before and after content. Do not send a single-file subset when other contract files also change.\n\nBranch on `execution_action` only. Do not branch on `decision` and do not branch on `safe_for_agent` (not_for_control_flow_use_execution_action). Canonical `execution_action` values: CONTINUE, CONTINUE_WITH_MONITORING, REQUEST_APPROVAL, STOP.\n\nAn unrecognised `execution_action` is not permission: fail closed (halt or re-preflight). Well-known code: `not_permission_fail_closed`.\n\n`CONTINUE_WITH_MONITORING` requires a wired monitoring sink (`monitoringSinkWired`). It is not "proceed with caution" without monitoring.\n\nDo not call CodeRifts tools for a documentation-only change (README, guides, comments) with no contract artifact content change.\n\nIf you already hold a chain receipt and only need authenticity/lifecycle: `verify_receipt`. If you need a past decision by id: `get_decision_details`. Neither replaces preflight for a new change set.\n\nFor mutating tools, put only the guarded version in the agent\'s tool table; keep the raw handler host-only and unreachable from that table. How you name tools is yours \u2014 this is a reachability property, not a product rename of host tools. CodeRifts cannot see or stop a raw call the host makes outside the table it returns; adopt this as a host convention, not as a guarantee from the package.\n\nCodeRifts reports a governance decision and `execution_action`; it does not by itself block merges. Blocking requires separate repository configuration (required status checks, enforcement) that this rule file does not set.\n'
97083
+ });
97084
+ module2.exports = { AGENT_HOST_FILES, AGENT_HOST_PATHS };
97085
+ }
97086
+ });
97087
+
97088
+ // src/commands/agent-setup.js
97089
+ var require_agent_setup = __commonJS({
97090
+ "src/commands/agent-setup.js"(exports2, module2) {
97091
+ "use strict";
97092
+ var fs = require("fs");
97093
+ var path = require("path");
97094
+ var chalk = require_source();
97095
+ var { AGENT_HOST_FILES, AGENT_HOST_PATHS } = require_agent_host_files_embedded();
97096
+ if (process.env.NO_COLOR) chalk.level = 0;
97097
+ var USAGE = `Usage: coderifts agent-setup [--out <dir>] [--check] [--force]
97098
+
97099
+ --out <dir> Target directory (default: current working directory)
97100
+ --check Exit 0 if on-disk files match embedded content; exit 1 on drift
97101
+ --force Overwrite existing files (default: skip collisions)
97102
+ Unknown flags exit 1 (never silently ignored).
97103
+ `;
97104
+ function parseAgentSetupArgs(argv) {
97105
+ const args = argv.slice(2);
97106
+ let out = null;
97107
+ let check = false;
97108
+ let force = false;
97109
+ let i = 0;
97110
+ while (i < args.length && !String(args[i]).startsWith("-")) i += 1;
97111
+ while (i < args.length) {
97112
+ const a = args[i];
97113
+ if (a === "--out") {
97114
+ const v = args[i + 1];
97115
+ if (v == null || v.startsWith("-")) {
97116
+ return { out, check, force, error: `agent-setup: --out requires a path
97117
+ ${USAGE}` };
97118
+ }
97119
+ out = path.resolve(v);
97120
+ i += 2;
97121
+ continue;
97122
+ }
97123
+ if (a === "--check") {
97124
+ check = true;
97125
+ i += 1;
97126
+ continue;
97127
+ }
97128
+ if (a === "--force") {
97129
+ force = true;
97130
+ i += 1;
97131
+ continue;
97132
+ }
97133
+ if (a.startsWith("-")) {
97134
+ return { out, check, force, error: `agent-setup: unrecognized argument: ${a}
97135
+ ${USAGE}` };
97136
+ }
97137
+ return { out, check, force, error: `agent-setup: unrecognized argument: ${a}
97138
+ ${USAGE}` };
97139
+ }
97140
+ return { out, check, force };
97141
+ }
97142
+ function runAgentSetup(options = {}, deps = {}) {
97143
+ const log = deps.log || console.log.bind(console);
97144
+ const logErr = deps.logErr || console.error.bind(console);
97145
+ const doExit = deps.exit !== false;
97146
+ const cwd = deps.cwd || process.cwd();
97147
+ const exists = deps.exists || fs.existsSync.bind(fs);
97148
+ const readFile = deps.readFile || ((p) => fs.readFileSync(p, "utf8"));
97149
+ const writeFile = deps.writeFile || ((p, c) => {
97150
+ fs.mkdirSync(path.dirname(p), { recursive: true });
97151
+ fs.writeFileSync(p, c, "utf8");
97152
+ });
97153
+ let outDir = options.out ? path.resolve(String(options.out)) : cwd;
97154
+ let check = !!options.check;
97155
+ let force = !!options.force;
97156
+ if (deps.argv) {
97157
+ const parsed = parseAgentSetupArgs(deps.argv);
97158
+ if (parsed.error) {
97159
+ logErr(parsed.error.trimEnd());
97160
+ if (doExit) process.exit(1);
97161
+ return { exitCode: 1, code: "USAGE", message: parsed.error };
97162
+ }
97163
+ if (parsed.out) outDir = parsed.out;
97164
+ check = parsed.check;
97165
+ force = parsed.force;
97166
+ }
97167
+ const files = deps.files || AGENT_HOST_FILES;
97168
+ const relPaths = deps.paths || AGENT_HOST_PATHS;
97169
+ if (check) {
97170
+ let stale = false;
97171
+ for (const rel of relPaths) {
97172
+ const fp = path.join(outDir, rel);
97173
+ const expected = files[rel];
97174
+ if (!exists(fp)) {
97175
+ logErr(chalk.red(`agent-setup --check: missing ${rel}`));
97176
+ stale = true;
97177
+ continue;
97178
+ }
97179
+ const onDisk = readFile(fp);
97180
+ if (onDisk !== expected) {
97181
+ logErr(chalk.red(`agent-setup --check: drift ${rel}`));
97182
+ stale = true;
97183
+ }
97184
+ }
97185
+ if (stale) {
97186
+ logErr("Run: coderifts agent-setup --out " + outDir + " --force");
97187
+ if (doExit) process.exit(1);
97188
+ return { exitCode: 1, code: "DRIFT", outDir };
97189
+ }
97190
+ log(chalk.green(`agent-setup: up to date (${outDir}, ${relPaths.length} files)`));
97191
+ if (doExit) process.exit(0);
97192
+ return { exitCode: 0, code: "UP_TO_DATE", outDir };
97193
+ }
97194
+ const summary = { written: [], skipped: [], forced: [] };
97195
+ for (const rel of relPaths) {
97196
+ const fp = path.join(outDir, rel);
97197
+ const content = files[rel];
97198
+ if (exists(fp) && !force) {
97199
+ summary.skipped.push(rel);
97200
+ continue;
97201
+ }
97202
+ if (exists(fp) && force) summary.forced.push(rel);
97203
+ writeFile(fp, content);
97204
+ summary.written.push(rel);
97205
+ }
97206
+ if (!options.json) {
97207
+ log(chalk.bold("CodeRifts agent-setup"));
97208
+ log(` target: ${outDir}`);
97209
+ for (const rel of summary.written) {
97210
+ const tag = summary.forced.includes(rel) ? "overwrote" : "wrote";
97211
+ log(chalk.green(` ${tag}: ${rel}`));
97212
+ }
97213
+ for (const rel of summary.skipped) {
97214
+ log(chalk.yellow(` skipped: ${rel} (exists; use --force to overwrite)`));
97215
+ }
97216
+ log("");
97217
+ log(chalk.dim(` ${summary.written.length} written, ${summary.skipped.length} skipped`));
97218
+ }
97219
+ if (doExit) process.exit(0);
97220
+ return { exitCode: 0, code: "OK", outDir, ...summary };
97221
+ }
97222
+ module2.exports = {
97223
+ runAgentSetup,
97224
+ parseAgentSetupArgs,
97225
+ AGENT_HOST_FILES,
97226
+ AGENT_HOST_PATHS,
97227
+ USAGE
97228
+ };
97229
+ }
97230
+ });
97231
+
95484
97232
  // corpus/vectors-mcp-fpfn.json
95485
97233
  var require_vectors_mcp_fpfn = __commonJS({
95486
97234
  "corpus/vectors-mcp-fpfn.json"(exports2, module2) {
@@ -97380,6 +99128,18 @@ program.command("publish-gate").description("Gate npm publish on contract-artifa
97380
99128
  process.exitCode = code;
97381
99129
  process.exit(code);
97382
99130
  });
99131
+ program.command("registry-gate [dir]").description("Admit a directory of OpenAPI specs via local registry validation (CI gate, no cloud)").option("--glob <pattern>", "Filter discovered paths with agent-guard matchGlob (relative to dir)").option("--errors-only", "Fail only on ERROR severity (warnings are printed, exit 0)").option("--warn-only", "Advisory: print all findings, always exit 0").action((dir, options) => {
99132
+ const { runRegistryGate } = require_registry_gate();
99133
+ const result = runRegistryGate({
99134
+ dir: dir || ".",
99135
+ glob: options.glob,
99136
+ errorsOnly: !!options.errorsOnly,
99137
+ warnOnly: !!options.warnOnly
99138
+ });
99139
+ const code = result && typeof result.exitCode === "number" ? result.exitCode : 1;
99140
+ process.exitCode = code;
99141
+ process.exit(code);
99142
+ });
97383
99143
  program.command("init [template]").description("Generate a .coderifts.yml from a policy template (startup, growth, fintech, public-api, microservices)").action(async (template) => {
97384
99144
  const { init } = require_init();
97385
99145
  await init(template);
@@ -97388,6 +99148,38 @@ program.command("login").description("Save your API key for cloud features").act
97388
99148
  const { login } = require_login();
97389
99149
  await login();
97390
99150
  });
99151
+ program.command("setup-required-check").description('Guide setup of required status check "CodeRifts / contract-gate" (uses gh, your credentials)').option("--branch <name>", "Branch to protect (default: repo default branch)").option("--repo <owner/repo>", "Override owner/repo (default: git remote origin)").option("--apply", "Apply the protection change (default: print the exact gh command only)").option("--json", "Machine-readable JSON result").action(async (options) => {
99152
+ const { runSetupRequiredCheck } = require_setup_required_check();
99153
+ const result = await runSetupRequiredCheck(options);
99154
+ if (result && typeof result.exitCode === "number") {
99155
+ process.exitCode = result.exitCode;
99156
+ }
99157
+ });
99158
+ program.command("status [repo]").description("Show cross-layer enforcement status (Runtime / Merge / Deploy) for a repo \u2014 read-only").option("--repo <owner/repo>", "Repository (owner/repo); also accepted as a positional argument").option("--json", "Machine-readable JSON (raw API body)").action(async (repoPositional, options) => {
99159
+ const { runStatus } = require_status();
99160
+ const result = await runStatus({
99161
+ ...options,
99162
+ repo: options.repo || repoPositional || null
99163
+ });
99164
+ if (result && typeof result.exitCode === "number") {
99165
+ process.exitCode = result.exitCode;
99166
+ }
99167
+ });
99168
+ program.command("enforce [repo]").description("Close enforcement gaps by chaining setup-required-check / hook / deploy guidance (dry-run default; use --apply to mutate)").option("--repo <owner/repo>", "Repository (owner/repo); also accepted as a positional argument").option("--apply", "Actually run underlying setup commands (default: dry-run only)").option("--json", "Machine-readable JSON result").action(async (repoPositional, options) => {
99169
+ const { runEnforce } = require_enforce();
99170
+ const result = await runEnforce({
99171
+ ...options,
99172
+ repo: options.repo || repoPositional || null,
99173
+ apply: !!options.apply
99174
+ });
99175
+ if (result && typeof result.exitCode === "number") {
99176
+ process.exitCode = result.exitCode;
99177
+ }
99178
+ });
99179
+ program.command("agent-setup").description("Write AGENTS.md / CLAUDE.md / Cursor / Copilot / LangGraph / OpenAI agent rule files").option("--out <dir>", "Target directory (default: current working directory)").option("--check", "Exit 0 if on-disk files match embedded content; exit 1 on drift").option("--force", "Overwrite existing files (default: skip collisions)").action((options) => {
99180
+ const { runAgentSetup } = require_agent_setup();
99181
+ runAgentSetup(options, { exit: true });
99182
+ });
97391
99183
  var hookCmd = program.command("hook").description("Manage the CodeRifts pre-push Git hook");
97392
99184
  hookCmd.command("install").description("Install the CodeRifts pre-push hook in the current Git repo").action(() => {
97393
99185
  const { install } = require_hook();