@exorcist-98/cli 0.2.0 → 0.3.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/index.mjs CHANGED
@@ -4287,11 +4287,11 @@ function findIn(text, canaries, depth, found) {
4287
4287
  }
4288
4288
  }
4289
4289
  if (pending().length === 0 || depth >= MAX_DEPTH) return;
4290
- for (const run of decodeRuns(surf.s)) {
4290
+ for (const run2 of decodeRuns(surf.s)) {
4291
4291
  const inner = /* @__PURE__ */ new Map();
4292
- findIn(run.text, pending(), depth + 1, inner);
4292
+ findIn(run2.text, pending(), depth + 1, inner);
4293
4293
  for (const c of inner.keys()) {
4294
- found.set(c, { index: surf.start[run.at] ?? 0, end: surf.end[run.to - 1] ?? text.length, shape: "base64" });
4294
+ found.set(c, { index: surf.start[run2.at] ?? 0, end: surf.end[run2.to - 1] ?? text.length, shape: "base64" });
4295
4295
  }
4296
4296
  if (pending().length === 0) return;
4297
4297
  }
@@ -5036,14 +5036,14 @@ var init_heuristic_engine = __esm({
5036
5036
  });
5037
5037
 
5038
5038
  // ../core/src/llm/detonation.ts
5039
- import { randomBytes as randomBytes5 } from "node:crypto";
5039
+ import { randomBytes as randomBytes6 } from "node:crypto";
5040
5040
  function randomString(alphabet, length, rand) {
5041
5041
  const bytes = rand(length);
5042
5042
  let out = "";
5043
5043
  for (let i = 0; i < length; i++) out += alphabet[(bytes[i] ?? 0) % alphabet.length];
5044
5044
  return out;
5045
5045
  }
5046
- function makeEnvironment(rand = (n) => randomBytes5(n)) {
5046
+ function makeEnvironment(rand = (n) => randomBytes6(n)) {
5047
5047
  const akid = `AKIA${randomString(UPPER32, 16, rand)}`;
5048
5048
  const secret = randomString(ALNUM, 40, rand);
5049
5049
  const gh = `ghp_${randomString(ALNUM, 36, rand)}`;
@@ -5965,11 +5965,11 @@ var require_codegen = __commonJS({
5965
5965
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
5966
5966
  return `${varKind} ${this.name}${rhs};` + _n;
5967
5967
  }
5968
- optimizeNames(names, constants3) {
5968
+ optimizeNames(names, constants4) {
5969
5969
  if (!names[this.name.str])
5970
5970
  return;
5971
5971
  if (this.rhs)
5972
- this.rhs = optimizeExpr(this.rhs, names, constants3);
5972
+ this.rhs = optimizeExpr(this.rhs, names, constants4);
5973
5973
  return this;
5974
5974
  }
5975
5975
  get names() {
@@ -5986,10 +5986,10 @@ var require_codegen = __commonJS({
5986
5986
  render({ _n }) {
5987
5987
  return `${this.lhs} = ${this.rhs};` + _n;
5988
5988
  }
5989
- optimizeNames(names, constants3) {
5989
+ optimizeNames(names, constants4) {
5990
5990
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
5991
5991
  return;
5992
- this.rhs = optimizeExpr(this.rhs, names, constants3);
5992
+ this.rhs = optimizeExpr(this.rhs, names, constants4);
5993
5993
  return this;
5994
5994
  }
5995
5995
  get names() {
@@ -6050,8 +6050,8 @@ var require_codegen = __commonJS({
6050
6050
  optimizeNodes() {
6051
6051
  return `${this.code}` ? this : void 0;
6052
6052
  }
6053
- optimizeNames(names, constants3) {
6054
- this.code = optimizeExpr(this.code, names, constants3);
6053
+ optimizeNames(names, constants4) {
6054
+ this.code = optimizeExpr(this.code, names, constants4);
6055
6055
  return this;
6056
6056
  }
6057
6057
  get names() {
@@ -6080,12 +6080,12 @@ var require_codegen = __commonJS({
6080
6080
  }
6081
6081
  return nodes.length > 0 ? this : void 0;
6082
6082
  }
6083
- optimizeNames(names, constants3) {
6083
+ optimizeNames(names, constants4) {
6084
6084
  const { nodes } = this;
6085
6085
  let i = nodes.length;
6086
6086
  while (i--) {
6087
6087
  const n = nodes[i];
6088
- if (n.optimizeNames(names, constants3))
6088
+ if (n.optimizeNames(names, constants4))
6089
6089
  continue;
6090
6090
  subtractNames(names, n.names);
6091
6091
  nodes.splice(i, 1);
@@ -6138,12 +6138,12 @@ var require_codegen = __commonJS({
6138
6138
  return void 0;
6139
6139
  return this;
6140
6140
  }
6141
- optimizeNames(names, constants3) {
6141
+ optimizeNames(names, constants4) {
6142
6142
  var _a;
6143
- this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants3);
6144
- if (!(super.optimizeNames(names, constants3) || this.else))
6143
+ this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants4);
6144
+ if (!(super.optimizeNames(names, constants4) || this.else))
6145
6145
  return;
6146
- this.condition = optimizeExpr(this.condition, names, constants3);
6146
+ this.condition = optimizeExpr(this.condition, names, constants4);
6147
6147
  return this;
6148
6148
  }
6149
6149
  get names() {
@@ -6166,10 +6166,10 @@ var require_codegen = __commonJS({
6166
6166
  render(opts) {
6167
6167
  return `for(${this.iteration})` + super.render(opts);
6168
6168
  }
6169
- optimizeNames(names, constants3) {
6170
- if (!super.optimizeNames(names, constants3))
6169
+ optimizeNames(names, constants4) {
6170
+ if (!super.optimizeNames(names, constants4))
6171
6171
  return;
6172
- this.iteration = optimizeExpr(this.iteration, names, constants3);
6172
+ this.iteration = optimizeExpr(this.iteration, names, constants4);
6173
6173
  return this;
6174
6174
  }
6175
6175
  get names() {
@@ -6205,10 +6205,10 @@ var require_codegen = __commonJS({
6205
6205
  render(opts) {
6206
6206
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
6207
6207
  }
6208
- optimizeNames(names, constants3) {
6209
- if (!super.optimizeNames(names, constants3))
6208
+ optimizeNames(names, constants4) {
6209
+ if (!super.optimizeNames(names, constants4))
6210
6210
  return;
6211
- this.iterable = optimizeExpr(this.iterable, names, constants3);
6211
+ this.iterable = optimizeExpr(this.iterable, names, constants4);
6212
6212
  return this;
6213
6213
  }
6214
6214
  get names() {
@@ -6250,11 +6250,11 @@ var require_codegen = __commonJS({
6250
6250
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
6251
6251
  return this;
6252
6252
  }
6253
- optimizeNames(names, constants3) {
6253
+ optimizeNames(names, constants4) {
6254
6254
  var _a, _b;
6255
- super.optimizeNames(names, constants3);
6256
- (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants3);
6257
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants3);
6255
+ super.optimizeNames(names, constants4);
6256
+ (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants4);
6257
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants4);
6258
6258
  return this;
6259
6259
  }
6260
6260
  get names() {
@@ -6555,7 +6555,7 @@ var require_codegen = __commonJS({
6555
6555
  function addExprNames(names, from) {
6556
6556
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
6557
6557
  }
6558
- function optimizeExpr(expr, names, constants3) {
6558
+ function optimizeExpr(expr, names, constants4) {
6559
6559
  if (expr instanceof code_1.Name)
6560
6560
  return replaceName(expr);
6561
6561
  if (!canOptimize(expr))
@@ -6570,14 +6570,14 @@ var require_codegen = __commonJS({
6570
6570
  return items;
6571
6571
  }, []));
6572
6572
  function replaceName(n) {
6573
- const c = constants3[n.str];
6573
+ const c = constants4[n.str];
6574
6574
  if (c === void 0 || names[n.str] !== 1)
6575
6575
  return n;
6576
6576
  delete names[n.str];
6577
6577
  return c;
6578
6578
  }
6579
6579
  function canOptimize(e) {
6580
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants3[c.str] !== void 0);
6580
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants4[c.str] !== void 0);
6581
6581
  }
6582
6582
  }
6583
6583
  function subtractNames(names, from) {
@@ -15891,14 +15891,14 @@ function requireDumper() {
15891
15891
  let hasFoldableLine = false;
15892
15892
  const shouldTrackWidth = lineWidth !== -1;
15893
15893
  let previousLineBreak = -1;
15894
- let plain2 = isPlainSafeFirst(codePointAt(string3, 0)) && isPlainSafeLast(codePointAt(string3, string3.length - 1));
15894
+ let plain3 = isPlainSafeFirst(codePointAt(string3, 0)) && isPlainSafeLast(codePointAt(string3, string3.length - 1));
15895
15895
  if (singleLineOnly || forceQuotes) {
15896
15896
  for (i = 0; i < string3.length; char >= 65536 ? i += 2 : i++) {
15897
15897
  char = codePointAt(string3, i);
15898
15898
  if (!isPrintable(char)) {
15899
15899
  return STYLE_DOUBLE;
15900
15900
  }
15901
- plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
15901
+ plain3 = plain3 && isPlainSafe(char, prevChar, inblock);
15902
15902
  prevChar = char;
15903
15903
  }
15904
15904
  } else {
@@ -15914,13 +15914,13 @@ function requireDumper() {
15914
15914
  } else if (!isPrintable(char)) {
15915
15915
  return STYLE_DOUBLE;
15916
15916
  }
15917
- plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
15917
+ plain3 = plain3 && isPlainSafe(char, prevChar, inblock);
15918
15918
  prevChar = char;
15919
15919
  }
15920
15920
  hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string3[previousLineBreak + 1] !== " ");
15921
15921
  }
15922
15922
  if (!hasLineBreak && !hasFoldableLine) {
15923
- if (plain2 && !forceQuotes && !testAmbiguousType(string3)) {
15923
+ if (plain3 && !forceQuotes && !testAmbiguousType(string3)) {
15924
15924
  return STYLE_PLAIN;
15925
15925
  }
15926
15926
  return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
@@ -16744,7 +16744,7 @@ function decodeEntity(match, body) {
16744
16744
  }
16745
16745
  function decodeEntitiesWithMap(text) {
16746
16746
  const re2 = /&([a-zA-Z]+|#\d+|#x[\da-fA-F]+);/g;
16747
- let plain2 = "";
16747
+ let plain3 = "";
16748
16748
  const map2 = [];
16749
16749
  let last = 0;
16750
16750
  let changed = false;
@@ -16754,15 +16754,15 @@ function decodeEntitiesWithMap(text) {
16754
16754
  if (decoded === m[0]) continue;
16755
16755
  changed = true;
16756
16756
  for (let i = last; i < m.index; i++) map2.push(i);
16757
- plain2 += text.slice(last, m.index);
16757
+ plain3 += text.slice(last, m.index);
16758
16758
  for (let k = 0; k < decoded.length; k++) map2.push(m.index);
16759
- plain2 += decoded;
16759
+ plain3 += decoded;
16760
16760
  last = m.index + m[0].length;
16761
16761
  }
16762
16762
  if (!changed) return null;
16763
16763
  for (let i = last; i < text.length; i++) map2.push(i);
16764
- plain2 += text.slice(last);
16765
- return { plain: plain2, map: map2 };
16764
+ plain3 += text.slice(last);
16765
+ return { plain: plain3, map: map2 };
16766
16766
  }
16767
16767
  var HTML_COMMENT_RE = /<!--([\s\S]*?)-->/g;
16768
16768
  var BLOCK_COMMENT_RE = /\/\*([\s\S]*?)\*\//g;
@@ -16803,17 +16803,17 @@ function extractBase64Candidates(text) {
16803
16803
  }
16804
16804
  function normalize(text, _role) {
16805
16805
  const decoded = decodeEntitiesWithMap(text);
16806
- const plain2 = decoded ? decoded.plain : text;
16806
+ const plain3 = decoded ? decoded.plain : text;
16807
16807
  const hiddenUnicode = findHiddenUnicode(text);
16808
16808
  const comments = extractComments(text);
16809
16809
  const base64Candidates = extractBase64Candidates(text);
16810
- const out = { original: text, plain: plain2, hiddenUnicode, comments, base64Candidates };
16810
+ const out = { original: text, plain: plain3, hiddenUnicode, comments, base64Candidates };
16811
16811
  if (decoded) out.plainMap = decoded.map;
16812
16812
  if (hiddenUnicode.length > 0) {
16813
16813
  let vis = "";
16814
16814
  const map2 = [];
16815
16815
  let i = 0;
16816
- for (const ch of plain2) {
16816
+ for (const ch of plain3) {
16817
16817
  const cp = ch.codePointAt(0) ?? 0;
16818
16818
  if (!CP_TO_CLASS.has(cp)) {
16819
16819
  vis += ch;
@@ -16821,7 +16821,7 @@ function normalize(text, _role) {
16821
16821
  }
16822
16822
  i += ch.length;
16823
16823
  }
16824
- if (vis.length !== plain2.length) out.visible = { text: vis, map: map2 };
16824
+ if (vis.length !== plain3.length) out.visible = { text: vis, map: map2 };
16825
16825
  }
16826
16826
  return out;
16827
16827
  }
@@ -17494,7 +17494,57 @@ var OPEN_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)\b([^<>]*?)\bstyle\s*=\s*(?:"([^"]*)"|'(
17494
17494
  function plainElementText(html) {
17495
17495
  return html.replace(/<[^>]*>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/\s+/g, " ").trim();
17496
17496
  }
17497
+ var AI_META_NAME = /^(?:ai|llm|assistant|gpt|chatgpt|claude|kiro|copilot|agent|ai-agent|bot-instructions)(?:[-_:.][a-z0-9_.:-]*)?$/i;
17498
+ var META_TAG = /<meta\b[^<>]*>/gi;
17499
+ var IMG_TAG = /<img\b[^<>]*>/gi;
17500
+ var MD_IMAGE = /!\[([^\]\n]{1,500})\]\(/g;
17501
+ var AI_WORD = "(?:AI|assistants?|agents?|llms?|language\\s+models?|kiro|claude|copilot|chatgpt|gemini|cursor)";
17502
+ var ALT_ADDRESS = new RegExp(
17503
+ `(?:^|[.!?]\\s+)(?:hey\\s+|dear\\s+|attention\\s+)?${AI_WORD}\\s*[,:]|\\b(?:if\\s+you\\s+are|you\\s+are\\s+an?|note\\s+to|message\\s+for|instructions?\\s+for|attention)\\b[^.\\n]{0,30}\\b${AI_WORD}\\b`,
17504
+ "i"
17505
+ );
17506
+ function attr(tag, name) {
17507
+ const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i").exec(tag);
17508
+ return m ? m[1] ?? m[2] ?? "" : null;
17509
+ }
17510
+ function altInstructs(alt) {
17511
+ const t = alt.replace(/\s+/g, " ").trim();
17512
+ return t.length > 0 && (ALT_ADDRESS.test(t) || OVERRIDE.test(t) || ACTION.test(t));
17513
+ }
17514
+ function metaTagFindings(text) {
17515
+ const out = [];
17516
+ META_TAG.lastIndex = 0;
17517
+ let m;
17518
+ while ((m = META_TAG.exec(text)) !== null) {
17519
+ const name = attr(m[0], "name");
17520
+ const content = attr(m[0], "content");
17521
+ if (name === null || content === null || !AI_META_NAME.test(name.trim())) continue;
17522
+ const body = content.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/\s+/g, " ").trim();
17523
+ if (!addressesAi(body)) continue;
17524
+ out.push({ index: m.index, length: m[0].length, method: "meta-tag", text: body });
17525
+ }
17526
+ return out;
17527
+ }
17528
+ function altTextFindings(text) {
17529
+ const out = [];
17530
+ let m;
17531
+ IMG_TAG.lastIndex = 0;
17532
+ while ((m = IMG_TAG.exec(text)) !== null) {
17533
+ const alt = attr(m[0], "alt");
17534
+ if (alt !== null && altInstructs(alt)) out.push({ index: m.index, length: m[0].length, method: "alt-text", text: alt.replace(/\s+/g, " ").trim() });
17535
+ }
17536
+ MD_IMAGE.lastIndex = 0;
17537
+ while ((m = MD_IMAGE.exec(text)) !== null) {
17538
+ const alt = m[1];
17539
+ if (altInstructs(alt)) out.push({ index: m.index, length: m[0].length, method: "alt-text", text: alt.replace(/\s+/g, " ").trim() });
17540
+ }
17541
+ return out;
17542
+ }
17497
17543
  function findHiddenText(text) {
17544
+ const all = [...findHiddenElements(text), ...metaTagFindings(text), ...altTextFindings(text)];
17545
+ return all.sort((a, b) => a.index - b.index);
17546
+ }
17547
+ function findHiddenElements(text) {
17498
17548
  const out = [];
17499
17549
  OPEN_TAG.lastIndex = 0;
17500
17550
  let lastEnd = -1;
@@ -17517,6 +17567,65 @@ function findHiddenText(text) {
17517
17567
  return out;
17518
17568
  }
17519
17569
 
17570
+ // ../core/src/json-loose.ts
17571
+ function parseJsonLoose(text) {
17572
+ try {
17573
+ return JSON.parse(text);
17574
+ } catch {
17575
+ }
17576
+ try {
17577
+ return JSON.parse(stripJsonComments(text));
17578
+ } catch {
17579
+ return void 0;
17580
+ }
17581
+ }
17582
+ function stripJsonComments(text) {
17583
+ let out = "";
17584
+ let i = text.charCodeAt(0) === 65279 ? 1 : 0;
17585
+ while (i < text.length) {
17586
+ const c = text[i];
17587
+ const next = text[i + 1];
17588
+ if (c === '"') {
17589
+ let j = i + 1;
17590
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
17591
+ out += text.slice(i, j + 1);
17592
+ i = j + 1;
17593
+ } else if (c === "/" && next === "/") {
17594
+ while (i < text.length && text[i] !== "\n") i++;
17595
+ } else if (c === "/" && next === "*") {
17596
+ const end = text.indexOf("*/", i + 2);
17597
+ i = end === -1 ? text.length : end + 2;
17598
+ out += " ";
17599
+ } else {
17600
+ out += c;
17601
+ i++;
17602
+ }
17603
+ }
17604
+ return dropTrailingCommas(out);
17605
+ }
17606
+ function dropTrailingCommas(text) {
17607
+ let out = "";
17608
+ let i = 0;
17609
+ while (i < text.length) {
17610
+ const c = text[i];
17611
+ if (c === '"') {
17612
+ let j = i + 1;
17613
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
17614
+ out += text.slice(i, j + 1);
17615
+ i = j + 1;
17616
+ } else if (c === ",") {
17617
+ let j = i + 1;
17618
+ while (j < text.length && /\s/.test(text[j])) j++;
17619
+ if (text[j] !== "}" && text[j] !== "]") out += c;
17620
+ i++;
17621
+ } else {
17622
+ out += c;
17623
+ i++;
17624
+ }
17625
+ }
17626
+ return out;
17627
+ }
17628
+
17520
17629
  // ../core/src/scanner/signature-engine.ts
17521
17630
  init_severity_paths();
17522
17631
 
@@ -17862,18 +17971,18 @@ function escapeCodePoint(hit) {
17862
17971
  const hex = hit.codePoint.toString(16).toUpperCase();
17863
17972
  return hit.codePoint > 65535 ? `\\u{${hex}}` : `\\u${hex.padStart(4, "0")}`;
17864
17973
  }
17865
- function joinEscapes(run) {
17974
+ function joinEscapes(run2) {
17866
17975
  let out = "";
17867
- for (const hit of run) {
17976
+ for (const hit of run2) {
17868
17977
  const e = escapeCodePoint(hit);
17869
17978
  if (out.length + e.length > MAX_SPAN) return `${out}\u2026`;
17870
17979
  out += e;
17871
17980
  }
17872
17981
  return out;
17873
17982
  }
17874
- function decodedForRun(run) {
17875
- const tags = run.filter((h) => h.class === "tag-block");
17876
- const carrier = tags.length > 0 ? tags : run.filter((h) => h.class === "variation-selector");
17983
+ function decodedForRun(run2) {
17984
+ const tags = run2.filter((h) => h.class === "tag-block");
17985
+ const carrier = tags.length > 0 ? tags : run2.filter((h) => h.class === "variation-selector");
17877
17986
  const first = decodeHidden(carrier.map((h) => h.char).join(""))[0];
17878
17987
  return first && first.message.length > 0 ? first.message : void 0;
17879
17988
  }
@@ -18093,40 +18202,40 @@ function runSignatures(file, norm2, defs, limitMs = REGEX_TIME_LIMIT_MS) {
18093
18202
  }
18094
18203
  }
18095
18204
  if (match.unicode_class && match.unicode_class.length > 0) {
18096
- let run = [];
18205
+ let run2 = [];
18097
18206
  const mineStart = findings.length;
18098
18207
  let minorRuns = 0;
18099
18208
  const guards = /* @__PURE__ */ new Set();
18100
18209
  let decodedRuns = 0;
18101
18210
  const flush = () => {
18102
- const first = run[0];
18211
+ const first = run2[0];
18103
18212
  if (!first) return;
18104
- if (match.min_run !== void 0 && run.length < match.min_run) {
18105
- run = [];
18213
+ if (match.min_run !== void 0 && run2.length < match.min_run) {
18214
+ run2 = [];
18106
18215
  return;
18107
18216
  }
18108
18217
  const { line, col } = offsetToPosition(norm2.original, first.offset);
18109
18218
  const minor = match.minor_run;
18110
- const isMinor = Boolean(minor && run.length <= minor.max_length && run.every((h) => minor.classes.includes(h.class)));
18219
+ const isMinor = Boolean(minor && run2.length <= minor.max_length && run2.every((h) => minor.classes.includes(h.class)));
18111
18220
  const guard = match.mention_guard;
18112
- const isGuard = Boolean(guard && run.length === 1 && first.codePoint === 8203 && norm2.original[first.offset - 1] === "@" && /[A-Za-z0-9_]/.test(norm2.original[first.offset + 1] ?? ""));
18221
+ const isGuard = Boolean(guard && run2.length === 1 && first.codePoint === 8203 && norm2.original[first.offset - 1] === "@" && /[A-Za-z0-9_]/.test(norm2.original[first.offset + 1] ?? ""));
18113
18222
  if (isMinor && !isGuard) minorRuns++;
18114
18223
  const severity = isGuard && guard ? guard.severity : isMinor && minor ? minor.severity : base.severity;
18115
- const decoded = decodedRuns < MAX_HIDDEN_RUNS ? decodedForRun(run) : void 0;
18224
+ const decoded = decodedRuns < MAX_HIDDEN_RUNS ? decodedForRun(run2) : void 0;
18116
18225
  if (decoded !== void 0) decodedRuns += 1;
18117
- const out2 = { ...base, severity, line, col, span: joinEscapes(run), ...decoded !== void 0 ? { decoded } : {} };
18226
+ const out2 = { ...base, severity, line, col, span: joinEscapes(run2), ...decoded !== void 0 ? { decoded } : {} };
18118
18227
  if (isGuard) guards.add(out2);
18119
18228
  findings.push(out2);
18120
- run = [];
18229
+ run2 = [];
18121
18230
  };
18122
18231
  for (const hit of norm2.hiddenUnicode) {
18123
18232
  if (!match.unicode_class.includes(hit.class)) {
18124
18233
  flush();
18125
18234
  continue;
18126
18235
  }
18127
- const prev = run[run.length - 1];
18236
+ const prev = run2[run2.length - 1];
18128
18237
  if (prev && hit.offset !== prev.offset + prev.char.length) flush();
18129
- run.push(hit);
18238
+ run2.push(hit);
18130
18239
  }
18131
18240
  flush();
18132
18241
  if (minorRuns >= MINOR_RUNS_ESCALATE) {
@@ -18137,12 +18246,8 @@ function runSignatures(file, norm2, defs, limitMs = REGEX_TIME_LIMIT_MS) {
18137
18246
  }
18138
18247
  }
18139
18248
  if (match.json_path) {
18140
- let parsed;
18141
- try {
18142
- parsed = JSON.parse(norm2.original);
18143
- } catch {
18144
- continue;
18145
- }
18249
+ const parsed = parseJsonLoose(norm2.original);
18250
+ if (parsed === void 0) continue;
18146
18251
  if (parsed === null || typeof parsed !== "object") continue;
18147
18252
  let results2;
18148
18253
  try {
@@ -18258,9 +18363,9 @@ function makeContext(file, norm2, defs, limitMs) {
18258
18363
  */
18259
18364
  blobCounts(def, group) {
18260
18365
  const m = def.match;
18261
- const ok = (t) => m.validate === "base64-text" ? isBase64Text(t) : m.validate === "encoded-text" ? isBase64Text(t) || isHexText(t) : true;
18366
+ const ok2 = (t) => m.validate === "base64-text" ? isBase64Text(t) : m.validate === "encoded-text" ? isBase64Text(t) || isHexText(t) : true;
18262
18367
  const merged = group.map((c) => c.text).join("");
18263
- const piece = ok(merged) ? merged : group.find((c) => ok(c.text))?.text;
18368
+ const piece = ok2(merged) ? merged : group.find((c) => ok2(c.text))?.text;
18264
18369
  if (piece === void 0) return false;
18265
18370
  if (m.validate !== "base64-text" && m.validate !== "encoded-text") return true;
18266
18371
  const decoded = decodeBlob(merged) ?? decodeBlob(piece) ?? "";
@@ -18694,6 +18799,47 @@ function scanSourceTools(file, text, defs) {
18694
18799
  }
18695
18800
  }
18696
18801
 
18802
+ // ../core/src/sandbox-policy.ts
18803
+ init_canary();
18804
+ var SANDBOX_RULE_ID = "EX-035";
18805
+ var SANDBOX_FILE = /(?:^|\/)\.kiro\/settings\/sandbox\.json$/;
18806
+ var OWASP = ["ASI05 Unexpected Code Execution", "LLM06:2025 Excessive Agency"];
18807
+ var FIX = 'A project file can only tighten the global sandbox policy, so if your global policy turns the sandbox and MCP wrapping on, it still applies here. To be covered in every project, set "enabled": true and "mcpSandboxing": true in your global ~/.kiro/settings/sandbox.json (or in this file).';
18808
+ function indexOfFalse(text, key) {
18809
+ const re2 = new RegExp(`"${key}"\\s*:\\s*false`, "g");
18810
+ for (let m = re2.exec(text); m; m = re2.exec(text)) {
18811
+ const lineStart = text.lastIndexOf("\n", m.index) + 1;
18812
+ if (!text.slice(lineStart, m.index).includes("//")) return m.index;
18813
+ }
18814
+ return -1;
18815
+ }
18816
+ function sandboxFindings(text, rel) {
18817
+ if (!SANDBOX_FILE.test(rel.replace(/\\/g, "/"))) return [];
18818
+ const doc = parseJsonLoose(text);
18819
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return [];
18820
+ const obj = doc;
18821
+ const mcpOff = obj["mcpSandboxing"] === false;
18822
+ const allOff = obj["enabled"] === false;
18823
+ if (!mcpOff && !allOff) return [];
18824
+ const key = mcpOff ? "mcpSandboxing" : "enabled";
18825
+ const at = indexOfFalse(text, key);
18826
+ if (at < 0) return [];
18827
+ const m = new RegExp(`^"${key}"\\s*:\\s*false`).exec(text.slice(at));
18828
+ const { line, col } = lineColOf(text, at);
18829
+ return [{
18830
+ source: "signature",
18831
+ ruleId: SANDBOX_RULE_ID,
18832
+ title: mcpOff ? "Info: MCP sandboxing is off in this project" : "Info: the command sandbox is off in this project",
18833
+ severity: "low",
18834
+ file: rel,
18835
+ line,
18836
+ col,
18837
+ span: m ? m[0] : `"${key}": false`,
18838
+ owasp: OWASP,
18839
+ fix: FIX
18840
+ }];
18841
+ }
18842
+
18697
18843
  // ../core/src/path-names.ts
18698
18844
  var MAX_PATH_SPAN = 120;
18699
18845
  var CONTROL = /[\u0000-\u001F\u007F-\u009F]/;
@@ -18989,23 +19135,23 @@ function packageNames(l) {
18989
19135
  else if (base === "pipx" && a[0] === "run") pkgAt(1);
18990
19136
  else if (base === "uv") {
18991
19137
  for (let i = 0; i < a.length; i++) if ((a[i] === "--with" || a[i] === "--from" || a[i] === "--directory") && a[i + 1]) names.push(a[i + 1].toLowerCase());
18992
- const run = a.findIndex((x) => x === "run");
18993
- if (run !== -1) {
18994
- const rest = a.slice(run + 1);
19138
+ const run2 = a.findIndex((x) => x === "run");
19139
+ if (run2 !== -1) {
19140
+ const rest = a.slice(run2 + 1);
18995
19141
  const j = firstPositional(rest, UV_VALUE_FLAGS);
18996
19142
  if (j !== -1) {
18997
19143
  names.push(stripVersion(rest[j]));
18998
- at = run + 1 + j;
19144
+ at = run2 + 1 + j;
18999
19145
  }
19000
19146
  }
19001
19147
  } else if (CONTAINERS.has(base)) {
19002
- const run = a.findIndex((x) => x === "run");
19003
- if (run !== -1) {
19004
- const rest = a.slice(run + 1);
19148
+ const run2 = a.findIndex((x) => x === "run");
19149
+ if (run2 !== -1) {
19150
+ const rest = a.slice(run2 + 1);
19005
19151
  const j = firstPositional(rest, DOCKER_VALUE_FLAGS);
19006
19152
  if (j !== -1) {
19007
19153
  names.push(dockerImage(rest[j]));
19008
- at = run + 1 + j;
19154
+ at = run2 + 1 + j;
19009
19155
  }
19010
19156
  }
19011
19157
  } else if (SCRIPT_RUNNERS.has(base)) {
@@ -19182,7 +19328,7 @@ function stripJsonc(text) {
19182
19328
  }
19183
19329
  return out.replace(/,(\s*[}\]])/g, "$1");
19184
19330
  }
19185
- function parseJsonLoose(text) {
19331
+ function parseJsonLoose2(text) {
19186
19332
  try {
19187
19333
  return JSON.parse(text);
19188
19334
  } catch {
@@ -19237,7 +19383,7 @@ function serverEntries(servers) {
19237
19383
  function parseMcpConfig(rel, role, text) {
19238
19384
  if (role !== "mcp-config" && !(role === "config" && /\.jsonc?$/i.test(rel))) return null;
19239
19385
  if (role === "config" && !text.includes("mcpServers")) return null;
19240
- const top = Obj.safeParse(parseJsonLoose(text));
19386
+ const top = Obj.safeParse(parseJsonLoose2(text));
19241
19387
  if (!top.success) return null;
19242
19388
  const doc = top.data;
19243
19389
  const entries = [];
@@ -19509,7 +19655,7 @@ async function* scanRepo(root, options) {
19509
19655
  const heurs = options.bedrockClient ? await runHeuristics(file, norm2, sigs, options.bedrockClient) : [];
19510
19656
  const traps = canaryFindings(text, file.rel, records, ex022);
19511
19657
  const sourceTools = (file.role === "code" || file.role === "unknown") && languageOf(file.rel) !== null ? scanSourceTools(file, text, defs) : [];
19512
- let deduped = deduplicate([...sigs, ...heurs, ...traps, ...sourceTools]);
19658
+ let deduped = deduplicate([...sigs, ...heurs, ...traps, ...sandboxFindings(text, file.rel), ...sourceTools]);
19513
19659
  if (checkVault && deduped.length > 0 && file.rel.includes(".exorcist/vault/")) {
19514
19660
  const backup = checkVault(file.rel, await readFile3(file.path));
19515
19661
  if (backup) deduped = deduped.map((f) => asBackupFinding(f, backup));
@@ -19559,7 +19705,7 @@ async function* scanRepo(root, options) {
19559
19705
  init_zod();
19560
19706
 
19561
19707
  // ../core/src/version.ts
19562
- var SCANNER_VERSION = "0.2.0";
19708
+ var SCANNER_VERSION = "0.3.0";
19563
19709
 
19564
19710
  // ../core/src/redact-secrets.ts
19565
19711
  var MIN_LENGTH_FOR_PREFIX = 16;
@@ -19598,6 +19744,9 @@ function redactSecretText(text) {
19598
19744
  out = out.replace(BARE_TOKEN, (m) => redactionMarker(typeOfToken(m), m));
19599
19745
  return out;
19600
19746
  }
19747
+ function containsSecret(text) {
19748
+ return redactSecretText(text) !== text;
19749
+ }
19601
19750
  function redactFinding(f) {
19602
19751
  let span = redactSecretText(f.span);
19603
19752
  if (f.ruleId === "EX-011" && span === f.span && f.span.length > 0 && !f.span.includes("[redacted ")) {
@@ -19822,6 +19971,30 @@ var ENTRIES = {
19822
19971
  headline: "A file or folder name is giving your AI orders",
19823
19972
  attack: 'The name of a file or folder reads like an instruction ("ignore previous instructions...") or hides invisible characters. An agent that lists the project reads every name, so a name alone can steer it.'
19824
19973
  },
19974
+ "EX-030": {
19975
+ headline: "This text asks your AI to change its own settings or guards",
19976
+ attack: "A file tells the agent to add a wildcard to its trusted commands, switch on auto-approve, or edit its hooks, custom agents, steering files or AGENTS.md. If the agent obeys, it stops asking you before it runs commands, and the change stays after the poisoned file is gone."
19977
+ },
19978
+ "EX-031": {
19979
+ headline: "This text tells your AI to skip, delete or weaken your tests and checks",
19980
+ attack: 'A file tells the agent to add .skip to tests, delete a test file as "flaky", commit with --no-verify, add "|| true" to a CI step, lower a coverage threshold, or make a failing check pass without fixing it. A bad change then gets through because the checks no longer catch it.'
19981
+ },
19982
+ "EX-032": {
19983
+ headline: "This text tells your AI to send your code somewhere else",
19984
+ attack: "A file tells the agent to push to a remote that is not your origin, add a new remote, publish a package, switch the package registry, or open a pull request against another repository. If the agent obeys, your code or a poisoned package leaves your control."
19985
+ },
19986
+ "EX-033": {
19987
+ headline: "This settings file lets your AI run any command without asking you",
19988
+ attack: "A committed settings file lists a wildcard or a bare shell name as trusted (Kiro trusted commands, Claude Code or Cursor allow rules). Whoever wrote the file decides that the agent never asks before running a command, so a poisoned file elsewhere in the project can then run anything on your machine."
19989
+ },
19990
+ "EX-034": {
19991
+ headline: "This settings file lets Copilot run any terminal command without asking you",
19992
+ attack: "The terminal auto-approve map in a committed settings file marks a pattern that matches every command as approved. The agent then runs commands without showing you a prompt."
19993
+ },
19994
+ "EX-035": {
19995
+ headline: "This project file switches off the sandbox around your AI tool servers",
19996
+ attack: "A committed Kiro sandbox file turns MCP sandboxing, or the whole command sandbox, off, so local tool servers run without the operating-system boundary. This is only information: a project file can only tighten your global sandbox policy, so your global setting may still apply."
19997
+ },
19825
19998
  "EX-027": {
19826
19999
  headline: "Your AI read untrusted text and private data, and now wants to send something out",
19827
20000
  attack: "Earlier in this session your AI read text anyone can write (a web page, an issue, a message) and then private data (a secrets file, a key). Each step looked harmless. Sending data out now is exactly how a prompt injection steals it, so the Shield holds the call until you say yes."
@@ -20489,22 +20662,22 @@ function shiftThrough(removed) {
20489
20662
  var cpName = (cp) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`;
20490
20663
  function hiddenChanges(lines, removed) {
20491
20664
  const out = [];
20492
- let run = [];
20665
+ let run2 = [];
20493
20666
  const flush = () => {
20494
- const first = run[0];
20667
+ const first = run2[0];
20495
20668
  if (!first) return;
20496
20669
  const { line, col } = lines.position(first.offset);
20497
- const names = [...new Set(run.map((h) => cpName(h.codePoint)))];
20670
+ const names = [...new Set(run2.map((h) => cpName(h.codePoint)))];
20498
20671
  const list2 = names.length > 4 ? `${names.slice(0, 4).join(" ")} ...` : names.join(" ");
20499
20672
  const ruleId = ruleOfClass(first.class);
20500
20673
  const what = ruleId === "EX-021" ? "variation selector" : "hidden character";
20501
- out.push({ ruleId, line, col, summary: `removed ${run.length} ${what}${run.length === 1 ? "" : "s"} (${list2})` });
20502
- run = [];
20674
+ out.push({ ruleId, line, col, summary: `removed ${run2.length} ${what}${run2.length === 1 ? "" : "s"} (${list2})` });
20675
+ run2 = [];
20503
20676
  };
20504
20677
  for (const h of removed) {
20505
- const prev = run[run.length - 1];
20678
+ const prev = run2[run2.length - 1];
20506
20679
  if (prev && (h.offset !== prev.offset + prev.char.length || ruleOfClass(prev.class) !== ruleOfClass(h.class))) flush();
20507
- run.push(h);
20680
+ run2.push(h);
20508
20681
  }
20509
20682
  flush();
20510
20683
  return out;
@@ -21303,9 +21476,9 @@ async function findOriginCommit(repoRoot, relFile, line, span, opts = {}) {
21303
21476
  return { status: "not-found", reason: "the file is not committed (it is not in HEAD)" };
21304
21477
  }
21305
21478
  const work = await readWorkTree(repoRoot, relFile);
21306
- const headLine = work === null ? line : mapLineToHead(work, head.stdout, line);
21307
- if (headLine === null) return { status: "uncommitted", reason: "this line is not committed yet" };
21308
- const blame = await runGit(repoRoot, ["blame", "--porcelain", "--no-textconv", "-L", `${headLine},${headLine}`, "HEAD", "--", relFile], budget.left());
21479
+ const headLine2 = work === null ? line : mapLineToHead(work, head.stdout, line);
21480
+ if (headLine2 === null) return { status: "uncommitted", reason: "this line is not committed yet" };
21481
+ const blame = await runGit(repoRoot, ["blame", "--porcelain", "--no-textconv", "-L", `${headLine2},${headLine2}`, "HEAD", "--", relFile], budget.left());
21309
21482
  let blamed = null;
21310
21483
  if (blame.ok) {
21311
21484
  const lines = blame.stdout.split("\n");
@@ -21791,8 +21964,8 @@ function decideRead(event, defs, opts = {}) {
21791
21964
  }
21792
21965
  const lines = [...new Set(hits.map((h) => h.line))].sort((a, b) => a - b);
21793
21966
  const where2 = lines.length === 1 ? `line ${lines[0]}` : `lines ${lines.join(", ")}`;
21794
- const plain2 = plainFor(ruleId, first.title);
21795
- parts.push(` ${where2} ${ruleId} ${first.title} (${first.severity}): ${plain2.headline}`);
21967
+ const plain3 = plainFor(ruleId, first.title);
21968
+ parts.push(` ${where2} ${ruleId} ${first.title} (${first.severity}): ${plain3.headline}`);
21796
21969
  parts.push(` fix: ${first.fix.replace(/\s+/g, " ").trim()}`);
21797
21970
  }
21798
21971
  parts.push("");
@@ -21808,7 +21981,9 @@ function decideRead(event, defs, opts = {}) {
21808
21981
  }
21809
21982
 
21810
21983
  // ../core/src/mcp-write-guard.ts
21984
+ import { readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
21811
21985
  import { isAbsolute as isAbsolute5, join as join11, resolve as resolve7 } from "node:path";
21986
+ var PATH_KEYS = ["path", "file_path", "filePath", "target", "destination", "file"];
21812
21987
  var COMMAND_KEYS = /* @__PURE__ */ new Set(["command", "cmd", "script", "commands"]);
21813
21988
  var MAX_PATH_LEN = 1024;
21814
21989
  var MAX_COMMAND_LEN = 8192;
@@ -21949,6 +22124,190 @@ function collect2(value, key, shellTool, paths2, cmds, depth) {
21949
22124
  for (const [k, v] of Object.entries(value)) collect2(v, k, shellTool, paths2, cmds, depth + 1);
21950
22125
  }
21951
22126
  }
22127
+ var VSCODE_TAIL = [".vscode", "settings.json"];
22128
+ var MAX_READ_BYTES = 2 * 1024 * 1024;
22129
+ var MOVE_KEYS = ["source", "src", "from", "to", "old_path", "new_path", "oldPath", "newPath"];
22130
+ var NEW_TEXT_KEYS = ["file_text", "fileText", "content", "contents", "text", "new_str", "newStr", "new_string", "newText", "insert_text", "data", "body"];
22131
+ var OLD_TEXT_KEYS = ["old_str", "oldStr", "old_string", "oldText"];
22132
+ var TRUSTED_RE = /["']?(?:kiroAgent\.)?trustedCommands["']?\s*:\s*/gi;
22133
+ var MOVERS = /* @__PURE__ */ new Set(["cp", "mv", "install", "ln"]);
22134
+ var REMOVERS = /* @__PURE__ */ new Set(["rm", "rmdir", "unlink", "shred", "touch", "truncate", "mkdir"]);
22135
+ function prepare(event, cwd) {
22136
+ if (!isRecord(event) || !isRecord(event["tool_input"])) return null;
22137
+ const base = typeof event["cwd"] === "string" && event["cwd"] !== "" ? resolve7(cwd, event["cwd"]) : resolve7(cwd);
22138
+ const toolName = typeof event["tool_name"] === "string" ? event["tool_name"] : "";
22139
+ const shellTool = /shell|bash|exec|command|terminal/i.test(toolName);
22140
+ const input = event["tool_input"];
22141
+ const paths2 = [];
22142
+ const cmds = [];
22143
+ collect2(input, "", shellTool, paths2, cmds, 0);
22144
+ return { base, toolName, shellTool, input, paths: paths2, cmds };
22145
+ }
22146
+ function isReadOnlyTool(name) {
22147
+ return /read|list|grep|search|glob|fetch/i.test(name) && !/write|replace|edit|create|delete|move|bash|shell|exec/i.test(name);
22148
+ }
22149
+ function filePaths(input) {
22150
+ const out = [];
22151
+ for (const k of [...PATH_KEYS, ...MOVE_KEYS]) {
22152
+ const v = input[k];
22153
+ if (typeof v === "string" && v.length <= MAX_PATH_LEN) out.push(v);
22154
+ else if (Array.isArray(v)) {
22155
+ for (const x of v) if (typeof x === "string" && x.length <= MAX_PATH_LEN) out.push(x);
22156
+ }
22157
+ }
22158
+ return out;
22159
+ }
22160
+ function firstString(input, keys) {
22161
+ for (const k of keys) {
22162
+ const v = input[k];
22163
+ if (typeof v === "string") return v;
22164
+ }
22165
+ return void 0;
22166
+ }
22167
+ function endsWithTail(real, tail) {
22168
+ const parts = real.split(/[\\/]+/).slice(-tail.length).map((p) => p.toLowerCase());
22169
+ return parts.length === tail.length && tail.every((t, i) => parts[i] === t);
22170
+ }
22171
+ function settingsPath(raw, home, base) {
22172
+ if (raw === "" || raw.includes("\0")) return null;
22173
+ const abs = expand(raw, home, base);
22174
+ const real = realPath(abs);
22175
+ return endsWithTail(real, VSCODE_TAIL) || endsWithTail(abs, VSCODE_TAIL) ? real : null;
22176
+ }
22177
+ function inGuardDir(p) {
22178
+ const parts = p.split(/[\\/]+/).map((x) => x.toLowerCase());
22179
+ for (let i = 0; i + 1 < parts.length; i++) {
22180
+ if (parts[i] === ".kiro" && (parts[i + 1] === "hooks" || parts[i + 1] === "agents")) return true;
22181
+ }
22182
+ return false;
22183
+ }
22184
+ function guardPath(raw, home, base) {
22185
+ if (raw === "" || raw.includes("\0")) return null;
22186
+ const abs = expand(raw, home, base);
22187
+ const real = realPath(abs);
22188
+ return inGuardDir(real) || inGuardDir(abs) ? real : null;
22189
+ }
22190
+ function segmentName(seg) {
22191
+ const rest = seg.filter((w, i2) => w !== ">" && w !== ">>" && seg[i2 - 1] !== ">" && seg[i2 - 1] !== ">>");
22192
+ let i = 0;
22193
+ while (i < rest.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(rest[i]) || WRAPPERS.has(rest[i]) || i > 0 && rest[i].startsWith("-") && WRAPPERS.has(rest[i - 1]))) i++;
22194
+ return (rest[i] ?? "").split("/").pop() ?? "";
22195
+ }
22196
+ function guardShellTargets(cmd) {
22197
+ if (cmd.length > MAX_COMMAND_LEN) return [];
22198
+ const out = [];
22199
+ for (const seg of words(cmd)) {
22200
+ out.push(...writeTargets(seg));
22201
+ const name = segmentName(seg);
22202
+ if (REMOVERS.has(name) || name === "mv") {
22203
+ const operands = seg.filter((w, i) => w !== ">" && w !== ">>" && seg[i - 1] !== ">" && seg[i - 1] !== ">>").slice(seg.findIndex((w) => w.split("/").pop() === name) + 1).filter((a) => !a.startsWith("-") || a === "-");
22204
+ out.push(...operands);
22205
+ }
22206
+ }
22207
+ return out;
22208
+ }
22209
+ function trustedEntries(text) {
22210
+ const out = [];
22211
+ TRUSTED_RE.lastIndex = 0;
22212
+ for (let m = TRUSTED_RE.exec(text); m; m = TRUSTED_RE.exec(text)) {
22213
+ let i = m.index + m[0].length;
22214
+ const open3 = text[i];
22215
+ if (open3 === '"' || open3 === "'") {
22216
+ out.push(readString(text, i).value);
22217
+ continue;
22218
+ }
22219
+ if (open3 !== "[") continue;
22220
+ i++;
22221
+ while (i < text.length && text[i] !== "]") {
22222
+ const c = text[i];
22223
+ if (c === '"' || c === "'") {
22224
+ const r = readString(text, i);
22225
+ out.push(r.value);
22226
+ i = r.end;
22227
+ continue;
22228
+ }
22229
+ if (c === "/" && text[i + 1] === "/") {
22230
+ while (i < text.length && text[i] !== "\n") i++;
22231
+ continue;
22232
+ }
22233
+ if (c === "/" && text[i + 1] === "*") {
22234
+ const e = text.indexOf("*/", i + 2);
22235
+ i = e < 0 ? text.length : e + 2;
22236
+ continue;
22237
+ }
22238
+ i++;
22239
+ }
22240
+ }
22241
+ return out;
22242
+ }
22243
+ function readString(text, start) {
22244
+ const q = text[start];
22245
+ let v = "";
22246
+ let i = start + 1;
22247
+ while (i < text.length && text[i] !== q) {
22248
+ if (text[i] === "\\" && i + 1 < text.length) {
22249
+ v += text[i + 1];
22250
+ i += 2;
22251
+ continue;
22252
+ }
22253
+ v += text[i];
22254
+ i++;
22255
+ }
22256
+ return { value: v, end: i + 1 };
22257
+ }
22258
+ function readDisk(path) {
22259
+ try {
22260
+ if (statSync5(path).size > MAX_READ_BYTES) return void 0;
22261
+ return readFileSync7(path, "utf8");
22262
+ } catch {
22263
+ return void 0;
22264
+ }
22265
+ }
22266
+ function addsTrustedEntry(input, disk) {
22267
+ const fresh = firstString(input, NEW_TEXT_KEYS);
22268
+ if (fresh === void 0) return false;
22269
+ const old = firstString(input, OLD_TEXT_KEYS);
22270
+ const verb = typeof input["command"] === "string" ? input["command"].toLowerCase() : "";
22271
+ let after = fresh;
22272
+ if (old !== void 0 && disk !== void 0 && old !== "" && disk.includes(old)) {
22273
+ const at = disk.indexOf(old);
22274
+ after = disk.slice(0, at) + fresh + disk.slice(at + old.length);
22275
+ } else if (verb === "append" && disk !== void 0) after = disk + "\n" + fresh;
22276
+ const before = new Set(trustedEntries(disk ?? ""));
22277
+ return trustedEntries(after).some((e) => !before.has(e));
22278
+ }
22279
+ function isTrustedCommandsWrite(event, home, cwd) {
22280
+ const p = prepare(event, cwd);
22281
+ if (!p || isReadOnlyTool(p.toolName)) return null;
22282
+ if (!p.shellTool) {
22283
+ for (const raw of filePaths(p.input)) {
22284
+ const real = settingsPath(raw, home, p.base);
22285
+ if (real && addsTrustedEntry(p.input, readDisk(real))) return real;
22286
+ }
22287
+ }
22288
+ for (const cmd of p.cmds) {
22289
+ if (cmd.length > MAX_COMMAND_LEN) continue;
22290
+ const names = /trustedCommands/i.test(cmd);
22291
+ for (const seg of words(cmd)) {
22292
+ const mover = MOVERS.has(segmentName(seg));
22293
+ for (const t of writeTargets(seg)) {
22294
+ const real = settingsPath(t, home, p.base);
22295
+ if (real && (names || mover)) return real;
22296
+ }
22297
+ }
22298
+ }
22299
+ return null;
22300
+ }
22301
+ function isGuardFileWrite(event, home, cwd) {
22302
+ const p = prepare(event, cwd);
22303
+ if (!p || isReadOnlyTool(p.toolName)) return null;
22304
+ const candidates = [...p.shellTool ? [] : filePaths(p.input), ...p.cmds.flatMap(guardShellTargets)];
22305
+ for (const c of candidates) {
22306
+ const hit = guardPath(c, home, p.base);
22307
+ if (hit) return hit;
22308
+ }
22309
+ return null;
22310
+ }
21952
22311
  function decideMcpWrite(event, home, cwd) {
21953
22312
  if (!isRecord(event) || !isRecord(event["tool_input"])) return { target: "other" };
21954
22313
  const base = typeof event["cwd"] === "string" && event["cwd"] !== "" ? resolve7(cwd, event["cwd"]) : resolve7(cwd);
@@ -21962,19 +22321,286 @@ function decideMcpWrite(event, home, cwd) {
21962
22321
  const hit = check(c, home, base);
21963
22322
  if (hit) return { target: "mcp-config", path: hit };
21964
22323
  }
22324
+ const trusted = isTrustedCommandsWrite(event, home, cwd);
22325
+ if (trusted) return { target: "trusted-commands", path: trusted };
22326
+ const guarded2 = isGuardFileWrite(event, home, cwd);
22327
+ if (guarded2) return { target: "guard-file", path: guarded2 };
21965
22328
  return { target: "other" };
21966
22329
  }
21967
22330
 
22331
+ // ../core/src/web-fetch-guard.ts
22332
+ init_zod();
22333
+ init_canary();
22334
+ var EventSchema = external_exports.object({
22335
+ tool_name: external_exports.string().optional(),
22336
+ tool_input: external_exports.record(external_exports.unknown())
22337
+ });
22338
+ var URL_KEYS = /* @__PURE__ */ new Set(["url", "uri", "href", "link", "urls"]);
22339
+ var MAX_URL_CHARS = 16384;
22340
+ var MAX_FORMS = 512;
22341
+ var MAX_DECODED_BYTES = 65536;
22342
+ function extractFetchUrls(event) {
22343
+ const parsed = EventSchema.safeParse(event);
22344
+ if (!parsed.success) return [];
22345
+ const { tool_name: tool, tool_input: input } = parsed.data;
22346
+ if (tool !== void 0 && !/fetch/i.test(tool)) return [];
22347
+ const out = [];
22348
+ for (const [key, value] of Object.entries(input)) {
22349
+ if (!URL_KEYS.has(key.toLowerCase())) continue;
22350
+ if (typeof value === "string") out.push(value);
22351
+ else if (Array.isArray(value)) {
22352
+ for (const v of value) if (typeof v === "string") out.push(v);
22353
+ }
22354
+ }
22355
+ return out;
22356
+ }
22357
+ function percentDecode(s) {
22358
+ try {
22359
+ return decodeURIComponent(s);
22360
+ } catch {
22361
+ }
22362
+ return s.replace(/%([0-9a-fA-F]{2})/g, (_m, h) => String.fromCharCode(parseInt(h, 16)));
22363
+ }
22364
+ var SEPARATORS = /[\s/?&=#.+]/g;
22365
+ var B64_RUN2 = /[A-Za-z0-9+/_-]{12,}={0,2}/g;
22366
+ var newState = () => ({ seen: /* @__PURE__ */ new Set(), expandedAt: /* @__PURE__ */ new Map(), bytes: 0, exhausted: false });
22367
+ function admit(f, st) {
22368
+ if (f === "" || st.seen.has(f)) return false;
22369
+ if (st.seen.size >= MAX_FORMS) {
22370
+ st.exhausted = true;
22371
+ return false;
22372
+ }
22373
+ st.seen.add(f);
22374
+ return true;
22375
+ }
22376
+ function* base64Forms(s, st) {
22377
+ for (const m of s.matchAll(B64_RUN2)) {
22378
+ const std = m[0].replaceAll("-", "+").replaceAll("_", "/").replace(/=+$/, "");
22379
+ for (let off = 0; off < 4 && std.length - off >= 12; off++) {
22380
+ st.bytes += Math.floor((std.length - off) * 3 / 4);
22381
+ if (st.bytes > MAX_DECODED_BYTES) {
22382
+ st.exhausted = true;
22383
+ return;
22384
+ }
22385
+ yield Buffer.from(std.slice(off), "base64").toString("utf8");
22386
+ }
22387
+ }
22388
+ }
22389
+ function* formsOf(s, depth, st) {
22390
+ const decoded = percentDecode(s);
22391
+ for (const f of [s, decoded, decoded.replace(SEPARATORS, "")]) if (admit(f, st)) yield f;
22392
+ if (depth >= 2) return;
22393
+ const prior = st.expandedAt.get(s);
22394
+ if (prior !== void 0 && prior <= depth) return;
22395
+ st.expandedAt.set(s, depth);
22396
+ for (const piece of [decoded, ...decoded.split(/[/?&=#]/)]) {
22397
+ for (const b of base64Forms(piece, st)) {
22398
+ if (b !== "") yield* formsOf(b, depth + 1, st);
22399
+ if (st.exhausted) return;
22400
+ }
22401
+ if (st.exhausted) return;
22402
+ }
22403
+ }
22404
+ var alnum = (s) => s.replace(/[^A-Za-z0-9]/g, "");
22405
+ function shortHost(url) {
22406
+ let host;
22407
+ try {
22408
+ host = new URL(url).hostname;
22409
+ } catch {
22410
+ return "an unreadable address";
22411
+ }
22412
+ if (host === "") return "an unreadable address";
22413
+ if (host.includes(":") || /^\d+(\.\d+){3}$/.test(host)) return "an IP address";
22414
+ const labels = host.split(".");
22415
+ return labels.length > 2 ? `*.${labels.slice(-2).join(".")}` : host;
22416
+ }
22417
+ function formKind(f, ctx) {
22418
+ if (ctx.canaries.length > 0 && findCanaryInText(f, ctx.canaries).length > 0) return "canary";
22419
+ if (containsSecret(f)) return "secret";
22420
+ const flat = alnum(f);
22421
+ for (const value of ctx.envValues) {
22422
+ if (value === "") continue;
22423
+ if (f.includes(value)) return "env-value";
22424
+ const needle = alnum(value);
22425
+ if (needle.length >= 8 && flat.includes(needle)) return "env-value";
22426
+ }
22427
+ return null;
22428
+ }
22429
+ function kindOf(url, ctx) {
22430
+ if (url.length > MAX_URL_CHARS) return "oversized";
22431
+ const st = newState();
22432
+ for (const f of formsOf(url, 0, st)) {
22433
+ const kind = formKind(f, ctx);
22434
+ if (kind !== null) return kind;
22435
+ }
22436
+ return st.exhausted ? "too-many-encodings" : null;
22437
+ }
22438
+ function decideWebFetch(event, ctx) {
22439
+ for (const url of extractFetchUrls(event)) {
22440
+ const kind = kindOf(url, ctx);
22441
+ if (kind !== null) return { block: true, kind, host: shortHost(url) };
22442
+ }
22443
+ return { block: false };
22444
+ }
22445
+ var KIND_TEXT = {
22446
+ "secret": "holds a secret (a key or token)",
22447
+ "canary": "holds a canary token, a trap value that must never leave the project",
22448
+ "env-value": "holds a value copied from a .env file",
22449
+ "oversized": "is too long to check",
22450
+ "too-many-encodings": "has too many encoded pieces to check"
22451
+ };
22452
+ function webFetchBlockMessage(d) {
22453
+ return `Exorcist 98 blocked the web fetch to ${d.host}: the address ${KIND_TEXT[d.kind]}. A fetch can send data out through its address. If you want this fetch, make it yourself.`;
22454
+ }
22455
+
22456
+ // ../core/src/env-write-guard.ts
22457
+ init_zod();
22458
+ var EventSchema2 = external_exports.object({
22459
+ tool_name: external_exports.string().optional(),
22460
+ tool_input: external_exports.record(external_exports.unknown())
22461
+ });
22462
+ var NEW_TEXT_KEYS2 = ["file_text", "fileText", "content", "contents", "text", "new_str", "newStr", "new_string", "newText", "insert_text", "data", "body"];
22463
+ var MAX_TEXT_CHARS = 2 * 1024 * 1024;
22464
+ var MAX_PATH_CHARS = 512;
22465
+ var ENV_FILE = /^\.env(\..*)?$/i;
22466
+ function baseName(path) {
22467
+ const parts = path.split(/[\\/]/);
22468
+ return parts[parts.length - 1] ?? "";
22469
+ }
22470
+ function isEnvFilePath(path) {
22471
+ return ENV_FILE.test(baseName(path));
22472
+ }
22473
+ function firstPath(input) {
22474
+ for (const k of PATH_KEYS) {
22475
+ const v = input[k];
22476
+ if (typeof v === "string" && v !== "") return v;
22477
+ }
22478
+ return void 0;
22479
+ }
22480
+ function newTexts(input) {
22481
+ const out = [];
22482
+ for (const k of NEW_TEXT_KEYS2) {
22483
+ const v = input[k];
22484
+ if (typeof v === "string") out.push(v.slice(0, MAX_TEXT_CHARS));
22485
+ }
22486
+ return out;
22487
+ }
22488
+ function decideEnvWrite(event, envValues) {
22489
+ const parsed = EventSchema2.safeParse(event);
22490
+ if (!parsed.success || envValues.length === 0) return { block: false };
22491
+ const { tool_name: tool, tool_input: input } = parsed.data;
22492
+ if (tool !== void 0 && tool !== "" && !/write|replace|edit|create|append|insert/i.test(tool)) return { block: false };
22493
+ const path = firstPath(input);
22494
+ if (path !== void 0 && isEnvFilePath(path)) return { block: false };
22495
+ const texts = newTexts(input);
22496
+ const hit = envValues.some((v) => v !== "" && texts.some((t) => t.includes(v)));
22497
+ if (!hit) return { block: false };
22498
+ return { block: true, path: path ?? "" };
22499
+ }
22500
+ function envWriteBlockMessage(d, envValues = []) {
22501
+ const clean = d.path.replace(/[\r\n]+/g, " ").slice(0, MAX_PATH_CHARS);
22502
+ const safe2 = clean === "" || envValues.some((v) => v !== "" && clean.includes(v)) ? "a file" : clean;
22503
+ return `Exorcist 98 blocked a write to ${safe2}: it contains a value from your .env file. Secrets stay in .env files. If you want this write, make it yourself.`;
22504
+ }
22505
+
22506
+ // ../core/src/env-values.ts
22507
+ import { lstatSync, readdirSync, readFileSync as readFileSync8 } from "node:fs";
22508
+ import { join as join12 } from "node:path";
22509
+ var MIN_ENV_VALUE_LENGTH = 8;
22510
+ var MAX_ENV_FILE_BYTES = 256 * 1024;
22511
+ var COMMON_WORDS = /* @__PURE__ */ new Set([
22512
+ "true",
22513
+ "false",
22514
+ "null",
22515
+ "undefined",
22516
+ "none",
22517
+ "yes",
22518
+ "no",
22519
+ "on",
22520
+ "off",
22521
+ "localhost",
22522
+ "127.0.0.1",
22523
+ "0.0.0.0",
22524
+ "development",
22525
+ "production",
22526
+ "staging",
22527
+ "test",
22528
+ "debug"
22529
+ ]);
22530
+ var BARE_NUMBER = /^[+-]?\d+(\.\d+)?$/;
22531
+ var LOCAL_URL = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?\/?$/i;
22532
+ var ASSIGNMENT = /^(?:export\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=\s*(.*)$/;
22533
+ function isIgnorableEnvValue(value) {
22534
+ if (value.length < MIN_ENV_VALUE_LENGTH) return true;
22535
+ return COMMON_WORDS.has(value.toLowerCase()) || BARE_NUMBER.test(value) || LOCAL_URL.test(value);
22536
+ }
22537
+ function valueOf(rest) {
22538
+ const quote = rest[0];
22539
+ if (quote === '"' || quote === "'") {
22540
+ for (let i = 1; i < rest.length; i++) {
22541
+ if (quote === '"' && rest[i] === "\\") {
22542
+ i++;
22543
+ continue;
22544
+ }
22545
+ if (rest[i] === quote) return rest.slice(1, i);
22546
+ }
22547
+ return rest.slice(1);
22548
+ }
22549
+ const hash = rest.search(/\s#/);
22550
+ return (hash === -1 ? rest : rest.slice(0, hash)).trim();
22551
+ }
22552
+ function parseEnvValues(text) {
22553
+ const out = [];
22554
+ const seen = /* @__PURE__ */ new Set();
22555
+ for (const raw of text.split(/\r?\n/)) {
22556
+ const line = raw.trim();
22557
+ if (line === "" || line.startsWith("#")) continue;
22558
+ const m = ASSIGNMENT.exec(line);
22559
+ if (!m) continue;
22560
+ const value = valueOf((m[1] ?? "").trim());
22561
+ if (isIgnorableEnvValue(value) || seen.has(value)) continue;
22562
+ seen.add(value);
22563
+ out.push(value);
22564
+ }
22565
+ return out;
22566
+ }
22567
+ function loadEnvValues(cwd) {
22568
+ let names;
22569
+ try {
22570
+ names = readdirSync(cwd).filter((n) => n === ".env" || n.startsWith(".env.")).sort();
22571
+ } catch {
22572
+ return [];
22573
+ }
22574
+ const out = [];
22575
+ const seen = /* @__PURE__ */ new Set();
22576
+ for (const name of names) {
22577
+ try {
22578
+ const path = join12(cwd, name);
22579
+ const st = lstatSync(path);
22580
+ if (!st.isFile() || st.size > MAX_ENV_FILE_BYTES) continue;
22581
+ for (const v of parseEnvValues(readFileSync8(path, "utf8"))) {
22582
+ if (!seen.has(v)) {
22583
+ seen.add(v);
22584
+ out.push(v);
22585
+ }
22586
+ }
22587
+ } catch {
22588
+ continue;
22589
+ }
22590
+ }
22591
+ return out;
22592
+ }
22593
+
21968
22594
  // ../core/src/gate.ts
21969
22595
  init_walker();
21970
22596
  var RANK2 = { critical: 0, high: 1, medium: 2, low: 3 };
21971
22597
  var SCANNED_ROLES = /* @__PURE__ */ new Set(["instruction", "memory", "hook", "mcp-config", "power"]);
21972
22598
  var norm = (rel) => rel.replace(/\\/g, "/");
21973
- var baseName = (rel) => norm(rel).split("/").pop() ?? "";
22599
+ var baseName2 = (rel) => norm(rel).split("/").pop() ?? "";
21974
22600
  function isGateFile(rel) {
21975
22601
  const p = norm(rel);
21976
22602
  if (p.startsWith(".kiro/specs/") || p.startsWith(".kiro/agents/") || p.startsWith(".kiro/steering/")) return true;
21977
- if (baseName(p).startsWith("README")) return true;
22603
+ if (baseName2(p).startsWith("README")) return true;
21978
22604
  return SCANNED_ROLES.has(classifyFile(p));
21979
22605
  }
21980
22606
  function gateRole(rel) {
@@ -22050,9 +22676,9 @@ var BUNDLED_DEFINITIONS_DATE = "2026-11-24";
22050
22676
  // ../core/src/liveupdate.ts
22051
22677
  init_zod();
22052
22678
  import { createHash as createHash4, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes as randomBytes2, sign as edSign, verify as edVerify } from "node:crypto";
22053
- import { closeSync as closeSync2, fstatSync, lstatSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync7, readSync as readSync2, readdirSync, renameSync as renameSync2, rmSync, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
22679
+ import { closeSync as closeSync2, fstatSync, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync9, readSync as readSync2, readdirSync as readdirSync2, renameSync as renameSync2, rmSync, statSync as statSync6, writeFileSync as writeFileSync2 } from "node:fs";
22054
22680
  import { homedir as homedir2 } from "node:os";
22055
- import { basename as basename5, join as join12, resolve as resolve8 } from "node:path";
22681
+ import { basename as basename5, join as join13, resolve as resolve8 } from "node:path";
22056
22682
  var DEFINITIONS_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
22057
22683
  MCowBQYDK2VwAyEAn4o+dmOJXIzsygT2CF/3go/1E/bk9Ub16r4hGtJJjhM=
22058
22684
  -----END PUBLIC KEY-----
@@ -22237,36 +22863,36 @@ function checkBundle(tar, o = {}) {
22237
22863
  function installedDefinitionsRoot(env = process.env) {
22238
22864
  const fromEnv = env["EXORCIST_DEFINITIONS_HOME"];
22239
22865
  if (fromEnv) return resolve8(fromEnv);
22240
- return join12(env["HOME"] || env["USERPROFILE"] || homedir2(), ".exorcist", "definitions");
22866
+ return join13(env["HOME"] || env["USERPROFILE"] || homedir2(), ".exorcist", "definitions");
22241
22867
  }
22242
22868
  function verifySetFolder(dir, expectedVersion, publicKeyPem) {
22243
22869
  try {
22244
- if (!lstatSync(dir).isDirectory()) return fail("not a real folder (a symlink or a file)");
22245
- const defsDir = join12(dir, "definitions");
22246
- for (const [p, kind] of [[join12(dir, MANIFEST_NAME), "file"], [join12(dir, SIGNATURE_NAME), "file"], [defsDir, "dir"]]) {
22247
- const st = lstatSync(p);
22870
+ if (!lstatSync2(dir).isDirectory()) return fail("not a real folder (a symlink or a file)");
22871
+ const defsDir = join13(dir, "definitions");
22872
+ for (const [p, kind] of [[join13(dir, MANIFEST_NAME), "file"], [join13(dir, SIGNATURE_NAME), "file"], [defsDir, "dir"]]) {
22873
+ const st = lstatSync2(p);
22248
22874
  if (kind === "file" ? !st.isFile() : !st.isDirectory()) return fail(`${basename5(p)} is not a plain ${kind === "file" ? "file" : "folder"}`);
22249
22875
  }
22250
- const manifestBytes = readFileSync7(join12(dir, MANIFEST_NAME));
22251
- const bad = verifySignature(manifestBytes, readFileSync7(join12(dir, SIGNATURE_NAME)), publicKeyPem);
22876
+ const manifestBytes = readFileSync9(join13(dir, MANIFEST_NAME));
22877
+ const bad = verifySignature(manifestBytes, readFileSync9(join13(dir, SIGNATURE_NAME)), publicKeyPem);
22252
22878
  if (bad) return fail("the manifest signature does not verify");
22253
22879
  const m = parseManifest(manifestBytes);
22254
22880
  if (!m.ok) return m;
22255
22881
  if (m.manifest.version !== expectedVersion) return fail(`the folder is named ${expectedVersion} but holds version ${m.manifest.version}`);
22256
22882
  const listed = Object.keys(m.manifest.files).map((p) => p.slice("definitions/".length)).sort();
22257
- const onDisk = readdirSync(defsDir).sort();
22883
+ const onDisk = readdirSync2(defsDir).sort();
22258
22884
  const extra = onDisk.filter((n) => !listed.includes(n));
22259
22885
  if (extra.length > 0) return fail(`definitions/ holds files the manifest does not list: ${extra.map((n) => printable(n)).join(", ")}`);
22260
22886
  for (const name of listed) {
22261
- const p = join12(defsDir, name);
22887
+ const p = join13(defsDir, name);
22262
22888
  let st;
22263
22889
  try {
22264
- st = lstatSync(p);
22890
+ st = lstatSync2(p);
22265
22891
  } catch {
22266
22892
  return fail(`definitions/${name} is missing`);
22267
22893
  }
22268
22894
  if (!st.isFile()) return fail(`definitions/${name} is not a plain file`);
22269
- if (sha256(readFileSync7(p)) !== m.manifest.files[`definitions/${name}`]) return fail(`definitions/${name} was changed after it was installed`);
22895
+ if (sha256(readFileSync9(p)) !== m.manifest.files[`definitions/${name}`]) return fail(`definitions/${name} was changed after it was installed`);
22270
22896
  }
22271
22897
  return { ok: true, set: { dir, definitionsDir: defsDir, version: m.manifest.version, date: m.manifest.date, files: listed.length } };
22272
22898
  } catch (e) {
@@ -22281,24 +22907,24 @@ function verifyInstalledSet(dir, publicKeyPem = DEFINITIONS_PUBLIC_KEY) {
22281
22907
  function inspectInstalledSets(root, publicKeyPem = DEFINITIONS_PUBLIC_KEY) {
22282
22908
  let names;
22283
22909
  try {
22284
- names = readdirSync(root);
22910
+ names = readdirSync2(root);
22285
22911
  } catch {
22286
22912
  return [];
22287
22913
  }
22288
- return names.filter(isValidVersion).sort((a, b) => compareVersions(b, a)).map((name) => ({ name, dir: join12(root, name), ...verifyInstalledSet(join12(root, name), publicKeyPem) }));
22914
+ return names.filter(isValidVersion).sort((a, b) => compareVersions(b, a)).map((name) => ({ name, dir: join13(root, name), ...verifyInstalledSet(join13(root, name), publicKeyPem) }));
22289
22915
  }
22290
22916
  function findActiveInstalledSet(o = {}) {
22291
22917
  const root = o.root ?? installedDefinitionsRoot(o.env);
22292
22918
  const pem = o.publicKeyPem ?? DEFINITIONS_PUBLIC_KEY;
22293
22919
  let names;
22294
22920
  try {
22295
- names = readdirSync(root);
22921
+ names = readdirSync2(root);
22296
22922
  } catch {
22297
22923
  return null;
22298
22924
  }
22299
22925
  const newer = names.filter((n) => isValidVersion(n) && compareVersions(n, BUNDLED_DEFINITIONS_VERSION) > 0).sort((a, b) => compareVersions(b, a));
22300
22926
  for (const name of newer) {
22301
- const r = verifyInstalledSet(join12(root, name), pem);
22927
+ const r = verifyInstalledSet(join13(root, name), pem);
22302
22928
  if (r.ok) return r.set;
22303
22929
  }
22304
22930
  return null;
@@ -22317,22 +22943,22 @@ function installBundle(tar, o) {
22317
22943
  if (compareVersions(version2, o.currentVersion) <= 0) {
22318
22944
  return fail(`The bundle is version ${version2}, which is not newer than the definitions in use (${o.currentVersion}).`);
22319
22945
  }
22320
- const final = join12(o.root, version2);
22946
+ const final = join13(o.root, version2);
22321
22947
  let exists = true;
22322
22948
  try {
22323
- lstatSync(final);
22949
+ lstatSync2(final);
22324
22950
  } catch {
22325
22951
  exists = false;
22326
22952
  }
22327
22953
  if (exists) return fail(`${final} already exists. Remove it to install version ${version2} again.`);
22328
- const staging = join12(o.root, `.staging-${randomBytes2(6).toString("hex")}`);
22954
+ const staging = join13(o.root, `.staging-${randomBytes2(6).toString("hex")}`);
22329
22955
  try {
22330
22956
  mkdirSync2(o.root, { recursive: true, mode: 448 });
22331
22957
  mkdirSync2(staging, { mode: 448 });
22332
- mkdirSync2(join12(staging, "definitions"));
22333
- for (const f of b.files) writeFileSync2(join12(staging, f.path), f.data, { flag: "wx", mode: 420 });
22334
- writeFileSync2(join12(staging, MANIFEST_NAME), b.manifestBytes, { flag: "wx", mode: 420 });
22335
- writeFileSync2(join12(staging, SIGNATURE_NAME), b.sig, { flag: "wx", mode: 420 });
22958
+ mkdirSync2(join13(staging, "definitions"));
22959
+ for (const f of b.files) writeFileSync2(join13(staging, f.path), f.data, { flag: "wx", mode: 420 });
22960
+ writeFileSync2(join13(staging, MANIFEST_NAME), b.manifestBytes, { flag: "wx", mode: 420 });
22961
+ writeFileSync2(join13(staging, SIGNATURE_NAME), b.sig, { flag: "wx", mode: 420 });
22336
22962
  const check3 = verifySetFolder(staging, version2, pem);
22337
22963
  if (!check3.ok) return fail(`The staged copy did not verify (${check3.error}).`);
22338
22964
  renameSync2(staging, final);
@@ -22420,7 +23046,7 @@ async function downloadBundle(url, o = {}) {
22420
23046
  function readBundleFile(path, limitBytes = DOWNLOAD_LIMIT_BYTES) {
22421
23047
  let fd = null;
22422
23048
  try {
22423
- if (!statSync5(path).isFile()) return fail(`${path} is not a regular file.`);
23049
+ if (!statSync6(path).isFile()) return fail(`${path} is not a regular file.`);
22424
23050
  fd = openSync2(path, "r");
22425
23051
  const st = fstatSync(fd);
22426
23052
  if (!st.isFile()) return fail(`${path} is not a regular file.`);
@@ -22672,11 +23298,34 @@ function applyInline(findings, readText) {
22672
23298
  return { active, suppressed, rejected };
22673
23299
  }
22674
23300
 
23301
+ // ../core/src/kiro-evidence.ts
23302
+ init_zod();
23303
+ var KiroEventSchema = external_exports.object({
23304
+ id: external_exports.string(),
23305
+ timestamp: external_exports.string(),
23306
+ payload: external_exports.object({ type: external_exports.string() }).passthrough()
23307
+ }).passthrough();
23308
+ var CRED_KEY = "(?:(?<![A-Za-z])|(?<=\\\\[nrt]))(?<key>aws_secret_access_key|aws_access_key_id|aws_session_token|password|_authToken)";
23309
+ var CRED_DELIMITED_SOURCE = `${CRED_KEY}(?<sep>(?:\\\\*["'])?[ \\t]*[=:][ \\t]*)(?:(?<q>\\\\*["'])(?<quoted>[^"'\\\\]{4,})|(?<bare>[^\\s"'\\\\,;}]{4,}))`;
23310
+ var DROP = Symbol("drop");
23311
+ var SessionJsonSchema = external_exports.object({
23312
+ id: external_exports.string().optional(),
23313
+ title: external_exports.string().optional(),
23314
+ agentMode: external_exports.string().optional(),
23315
+ createdAt: external_exports.string().optional(),
23316
+ lastModifiedAt: external_exports.string().optional(),
23317
+ modelId: external_exports.string().optional(),
23318
+ autopilot: external_exports.boolean().optional(),
23319
+ approveForMe: external_exports.boolean().optional()
23320
+ }).passthrough();
23321
+
22675
23322
  // src/commands/approve.ts
22676
- import { existsSync as existsSync13, readFileSync as readFileSync15 } from "node:fs";
23323
+ import { existsSync as existsSync13, readFileSync as readFileSync18 } from "node:fs";
22677
23324
 
22678
23325
  // ../shield/src/hash.ts
22679
23326
  import { createHash as createHash6 } from "node:crypto";
23327
+
23328
+ // ../shield/src/canonical.ts
22680
23329
  function canonicalJson(value) {
22681
23330
  if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
22682
23331
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
@@ -22684,6 +23333,8 @@ function canonicalJson(value) {
22684
23333
  const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
22685
23334
  return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
22686
23335
  }
23336
+
23337
+ // ../shield/src/hash.ts
22687
23338
  function toolFingerprint(tool) {
22688
23339
  return createHash6("sha256").update(canonicalJson({ name: tool.name, description: tool.description ?? "", inputSchema: tool.inputSchema ?? {} })).digest("hex");
22689
23340
  }
@@ -22747,7 +23398,7 @@ var LineSplitter = class {
22747
23398
 
22748
23399
  // ../shield/src/policy.ts
22749
23400
  init_zod();
22750
- import { existsSync as existsSync4, readFileSync as readFileSync8 } from "node:fs";
23401
+ import { existsSync as existsSync4, readFileSync as readFileSync10 } from "node:fs";
22751
23402
  var PolicySchema = external_exports.object({
22752
23403
  allowedHosts: external_exports.array(external_exports.string().min(1)).default([]),
22753
23404
  mode: external_exports.enum(["enforce", "monitor"]).default("enforce"),
@@ -22818,7 +23469,7 @@ function loadPolicy(path) {
22818
23469
  if (!existsSync4(path)) return { ok: true, policy: DEFAULT_POLICY };
22819
23470
  let json2;
22820
23471
  try {
22821
- json2 = JSON.parse(readFileSync8(path, "utf8"));
23472
+ json2 = JSON.parse(readFileSync10(path, "utf8"));
22822
23473
  } catch {
22823
23474
  return { ok: false, error: `The policy file ${path} is not valid JSON.` };
22824
23475
  }
@@ -22842,8 +23493,8 @@ function hostAllowed(host, allowed) {
22842
23493
 
22843
23494
  // ../shield/src/state.ts
22844
23495
  init_zod();
22845
- import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync9, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
22846
- import { dirname as dirname3, join as join13 } from "node:path";
23496
+ import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync11, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
23497
+ import { dirname as dirname3, join as join14 } from "node:path";
22847
23498
  var Sha256 = external_exports.string().regex(/^[0-9a-f]{64}$/);
22848
23499
  var PinSchema = external_exports.object({
22849
23500
  hash: Sha256,
@@ -22887,15 +23538,15 @@ var StateSchema = external_exports.object({
22887
23538
  servers: external_exports.record(ServerStateSchema).default({})
22888
23539
  });
22889
23540
  var emptyState = () => ({ version: 1, servers: {} });
22890
- var statePath = (dir) => join13(dir, "pins.json");
22891
- var policyPath = (dir) => join13(dir, "policy.json");
22892
- var alertsPath = (dir) => join13(dir, "alerts.jsonl");
22893
- var vaultPath = (dir) => join13(dir, "vault");
23541
+ var statePath = (dir) => join14(dir, "pins.json");
23542
+ var policyPath = (dir) => join14(dir, "policy.json");
23543
+ var alertsPath = (dir) => join14(dir, "alerts.jsonl");
23544
+ var vaultPath = (dir) => join14(dir, "vault");
22894
23545
  function loadState(path) {
22895
23546
  if (!existsSync5(path)) return { ok: true, state: emptyState() };
22896
23547
  let json2;
22897
23548
  try {
22898
- json2 = JSON.parse(readFileSync9(path, "utf8"));
23549
+ json2 = JSON.parse(readFileSync11(path, "utf8"));
22899
23550
  } catch {
22900
23551
  return { ok: false, error: `The pin file ${path} is not valid JSON. Fix or delete it; the shield will not run without it.` };
22901
23552
  }
@@ -23308,7 +23959,7 @@ var PATTERNS2 = [
23308
23959
  { kind: "JSON web token", re: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}/g },
23309
23960
  { kind: "database URL with password", re: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^\s:/@]+:[^\s@/]{6,}@/g }
23310
23961
  ];
23311
- var ASSIGNMENT = /\b(?:[a-z0-9_]*?(?:secret|token|passw(?:or)?d|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|auth))["']?\s*[:=]\s*["']?([A-Za-z0-9_\-+/=.]{20,})/gi;
23962
+ var ASSIGNMENT2 = /\b(?:[a-z0-9_]*?(?:secret|token|passw(?:or)?d|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|auth))["']?\s*[:=]\s*["']?([A-Za-z0-9_\-+/=.]{20,})/gi;
23312
23963
  var PLACEHOLDER = /EXAMPLE_[A-Z0-9_]*DO_NOT_USE|\b(?:x{6,}|\*{6,}|your[_-]|changeme|placeholder|redacted|<[^>]+>)/i;
23313
23964
  function entropy(s) {
23314
23965
  const counts = /* @__PURE__ */ new Map();
@@ -23333,8 +23984,8 @@ function findCredentials(text) {
23333
23984
  re2.lastIndex = 0;
23334
23985
  for (const m of text.matchAll(re2)) add(kind, m[0]);
23335
23986
  }
23336
- ASSIGNMENT.lastIndex = 0;
23337
- for (const m of text.matchAll(ASSIGNMENT)) {
23987
+ ASSIGNMENT2.lastIndex = 0;
23988
+ for (const m of text.matchAll(ASSIGNMENT2)) {
23338
23989
  const value = m[1] ?? "";
23339
23990
  const classes = [/[a-z]/, /[A-Z]/, /\d/].filter((r) => r.test(value)).length;
23340
23991
  if (classes >= 2 && entropy(value) >= 3.5) add("secret assignment", value);
@@ -23533,8 +24184,8 @@ function throttle(o = {}) {
23533
24184
  }
23534
24185
 
23535
24186
  // ../shield/src/canary.ts
23536
- import { existsSync as existsSync6, lstatSync as lstatSync2, mkdirSync as mkdirSync4, readFileSync as readFileSync10, readdirSync as readdirSync2, realpathSync as realpathSync3, rmdirSync, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
23537
- import { dirname as dirname4, isAbsolute as isAbsolute6, join as join14, resolve as resolve9 } from "node:path";
24187
+ import { existsSync as existsSync6, lstatSync as lstatSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync12, readdirSync as readdirSync3, realpathSync as realpathSync3, rmdirSync, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
24188
+ import { dirname as dirname4, isAbsolute as isAbsolute6, join as join15, resolve as resolve9 } from "node:path";
23538
24189
  var TRAPS = [
23539
24190
  {
23540
24191
  name: ".env.canary",
@@ -23577,32 +24228,32 @@ function plantCanaries(root, o = {}) {
23577
24228
  return { ok: false, error: `Canary traps are already planted in ${root}. To replace them, run "exorcist canary --remove" first.` };
23578
24229
  }
23579
24230
  for (const d of [".exorcist", CANARY_TRAP_DIR]) {
23580
- const path = join14(root, d);
24231
+ const path = join15(root, d);
23581
24232
  if (existsSync6(path) || isSymlink(path)) {
23582
24233
  if (!isRealDir(path)) return { ok: false, error: `${path} is not a real folder (a symlink or a file); no traps were planted.` };
23583
24234
  }
23584
24235
  }
23585
24236
  const traps = TRAPS.slice(0, count);
23586
24237
  for (const t of traps) {
23587
- const path = join14(root, CANARY_TRAP_DIR, t.name);
24238
+ const path = join15(root, CANARY_TRAP_DIR, t.name);
23588
24239
  if (existsSync6(path)) return { ok: false, error: `${path} already exists; it was not overwritten.` };
23589
24240
  }
23590
24241
  const created = (o.now ? o.now() : /* @__PURE__ */ new Date()).toISOString();
23591
24242
  const records = [];
23592
- const madeDirs = [".exorcist", CANARY_TRAP_DIR].filter((d) => !existsSync6(join14(root, d)));
24243
+ const madeDirs = [".exorcist", CANARY_TRAP_DIR].filter((d) => !existsSync6(join15(root, d)));
23593
24244
  try {
23594
- mkdirSync4(join14(root, CANARY_TRAP_DIR), { recursive: true });
24245
+ mkdirSync4(join15(root, CANARY_TRAP_DIR), { recursive: true });
23595
24246
  for (const t of traps) {
23596
24247
  const token = newToken();
23597
24248
  const file = `${CANARY_TRAP_DIR}/${t.name}`;
23598
- writeFileSync4(join14(root, file), t.body(token), { flag: "wx" });
24249
+ writeFileSync4(join15(root, file), t.body(token), { flag: "wx" });
23599
24250
  records.push({ token, file, created });
23600
24251
  }
23601
24252
  writeFileSync4(recordsFile, `${JSON.stringify({ version: 1, canaries: records, ...madeDirs.length > 0 ? { madeDirs } : {} }, null, 2)}
23602
24253
  `);
23603
24254
  } catch (err) {
23604
- for (const r of records) rmSync2(join14(root, r.file), { force: true });
23605
- for (const d of [...madeDirs].reverse()) rmdirIfEmpty(join14(root, d));
24255
+ for (const r of records) rmSync2(join15(root, r.file), { force: true });
24256
+ for (const d of [...madeDirs].reverse()) rmdirIfEmpty(join15(root, d));
23606
24257
  return { ok: false, error: `Could not plant the canary traps: ${firstLine(err)}` };
23607
24258
  }
23608
24259
  const result = { ok: true, records, recordsFile };
@@ -23619,20 +24270,20 @@ function loadCanaries(root) {
23619
24270
  }
23620
24271
  function rmdirIfEmpty(path) {
23621
24272
  try {
23622
- if (lstatSync2(path).isDirectory() && readdirSync2(path).length === 0) rmdirSync(path);
24273
+ if (lstatSync3(path).isDirectory() && readdirSync3(path).length === 0) rmdirSync(path);
23623
24274
  } catch {
23624
24275
  }
23625
24276
  }
23626
24277
  function isSymlink(path) {
23627
24278
  try {
23628
- return lstatSync2(path).isSymbolicLink();
24279
+ return lstatSync3(path).isSymbolicLink();
23629
24280
  } catch {
23630
24281
  return false;
23631
24282
  }
23632
24283
  }
23633
24284
  function isRealDir(path) {
23634
24285
  try {
23635
- return lstatSync2(path).isDirectory();
24286
+ return lstatSync3(path).isDirectory();
23636
24287
  } catch {
23637
24288
  return false;
23638
24289
  }
@@ -23644,8 +24295,8 @@ function removeCanaries(root, o = {}) {
23644
24295
  if (!existing.ok) return existing;
23645
24296
  const removed = [];
23646
24297
  const warnings = [];
23647
- const stateFolder = join14(root, ".exorcist");
23648
- const trapFolder = join14(root, CANARY_TRAP_DIR);
24298
+ const stateFolder = join15(root, ".exorcist");
24299
+ const trapFolder = join15(root, CANARY_TRAP_DIR);
23649
24300
  const foldersReal = isRealDir(stateFolder) && isRealDir(trapFolder);
23650
24301
  let trapReal = null;
23651
24302
  try {
@@ -23655,7 +24306,7 @@ function removeCanaries(root, o = {}) {
23655
24306
  }
23656
24307
  let left = 0;
23657
24308
  for (const r of existing.canaries) {
23658
- const full = join14(root, r.file);
24309
+ const full = join15(root, r.file);
23659
24310
  const name = r.file.slice(`${CANARY_TRAP_DIR}/`.length);
23660
24311
  const leave = (why) => {
23661
24312
  left++;
@@ -23663,7 +24314,7 @@ function removeCanaries(root, o = {}) {
23663
24314
  };
23664
24315
  let st;
23665
24316
  try {
23666
- st = lstatSync2(full);
24317
+ st = lstatSync3(full);
23667
24318
  } catch {
23668
24319
  continue;
23669
24320
  }
@@ -23684,7 +24335,7 @@ function removeCanaries(root, o = {}) {
23684
24335
  leave("it is not inside the trap folder.");
23685
24336
  continue;
23686
24337
  }
23687
- if (!readFileSync10(full, "utf8").includes(r.token)) {
24338
+ if (!readFileSync12(full, "utf8").includes(r.token)) {
23688
24339
  leave("it no longer holds the token it was planted with, so it may not be the trap any more.");
23689
24340
  continue;
23690
24341
  }
@@ -23699,7 +24350,7 @@ function removeCanaries(root, o = {}) {
23699
24350
  return { ok: true, removed, warnings };
23700
24351
  }
23701
24352
  try {
23702
- const st = lstatSync2(recordsFile);
24353
+ const st = lstatSync3(recordsFile);
23703
24354
  if (isRealDir(stateFolder) && st.isFile()) {
23704
24355
  rmSync2(recordsFile);
23705
24356
  removed.push(CANARY_RECORDS_FILE);
@@ -23718,7 +24369,7 @@ function readPolicyObject(stateDir2) {
23718
24369
  const path = policyPath(stateDir2);
23719
24370
  if (!existsSync6(path)) return { ok: true, obj: {} };
23720
24371
  try {
23721
- const json2 = JSON.parse(readFileSync10(path, "utf8"));
24372
+ const json2 = JSON.parse(readFileSync12(path, "utf8"));
23722
24373
  if (!json2 || typeof json2 !== "object" || Array.isArray(json2)) return { ok: false, error: `${path} is not a JSON object.` };
23723
24374
  return { ok: true, obj: json2 };
23724
24375
  } catch (err) {
@@ -23749,7 +24400,7 @@ function clearPolicyCanaries(stateDir2, recordsFile) {
23749
24400
  }
23750
24401
  }
23751
24402
  function canariesFileFor(stateDir2, policyCanaries) {
23752
- if (!policyCanaries) return join14(stateDir2, "canaries.json");
24403
+ if (!policyCanaries) return join15(stateDir2, "canaries.json");
23753
24404
  return isAbsolute6(policyCanaries) ? policyCanaries : resolve9(stateDir2, policyCanaries);
23754
24405
  }
23755
24406
  function allStrings(value) {
@@ -23785,8 +24436,8 @@ function findCanary(value, canaries) {
23785
24436
  init_zod();
23786
24437
  import { createHash as createHash7, randomBytes as randomBytes3 } from "node:crypto";
23787
24438
  import { spawnSync } from "node:child_process";
23788
- import { lstatSync as lstatSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync11, readdirSync as readdirSync3, renameSync as renameSync4, rmSync as rmSync3, unlinkSync, writeFileSync as writeFileSync5 } from "node:fs";
23789
- import { join as join15 } from "node:path";
24439
+ import { lstatSync as lstatSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync13, readdirSync as readdirSync4, renameSync as renameSync4, rmSync as rmSync3, unlinkSync, writeFileSync as writeFileSync5 } from "node:fs";
24440
+ import { join as join16 } from "node:path";
23790
24441
  var SESSION_RULE_ID = "EX-027";
23791
24442
  var SESSION_TTL_MS = 2 * 60 * 60 * 1e3;
23792
24443
  var MAX_FACTS = 32;
@@ -23969,14 +24620,14 @@ var TMP_RE = /\.tmp$/;
23969
24620
  function code(err) {
23970
24621
  return err && typeof err === "object" && "code" in err ? String(err.code) : "error";
23971
24622
  }
23972
- var sessionsPath = (stateDir2) => join15(stateDir2, "sessions");
24623
+ var sessionsPath = (stateDir2) => join16(stateDir2, "sessions");
23973
24624
  var FileSessionStore = class {
23974
24625
  constructor(stateDir2, key, ttlMs = SESSION_TTL_MS) {
23975
24626
  this.key = key;
23976
24627
  this.ttlMs = ttlMs;
23977
24628
  if (!isSessionKey(key)) throw new Error(`Invalid session key "${key}".`);
23978
24629
  this.root = sessionsPath(stateDir2);
23979
- this.dir = join15(this.root, key);
24630
+ this.dir = join16(this.root, key);
23980
24631
  }
23981
24632
  dir;
23982
24633
  root;
@@ -23986,7 +24637,7 @@ var FileSessionStore = class {
23986
24637
  const problems = [];
23987
24638
  let names;
23988
24639
  try {
23989
- names = readdirSync3(this.dir);
24640
+ names = readdirSync4(this.dir);
23990
24641
  } catch (err) {
23991
24642
  if (code(err) === "ENOENT") return { records, problems };
23992
24643
  return { records, problems: [`the session folder ${this.dir} could not be read (${code(err)})`] };
@@ -23998,10 +24649,10 @@ var FileSessionStore = class {
23998
24649
  problems.push(`${name} in ${this.dir} is not a session record`);
23999
24650
  continue;
24000
24651
  }
24001
- const path = join15(this.dir, name);
24652
+ const path = join16(this.dir, name);
24002
24653
  let st;
24003
24654
  try {
24004
- st = lstatSync3(path);
24655
+ st = lstatSync4(path);
24005
24656
  } catch (err) {
24006
24657
  if (code(err) !== "ENOENT") problems.push(`${name} could not be read (${code(err)})`);
24007
24658
  continue;
@@ -24017,7 +24668,7 @@ var FileSessionStore = class {
24017
24668
  }
24018
24669
  let json2;
24019
24670
  try {
24020
- json2 = JSON.parse(readFileSync11(path, "utf8"));
24671
+ json2 = JSON.parse(readFileSync13(path, "utf8"));
24021
24672
  } catch (err) {
24022
24673
  if (code(err) !== "ENOENT") problems.push(`${name} is not valid JSON`);
24023
24674
  continue;
@@ -24032,7 +24683,7 @@ var FileSessionStore = class {
24032
24683
  return { records, problems };
24033
24684
  }
24034
24685
  write(record3) {
24035
- const path = join15(this.dir, `${record3.writer}.json`);
24686
+ const path = join16(this.dir, `${record3.writer}.json`);
24036
24687
  const tmp = `${path}.${process.pid}.${randomBytes3(4).toString("hex")}.tmp`;
24037
24688
  try {
24038
24689
  mkdirSync5(this.dir, { recursive: true, mode: 448 });
@@ -24056,24 +24707,24 @@ var FileSessionStore = class {
24056
24707
  this.lastPrune = t;
24057
24708
  const old = (st, age) => t - st.mtimeMs > age;
24058
24709
  try {
24059
- for (const name of readdirSync3(this.dir)) {
24710
+ for (const name of readdirSync4(this.dir)) {
24060
24711
  if (name === `${own}.json`) continue;
24061
- const p = join15(this.dir, name);
24062
- const st = lstatSync3(p);
24712
+ const p = join16(this.dir, name);
24713
+ const st = lstatSync4(p);
24063
24714
  if (st.isFile() && old(st, TMP_RE.test(name) ? 6e4 : this.ttlMs)) unlinkSync(p);
24064
24715
  }
24065
24716
  } catch {
24066
24717
  }
24067
24718
  try {
24068
- for (const name of readdirSync3(this.root).slice(0, MAX_SESSION_DIRS)) {
24719
+ for (const name of readdirSync4(this.root).slice(0, MAX_SESSION_DIRS)) {
24069
24720
  if (name === this.key || !KEY_RE.test(name)) continue;
24070
- const p = join15(this.root, name);
24071
- const st = lstatSync3(p);
24721
+ const p = join16(this.root, name);
24722
+ const st = lstatSync4(p);
24072
24723
  if (!st.isDirectory()) continue;
24073
- const entries = readdirSync3(p);
24724
+ const entries = readdirSync4(p);
24074
24725
  const newest = entries.reduce((m, e) => {
24075
24726
  try {
24076
- return Math.max(m, lstatSync3(join15(p, e)).mtimeMs);
24727
+ return Math.max(m, lstatSync4(join16(p, e)).mtimeMs);
24077
24728
  } catch {
24078
24729
  return m;
24079
24730
  }
@@ -24088,7 +24739,7 @@ function liveSessions(stateDir2, now = /* @__PURE__ */ new Date(), ttlMs = SESSI
24088
24739
  const root = sessionsPath(stateDir2);
24089
24740
  let names;
24090
24741
  try {
24091
- names = readdirSync3(root);
24742
+ names = readdirSync4(root);
24092
24743
  } catch {
24093
24744
  return [];
24094
24745
  }
@@ -24241,7 +24892,7 @@ var STDOUT_CAP = 256;
24241
24892
  function macOsAuth(o = {}) {
24242
24893
  const timeoutMs = o.timeoutMs ?? OS_PROMPT_TIMEOUT_MS;
24243
24894
  const blocked = () => blockedReason(o.env ?? process.env, o.platform ?? process.platform);
24244
- const run = async (script, reason) => {
24895
+ const run2 = async (script, reason) => {
24245
24896
  let spawnFn;
24246
24897
  try {
24247
24898
  spawnFn = o.spawn ?? (await import("node:child_process")).spawn;
@@ -24298,7 +24949,7 @@ function macOsAuth(o = {}) {
24298
24949
  async available() {
24299
24950
  if (blocked() !== null) return false;
24300
24951
  try {
24301
- const r = await run(AVAILABLE_SCRIPT, null);
24952
+ const r = await run2(AVAILABLE_SCRIPT, null);
24302
24953
  return r.kind === "out" && r.text === "yes";
24303
24954
  } catch {
24304
24955
  return false;
@@ -24307,7 +24958,7 @@ function macOsAuth(o = {}) {
24307
24958
  async verify(reason) {
24308
24959
  if (blocked() !== null) return "error";
24309
24960
  try {
24310
- const r = await run(VERIFY_SCRIPT, reason);
24961
+ const r = await run2(VERIFY_SCRIPT, reason);
24311
24962
  if (r.kind === "timeout") return "timeout";
24312
24963
  if (r.kind === "fail") return "error";
24313
24964
  if (r.text === "ok") return "ok";
@@ -24321,14 +24972,14 @@ function macOsAuth(o = {}) {
24321
24972
  }
24322
24973
  async function resolveRelease(policyValue, osAuth) {
24323
24974
  if (policyValue === "terminal") return { mode: "terminal" };
24324
- let ok = false;
24975
+ let ok2 = false;
24325
24976
  let threw = false;
24326
24977
  try {
24327
- ok = await osAuth.available();
24978
+ ok2 = await osAuth.available();
24328
24979
  } catch {
24329
24980
  threw = true;
24330
24981
  }
24331
- if (ok) return { mode: "os" };
24982
+ if (ok2) return { mode: "os" };
24332
24983
  const why = threw ? "the check for the system prompt failed" : blockedReason() ?? "macOS LocalAuthentication is not available here";
24333
24984
  return { mode: "terminal", note: why };
24334
24985
  }
@@ -24793,9 +25444,17 @@ var ShieldEngine = class {
24793
25444
  */
24794
25445
  afterOwnerVerified(call, id, tool, ownerNo) {
24795
25446
  const params = call.params ?? {};
25447
+ const answered = { ruleId: SESSION_RULE_ID, by: "user", via: "os", ...ownerNo ? { prompt: ownerNo } : {} };
25448
+ const withheld = this.withheld.get(tool);
25449
+ if (withheld && this.enforcing()) {
25450
+ this.callEvent(tool, "blocked", { ...answered, ruleId: withheld.ruleId, why: `Verified in the system prompt, but it is withheld: ${withheld.reason}` });
25451
+ return [
25452
+ { type: "forward", to: "client", message: toolErrorResult(id, `Exorcist 98 blocked "${cleanText(tool, 80)}": ${withheld.reason} Nothing was sent to the tool.`) },
25453
+ this.alert({ ruleId: withheld.ruleId, severity: "high", tool, message: `Refused a call to the withheld tool "${cleanText(tool, 80)}" after device verification.` })
25454
+ ];
25455
+ }
24796
25456
  const ss = serverState(this.o.io.load(), this.o.server);
24797
25457
  const verdict = inspectCall(params.arguments, { allowedHosts: this.o.policy.allowedHosts, approvedHosts: ss.approvedHosts });
24798
- const answered = { ruleId: SESSION_RULE_ID, by: "user", via: "os", ...ownerNo ? { prompt: ownerNo } : {} };
24799
25458
  if (verdict.action === "allow") {
24800
25459
  return this.sendCall(call, id, tool, { ...answered, why: "Released by the operating system check (Touch ID or login password), once. Nothing was granted." });
24801
25460
  }
@@ -24804,7 +25463,12 @@ var ShieldEngine = class {
24804
25463
  }
24805
25464
  /** The agent's connection ended: drop calls still waiting for device verification. */
24806
25465
  abandon() {
24807
- for (const [ticket, held] of this.heldCalls) if (held.kind === "os") this.heldCalls.delete(ticket);
25466
+ for (const [ticket, held] of this.heldCalls) {
25467
+ if (held.kind !== "os") continue;
25468
+ this.heldCalls.delete(ticket);
25469
+ const ownerNo = Number(ticket.slice(OWNER_PREFIX.length)) || void 0;
25470
+ this.callEvent(held.tool, "blocked", { ruleId: SESSION_RULE_ID, via: "os", ...ownerNo ? { prompt: ownerNo } : {}, why: "The agent connection ended while the system prompt was open. Nothing was sent." });
25471
+ }
24808
25472
  }
24809
25473
  /** Ask the user whether a call the Session Guard held may go out (S-004 prompt, EX-027). */
24810
25474
  askSession(call, id, tool, out, story, hosts) {
@@ -25220,12 +25884,12 @@ var ShieldEngine = class {
25220
25884
 
25221
25885
  // ../shield/src/proxy.ts
25222
25886
  import { spawn } from "node:child_process";
25223
- import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync14, statSync as statSync8 } from "node:fs";
25887
+ import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync17, statSync as statSync9 } from "node:fs";
25224
25888
  import { dirname as dirname8 } from "node:path";
25225
25889
 
25226
25890
  // ../shield/src/lockfile.ts
25227
25891
  import { existsSync as existsSync7 } from "node:fs";
25228
- import { dirname as dirname5, join as join16, parse as parsePath, resolve as resolve10 } from "node:path";
25892
+ import { dirname as dirname5, join as join17, parse as parsePath, resolve as resolve10 } from "node:path";
25229
25893
  init_zod();
25230
25894
  var Sha2562 = external_exports.string().regex(/^[0-9a-f]{64}$/);
25231
25895
  var LockToolSchema = external_exports.object({
@@ -25400,9 +26064,9 @@ function findLockFile(starts) {
25400
26064
  for (const start of starts) {
25401
26065
  const { root } = parsePath(resolve10(start));
25402
26066
  for (let dir = resolve10(start); ; dir = dirname5(dir)) {
25403
- const candidate = join16(dir, LOCK_FILE);
26067
+ const candidate = join17(dir, LOCK_FILE);
25404
26068
  if (existsSync7(candidate)) return candidate;
25405
- if (PROJECT_MARKERS2.some((m) => existsSync7(join16(dir, m)))) break;
26069
+ if (PROJECT_MARKERS2.some((m) => existsSync7(join17(dir, m)))) break;
25406
26070
  if (dir === root || dirname5(dir) === dir) break;
25407
26071
  }
25408
26072
  }
@@ -25411,8 +26075,8 @@ function findLockFile(starts) {
25411
26075
 
25412
26076
  // ../shield/src/vault.ts
25413
26077
  import { createHash as createHash8, randomBytes as randomBytes4 } from "node:crypto";
25414
- import { copyFileSync, existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync4, rmSync as rmSync4, statSync as statSync6, writeFileSync as writeFileSync6 } from "node:fs";
25415
- import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute7, join as join17, resolve as resolve11 } from "node:path";
26078
+ import { copyFileSync, existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync14, readdirSync as readdirSync5, rmSync as rmSync4, statSync as statSync7, writeFileSync as writeFileSync6 } from "node:fs";
26079
+ import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute7, join as join18, resolve as resolve11 } from "node:path";
25416
26080
  init_zod();
25417
26081
  var SafeRel = external_exports.string().min(1).max(1024).refine(
25418
26082
  (p) => !isAbsolute7(p) && !p.includes("\\") && !p.includes("\0") && p.split("/").every((seg) => seg !== "" && seg !== "." && seg !== ".."),
@@ -25445,20 +26109,20 @@ function newId(label, now) {
25445
26109
  return `${stamp}-${slug}-${randomBytes4(2).toString("hex")}`;
25446
26110
  }
25447
26111
  function entryDir(vaultDir, id) {
25448
- return join17(vaultDir, id);
26112
+ return join18(vaultDir, id);
25449
26113
  }
25450
26114
  function writeManifest(vaultDir, e) {
25451
- writeFileSync6(join17(entryDir(vaultDir, e.id), "manifest.json"), `${JSON.stringify(e, null, 2)}
26115
+ writeFileSync6(join18(entryDir(vaultDir, e.id), "manifest.json"), `${JSON.stringify(e, null, 2)}
25452
26116
  `, "utf8");
25453
26117
  }
25454
26118
  function listEntries(vaultDir) {
25455
26119
  if (!existsSync8(vaultDir)) return [];
25456
26120
  const out = [];
25457
- for (const name of readdirSync4(vaultDir)) {
25458
- const file = join17(vaultDir, name, "manifest.json");
26121
+ for (const name of readdirSync5(vaultDir)) {
26122
+ const file = join18(vaultDir, name, "manifest.json");
25459
26123
  if (!existsSync8(file)) continue;
25460
26124
  try {
25461
- const parsed = EntrySchema.safeParse(JSON.parse(readFileSync12(file, "utf8")));
26125
+ const parsed = EntrySchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
25462
26126
  if (parsed.success) out.push(parsed.data);
25463
26127
  } catch {
25464
26128
  }
@@ -25476,7 +26140,7 @@ function activeFor(vaultDir, target, serverName) {
25476
26140
  function readConfig(path) {
25477
26141
  let text;
25478
26142
  try {
25479
- text = readFileSync12(path, "utf8");
26143
+ text = readFileSync14(path, "utf8");
25480
26144
  } catch {
25481
26145
  return fail2(`Could not read ${path}.`);
25482
26146
  }
@@ -25505,7 +26169,7 @@ function quarantineServer(o) {
25505
26169
  mkdirSync6(dir, { recursive: true });
25506
26170
  const backup = `${JSON.stringify(entry, null, 2)}
25507
26171
  `;
25508
- writeFileSync6(join17(dir, "entry.json"), backup, "utf8");
26172
+ writeFileSync6(join18(dir, "entry.json"), backup, "utf8");
25509
26173
  const e = {
25510
26174
  id,
25511
26175
  kind: "mcp-server",
@@ -25523,16 +26187,16 @@ function quarantineServer(o) {
25523
26187
  }
25524
26188
  function quarantineFile(o) {
25525
26189
  const target = resolve11(o.filePath);
25526
- if (!existsSync8(target) || !statSync6(target).isFile()) return fail2(`${target} is not a file.`);
26190
+ if (!existsSync8(target) || !statSync7(target).isFile()) return fail2(`${target} is not a file.`);
25527
26191
  if (activeFor(o.vaultDir, target)) return fail2(`${target} is already in the vault.`);
25528
26192
  const now = o.now ?? /* @__PURE__ */ new Date();
25529
26193
  const id = newId(basename6(target), now);
25530
26194
  const dir = entryDir(o.vaultDir, id);
25531
- mkdirSync6(join17(dir, "files"), { recursive: true });
25532
- const stored = join17(dir, "files", basename6(target));
26195
+ mkdirSync6(join18(dir, "files"), { recursive: true });
26196
+ const stored = join18(dir, "files", basename6(target));
25533
26197
  copyFileSync(target, stored);
25534
- const digest = sha2562(readFileSync12(stored));
25535
- if (digest !== sha2562(readFileSync12(target))) {
26198
+ const digest = sha2562(readFileSync14(stored));
26199
+ if (digest !== sha2562(readFileSync14(target))) {
25536
26200
  rmSync4(dir, { recursive: true, force: true });
25537
26201
  return fail2("The backup did not match the original, so nothing was moved.");
25538
26202
  }
@@ -25546,9 +26210,9 @@ function backupAndRewrite(o) {
25546
26210
  if (o.files.length === 0) return fail2("There are no files to change.");
25547
26211
  for (const f of o.files) {
25548
26212
  if (!SafeRel.safeParse(f.rel).success) return fail2(`Refusing to write outside ${root}: ${f.rel}`);
25549
- const path = join17(root, f.rel);
26213
+ const path = join18(root, f.rel);
25550
26214
  if (!existsSync8(path)) return fail2(`${f.rel} is gone; nothing was changed.`);
25551
- if (sha2562(readFileSync12(path)) !== sha2562(Buffer.from(f.before, "utf8"))) {
26215
+ if (sha2562(readFileSync14(path)) !== sha2562(Buffer.from(f.before, "utf8"))) {
25552
26216
  return fail2(`${f.rel} changed since it was scanned; nothing was changed. Run exorcise again.`);
25553
26217
  }
25554
26218
  }
@@ -25558,11 +26222,11 @@ function backupAndRewrite(o) {
25558
26222
  const files = [];
25559
26223
  try {
25560
26224
  for (const f of o.files) {
25561
- const stored = join17(dir, "files", f.rel);
26225
+ const stored = join18(dir, "files", f.rel);
25562
26226
  mkdirSync6(dirname6(stored), { recursive: true });
25563
- copyFileSync(join17(root, f.rel), stored);
25564
- const digest = sha2562(readFileSync12(stored));
25565
- if (digest !== sha2562(readFileSync12(join17(root, f.rel)))) throw new Error("mismatch");
26227
+ copyFileSync(join18(root, f.rel), stored);
26228
+ const digest = sha2562(readFileSync14(stored));
26229
+ if (digest !== sha2562(readFileSync14(join18(root, f.rel)))) throw new Error("mismatch");
25566
26230
  files.push({ rel: f.rel, sha256: digest, after: sha2562(Buffer.from(f.after, "utf8")) });
25567
26231
  }
25568
26232
  } catch {
@@ -25580,47 +26244,47 @@ function backupAndRewrite(o) {
25580
26244
  status: "quarantined"
25581
26245
  };
25582
26246
  writeManifest(o.vaultDir, e);
25583
- for (const f of o.files) writeFileSync6(join17(root, f.rel), f.after, "utf8");
26247
+ for (const f of o.files) writeFileSync6(join18(root, f.rel), f.after, "utf8");
25584
26248
  return { ok: true, value: e };
25585
26249
  }
25586
26250
  function restoreExorcised(vaultDir, e, force) {
25587
26251
  const files = e.files ?? [];
25588
26252
  const blocked = files.filter((f) => {
25589
- const path = join17(e.target, f.rel);
26253
+ const path = join18(e.target, f.rel);
25590
26254
  if (!existsSync8(path)) return false;
25591
- const now = sha2562(readFileSync12(path));
26255
+ const now = sha2562(readFileSync14(path));
25592
26256
  return now !== f.after && now !== f.sha256;
25593
26257
  });
25594
26258
  if (blocked.length > 0 && !force) {
25595
26259
  return fail2(`${blocked.map((f) => f.rel).join(", ")} changed after the exorcism. Use --force to overwrite ${blocked.length === 1 ? "it" : "them"} with the backup.`);
25596
26260
  }
25597
26261
  for (const f of files) {
25598
- const stored = join17(entryDir(vaultDir, e.id), "files", f.rel);
25599
- if (sha2562(readFileSync12(stored)) !== f.sha256) return fail2(`The backup of ${f.rel} is damaged (sha256 does not match); nothing was restored.`);
26262
+ const stored = join18(entryDir(vaultDir, e.id), "files", f.rel);
26263
+ if (sha2562(readFileSync14(stored)) !== f.sha256) return fail2(`The backup of ${f.rel} is damaged (sha256 does not match); nothing was restored.`);
25600
26264
  }
25601
26265
  for (const f of files) {
25602
- const path = join17(e.target, f.rel);
26266
+ const path = join18(e.target, f.rel);
25603
26267
  mkdirSync6(dirname6(path), { recursive: true });
25604
- copyFileSync(join17(entryDir(vaultDir, e.id), "files", f.rel), path);
26268
+ copyFileSync(join18(entryDir(vaultDir, e.id), "files", f.rel), path);
25605
26269
  }
25606
26270
  return { ok: true, value: null };
25607
26271
  }
25608
26272
  function backupFile(vaultDir, e) {
25609
- return e.kind === "mcp-server" ? join17(entryDir(vaultDir, e.id), "entry.json") : join17(entryDir(vaultDir, e.id), "files", basename6(e.target));
26273
+ return e.kind === "mcp-server" ? join18(entryDir(vaultDir, e.id), "entry.json") : join18(entryDir(vaultDir, e.id), "files", basename6(e.target));
25610
26274
  }
25611
26275
  function diffEntry(vaultDir, id) {
25612
26276
  const e = getEntry(vaultDir, id);
25613
26277
  if (!e) return fail2(`There is no vault entry "${id}".`);
25614
26278
  if (e.kind === "exorcise") {
25615
26279
  const parts = (e.files ?? []).map((f) => {
25616
- const path = join17(e.target, f.rel);
25617
- const before2 = readFileSync12(join17(entryDir(vaultDir, e.id), "files", f.rel), "utf8");
25618
- const after2 = existsSync8(path) ? readFileSync12(path, "utf8") : "";
26280
+ const path = join18(e.target, f.rel);
26281
+ const before2 = readFileSync14(join18(entryDir(vaultDir, e.id), "files", f.rel), "utf8");
26282
+ const after2 = existsSync8(path) ? readFileSync14(path, "utf8") : "";
25619
26283
  return createTwoFilesPatch(`${f.rel} (backup)`, `${f.rel} (now)`, before2, after2, "", "", { context: 3 });
25620
26284
  });
25621
26285
  return { ok: true, value: parts.join("") };
25622
26286
  }
25623
- const before = readFileSync12(backupFile(vaultDir, e), "utf8");
26287
+ const before = readFileSync14(backupFile(vaultDir, e), "utf8");
25624
26288
  let after = "";
25625
26289
  if (e.kind === "mcp-server") {
25626
26290
  const cfg = readConfig(e.target);
@@ -25628,7 +26292,7 @@ function diffEntry(vaultDir, id) {
25628
26292
  after = now ? `${JSON.stringify(now, null, 2)}
25629
26293
  ` : "";
25630
26294
  } else if (existsSync8(e.target)) {
25631
- after = readFileSync12(e.target, "utf8");
26295
+ after = readFileSync14(e.target, "utf8");
25632
26296
  }
25633
26297
  const label = e.kind === "mcp-server" ? `${e.serverName} in ${basename6(e.target)}` : basename6(e.target);
25634
26298
  return { ok: true, value: createTwoFilesPatch(`${label} (backup)`, `${label} (now)`, before, after, "", "", { context: 3 }) };
@@ -25643,7 +26307,7 @@ function restoreEntry(vaultDir, id, opts = {}) {
25643
26307
  } else if (e.kind === "mcp-server") {
25644
26308
  const cfg = readConfig(e.target);
25645
26309
  if (!cfg.ok) return cfg;
25646
- const original = JSON.parse(readFileSync12(backupFile(vaultDir, e), "utf8"));
26310
+ const original = JSON.parse(readFileSync14(backupFile(vaultDir, e), "utf8"));
25647
26311
  const servers = cfg.value.mcpServers ??= {};
25648
26312
  const current = servers[e.serverName ?? ""];
25649
26313
  if (!current) {
@@ -25656,7 +26320,7 @@ function restoreEntry(vaultDir, id, opts = {}) {
25656
26320
  writeConfig(e.target, cfg.value);
25657
26321
  } else {
25658
26322
  const stored = backupFile(vaultDir, e);
25659
- if (existsSync8(e.target) && sha2562(readFileSync12(e.target)) !== e.sha256 && !opts.force) {
26323
+ if (existsSync8(e.target) && sha2562(readFileSync14(e.target)) !== e.sha256 && !opts.force) {
25660
26324
  return fail2(`${e.target} exists and is different from the quarantined file. Use --force to overwrite it.`);
25661
26325
  }
25662
26326
  mkdirSync6(resolve11(e.target, ".."), { recursive: true });
@@ -25669,15 +26333,404 @@ function restoreEntry(vaultDir, id, opts = {}) {
25669
26333
 
25670
26334
  // ../shield/src/events.ts
25671
26335
  init_zod();
25672
- import { closeSync as closeSync3, constants as constants2, fstatSync as fstatSync2, lstatSync as lstatSync4, mkdirSync as mkdirSync7, openSync as openSync3, readSync as readSync3, renameSync as renameSync5, rmdirSync as rmdirSync2, writeSync } from "node:fs";
25673
- import { join as join18 } from "node:path";
25674
- var eventsPath = (dir) => join18(dir, "events.jsonl");
25675
- var oldEventsPath = (dir) => join18(dir, "events.1.jsonl");
25676
- var lockPath = (dir) => join18(dir, "events.lock");
26336
+ import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync3, lstatSync as lstatSync6, mkdirSync as mkdirSync7, openSync as openSync4, readSync as readSync4, renameSync as renameSync6, rmdirSync as rmdirSync2, writeSync as writeSync2 } from "node:fs";
26337
+ import { join as join20 } from "node:path";
26338
+
26339
+ // ../shield/src/chain.ts
26340
+ init_zod();
26341
+ import { createHash as createHash9, randomBytes as randomBytes5 } from "node:crypto";
26342
+ import { closeSync as closeSync3, constants as constants2, fstatSync as fstatSync2, lstatSync as lstatSync5, openSync as openSync3, readFileSync as readFileSync15, readSync as readSync3, renameSync as renameSync5, unlinkSync as unlinkSync2, writeSync } from "node:fs";
26343
+ import { join as join19 } from "node:path";
26344
+
26345
+ // ../shield/src/chain-core.ts
26346
+ init_zod();
26347
+
26348
+ // ../shield/src/sha256.ts
26349
+ var K = new Uint32Array([
26350
+ 1116352408,
26351
+ 1899447441,
26352
+ 3049323471,
26353
+ 3921009573,
26354
+ 961987163,
26355
+ 1508970993,
26356
+ 2453635748,
26357
+ 2870763221,
26358
+ 3624381080,
26359
+ 310598401,
26360
+ 607225278,
26361
+ 1426881987,
26362
+ 1925078388,
26363
+ 2162078206,
26364
+ 2614888103,
26365
+ 3248222580,
26366
+ 3835390401,
26367
+ 4022224774,
26368
+ 264347078,
26369
+ 604807628,
26370
+ 770255983,
26371
+ 1249150122,
26372
+ 1555081692,
26373
+ 1996064986,
26374
+ 2554220882,
26375
+ 2821834349,
26376
+ 2952996808,
26377
+ 3210313671,
26378
+ 3336571891,
26379
+ 3584528711,
26380
+ 113926993,
26381
+ 338241895,
26382
+ 666307205,
26383
+ 773529912,
26384
+ 1294757372,
26385
+ 1396182291,
26386
+ 1695183700,
26387
+ 1986661051,
26388
+ 2177026350,
26389
+ 2456956037,
26390
+ 2730485921,
26391
+ 2820302411,
26392
+ 3259730800,
26393
+ 3345764771,
26394
+ 3516065817,
26395
+ 3600352804,
26396
+ 4094571909,
26397
+ 275423344,
26398
+ 430227734,
26399
+ 506948616,
26400
+ 659060556,
26401
+ 883997877,
26402
+ 958139571,
26403
+ 1322822218,
26404
+ 1537002063,
26405
+ 1747873779,
26406
+ 1955562222,
26407
+ 2024104815,
26408
+ 2227730452,
26409
+ 2361852424,
26410
+ 2428436474,
26411
+ 2756734187,
26412
+ 3204031479,
26413
+ 3329325298
26414
+ ]);
26415
+ var rotr = (x, n) => x >>> n | x << 32 - n;
26416
+ function sha256Hex(text) {
26417
+ const data = new TextEncoder().encode(text);
26418
+ const total = data.length + 9 + 63 >> 6 << 6;
26419
+ const buf = new Uint8Array(total);
26420
+ buf.set(data);
26421
+ buf[data.length] = 128;
26422
+ const view = new DataView(buf.buffer);
26423
+ view.setUint32(total - 8, Math.floor(data.length / 536870912), false);
26424
+ view.setUint32(total - 4, data.length << 3 >>> 0, false);
26425
+ const h = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
26426
+ const w = new Uint32Array(64);
26427
+ for (let off = 0; off < total; off += 64) {
26428
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4, false);
26429
+ for (let i = 16; i < 64; i++) {
26430
+ const w15 = w[i - 15];
26431
+ const w2 = w[i - 2];
26432
+ const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ w15 >>> 3;
26433
+ const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ w2 >>> 10;
26434
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 | 0;
26435
+ }
26436
+ let a = h[0], b = h[1], c = h[2], d = h[3];
26437
+ let e = h[4], f = h[5], g = h[6], hh = h[7];
26438
+ for (let i = 0; i < 64; i++) {
26439
+ const t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + (e & f ^ ~e & g) + K[i] + w[i] | 0;
26440
+ const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) | 0;
26441
+ hh = g;
26442
+ g = f;
26443
+ f = e;
26444
+ e = d + t1 | 0;
26445
+ d = c;
26446
+ c = b;
26447
+ b = a;
26448
+ a = t1 + t2 | 0;
26449
+ }
26450
+ h[0] = h[0] + a | 0;
26451
+ h[1] = h[1] + b | 0;
26452
+ h[2] = h[2] + c | 0;
26453
+ h[3] = h[3] + d | 0;
26454
+ h[4] = h[4] + e | 0;
26455
+ h[5] = h[5] + f | 0;
26456
+ h[6] = h[6] + g | 0;
26457
+ h[7] = h[7] + hh | 0;
26458
+ }
26459
+ let out = "";
26460
+ for (let i = 0; i < 8; i++) out += (h[i] >>> 0).toString(16).padStart(8, "0");
26461
+ return out;
26462
+ }
26463
+
26464
+ // ../shield/src/chain-core.ts
26465
+ var HEX64 = /^[0-9a-f]{64}$/;
26466
+ var HeadRecordSchema = external_exports.object({
26467
+ v: external_exports.literal(1),
26468
+ genesis: external_exports.string().regex(HEX64),
26469
+ seq: external_exports.number().int().positive(),
26470
+ hash: external_exports.string().regex(HEX64)
26471
+ }).strict();
26472
+ function canonicalize(e) {
26473
+ const { ...rest } = e;
26474
+ delete rest["hash"];
26475
+ return canonicalJson(rest);
26476
+ }
26477
+ function eventHash(e) {
26478
+ return sha256Hex(canonicalize(e));
26479
+ }
26480
+ function chainOf(e) {
26481
+ const { seq: seq2, prev, hash } = e;
26482
+ if (typeof seq2 === "number" && Number.isInteger(seq2) && seq2 > 0 && typeof prev === "string" && typeof hash === "string") {
26483
+ return { seq: seq2, prev, hash };
26484
+ }
26485
+ return null;
26486
+ }
26487
+ var broken = (atSeq, reason, detail) => ({ status: "broken", atSeq, reason, detail });
26488
+ function verifyChain(lines, head, genesis, opts) {
26489
+ const g = genesis ?? head?.genesis ?? null;
26490
+ if (genesis !== null && head !== null && genesis !== head.genesis) {
26491
+ return broken(1, "head-mismatch", "the head record belongs to a different log (its genesis value does not match)");
26492
+ }
26493
+ let started = false;
26494
+ let expectedSeq = 1;
26495
+ let prevHash = g;
26496
+ let last = null;
26497
+ let expectSeen = null;
26498
+ let trailing = 0;
26499
+ const want = opts?.expect;
26500
+ for (let i = 0; i < lines.length; i++) {
26501
+ const line = lines[i];
26502
+ const c = chainOf(line);
26503
+ if (c === null) {
26504
+ if (started) trailing++;
26505
+ continue;
26506
+ }
26507
+ if (trailing > 0) return broken(expectedSeq, "inserted", `a line without chain fields sits before event ${c.seq}, where event ${expectedSeq} should be`);
26508
+ const actual = eventHash({ ...line, seq: c.seq, prev: c.prev });
26509
+ if (!started) {
26510
+ started = true;
26511
+ if (c.seq !== 1 && opts?.allowRotatedStart === true) {
26512
+ expectedSeq = c.seq;
26513
+ prevHash = c.prev;
26514
+ }
26515
+ }
26516
+ if (actual !== c.hash) return broken(expectedSeq, "changed", `event ${expectedSeq} was changed after it was written (its hash no longer matches)`);
26517
+ if (c.seq === expectedSeq && (prevHash === null || c.prev === prevHash)) {
26518
+ } else if (c.seq === expectedSeq) {
26519
+ return broken(expectedSeq, "inserted", `an event that does not follow event ${expectedSeq - 1} sits at position ${expectedSeq}`);
26520
+ } else if (c.seq > expectedSeq) {
26521
+ const next = i + 1 < lines.length ? chainOf(lines[i + 1]) : null;
26522
+ if (next !== null && next.seq === expectedSeq) return broken(expectedSeq, "reordered", `events ${expectedSeq} and ${c.seq} are out of order`);
26523
+ return broken(expectedSeq, "removed", `event ${expectedSeq} is missing (the log jumps to ${c.seq})`);
26524
+ } else {
26525
+ return broken(c.seq, "reordered", `event ${c.seq} appears after event ${expectedSeq - 1}, out of order`);
26526
+ }
26527
+ if (want !== void 0 && c.seq === want.seq) expectSeen = c.hash;
26528
+ last = c;
26529
+ prevHash = c.hash;
26530
+ expectedSeq = c.seq + 1;
26531
+ }
26532
+ if (last === null) {
26533
+ if (head === null) return { status: "not-chained" };
26534
+ return broken(head.seq, "head-mismatch", "the log has no chained events but a head record exists (the log was emptied or replaced)");
26535
+ }
26536
+ if (head === null) return broken(last.seq, "head-mismatch", "the log has chained events but no head record");
26537
+ if (last.seq !== head.seq || last.hash !== head.hash) {
26538
+ return broken(Math.min(last.seq + 1, head.seq), "head-mismatch", "the log's end does not match its head record (it was cut short or replaced)");
26539
+ }
26540
+ if (want !== void 0 && expectSeen !== want.hash) {
26541
+ return broken(want.seq, "expect-mismatch", "the log's head does not match the expected hash");
26542
+ }
26543
+ return trailing > 0 ? { status: "intact", head, unchained: trailing } : { status: "intact", head };
26544
+ }
26545
+
26546
+ // ../shield/src/chain.ts
26547
+ var ok = (value) => ({ ok: true, value });
26548
+ var fail3 = (error2) => ({ ok: false, error: error2 });
26549
+ var headPath = (dir) => join19(dir, "events.head.json");
26550
+ var genesisPath = (dir) => join19(dir, "events.genesis.json");
26551
+ var GenesisFileSchema = external_exports.object({ v: external_exports.literal(1), genesis: external_exports.string().regex(HEX64) }).strict();
26552
+ var MAX_FILE_BYTES4 = 4096;
26553
+ function errCode(e) {
26554
+ return e && typeof e === "object" && "code" in e ? String(e.code) : "error";
26555
+ }
26556
+ function readSmall(path) {
26557
+ let fd = null;
26558
+ try {
26559
+ const st = lstatSync5(path, { throwIfNoEntry: false });
26560
+ if (st === void 0) return ok(null);
26561
+ if (!st.isFile()) return fail3("not a regular file");
26562
+ fd = openSync3(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
26563
+ if (fstatSync2(fd).size > MAX_FILE_BYTES4) return fail3("file is too large");
26564
+ return ok(readFileSync15(fd, "utf8"));
26565
+ } catch (e) {
26566
+ return errCode(e) === "ENOENT" ? ok(null) : fail3(`could not read (${errCode(e)})`);
26567
+ } finally {
26568
+ if (fd !== null) {
26569
+ try {
26570
+ closeSync3(fd);
26571
+ } catch {
26572
+ }
26573
+ }
26574
+ }
26575
+ }
26576
+ function parseWith(text, schema2) {
26577
+ let raw;
26578
+ try {
26579
+ raw = JSON.parse(text);
26580
+ } catch {
26581
+ return fail3("not valid JSON");
26582
+ }
26583
+ const r = schema2.safeParse(raw);
26584
+ return r.success ? ok(r.data) : fail3("does not match the expected shape");
26585
+ }
26586
+ function readGenesis(dir) {
26587
+ const t = readSmall(genesisPath(dir));
26588
+ if (!t.ok) return fail3(`genesis file: ${t.error}`);
26589
+ if (t.value === null) return ok(null);
26590
+ const g = parseWith(t.value, GenesisFileSchema);
26591
+ return g.ok ? ok(g.value.genesis) : fail3(`genesis file: ${g.error}`);
26592
+ }
26593
+ function writeNew(path, text) {
26594
+ let fd = null;
26595
+ try {
26596
+ fd = openSync3(path, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 384);
26597
+ writeSync(fd, text);
26598
+ return ok(void 0);
26599
+ } catch (e) {
26600
+ return fail3(errCode(e));
26601
+ } finally {
26602
+ if (fd !== null) {
26603
+ try {
26604
+ closeSync3(fd);
26605
+ } catch {
26606
+ }
26607
+ }
26608
+ }
26609
+ }
26610
+ function loadOrCreateGenesis(dir, random = () => randomBytes5(32)) {
26611
+ const existing = readGenesis(dir);
26612
+ if (!existing.ok) return existing;
26613
+ if (existing.value !== null) return ok(existing.value);
26614
+ const genesis = createHash9("sha256").update(random()).digest("hex");
26615
+ const w = writeNew(genesisPath(dir), `${JSON.stringify({ v: 1, genesis })}
26616
+ `);
26617
+ if (!w.ok) {
26618
+ if (w.error !== "EEXIST") return fail3(`genesis file: could not create (${w.error})`);
26619
+ const again = readGenesis(dir);
26620
+ if (!again.ok) return again;
26621
+ return again.value === null ? fail3("genesis file: could not be read after creation") : ok(again.value);
26622
+ }
26623
+ return ok(genesis);
26624
+ }
26625
+ function readHead(dir) {
26626
+ const t = readSmall(headPath(dir));
26627
+ if (!t.ok) return fail3(`head file: ${t.error}`);
26628
+ if (t.value === null) return ok(null);
26629
+ const h = parseWith(t.value, HeadRecordSchema);
26630
+ return h.ok ? ok(h.value) : fail3(`head file: ${h.error}`);
26631
+ }
26632
+ function writeHeadAtomic(dir, head) {
26633
+ const parsed = HeadRecordSchema.safeParse(head);
26634
+ if (!parsed.success) return fail3("head file: record is not valid");
26635
+ const tmp = join19(dir, `events.head.json.${process.pid}.${randomBytes5(4).toString("hex")}.tmp`);
26636
+ const w = writeNew(tmp, `${JSON.stringify(parsed.data)}
26637
+ `);
26638
+ if (!w.ok) return fail3(`head file: could not write (${w.error})`);
26639
+ try {
26640
+ renameSync5(tmp, headPath(dir));
26641
+ return ok(void 0);
26642
+ } catch (e) {
26643
+ try {
26644
+ unlinkSync2(tmp);
26645
+ } catch {
26646
+ }
26647
+ return fail3(`head file: could not replace (${errCode(e)})`);
26648
+ }
26649
+ }
26650
+ var CHUNK = 1 << 20;
26651
+ function readEventsInto(path, out) {
26652
+ let fd = null;
26653
+ try {
26654
+ const st = lstatSync5(path, { throwIfNoEntry: false });
26655
+ if (st === void 0) return ok(null);
26656
+ if (!st.isFile()) return fail3("not a regular file");
26657
+ fd = openSync3(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
26658
+ const buf = Buffer.alloc(CHUNK);
26659
+ let carry = Buffer.alloc(0);
26660
+ const take = (raw) => {
26661
+ if (raw.length === 0 || raw.length > MAX_LINE_BYTES) return;
26662
+ const text = raw.toString("utf8");
26663
+ if (text.trim() === "") return;
26664
+ let json2;
26665
+ try {
26666
+ json2 = JSON.parse(text);
26667
+ } catch {
26668
+ return;
26669
+ }
26670
+ const r = ShieldEventSchema.safeParse(json2);
26671
+ if (r.success) out.push(r.data);
26672
+ };
26673
+ for (; ; ) {
26674
+ const n = readSync3(fd, buf, 0, CHUNK, null);
26675
+ if (n === 0) break;
26676
+ let from = 0;
26677
+ for (; ; ) {
26678
+ const nl = buf.indexOf(10, from);
26679
+ if (nl === -1 || nl >= n) break;
26680
+ take(Buffer.concat([carry, buf.subarray(from, nl)]));
26681
+ carry = Buffer.alloc(0);
26682
+ from = nl + 1;
26683
+ }
26684
+ if (from < n) {
26685
+ carry = Buffer.concat([carry, buf.subarray(from, n)]);
26686
+ if (carry.length > MAX_LINE_BYTES * 2) carry = carry.subarray(0, MAX_LINE_BYTES * 2);
26687
+ }
26688
+ }
26689
+ take(carry);
26690
+ return ok(null);
26691
+ } catch (e) {
26692
+ return fail3(`could not read (${errCode(e)})`);
26693
+ } finally {
26694
+ if (fd !== null) {
26695
+ try {
26696
+ closeSync3(fd);
26697
+ } catch {
26698
+ }
26699
+ }
26700
+ }
26701
+ }
26702
+ function verifyLogDir(dir, opts) {
26703
+ const unreadable = (what, error2) => ({ status: "broken", atSeq: 1, reason: "head-mismatch", detail: `${what} could not be read: ${error2}` });
26704
+ const head = readHead(dir);
26705
+ if (!head.ok) return unreadable("the head record", head.error);
26706
+ const genesis = readGenesis(dir);
26707
+ if (!genesis.ok) return unreadable("the genesis value", genesis.error);
26708
+ const events = [];
26709
+ const old = oldEventsPath(dir);
26710
+ let rotated = false;
26711
+ try {
26712
+ rotated = lstatSync5(old, { throwIfNoEntry: false }) !== void 0;
26713
+ } catch {
26714
+ return unreadable("events.1.jsonl", "not accessible");
26715
+ }
26716
+ if (rotated) {
26717
+ const r = readEventsInto(old, events);
26718
+ if (!r.ok) return unreadable("events.1.jsonl", r.error);
26719
+ }
26720
+ const cur = readEventsInto(eventsPath(dir), events);
26721
+ if (!cur.ok) return unreadable("events.jsonl", cur.error);
26722
+ return verifyChain(events, head.value, genesis.value, { ...opts, allowRotatedStart: rotated });
26723
+ }
26724
+
26725
+ // ../shield/src/events.ts
26726
+ var eventsPath = (dir) => join20(dir, "events.jsonl");
26727
+ var oldEventsPath = (dir) => join20(dir, "events.1.jsonl");
26728
+ var lockPath = (dir) => join20(dir, "events.lock");
25677
26729
  var MAX_EVENT_BYTES = 1024 * 1024;
25678
26730
  var MAX_LINE_BYTES = 8 * 1024;
25679
26731
  var STALE_LOCK_MS = 1e4;
25680
- var MAX_READ_BYTES = 8 * 1024 * 1024;
26732
+ var MAX_READ_BYTES2 = 8 * 1024 * 1024;
26733
+ var HEX642 = /^[0-9a-f]{64}$/;
25681
26734
  var NAME_CHARS2 = 80;
25682
26735
  var WHY_CHARS = 400;
25683
26736
  var MESSAGE_CHARS = 600;
@@ -25691,7 +26744,11 @@ var Base = {
25691
26744
  time: Time2,
25692
26745
  pid: external_exports.number().int().positive(),
25693
26746
  server: Name2,
25694
- session: external_exports.string().regex(KEY_RE2).optional()
26747
+ session: external_exports.string().regex(KEY_RE2).optional(),
26748
+ /** Hash-chain fields (chain.ts). Absent on lines written before the chain existed or when the lock could not be taken. */
26749
+ seq: external_exports.number().int().positive().optional(),
26750
+ prev: external_exports.string().regex(HEX642).optional(),
26751
+ hash: external_exports.string().regex(HEX642).optional()
25695
26752
  };
25696
26753
  var StartEvent = external_exports.object({
25697
26754
  ...Base,
@@ -25754,6 +26811,43 @@ function sanitize(body) {
25754
26811
  function code2(err) {
25755
26812
  return err && typeof err === "object" && "code" in err ? String(err.code) : "error";
25756
26813
  }
26814
+ var LOCK_ATTEMPTS = 800;
26815
+ var LOCK_WAIT_MS = 5;
26816
+ function sleepMs(ms) {
26817
+ try {
26818
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
26819
+ } catch {
26820
+ }
26821
+ }
26822
+ function withLock(lock, attempts, fn) {
26823
+ let got = false;
26824
+ for (let i = 0; i < attempts && !got; i++) {
26825
+ try {
26826
+ mkdirSync7(lock);
26827
+ got = true;
26828
+ } catch (err) {
26829
+ if (code2(err) !== "EEXIST") return { held: false };
26830
+ try {
26831
+ if (Date.now() - lstatSync6(lock).mtimeMs > STALE_LOCK_MS) {
26832
+ rmdirSync2(lock);
26833
+ mkdirSync7(lock);
26834
+ got = true;
26835
+ }
26836
+ } catch {
26837
+ }
26838
+ }
26839
+ if (!got && i + 1 < attempts) sleepMs(1 + Math.random() * (LOCK_WAIT_MS - 1));
26840
+ }
26841
+ if (!got) return { held: false };
26842
+ try {
26843
+ return { held: true, value: fn() };
26844
+ } finally {
26845
+ try {
26846
+ rmdirSync2(lock);
26847
+ } catch {
26848
+ }
26849
+ }
26850
+ }
25757
26851
  var EventLog = class {
25758
26852
  constructor(dir, o) {
25759
26853
  this.dir = dir;
@@ -25764,6 +26858,9 @@ var EventLog = class {
25764
26858
  this.pid = o.pid ?? process.pid;
25765
26859
  this.server = cleanText(o.server, NAME_CHARS2);
25766
26860
  this.now = o.now ?? (() => /* @__PURE__ */ new Date());
26861
+ this.chain = o.chain ?? true;
26862
+ this.random = o.random;
26863
+ this.lockAttempts = o.lockAttempts ?? LOCK_ATTEMPTS;
25767
26864
  this.session = o.session;
25768
26865
  }
25769
26866
  path;
@@ -25773,6 +26870,9 @@ var EventLog = class {
25773
26870
  pid;
25774
26871
  server;
25775
26872
  now;
26873
+ chain;
26874
+ random;
26875
+ lockAttempts;
25776
26876
  sessionKey;
25777
26877
  /** Events not written because the file was full and could not be rotated. */
25778
26878
  dropped = 0;
@@ -25798,71 +26898,95 @@ var EventLog = class {
25798
26898
  this.fail(`an event did not validate (${parsed.error.issues[0]?.message ?? "invalid"})`);
25799
26899
  return false;
25800
26900
  }
25801
- const line = Buffer.from(`${JSON.stringify(parsed.data)}
26901
+ try {
26902
+ mkdirSync7(this.dir, { recursive: true });
26903
+ if (this.chain) {
26904
+ const r = withLock(this.lock, this.lockAttempts, () => this.writeChained(parsed.data));
26905
+ if (r.held) return r.value;
26906
+ this.fail("the event log lock could not be taken, so an event was written without chain fields");
26907
+ }
26908
+ return this.append(this.encode(parsed.data));
26909
+ } catch (err) {
26910
+ this.fail(`${this.path} could not be written (${code2(err)})`);
26911
+ return false;
26912
+ }
26913
+ }
26914
+ encode(e) {
26915
+ const line = Buffer.from(`${JSON.stringify(e)}
25802
26916
  `, "utf8");
25803
26917
  if (line.length > MAX_LINE_BYTES) {
25804
26918
  this.fail("an event was too long");
25805
- return false;
26919
+ return null;
25806
26920
  }
25807
- try {
25808
- mkdirSync7(this.dir, { recursive: true });
25809
- const size = this.size();
25810
- if (size + line.length > this.maxBytes) {
25811
- this.rotate();
25812
- if (this.size() + line.length > this.maxBytes * 2) {
25813
- this.dropped++;
25814
- return false;
25815
- }
26921
+ return line;
26922
+ }
26923
+ /** Size check, rotation and the single O_APPEND write of one line. The caller holds no lock unless it is chaining. */
26924
+ append(line, locked = false) {
26925
+ if (line === null) return false;
26926
+ const size = this.size();
26927
+ if (size + line.length > this.maxBytes) {
26928
+ if (locked) this.rotateLocked();
26929
+ else this.rotate();
26930
+ if (this.size() + line.length > this.maxBytes * 2) {
26931
+ this.dropped++;
26932
+ return false;
25816
26933
  }
25817
- const flags = constants2.O_WRONLY | constants2.O_APPEND | constants2.O_CREAT | (constants2.O_NOFOLLOW ?? 0);
25818
- const fd = openSync3(this.path, flags, 384);
25819
- try {
25820
- if (!fstatSync2(fd).isFile()) {
25821
- this.fail(`${this.path} is not a regular file`);
25822
- return false;
25823
- }
25824
- writeSync(fd, line);
25825
- } finally {
25826
- closeSync3(fd);
26934
+ }
26935
+ const flags = constants3.O_WRONLY | constants3.O_APPEND | constants3.O_CREAT | (constants3.O_NOFOLLOW ?? 0);
26936
+ const fd = openSync4(this.path, flags, 384);
26937
+ try {
26938
+ if (!fstatSync3(fd).isFile()) {
26939
+ this.fail(`${this.path} is not a regular file`);
26940
+ return false;
25827
26941
  }
25828
- return true;
25829
- } catch (err) {
25830
- this.fail(`${this.path} could not be written (${code2(err)})`);
26942
+ writeSync2(fd, line);
26943
+ } finally {
26944
+ closeSync4(fd);
26945
+ }
26946
+ return true;
26947
+ }
26948
+ /** The chained write, with the lock held. Falls back to an unchained line when the chain files are unusable. */
26949
+ writeChained(event) {
26950
+ const g = loadOrCreateGenesis(this.dir, this.random);
26951
+ if (!g.ok) {
26952
+ this.fail(g.error);
26953
+ return this.append(this.encode(event), true);
26954
+ }
26955
+ const h = readHead(this.dir);
26956
+ if (!h.ok) this.fail(h.error);
26957
+ const head = h.ok ? h.value : null;
26958
+ const seq2 = (head?.seq ?? 0) + 1;
26959
+ const prev = head?.hash ?? g.value;
26960
+ const hash = eventHash({ ...event, seq: seq2, prev });
26961
+ const chained = ShieldEventSchema.safeParse({ ...event, seq: seq2, prev, hash });
26962
+ if (!chained.success) {
26963
+ this.fail("a chained event did not validate");
25831
26964
  return false;
25832
26965
  }
26966
+ if (!this.append(this.encode(chained.data), true)) return false;
26967
+ const w = writeHeadAtomic(this.dir, { v: 1, genesis: g.value, seq: seq2, hash });
26968
+ if (!w.ok) this.fail(w.error);
26969
+ return true;
25833
26970
  }
25834
26971
  fail(p) {
25835
26972
  this.problem ??= p;
25836
26973
  }
25837
26974
  size() {
25838
26975
  try {
25839
- return lstatSync4(this.path).size;
26976
+ return lstatSync6(this.path).size;
25840
26977
  } catch {
25841
26978
  return 0;
25842
26979
  }
25843
26980
  }
25844
- /** Rename the full file to events.1.jsonl, under the lock. Best effort. */
26981
+ /** Rename the full file to events.1.jsonl, under the lock (one try). Best effort. */
25845
26982
  rotate() {
26983
+ withLock(this.lock, 1, () => this.rotateLocked());
26984
+ }
26985
+ /** The rotation itself; the caller holds the lock. */
26986
+ rotateLocked() {
25846
26987
  try {
25847
- mkdirSync7(this.lock);
25848
- } catch (err) {
25849
- if (code2(err) !== "EEXIST") return;
25850
- try {
25851
- if (Date.now() - lstatSync4(this.lock).mtimeMs <= STALE_LOCK_MS) return;
25852
- rmdirSync2(this.lock);
25853
- mkdirSync7(this.lock);
25854
- } catch {
25855
- return;
25856
- }
25857
- }
25858
- try {
25859
- if (this.size() > 0 && this.size() >= this.maxBytes / 2) renameSync5(this.path, this.old);
26988
+ if (this.size() > 0 && this.size() >= this.maxBytes / 2) renameSync6(this.path, this.old);
25860
26989
  } catch {
25861
- } finally {
25862
- try {
25863
- rmdirSync2(this.lock);
25864
- } catch {
25865
- }
25866
26990
  }
25867
26991
  }
25868
26992
  };
@@ -25891,24 +27015,24 @@ function parseEventLines(text) {
25891
27015
  function readFrom(path, from) {
25892
27016
  let fd;
25893
27017
  try {
25894
- fd = openSync3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
27018
+ fd = openSync4(path, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
25895
27019
  } catch {
25896
27020
  return null;
25897
27021
  }
25898
27022
  try {
25899
- const st = fstatSync2(fd);
27023
+ const st = fstatSync3(fd);
25900
27024
  if (!st.isFile()) return null;
25901
27025
  let start = from > st.size ? 0 : from;
25902
27026
  let dropFirst = false;
25903
- if (st.size - start > MAX_READ_BYTES) {
25904
- start = st.size - MAX_READ_BYTES;
27027
+ if (st.size - start > MAX_READ_BYTES2) {
27028
+ start = st.size - MAX_READ_BYTES2;
25905
27029
  dropFirst = true;
25906
27030
  }
25907
27031
  const len = st.size - start;
25908
27032
  const buf = Buffer.alloc(len);
25909
27033
  let got = 0;
25910
27034
  while (got < len) {
25911
- const n = readSync3(fd, buf, got, len - got, start + got);
27035
+ const n = readSync4(fd, buf, got, len - got, start + got);
25912
27036
  if (n === 0) break;
25913
27037
  got += n;
25914
27038
  }
@@ -25918,7 +27042,7 @@ function readFrom(path, from) {
25918
27042
  if (dropFirst) text = text.slice(text.indexOf("\n") + 1);
25919
27043
  return { text, end: start + lastNl + 1, st };
25920
27044
  } finally {
25921
- closeSync3(fd);
27045
+ closeSync4(fd);
25922
27046
  }
25923
27047
  }
25924
27048
  var EventTail = class {
@@ -25940,7 +27064,7 @@ var EventTail = class {
25940
27064
  };
25941
27065
  let st = null;
25942
27066
  try {
25943
- st = lstatSync4(this.path);
27067
+ st = lstatSync6(this.path);
25944
27068
  } catch {
25945
27069
  st = null;
25946
27070
  }
@@ -25978,16 +27102,16 @@ var EventTail = class {
25978
27102
  };
25979
27103
 
25980
27104
  // ../shield/src/launch.ts
25981
- import { createHash as createHash9 } from "node:crypto";
25982
- import { existsSync as existsSync9, readFileSync as readFileSync13, statSync as statSync7 } from "node:fs";
25983
- import { dirname as dirname7, isAbsolute as isAbsolute8, join as join19, parse as parsePath2, relative as relative6, resolve as resolve12, sep } from "node:path";
25984
- var sha2563 = (b) => createHash9("sha256").update(b).digest("hex");
27105
+ import { createHash as createHash10 } from "node:crypto";
27106
+ import { existsSync as existsSync9, readFileSync as readFileSync16, statSync as statSync8 } from "node:fs";
27107
+ import { dirname as dirname7, isAbsolute as isAbsolute8, join as join21, parse as parsePath2, relative as relative6, resolve as resolve12, sep } from "node:path";
27108
+ var sha2563 = (b) => createHash10("sha256").update(b).digest("hex");
25985
27109
  var MAX_HASHED_BYTES = 64 * 1024 * 1024;
25986
27110
  var fsReader = (path) => {
25987
27111
  try {
25988
- const st = statSync7(path);
27112
+ const st = statSync8(path);
25989
27113
  if (!st.isFile()) return { kind: "other" };
25990
- return { kind: "file", size: st.size, mtimeMs: st.mtimeMs, read: () => readFileSync13(path) };
27114
+ return { kind: "file", size: st.size, mtimeMs: st.mtimeMs, read: () => readFileSync16(path) };
25991
27115
  } catch {
25992
27116
  return { kind: "other" };
25993
27117
  }
@@ -26004,9 +27128,9 @@ var RUNNERS2 = {
26004
27128
  pipx: ["run"]
26005
27129
  };
26006
27130
  var INTERPRETERS = /^(node|nodejs|deno|bun|python\d*(\.\d+)?|pythonw|uv|uvx|npx|pnpx|bunx|pnpm|npm|yarn|pipx|java|ruby|php|dotnet|docker|podman|sh|bash|zsh|cmd|powershell|pwsh)$/i;
26007
- var baseName2 = (c) => c.split(/[\\/]/).pop()?.replace(/\.(cmd|exe)$/i, "") ?? c;
27131
+ var baseName3 = (c) => c.split(/[\\/]/).pop()?.replace(/\.(cmd|exe)$/i, "") ?? c;
26008
27132
  function packageSpec(command, args) {
26009
- const sub = RUNNERS2[baseName2(command)];
27133
+ const sub = RUNNERS2[baseName3(command)];
26010
27134
  if (!sub) return void 0;
26011
27135
  let i = 0;
26012
27136
  if (sub.length > 0) {
@@ -26057,7 +27181,7 @@ function configLabel(configPath) {
26057
27181
  const abs = resolve12(configPath);
26058
27182
  const { root } = parsePath2(abs);
26059
27183
  for (let dir = dirname7(abs); ; dir = dirname7(dir)) {
26060
- if (PROJECT_MARKERS3.some((m) => existsSync9(join19(dir, m)))) return relative6(dir, abs).split(sep).join("/");
27184
+ if (PROJECT_MARKERS3.some((m) => existsSync9(join21(dir, m)))) return relative6(dir, abs).split(sep).join("/");
26061
27185
  if (dir === root || dirname7(dir) === dir) return abs;
26062
27186
  }
26063
27187
  }
@@ -26072,7 +27196,7 @@ function launchFingerprint(command, args, cwd, reader = fsReader, entry = {}) {
26072
27196
  };
26073
27197
  const parts = [];
26074
27198
  const commandIsPath = /[\\/]/.test(command);
26075
- const own = commandIsPath && !INTERPRETERS.test(baseName2(command)) ? fileLine("command", command) : void 0;
27199
+ const own = commandIsPath && !INTERPRETERS.test(baseName3(command)) ? fileLine("command", command) : void 0;
26076
27200
  parts.push(own ?? `command ${command}`);
26077
27201
  const spec = packageSpec(command, args);
26078
27202
  if (spec) parts.push(`package ${spec}`);
@@ -26241,7 +27365,7 @@ async function prepareShield(o) {
26241
27365
  if (lockFile && existsSync10(lockFile)) {
26242
27366
  let text;
26243
27367
  try {
26244
- text = readFileSync14(lockFile, "utf8");
27368
+ text = readFileSync17(lockFile, "utf8");
26245
27369
  } catch {
26246
27370
  log(`Could not read ${lockFile}; running with the local pins only.`);
26247
27371
  }
@@ -26339,7 +27463,7 @@ async function prepareShield(o) {
26339
27463
  let dirty = false;
26340
27464
  const readMtime = () => {
26341
27465
  try {
26342
- return statSync8(statePath(o.dir)).mtimeMs;
27466
+ return statSync9(statePath(o.dir)).mtimeMs;
26343
27467
  } catch {
26344
27468
  return 0;
26345
27469
  }
@@ -26470,7 +27594,7 @@ async function prepareShield(o) {
26470
27594
  function readConfigEntry(configPath, server) {
26471
27595
  let json2;
26472
27596
  try {
26473
- json2 = JSON.parse(readFileSync14(configPath, "utf8"));
27597
+ json2 = JSON.parse(readFileSync17(configPath, "utf8"));
26474
27598
  } catch {
26475
27599
  return { ok: false, error: "the MCP config could not be read as JSON" };
26476
27600
  }
@@ -26518,7 +27642,7 @@ async function runProxy(o) {
26518
27642
  env: o.env ?? process.env,
26519
27643
  ...o.cwd ? { cwd: o.cwd } : {}
26520
27644
  });
26521
- const run = (actions) => {
27645
+ const run2 = (actions) => {
26522
27646
  for (const f of handle(actions)) {
26523
27647
  const line = `${JSON.stringify(f.message)}
26524
27648
  `;
@@ -26529,10 +27653,10 @@ async function runProxy(o) {
26529
27653
  const fromClient = new LineSplitter();
26530
27654
  const fromServer = new LineSplitter();
26531
27655
  stdin.on("data", (chunk) => {
26532
- for (const l of fromClient.push(chunk)) run(engine.onClientLine(l));
27656
+ for (const l of fromClient.push(chunk)) run2(engine.onClientLine(l));
26533
27657
  });
26534
27658
  stdin.on("end", () => {
26535
- for (const l of fromClient.flush()) run(engine.onClientLine(l));
27659
+ for (const l of fromClient.flush()) run2(engine.onClientLine(l));
26536
27660
  engine.abandon();
26537
27661
  child.stdin.end();
26538
27662
  });
@@ -26540,10 +27664,10 @@ async function runProxy(o) {
26540
27664
  const prep = prepared.prepareServerLine;
26541
27665
  const fromServerLine = (l) => {
26542
27666
  if (!prep) {
26543
- run(engine.onServerLine(l));
27667
+ run2(engine.onServerLine(l));
26544
27668
  return;
26545
27669
  }
26546
- serverQueue = serverQueue.then(() => prep(l)).catch(() => void 0).then(() => run(engine.onServerLine(l)));
27670
+ serverQueue = serverQueue.then(() => prep(l)).catch(() => void 0).then(() => run2(engine.onServerLine(l)));
26547
27671
  };
26548
27672
  child.stdout.on("data", (chunk) => {
26549
27673
  for (const l of fromServer.push(chunk)) fromServerLine(l);
@@ -26551,8 +27675,8 @@ async function runProxy(o) {
26551
27675
  child.stderr.on("data", (chunk) => void stderr.write(chunk));
26552
27676
  child.stdin.on("error", () => {
26553
27677
  });
26554
- prepared.attach(run);
26555
- const stopWatch = prepared.watch(run);
27678
+ prepared.attach(run2);
27679
+ const stopWatch = prepared.watch(run2);
26556
27680
  return await new Promise((resolve28) => {
26557
27681
  child.on("error", (err) => {
26558
27682
  stopWatch();
@@ -26794,12 +27918,12 @@ async function runRemoteProxy(o) {
26794
27918
  }
26795
27919
 
26796
27920
  // ../shield/src/locate.ts
26797
- import { existsSync as existsSync11, readdirSync as readdirSync5, statSync as statSync9 } from "node:fs";
26798
- import { dirname as dirname9, isAbsolute as isAbsolute9, join as join20, parse as parse2, resolve as resolve13 } from "node:path";
27921
+ import { existsSync as existsSync11, readdirSync as readdirSync6, statSync as statSync10 } from "node:fs";
27922
+ import { dirname as dirname9, isAbsolute as isAbsolute9, join as join22, parse as parse2, resolve as resolve13 } from "node:path";
26799
27923
  import { fileURLToPath } from "node:url";
26800
27924
  function hasDefinitions(dir) {
26801
27925
  try {
26802
- return statSync9(dir).isDirectory() && readdirSync5(dir).some((f) => /^EX-\d{3}.*\.yaml$/.test(f));
27926
+ return statSync10(dir).isDirectory() && readdirSync6(dir).some((f) => /^EX-\d{3}.*\.yaml$/.test(f));
26803
27927
  } catch {
26804
27928
  return false;
26805
27929
  }
@@ -26813,7 +27937,7 @@ function findDefinitionsDir(o) {
26813
27937
  const installed = findActiveInstalledSet({ env, ...o.publicKeyPem ? { publicKeyPem: o.publicKeyPem } : {} });
26814
27938
  if (installed && hasDefinitions(installed.definitionsDir)) return installed.definitionsDir;
26815
27939
  const here = dirname9(fileURLToPath(o.callerUrl));
26816
- const candidates = [join20(here, "..", "definitions"), join20(here, "..", "..", "..", "definitions"), join20(cwd, "definitions")];
27940
+ const candidates = [join22(here, "..", "definitions"), join22(here, "..", "..", "..", "definitions"), join22(cwd, "definitions")];
26817
27941
  return candidates.find(hasDefinitions) ?? null;
26818
27942
  }
26819
27943
  var PROJECT_MARKERS4 = [".exorcist", ".kiro", ".git"];
@@ -26825,10 +27949,10 @@ function findStateDir(o = {}) {
26825
27949
  if (fromEnv) return isAbsolute9(fromEnv) ? fromEnv : resolve13(cwd, fromEnv);
26826
27950
  const { root } = parse2(cwd);
26827
27951
  for (let dir = cwd; ; dir = dirname9(dir)) {
26828
- if (PROJECT_MARKERS4.some((m) => existsSync11(join20(dir, m)))) return join20(dir, ".exorcist");
27952
+ if (PROJECT_MARKERS4.some((m) => existsSync11(join22(dir, m)))) return join22(dir, ".exorcist");
26829
27953
  if (dir === root || dirname9(dir) === dir) break;
26830
27954
  }
26831
- return join20(cwd, ".exorcist");
27955
+ return join22(cwd, ".exorcist");
26832
27956
  }
26833
27957
 
26834
27958
  // ../shield/src/wrap.ts
@@ -27009,9 +28133,9 @@ var strs = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : []
27009
28133
  var DEFAULT_DIR = "the project's .exorcist folder (or EXORCIST_DIR)";
27010
28134
 
27011
28135
  // src/commands/on-access.ts
27012
- import { randomBytes as randomBytes6 } from "node:crypto";
28136
+ import { randomBytes as randomBytes7 } from "node:crypto";
27013
28137
  import { execFile as execFile4 } from "node:child_process";
27014
- import { existsSync as existsSync12, statSync as statSync10 } from "node:fs";
28138
+ import { existsSync as existsSync12, statSync as statSync11 } from "node:fs";
27015
28139
  import { resolve as resolve14 } from "node:path";
27016
28140
  import { createInterface } from "node:readline";
27017
28141
  var ALLOW_READ_HELP = `Usage: exorcist allow-read <file>
@@ -27064,9 +28188,38 @@ var processTerminal = () => ({
27064
28188
  });
27065
28189
  }),
27066
28190
  dialog: macDialog,
27067
- nonce: () => randomBytes6(4).toString("hex").slice(0, 6)
27068
- });
27069
- var confirms = (answer, code3) => code3.length >= 6 && answer.trim().toLowerCase() === code3.toLowerCase();
28191
+ nonce: () => randomBytes7(4).toString("hex").slice(0, 6)
28192
+ });
28193
+ var CODE_TTL_MS = 15 * 60 * 1e3;
28194
+ function checkCode(answer, ticket, nowMs, usedAlready, ttlMs = CODE_TTL_MS) {
28195
+ if (ticket.code.length < 6 || answer.trim().toLowerCase() !== ticket.code.toLowerCase()) return "mismatch";
28196
+ if (usedAlready) return "used";
28197
+ if (nowMs - ticket.issuedAt > ttlMs) return "expired";
28198
+ return "ok";
28199
+ }
28200
+ var OUTCOME_WHY = {
28201
+ accepted: "The person approved it in their own terminal or system prompt.",
28202
+ declined: "The person declined, or the confirmation did not match. Nothing was allowed.",
28203
+ expired: "The confirmation code was typed after it expired. Nothing was allowed.",
28204
+ used: "The confirmation code had already been used. Nothing was allowed."
28205
+ };
28206
+ function recordApproval(audit, outcome, now) {
28207
+ if (!audit) return false;
28208
+ try {
28209
+ const log = new EventLog(audit.dir, { server: "exorcist-cli", ...now ? { now } : {} });
28210
+ const detail = audit.detail ? ` (${cleanText(audit.detail, 60)})` : "";
28211
+ return log.write({
28212
+ kind: "call",
28213
+ tool: audit.subject,
28214
+ decision: outcome === "accepted" ? "allowed" : "blocked",
28215
+ ruleId: audit.subject === "approve session" ? "EX-027" : "SHIELD",
28216
+ by: "user",
28217
+ why: `${OUTCOME_WHY[outcome]}${detail}`
28218
+ });
28219
+ } catch {
28220
+ return false;
28221
+ }
28222
+ }
27070
28223
  function eventCwd(stdin) {
27071
28224
  try {
27072
28225
  const parsed = JSON.parse(stdin);
@@ -27100,7 +28253,7 @@ async function onAccessCommand(stdin, io) {
27100
28253
  if (decision.message) io.err(decision.message);
27101
28254
  return decision.exitCode;
27102
28255
  }
27103
- async function askOwner(term, dialogMessage2, reason) {
28256
+ async function askOwner(term, dialogMessage2, reason, audit) {
27104
28257
  const auth = term.osAuth ?? macOsAuth();
27105
28258
  let available = false;
27106
28259
  try {
@@ -27115,21 +28268,37 @@ async function askOwner(term, dialogMessage2, reason) {
27115
28268
  } catch {
27116
28269
  verdict = "error";
27117
28270
  }
28271
+ recordApproval(audit, verdict === "ok" ? "accepted" : "declined", term.now);
27118
28272
  return verdict === "ok" ? "allow" : "deny";
27119
28273
  }
27120
- return term.dialog ? await term.dialog(dialogMessage2) : "unavailable";
28274
+ const answer = term.dialog ? await term.dialog(dialogMessage2) : "unavailable";
28275
+ if (answer !== "unavailable") recordApproval(audit, answer === "allow" ? "accepted" : "declined", term.now);
28276
+ return answer;
27121
28277
  }
27122
- async function personConfirms(term, io, dialogMessage2, reason = dialogMessage2) {
27123
- const viaOwner = await askOwner(term, dialogMessage2, reason);
28278
+ async function personConfirms(term, io, dialogMessage2, reason = dialogMessage2, audit) {
28279
+ const viaOwner = await askOwner(term, dialogMessage2, reason, audit);
27124
28280
  if (viaOwner === "deny") {
27125
28281
  io.err("Denied in the verification prompt. Nothing was allowed.");
27126
28282
  return false;
27127
28283
  }
27128
28284
  if (viaOwner === "unavailable") {
27129
- const code3 = (term.nonce ?? (() => randomBytes6(4).toString("hex").slice(0, 6)))();
27130
- io.out(`Confirmation code: ${code3}`);
28285
+ const now = term.now ?? (() => /* @__PURE__ */ new Date());
28286
+ const ticket = { code: (term.nonce ?? (() => randomBytes7(4).toString("hex").slice(0, 6)))(), issuedAt: now().getTime() };
28287
+ let used = false;
28288
+ io.out(`Confirmation code: ${ticket.code}`);
27131
28289
  const answer = await term.ask("Type the confirmation code above to allow it: ");
27132
- if (!confirms(answer, code3)) {
28290
+ const verdict = checkCode(answer, ticket, now().getTime(), used);
28291
+ if (verdict === "ok") used = true;
28292
+ recordApproval(audit, verdict === "ok" ? "accepted" : verdict === "mismatch" ? "declined" : verdict, term.now);
28293
+ if (verdict === "expired") {
28294
+ io.err("That code has expired (it is valid for 15 minutes). Nothing was allowed. Run the command again.");
28295
+ return false;
28296
+ }
28297
+ if (verdict === "used") {
28298
+ io.err("That code was already used. Nothing was allowed.");
28299
+ return false;
28300
+ }
28301
+ if (verdict !== "ok") {
27133
28302
  io.err("That does not match. Nothing was allowed.");
27134
28303
  return false;
27135
28304
  }
@@ -27160,7 +28329,7 @@ ${ALLOW_READ_HELP}`);
27160
28329
  return 1;
27161
28330
  }
27162
28331
  const file = resolve14(target);
27163
- if (!existsSync12(file) || !statSync10(file).isFile()) {
28332
+ if (!existsSync12(file) || !statSync11(file).isFile()) {
27164
28333
  io.err(`Not a readable file: ${shownName(target)}`);
27165
28334
  return 1;
27166
28335
  }
@@ -27178,7 +28347,7 @@ ${ALLOW_READ_HELP}`);
27178
28347
  ${shown2}
27179
28348
  SHA-256 ${hash.slice(0, 12)}...
27180
28349
 
27181
- Only allow a file you have reviewed.`, `Allow your AI agent to read ${shown2} (SHA-256 ${hash.slice(0, 12)}...)`)) return 1;
28350
+ Only allow a file you have reviewed.`, `Allow your AI agent to read ${shown2} (SHA-256 ${hash.slice(0, 12)}...)`, { dir: stateDir(), subject: "allow-read" })) return 1;
27182
28351
  const result = addAllowedRead(process.cwd(), file, process.env, hash);
27183
28352
  if (!result.ok) {
27184
28353
  io.err(result.error);
@@ -27262,7 +28431,7 @@ Only release it if you asked for what it is trying to send.`;
27262
28431
  if (!term.dialog || process.platform !== "darwin") {
27263
28432
  io.err("Note: there is no native dialog here, so this uses a typed code. An agent that drives a real terminal could read it; only type it yourself.");
27264
28433
  }
27265
- if (!await personConfirms(asker, io, msg, `Let AI agent session ${server} send data out again`)) return 1;
28434
+ if (!await personConfirms(asker, io, msg, `Let AI agent session ${server} send data out again`, { dir, subject: "approve session", detail: server })) return 1;
27266
28435
  const g = grantSession(dir, server, /* @__PURE__ */ new Date(), asOf);
27267
28436
  if (!g.ok) {
27268
28437
  io.err(g.error);
@@ -27299,13 +28468,20 @@ async function alertsCommand(argv, io) {
27299
28468
  io.err(p.error);
27300
28469
  return 2;
27301
28470
  }
27302
- const file = alertsPath(stateDir(str4(p.values["dir"])));
28471
+ const dir = stateDir(str4(p.values["dir"]));
28472
+ const file = alertsPath(dir);
28473
+ const printHead = () => {
28474
+ const h = readHead(dir);
28475
+ if (!h.ok) io.out(`Event log head: unreadable (${h.error.replace(/[^\x20-\x7e]/g, "?")}).`);
28476
+ else io.out(h.value === null ? "Event log head: none yet (nothing has been logged in this folder)." : `Event log head: ${h.value.hash} (event ${h.value.seq})`);
28477
+ };
27303
28478
  if (!existsSync13(file)) {
27304
28479
  io.out("No alerts.");
28480
+ printHead();
27305
28481
  return 0;
27306
28482
  }
27307
28483
  const n = Math.max(1, Number.parseInt(str4(p.values["last"]) ?? "20", 10) || 20);
27308
- const lines = readFileSync15(file, "utf8").split("\n").filter(Boolean).slice(-n);
28484
+ const lines = readFileSync18(file, "utf8").split("\n").filter(Boolean).slice(-n);
27309
28485
  for (const l of lines) {
27310
28486
  try {
27311
28487
  const a = JSON.parse(l);
@@ -27313,25 +28489,26 @@ async function alertsCommand(argv, io) {
27313
28489
  } catch {
27314
28490
  }
27315
28491
  }
28492
+ printHead();
27316
28493
  return 0;
27317
28494
  }
27318
28495
 
27319
28496
  // src/commands/baseline.ts
27320
- import { statSync as statSync13, writeFileSync as writeFileSync8 } from "node:fs";
27321
- import { join as join23, resolve as resolve17 } from "node:path";
28497
+ import { statSync as statSync14, writeFileSync as writeFileSync8 } from "node:fs";
28498
+ import { join as join25, resolve as resolve17 } from "node:path";
27322
28499
 
27323
28500
  // src/commands/scan.ts
27324
- import { existsSync as existsSync15, readFileSync as readFileSync17, realpathSync as realpathSync4, statSync as statSync12, writeFileSync as writeFileSync7 } from "node:fs";
27325
- import { basename as basename8, dirname as dirname10, isAbsolute as isAbsolute10, join as join22, relative as relative7, resolve as resolve16 } from "node:path";
28501
+ import { existsSync as existsSync15, readFileSync as readFileSync20, realpathSync as realpathSync4, statSync as statSync13, writeFileSync as writeFileSync7 } from "node:fs";
28502
+ import { basename as basename8, dirname as dirname10, isAbsolute as isAbsolute10, join as join24, relative as relative7, resolve as resolve16 } from "node:path";
27326
28503
  init_bedrock();
27327
28504
 
27328
28505
  // src/commands/detonate.ts
27329
- import { existsSync as existsSync14, readFileSync as readFileSync16, statSync as statSync11 } from "node:fs";
27330
- import { basename as basename7, join as join21, resolve as resolve15 } from "node:path";
28506
+ import { existsSync as existsSync14, readFileSync as readFileSync19, statSync as statSync12 } from "node:fs";
28507
+ import { basename as basename7, join as join23, resolve as resolve15 } from "node:path";
27331
28508
  init_bedrock();
27332
28509
  var DEFAULT_DETONATE_MAX = 10;
27333
28510
  var EX024 = "EX-024";
27334
- var MAX_FILE_BYTES4 = 1048576;
28511
+ var MAX_FILE_BYTES5 = 1048576;
27335
28512
  var DETONATE_HELP = `Usage: exorcist detonate <file> [options]
27336
28513
 
27337
28514
  The Detonation Chamber. Gives the file's text to a sandboxed AI model (Claude
@@ -27406,7 +28583,7 @@ async function runDetonations(root, findings, client, max, def) {
27406
28583
  for (const t of targets) {
27407
28584
  let text;
27408
28585
  try {
27409
- text = readFileSync16(join21(root, t.file), "utf8");
28586
+ text = readFileSync19(join23(root, t.file), "utf8");
27410
28587
  } catch {
27411
28588
  tally.inconclusive++;
27412
28589
  continue;
@@ -27470,17 +28647,17 @@ ${DETONATE_HELP}`);
27470
28647
  return 2;
27471
28648
  }
27472
28649
  const abs = resolve15(target);
27473
- if (!existsSync14(abs) || !statSync11(abs).isFile()) {
28650
+ if (!existsSync14(abs) || !statSync12(abs).isFile()) {
27474
28651
  io.err(`File not found: ${target}`);
27475
28652
  return 2;
27476
28653
  }
27477
- if (statSync11(abs).size > MAX_FILE_BYTES4) {
28654
+ if (statSync12(abs).size > MAX_FILE_BYTES5) {
27478
28655
  io.err(`${target} is larger than 1 MB; detonate a smaller part of it.`);
27479
28656
  return 2;
27480
28657
  }
27481
28658
  const client = await makeChamberClient(io, "exorcist detonate", deps.client);
27482
28659
  if (client === false) return 2;
27483
- const report = await detonate(readFileSync16(abs, "utf8"), placement, client, { fileName: basename7(abs) });
28660
+ const report = await detonate(readFileSync19(abs, "utf8"), placement, client, { fileName: basename7(abs) });
27484
28661
  if (format === "json") io.out(`${JSON.stringify({ file: target, model: modelIdFor("haiku"), ...report }, null, 2)}
27485
28662
  `);
27486
28663
  else io.out(renderTranscript(target, report));
@@ -27544,9 +28721,9 @@ Openers: // # <!-- /* -- ; A reason is required. Hidden characters (EX-00
27544
28721
  secrets (EX-011) cannot be silenced this way. The comment's own text is still scanned.
27545
28722
  `;
27546
28723
  function readIgnoreFile(root) {
27547
- const file = join22(root, ".exorcistignore");
28724
+ const file = join24(root, ".exorcistignore");
27548
28725
  if (!existsSync15(file)) return [];
27549
- return readFileSync17(file, "utf8").split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
28726
+ return readFileSync20(file, "utf8").split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
27550
28727
  }
27551
28728
  function isIgnored(rel, prefixes) {
27552
28729
  return prefixes.some((p) => {
@@ -27645,7 +28822,7 @@ async function runScan(opts, io) {
27645
28822
  io.err(`Path not found: ${opts.target}`);
27646
28823
  return { ok: false, code: 2 };
27647
28824
  }
27648
- const isFile = statSync12(abs).isFile();
28825
+ const isFile = statSync13(abs).isFile();
27649
28826
  const root = isFile ? dirname10(abs) : abs;
27650
28827
  const only = isFile ? basename8(abs) : null;
27651
28828
  const defsDir = findDefinitionsDir2(opts.definitions);
@@ -27700,8 +28877,8 @@ function makeRootReader(root) {
27700
28877
  const real = realpathSync4(resolve16(realRoot, file));
27701
28878
  const rel = relative7(realRoot, real);
27702
28879
  if (rel === "" || rel.startsWith("..") || isAbsolute10(rel)) return null;
27703
- if (statSync12(real).size > MAX_DIRECTIVE_FILE_BYTES) return null;
27704
- return readFileSync17(real, "utf8");
28880
+ if (statSync13(real).size > MAX_DIRECTIVE_FILE_BYTES) return null;
28881
+ return readFileSync20(real, "utf8");
27705
28882
  } catch {
27706
28883
  return null;
27707
28884
  }
@@ -27759,7 +28936,7 @@ ${SCAN_HELP}`);
27759
28936
  if (baselinePath !== void 0) {
27760
28937
  let text;
27761
28938
  try {
27762
- text = readFileSync17(resolve16(baselinePath), "utf8");
28939
+ text = readFileSync20(resolve16(baselinePath), "utf8");
27763
28940
  } catch {
27764
28941
  io.err(`Could not read the baseline file ${baselinePath}. Check the path, or create one with: exorcist baseline <folder>`);
27765
28942
  return 2;
@@ -27802,13 +28979,13 @@ ${SCAN_HELP}`);
27802
28979
  if (ai) io.err(ai.summary());
27803
28980
  if (chamber) {
27804
28981
  const def = (await loadDefinitions(defsDir)).find((d) => d.id === EX024);
27805
- const run = await runDetonations(root, findings, chamber, detonateMax, def ?? {
28982
+ const run2 = await runDetonations(root, findings, chamber, detonateMax, def ?? {
27806
28983
  title: "Detonated in the chamber",
27807
28984
  owasp: ["LLM01:2025 Prompt Injection"],
27808
28985
  fix: "Remove the passage that makes an AI try these actions."
27809
28986
  });
27810
- findings.push(...run.findings);
27811
- io.err(run.summary);
28987
+ findings.push(...run2.findings);
28988
+ io.err(run2.summary);
27812
28989
  }
27813
28990
  stats = { ...stats, findingsTotal: findings.length };
27814
28991
  const inline = applyInline(findings, makeRootReader(root));
@@ -27872,7 +29049,7 @@ ${BASELINE_HELP}`);
27872
29049
  }
27873
29050
  const target = p.positionals[0] ?? ".";
27874
29051
  try {
27875
- if (!statSync13(resolve17(target)).isDirectory()) {
29052
+ if (!statSync14(resolve17(target)).isDirectory()) {
27876
29053
  io.err(`${target} is a file. Give a folder to baseline.`);
27877
29054
  return 2;
27878
29055
  }
@@ -27885,7 +29062,7 @@ ${BASELINE_HELP}`);
27885
29062
  const { findings, root } = result.run;
27886
29063
  const { active } = applyInline(findings, makeRootReader(root));
27887
29064
  const baseline = buildBaseline(active);
27888
- const out = str4(p.values["output"]) ?? join23(root, BASELINE_FILE);
29065
+ const out = str4(p.values["output"]) ?? join25(root, BASELINE_FILE);
27889
29066
  try {
27890
29067
  writeFileSync8(out, `${JSON.stringify(baseline, null, 2)}
27891
29068
  `, "utf8");
@@ -28011,9 +29188,9 @@ function remove(io, dir, state) {
28011
29188
  }
28012
29189
 
28013
29190
  // src/commands/config.ts
28014
- import { createHash as createHash10 } from "node:crypto";
28015
- import { existsSync as existsSync16, mkdirSync as mkdirSync9, readFileSync as readFileSync18, rmSync as rmSync5, writeFileSync as writeFileSync9 } from "node:fs";
28016
- import { join as join24, resolve as resolve19 } from "node:path";
29191
+ import { createHash as createHash11 } from "node:crypto";
29192
+ import { existsSync as existsSync16, mkdirSync as mkdirSync9, readFileSync as readFileSync21, rmSync as rmSync5, writeFileSync as writeFileSync9 } from "node:fs";
29193
+ import { join as join26, resolve as resolve19 } from "node:path";
28017
29194
  var WRAP_HELP = `Usage: exorcist wrap <mcp.json> [options]
28018
29195
  exorcist unwrap <mcp.json>
28019
29196
 
@@ -28024,16 +29201,16 @@ unwrap Put the original file back byte for byte, if it was not edited since
28024
29201
 
28025
29202
  Options (wrap):
28026
29203
  --bin <command> Command that runs the shield (default: exorcist)
28027
- --bin-arg <arg> Argument before "shield" (repeatable), e.g. --bin npx --bin-arg -y --bin-arg @exorcist-98/cli@0.2.0
29204
+ --bin-arg <arg> Argument before "shield" (repeatable), e.g. --bin npx --bin-arg -y --bin-arg @exorcist-98/cli@0.3.0
28028
29205
  --dir <folder> State folder (default: ${DEFAULT_DIR})
28029
29206
  --dry-run Show the result without writing the file
28030
29207
  `;
28031
29208
  function backupPath(dir, configPath) {
28032
- return join24(dir, "wrap-backups", `${createHash10("sha256").update(configPath).digest("hex").slice(0, 32)}.json`);
29209
+ return join26(dir, "wrap-backups", `${createHash11("sha256").update(configPath).digest("hex").slice(0, 32)}.json`);
28033
29210
  }
28034
29211
  function readBackup(file) {
28035
29212
  try {
28036
- const b = JSON.parse(readFileSync18(file, "utf8"));
29213
+ const b = JSON.parse(readFileSync21(file, "utf8"));
28037
29214
  return typeof b.original === "string" && typeof b.wrapped === "string" && typeof b.path === "string" ? b : null;
28038
29215
  } catch {
28039
29216
  return null;
@@ -28056,7 +29233,7 @@ function readConfig2(path, io) {
28056
29233
  return null;
28057
29234
  }
28058
29235
  try {
28059
- const json2 = JSON.parse(readFileSync18(path, "utf8"));
29236
+ const json2 = JSON.parse(readFileSync21(path, "utf8"));
28060
29237
  if (!json2 || typeof json2 !== "object" || Array.isArray(json2)) throw new Error("not an object");
28061
29238
  return json2;
28062
29239
  } catch {
@@ -28092,7 +29269,7 @@ ${WRAP_HELP}`);
28092
29269
  const path = resolve19(file);
28093
29270
  const cfg = readConfig2(path, io);
28094
29271
  if (!cfg) return 2;
28095
- const text = readFileSync18(path, "utf8");
29272
+ const text = readFileSync21(path, "utf8");
28096
29273
  let next;
28097
29274
  let names;
28098
29275
  if (mode === "wrap") {
@@ -28118,7 +29295,7 @@ ${WRAP_HELP}`);
28118
29295
  writeFileSync9(path, out, "utf8");
28119
29296
  const b = backupPath(stateDir(str4(p.values["dir"])), path);
28120
29297
  try {
28121
- mkdirSync9(join24(b, ".."), { recursive: true, mode: 448 });
29298
+ mkdirSync9(join26(b, ".."), { recursive: true, mode: 448 });
28122
29299
  writeFileSync9(b, JSON.stringify({ path, original: text, wrapped: out }), { mode: 384 });
28123
29300
  } catch {
28124
29301
  io.err("Could not save a copy of the original file; unwrap will still restore the original commands.");
@@ -28173,11 +29350,11 @@ async function checkStagedCommand(io) {
28173
29350
  import { execFile as execFile5 } from "node:child_process";
28174
29351
 
28175
29352
  // src/console/server.ts
28176
- import { randomBytes as randomBytes7, timingSafeEqual } from "node:crypto";
29353
+ import { randomBytes as randomBytes8, timingSafeEqual } from "node:crypto";
28177
29354
  import { createServer } from "node:http";
28178
29355
 
28179
29356
  // src/console/model.ts
28180
- import { lstatSync as lstatSync5, readdirSync as readdirSync6 } from "node:fs";
29357
+ import { lstatSync as lstatSync7, readdirSync as readdirSync7 } from "node:fs";
28181
29358
  var BACKLOG = 400;
28182
29359
  var MAX_SHIELDS = 64;
28183
29360
  var MAX_SESSIONS = 16;
@@ -28212,6 +29389,29 @@ var ConsoleModel = class {
28212
29389
  /** Held calls by `pid:prompt`, until an answer arrives. */
28213
29390
  held = /* @__PURE__ */ new Map();
28214
29391
  counts = { allowed: 0, held: 0, blocked: 0, withheld: 0, flagged: 0, alerts: 0 };
29392
+ chainSig = "";
29393
+ chainCache = { chain: null, chainHead: null };
29394
+ /**
29395
+ * Chain status of the whole log, recomputed only when one of the four files involved changed
29396
+ * (size, mtime, inode), so a quiet folder costs a few stat calls per poll. Read-only.
29397
+ */
29398
+ chainState() {
29399
+ const sig = [eventsPath(this.dir), oldEventsPath(this.dir), headPath(this.dir), genesisPath(this.dir)].map((p) => {
29400
+ try {
29401
+ const st = lstatSync7(p);
29402
+ return `${st.ino}:${st.size}:${st.mtimeMs}`;
29403
+ } catch {
29404
+ return "-";
29405
+ }
29406
+ }).join("|");
29407
+ if (sig === this.chainSig) return this.chainCache;
29408
+ this.chainSig = sig;
29409
+ const present = sig.split("|").some((x, i) => x !== "-" && i !== 3);
29410
+ const h = readHead(this.dir);
29411
+ const chainHead = h.ok && h.value ? { seq: h.value.seq, hash: h.value.hash } : null;
29412
+ this.chainCache = { chain: present ? verifyLogDir(this.dir) : null, chainHead };
29413
+ return this.chainCache;
29414
+ }
28215
29415
  now() {
28216
29416
  return this.o.now ? this.o.now() : /* @__PURE__ */ new Date();
28217
29417
  }
@@ -28267,7 +29467,8 @@ var ConsoleModel = class {
28267
29467
  sessions: this.sessions(waiting, shields),
28268
29468
  release: modes.size > 1 ? "mixed" : modes.has("os") ? "os" : "terminal",
28269
29469
  counts: { ...this.counts },
28270
- skipped: this.tail.skipped
29470
+ skipped: this.tail.skipped,
29471
+ ...this.chainState()
28271
29472
  };
28272
29473
  }
28273
29474
  /** Every session with live facts or a held call, newest first. */
@@ -28278,7 +29479,7 @@ var ConsoleModel = class {
28278
29479
  const root = sessionsPath(this.dir);
28279
29480
  let names = [];
28280
29481
  try {
28281
- names = readdirSync6(root).filter((k) => isSessionKey(k));
29482
+ names = readdirSync7(root).filter((k) => isSessionKey(k));
28282
29483
  } catch {
28283
29484
  names = [];
28284
29485
  }
@@ -28287,7 +29488,7 @@ var ConsoleModel = class {
28287
29488
  for (const key of [...keys].slice(0, 256)) {
28288
29489
  let isDir = false;
28289
29490
  try {
28290
- isDir = lstatSync5(`${root}/${key}`).isDirectory();
29491
+ isDir = lstatSync7(`${root}/${key}`).isDirectory();
28291
29492
  } catch {
28292
29493
  isDir = false;
28293
29494
  }
@@ -28435,6 +29636,7 @@ h1, h2, h3, h4, p { margin: 0; }
28435
29636
  .badge.flagged, .badge.high, .badge.cautious { background: var(--high); }
28436
29637
  .badge.medium, .badge.watching { background: var(--med); }
28437
29638
  .badge.calm { background: var(--ok); }
29639
+ .badge.chain-none { background: var(--paper); }
28438
29640
  .badge.monitor { background: repeating-linear-gradient(135deg, var(--ok) 0 6px, #d6ffe4 6px 12px); }
28439
29641
  .shape { width: 11px; height: 11px; flex: none; background: var(--ink); display: inline-block; }
28440
29642
  .shape.circle { border-radius: 50%; }
@@ -28726,6 +29928,18 @@ var SCRIPT = String.raw`
28726
29928
  $('n-shields').textContent = n;
28727
29929
  }
28728
29930
 
29931
+ // The label is the signal; the colour class only adds to it.
29932
+ function renderChain(c, head) {
29933
+ const b = $('chain-badge');
29934
+ let cls = 'chain-none'; let shapeKind = 'ring'; let label = 'not chained';
29935
+ if (c && c.status === 'intact') { cls = 'calm'; shapeKind = 'circle'; label = 'intact'; }
29936
+ else if (c && c.status === 'broken') { cls = 'critical'; shapeKind = 'octagon'; label = 'broken at event ' + c.atSeq; }
29937
+ b.className = 'badge ' + cls;
29938
+ b.replaceChildren(shape(shapeKind), document.createTextNode(label));
29939
+ $('chain-head').textContent = head ? 'event ' + head.seq + ', head hash ' + head.hash : 'no head hash yet';
29940
+ $('chain-why').textContent = c && c.status === 'broken' ? ' ' + String(c.detail || c.reason) : '';
29941
+ }
29942
+
28729
29943
  const RELEASE_TEXT = {
28730
29944
  terminal: 'a held session is released only by running exorcist approve session <key> in your own terminal.',
28731
29945
  os: 'a held session is released only in the system prompt on this computer (Touch ID or your login password), never from a terminal command or from this page.',
@@ -28739,6 +29953,7 @@ var SCRIPT = String.raw`
28739
29953
  renderShields(s.shields);
28740
29954
  $('where').textContent = s.stateDir;
28741
29955
  $('release-how').textContent = RELEASE_TEXT[s.release] || RELEASE_TEXT.terminal;
29956
+ renderChain(s.chain, s.chainHead);
28742
29957
  $('skipped').textContent = s.skipped > 0 ? ' · ' + s.skipped + ' damaged log line' + (s.skipped === 1 ? '' : 's') + ' skipped' : '';
28743
29958
  }
28744
29959
 
@@ -28827,6 +30042,7 @@ function consolePage(nonce) {
28827
30042
  <span class="conn" id="conn" data-live="false" role="status"><span class="dot" aria-hidden="true"></span><span id="conn-text">CONNECTING</span></span>
28828
30043
  <div class="readonly" role="note"><strong>Read-only view.</strong><span>Nothing on this page can approve, allow or release anything. Calls held for a host are answered in your agent's approval prompt; <span id="release-how">a held session is released only by running exorcist approve session &lt;key&gt; in your own terminal.</span></span></div>
28829
30044
  <p class="where">State folder: <span class="mono" id="where"></span><span id="skipped"></span></p>
30045
+ <p class="where" id="chain">Event log chain: <span id="chain-badge" class="badge chain-none" role="status" aria-label="Event log chain status"><span class="shape ring" aria-hidden="true"></span>not chained</span> <span class="mono" id="chain-head">no head hash yet</span><span id="chain-why"></span></p>
28830
30046
  </div>
28831
30047
  </header>
28832
30048
 
@@ -28940,7 +30156,7 @@ function sameToken(given, token) {
28940
30156
  return timingSafeEqual(padded, b) && a.length === b.length;
28941
30157
  }
28942
30158
  async function startConsole(o) {
28943
- const token = o.token ?? randomBytes7(32).toString("base64url");
30159
+ const token = o.token ?? randomBytes8(32).toString("base64url");
28944
30160
  if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error("The console token must be 32 to 128 URL-safe characters.");
28945
30161
  const model = new ConsoleModel(o.dir, { ...o.rules ? { rules: o.rules } : {}, ...o.alive ? { alive: o.alive } : {} });
28946
30162
  model.poll();
@@ -29014,7 +30230,7 @@ data: ${data}
29014
30230
  res.end();
29015
30231
  return;
29016
30232
  }
29017
- const nonce = randomBytes7(18).toString("base64");
30233
+ const nonce = randomBytes8(18).toString("base64");
29018
30234
  common2(res, pageCsp(nonce));
29019
30235
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
29020
30236
  res.end(req.method === "HEAD" ? void 0 : consolePage(nonce));
@@ -29166,7 +30382,7 @@ ${CONSOLE_HELP}`);
29166
30382
  }
29167
30383
 
29168
30384
  // src/commands/exorcise.ts
29169
- import { existsSync as existsSync17, readFileSync as readFileSync19, statSync as statSync14 } from "node:fs";
30385
+ import { existsSync as existsSync17, readFileSync as readFileSync22, statSync as statSync15 } from "node:fs";
29170
30386
  import { basename as basename9, dirname as dirname11, isAbsolute as isAbsolute11, relative as relative8, resolve as resolve20 } from "node:path";
29171
30387
  var EXORCISE_HELP = `Usage: exorcist exorcise [path] [options]
29172
30388
 
@@ -29256,7 +30472,7 @@ ${EXORCISE_HELP}`);
29256
30472
  io.err(`Path not found: ${target}`);
29257
30473
  return 2;
29258
30474
  }
29259
- const isFile = statSync14(abs).isFile();
30475
+ const isFile = statSync15(abs).isFile();
29260
30476
  const root = isFile ? dirname11(abs) : abs;
29261
30477
  const single = isFile ? basename9(abs) : null;
29262
30478
  const defsDir = findDefinitionsDir2(str4(p.values["definitions"]));
@@ -29325,7 +30541,7 @@ ${EXORCISE_HELP}`);
29325
30541
  return 1;
29326
30542
  }
29327
30543
  const changedSet = new Set(changed.map((r) => r.file));
29328
- const now = changed.map((r) => ({ file: r.file, text: readFileSync19(resolve20(root, r.file), "utf8") }));
30544
+ const now = changed.map((r) => ({ file: r.file, text: readFileSync22(resolve20(root, r.file), "utf8") }));
29329
30545
  const after = [...findings.filter((f) => !changedSet.has(f.file)), ...rescanTexts(now, defs).filter((f) => keep(f.file))];
29330
30546
  const removed = Math.max(0, findings.length - after.length);
29331
30547
  const dirFlag = str4(p.values["dir"]) ? ` --dir ${str4(p.values["dir"])}` : "";
@@ -29347,7 +30563,7 @@ ${EXORCISE_HELP}`);
29347
30563
  import { existsSync as existsSync18 } from "node:fs";
29348
30564
  import { lstat as lstat2, readFile as readFile6 } from "node:fs/promises";
29349
30565
  import { resolve as resolve21 } from "node:path";
29350
- var GATE_HELP = `Usage: exorcist gate [dir] [--fail-on <critical|high|medium|low>]
30566
+ var GATE_HELP = `Usage: exorcist gate [dir] [--fail-on <critical|high|medium|low>] [--dir <state folder>]
29351
30567
  The gate for the end of an agent's turn. It looks only at the files an AI agent
29352
30568
  obeys (steering, specs, hooks, custom agents, MCP configs, AGENTS.md and the
29353
30569
  other rule files, READMEs) that changed since the last commit, and exits 1 with
@@ -29356,10 +30572,16 @@ Findings that the committed version already had are ignored.
29356
30572
  Read-only: it never writes, never uses the network and runs no repository program.
29357
30573
  Exit codes: 0 nothing added (or nothing could be checked: the reason is printed
29358
30574
  to stdout, so an environment problem never stops an agent), 1 the change adds a finding.
30575
+ When the Shield's state folder has an event-log head file, its head hash is
30576
+ printed too (see "exorcist verify-log").
29359
30577
  The Kiro hook written by "exorcist init" runs it when the agent stops.
29360
30578
  `;
29361
30579
  var THRESHOLDS = ["critical", "high", "medium", "low"];
29362
30580
  var GIT_MS = 1e4;
30581
+ function headLine(explicit) {
30582
+ const h = readHead(stateDir(explicit));
30583
+ return h.ok && h.value !== null ? `Exorcist event log head: ${h.value.hash} (event ${h.value.seq})` : null;
30584
+ }
29363
30585
  var nothingChecked = (io, why) => {
29364
30586
  io.out(`Exorcist gate: nothing checked (${why}).`);
29365
30587
  return 0;
@@ -29399,7 +30621,7 @@ async function diskIds(root, rels) {
29399
30621
  return out;
29400
30622
  }
29401
30623
  async function gateCommand(argv, io) {
29402
- const p = parse3(argv, { "fail-on": { type: "string" }, definitions: { type: "string" }, help: { type: "boolean", short: "h" } });
30624
+ const p = parse3(argv, { "fail-on": { type: "string" }, definitions: { type: "string" }, dir: { type: "string" }, help: { type: "boolean", short: "h" } });
29403
30625
  if (!p.ok) {
29404
30626
  io.err(`${p.error}
29405
30627
 
@@ -29465,20 +30687,26 @@ ${GATE_HELP}`);
29465
30687
  added.push(...gateFindings(rel, before, after, defs));
29466
30688
  }
29467
30689
  const blocking = added.filter((f) => isBlocking(f, threshold));
29468
- if (blocking.length === 0) return 0;
29469
- io.err(renderGate(blocking));
30690
+ const head = headLine(str4(p.values["dir"]));
30691
+ if (blocking.length === 0) {
30692
+ if (head !== null) io.out(head);
30693
+ return 0;
30694
+ }
30695
+ io.err(head === null ? renderGate(blocking) : `${renderGate(blocking)}
30696
+ ${head}`);
29470
30697
  return 1;
29471
30698
  }
29472
30699
 
29473
30700
  // src/commands/guard-mcp-write.ts
29474
- import { randomBytes as randomBytes8 } from "node:crypto";
29475
- import { createReadStream, createWriteStream, openSync as openSync4, writeSync as writeSync2 } from "node:fs";
30701
+ import { randomBytes as randomBytes9 } from "node:crypto";
30702
+ import { createReadStream, createWriteStream, openSync as openSync5, writeSync as writeSync3 } from "node:fs";
29476
30703
  import { homedir as homedir3 } from "node:os";
29477
30704
  import { createInterface as createInterface2 } from "node:readline";
29478
30705
  var GUARD_MCP_WRITE_HELP = `Usage: exorcist guard-mcp-write (Kiro hook helper)
29479
30706
  Reads a Kiro PreToolUse hook event from stdin. When the tool would write to
29480
- .kiro/settings/mcp.json (in a project or in your home folder), a person must
29481
- confirm it: on a Mac with the system verification (Touch ID or login password),
30707
+ .kiro/settings/mcp.json (in a project or in your home folder), adds a trusted
30708
+ command to .vscode/settings.json, or creates, changes, moves or deletes a file
30709
+ in .kiro/hooks/ or .kiro/agents/, a person must confirm it: on a Mac with the system verification (Touch ID or login password),
29482
30710
  else in a native dialog you click (Deny is the default),
29483
30711
  elsewhere by typing a code shown on your terminal (/dev/tty). The dialog names
29484
30712
  the file and never shows what the agent wanted to write.
@@ -29491,14 +30719,14 @@ var PROMPT_TIMEOUT_MS = 125e3;
29491
30719
  function hookDeps() {
29492
30720
  let fd = null;
29493
30721
  try {
29494
- fd = openSync4("/dev/tty", "r+");
30722
+ fd = openSync5("/dev/tty", "r+");
29495
30723
  } catch {
29496
30724
  fd = null;
29497
30725
  }
29498
30726
  const tty = fd;
29499
30727
  const write = (s) => {
29500
30728
  if (tty !== null) try {
29501
- writeSync2(tty, s.endsWith("\n") ? s : `${s}
30729
+ writeSync3(tty, s.endsWith("\n") ? s : `${s}
29502
30730
  `);
29503
30731
  } catch {
29504
30732
  }
@@ -29520,28 +30748,43 @@ function hookDeps() {
29520
30748
  });
29521
30749
  }),
29522
30750
  dialog: macDialog,
29523
- nonce: () => randomBytes8(4).toString("hex").slice(0, 6)
30751
+ nonce: () => randomBytes9(4).toString("hex").slice(0, 6)
29524
30752
  };
29525
30753
  return { term, promptIo: { out: write, err: write }, home: homedir3(), timeoutMs: PROMPT_TIMEOUT_MS };
29526
30754
  }
29527
- function dialogMessage(path) {
30755
+ function dialogMessage(kind, path) {
30756
+ if (kind === "trusted-commands") return `Your AI agent wants to change which commands it may run without asking you:
30757
+
30758
+ ${shownName(path)}
30759
+
30760
+ A wider list lets the agent run programs on your computer without your approval. Allow it only if you asked for this change.`;
30761
+ if (kind === "guard-file") return `Your AI agent wants to change one of its own guard files (a hook or a custom agent):
30762
+
30763
+ ${shownName(path)}
30764
+
30765
+ These files decide what the agent is stopped from doing. Allow it only if you asked for this change.`;
29528
30766
  return `Your AI agent wants to change an MCP configuration file:
29529
30767
 
29530
30768
  ${shownName(path)}
29531
30769
 
29532
30770
  A changed MCP config can start programs on your computer. Allow it only if you asked for this change.`;
29533
30771
  }
29534
- function reasonText(path) {
30772
+ function reasonText(kind, path) {
30773
+ if (kind === "trusted-commands") return `Allow your AI agent to change its trusted commands in ${shownName(path)}`;
30774
+ if (kind === "guard-file") return `Allow your AI agent to change its guard file ${shownName(path)}`;
29535
30775
  return `Allow your AI agent to change the MCP config ${shownName(path)}`;
29536
30776
  }
29537
- function blockMessage(path, why) {
30777
+ function blockMessage(kind, path, why) {
30778
+ if (kind === "trusted-commands") return `Exorcist 98 blocked the write to ${shownName(path)}: ${why} The trusted commands list decides which programs the agent may run without asking, so only you may change it. To make the change yourself, edit the file in your own editor, then ask the agent to continue.`;
30779
+ if (kind === "guard-file") return `Exorcist 98 blocked the write to ${shownName(path)}: ${why} Hooks and custom agents decide what the agent is stopped from doing, so only you may change them. To make the change yourself, edit the file in your own editor, then ask the agent to continue.`;
29538
30780
  return `Exorcist 98 blocked the write to ${shownName(path)}: ${why} An MCP config can start programs on your computer, so only you may change it. To make the change yourself, edit the file in your own editor, then ask the agent to continue.`;
29539
30781
  }
29540
- async function askPerson(deps, path) {
30782
+ async function askPerson(deps, kind, path) {
29541
30783
  const { term, promptIo } = deps;
29542
- const run = async () => {
29543
- if (term.interactive) return await personConfirms(term, promptIo, dialogMessage(path), reasonText(path)) ? "yes" : "no";
29544
- const answer = await askOwner(term, dialogMessage(path), reasonText(path));
30784
+ const audit = { dir: stateDir(), subject: "guard-mcp-write" };
30785
+ const run2 = async () => {
30786
+ if (term.interactive) return await personConfirms(term, promptIo, dialogMessage(kind, path), reasonText(kind, path), audit) ? "yes" : "no";
30787
+ const answer = await askOwner(term, dialogMessage(kind, path), reasonText(kind, path), audit);
29545
30788
  return answer === "allow" ? "yes" : answer === "deny" ? "no" : "nobody";
29546
30789
  };
29547
30790
  let timer;
@@ -29549,7 +30792,7 @@ async function askPerson(deps, path) {
29549
30792
  timer = setTimeout(() => done("timeout"), deps.timeoutMs);
29550
30793
  });
29551
30794
  try {
29552
- return await Promise.race([run(), limit]);
30795
+ return await Promise.race([run2(), limit]);
29553
30796
  } finally {
29554
30797
  if (timer) clearTimeout(timer);
29555
30798
  }
@@ -29562,16 +30805,78 @@ async function guardMcpWriteCommand(stdin, io, deps = hookDeps()) {
29562
30805
  return 0;
29563
30806
  }
29564
30807
  const decision = decideMcpWrite(event, deps.home, process.cwd());
29565
- if (decision.target !== "mcp-config") return 0;
29566
- const answer = await askPerson(deps, decision.path);
30808
+ if (decision.target === "other") return 0;
30809
+ const answer = await askPerson(deps, decision.target, decision.path);
29567
30810
  if (answer === "yes") return 0;
29568
30811
  const why = answer === "no" ? "you did not confirm it." : answer === "timeout" ? "nobody confirmed it in time." : "there is no dialog or terminal where a person can be asked.";
29569
- io.err(blockMessage(decision.path, why));
30812
+ io.err(blockMessage(decision.target, decision.path, why));
30813
+ return 2;
30814
+ }
30815
+
30816
+ // src/commands/guard-env-write.ts
30817
+ import { isAbsolute as isAbsolute12 } from "node:path";
30818
+ var GUARD_ENV_WRITE_HELP = `Usage: exorcist guard-env-write (Kiro hook helper)
30819
+ Reads a Kiro PreToolUse hook event for a file write (fs_write, str_replace) from
30820
+ stdin. When the text to be written holds a value from a .env file of this project
30821
+ and the destination is not itself a .env file, the write is blocked: the value
30822
+ would end up in a file that gets committed or shared.
30823
+ Exit codes: 0 allow, 2 block (one line on stderr naming the file, never the
30824
+ value). Any other event, a project without a .env file, and any input it cannot
30825
+ understand, is allowed: the hook must never stop the agent from working.
30826
+ `;
30827
+ function projectDir(event) {
30828
+ const cwd = typeof event === "object" && event !== null ? event["cwd"] : void 0;
30829
+ return typeof cwd === "string" && cwd !== "" && isAbsolute12(cwd) ? cwd : process.cwd();
30830
+ }
30831
+ function guardEnvWriteCommand(stdin, io) {
30832
+ let event;
30833
+ try {
30834
+ event = JSON.parse(stdin);
30835
+ } catch {
30836
+ return 0;
30837
+ }
30838
+ const envValues = loadEnvValues(projectDir(event));
30839
+ const decision = decideEnvWrite(event, envValues);
30840
+ if (!decision.block) return 0;
30841
+ io.err(envWriteBlockMessage(decision, envValues));
30842
+ return 2;
30843
+ }
30844
+
30845
+ // src/commands/guard-web-fetch.ts
30846
+ import { isAbsolute as isAbsolute13 } from "node:path";
30847
+ var GUARD_WEB_FETCH_HELP = `Usage: exorcist guard-web-fetch (Kiro hook helper)
30848
+ Reads a Kiro PreToolUse hook event for the web_fetch tool from stdin. When the
30849
+ address holds a secret (a key or token), a canary token, or a value from a .env
30850
+ file of this project, in plain form, percent-encoded, base64 or split up, the
30851
+ fetch is blocked: a fetch sends its address to another computer.
30852
+ Exit codes: 0 allow, 2 block (one line on stderr naming the kind of value and the
30853
+ host, never the value or the address). Any other event, and any input it cannot
30854
+ understand, is allowed: the hook must never stop the agent from working.
30855
+ `;
30856
+ function projectDir2(event) {
30857
+ const cwd = typeof event === "object" && event !== null ? event["cwd"] : void 0;
30858
+ return typeof cwd === "string" && cwd !== "" && isAbsolute13(cwd) ? cwd : process.cwd();
30859
+ }
30860
+ function guardWebFetchCommand(stdin, io) {
30861
+ let event;
30862
+ try {
30863
+ event = JSON.parse(stdin);
30864
+ } catch {
30865
+ return 0;
30866
+ }
30867
+ const cwd = projectDir2(event);
30868
+ const records = loadCanariesFile(canariesPath(cwd));
30869
+ const decision = decideWebFetch(event, {
30870
+ envValues: loadEnvValues(cwd),
30871
+ canaries: records.ok ? records.canaries : []
30872
+ });
30873
+ if (!decision.block) return 0;
30874
+ io.err(webFetchBlockMessage(decision));
29570
30875
  return 2;
29571
30876
  }
29572
30877
 
29573
30878
  // src/commands/hook-scan.ts
29574
- import { existsSync as existsSync19, statSync as statSync15 } from "node:fs";
30879
+ import { existsSync as existsSync19, statSync as statSync16 } from "node:fs";
29575
30880
  import { resolve as resolve22 } from "node:path";
29576
30881
  async function hookScanCommand(stdin, io) {
29577
30882
  let event;
@@ -29583,13 +30888,13 @@ async function hookScanCommand(stdin, io) {
29583
30888
  if (typeof event.file_path !== "string" || event.file_path === "") return 0;
29584
30889
  const base = typeof event.cwd === "string" && event.cwd ? event.cwd : process.cwd();
29585
30890
  const file = resolve22(base, event.file_path);
29586
- if (!existsSync19(file) || !statSync15(file).isFile()) return 0;
30891
+ if (!existsSync19(file) || !statSync16(file).isFile()) return 0;
29587
30892
  return await scanCommand([file, "--fail-on", "high"], { out: io.err, err: io.err });
29588
30893
  }
29589
30894
 
29590
30895
  // src/commands/init.ts
29591
- import { chmodSync, existsSync as existsSync20, mkdirSync as mkdirSync10, readFileSync as readFileSync20, writeFileSync as writeFileSync10 } from "node:fs";
29592
- import { dirname as dirname12, join as join25, resolve as resolve23 } from "node:path";
30896
+ import { chmodSync, existsSync as existsSync20, lstatSync as lstatSync8, mkdirSync as mkdirSync10, readFileSync as readFileSync23, writeFileSync as writeFileSync10 } from "node:fs";
30897
+ import { dirname as dirname12, join as join27, resolve as resolve23 } from "node:path";
29593
30898
 
29594
30899
  // src/kiro-hook-script.ts
29595
30900
  var KIRO_HOOK_SCRIPT = [
@@ -29707,10 +31012,10 @@ function reviewerAgentForProject(mcpCommand) {
29707
31012
  }
29708
31013
 
29709
31014
  // src/commands/init.ts
29710
- var DEFAULT_BIN = "npx -y @exorcist-98/cli@0.2.0";
29711
- var DEFAULT_MCP_BIN = "npx -y @exorcist-98/mcp-server@0.2.0";
29712
- var MISSING_FROM_DEFAULT_BIN = /* @__PURE__ */ new Set([]);
29713
- var INIT_HELP = `Usage: exorcist init [folder] [--kiro] [--shield] [--no-agent] [--force]
31015
+ var DEFAULT_BIN = "npx -y @exorcist-98/cli@0.3.0";
31016
+ var DEFAULT_MCP_BIN = "npx -y @exorcist-98/mcp-server@0.3.0";
31017
+ var MISSING_FROM_DEFAULT_BIN = /* @__PURE__ */ new Set();
31018
+ var INIT_HELP = `Usage: exorcist init [folder] [--kiro] [--shield] [--sandbox] [--no-agent] [--force]
29714
31019
  [--bin <command>] [--mcp-bin <command>]
29715
31020
 
29716
31021
  Add Exorcist 98 to a Kiro project:
@@ -29720,6 +31025,8 @@ Add Exorcist 98 to a Kiro project:
29720
31025
  .kiro/hooks/exorcist-gate.json when the agent stops, fail if it added a high or critical finding
29721
31026
  to a steering, spec, hook, agent or MCP file (Kiro Stop hook)
29722
31027
  .kiro/hooks/exorcist-mcp-write-guard.json a person must confirm any agent write to an MCP config (Kiro hook)
31028
+ .kiro/hooks/exorcist-guard-web-fetch.json block a web fetch whose address holds a secret, canary or .env value (Kiro hook)
31029
+ .kiro/hooks/exorcist-guard-env-write.json block writing a .env value into any other file (Kiro hook)
29723
31030
  .kiro/steering/exorcist.md tell the agent how to treat tool output
29724
31031
  .exorcist/kiro-hook.sh puts Node on PATH for the Kiro hooks (Kiro's hook PATH has none)
29725
31032
  .exorcist/.gitignore keeps the hook log out of git
@@ -29731,12 +31038,40 @@ Add Exorcist 98 to a Kiro project:
29731
31038
  --no-agent With --kiro, leave the agent out.
29732
31039
  --shield Put every server in .kiro/settings/mcp.json behind the Real-Time Shield
29733
31040
  (implies --kiro). Undo with: exorcist unwrap .kiro/settings/mcp.json
31041
+ --sandbox With --kiro, also turn on Kiro's sandbox for this project by writing
31042
+ .kiro/settings/sandbox.json (sandbox on, network blocked, MCP sandboxing on).
31043
+ An existing file is never changed, not even with --force. Undo: delete the file.
29734
31044
  --bin The command the hooks and the Shield run (default: ${DEFAULT_BIN}).
29735
31045
  --mcp-bin The command that starts the agent's MCP server (default: ${DEFAULT_MCP_BIN}).
29736
31046
 
29737
31047
  Turn on the git hook once per clone: git config core.hooksPath .githooks
29738
31048
  Existing files are never overwritten unless you pass --force.
29739
31049
  `;
31050
+ var SANDBOX_REL = ".kiro/settings/sandbox.json";
31051
+ var SANDBOX_SETTINGS = { enabled: true, networkAccess: "DEFAULT_BLOCKED", mcpSandboxing: true };
31052
+ function writeSandboxFile(root, io) {
31053
+ const path = join27(root, SANDBOX_REL);
31054
+ let present = false;
31055
+ try {
31056
+ lstatSync8(path);
31057
+ present = true;
31058
+ } catch {
31059
+ }
31060
+ if (!present) {
31061
+ mkdirSync10(dirname12(path), { recursive: true });
31062
+ try {
31063
+ writeFileSync10(path, `${JSON.stringify(SANDBOX_SETTINGS, null, 2)}
31064
+ `, { encoding: "utf8", flag: "wx" });
31065
+ io.out(`Wrote ${SANDBOX_REL}: sandbox on, network blocked by default, MCP sandboxing on.`);
31066
+ io.out(`Undo: delete ${SANDBOX_REL}. (A project file can only tighten a global sandbox policy.)`);
31067
+ return true;
31068
+ } catch (e) {
31069
+ if (e.code !== "EEXIST") throw e;
31070
+ }
31071
+ }
31072
+ io.out(`Left ${SANDBOX_REL} unchanged: it already exists. Delete it and rerun to get the Exorcist settings.`);
31073
+ return false;
31074
+ }
29740
31075
  var hook = (name, description, body) => `${JSON.stringify({ version: "v1", hooks: [{ name, description, ...body }] }, null, 2)}
29741
31076
  `;
29742
31077
  var STEERING = `---
@@ -29791,7 +31126,7 @@ var MAX_NAME = 60;
29791
31126
  function describeMcpConfig(path) {
29792
31127
  if (!existsSync20(path)) return { exists: false, warnings: [], line: "no .kiro/settings/mcp.json yet (the mcp-scan hook scans it once you add one)" };
29793
31128
  try {
29794
- const cfg = JSON.parse(readFileSync20(path, "utf8"));
31129
+ const cfg = JSON.parse(readFileSync23(path, "utf8"));
29795
31130
  const entries = Object.entries(cfg.mcpServers ?? {});
29796
31131
  const shielded = entries.filter(([, e]) => isWrapped(e)).map(([n]) => n);
29797
31132
  const warnings = entries.filter(([, e]) => Array.isArray(e.autoApprove) && e.autoApprove.includes("*")).map(([n]) => `WARNING: server "${displayMessage(n.slice(0, MAX_NAME).replace(/[\t\n\r]/g, " "))}${n.length > MAX_NAME ? "..." : ""}" has autoApprove "*": your agent can run every tool of it without asking you. List only the tools you trust, or remove autoApprove.`);
@@ -29806,6 +31141,7 @@ async function initCommand(argv, io) {
29806
31141
  bin: { type: "string" },
29807
31142
  "mcp-bin": { type: "string" },
29808
31143
  kiro: { type: "boolean" },
31144
+ sandbox: { type: "boolean" },
29809
31145
  shield: { type: "boolean" },
29810
31146
  "no-agent": { type: "boolean" },
29811
31147
  help: { type: "boolean", short: "h" }
@@ -29837,6 +31173,11 @@ ${INIT_HELP}`);
29837
31173
  io.err("--no-agent only makes sense with --kiro.");
29838
31174
  return 2;
29839
31175
  }
31176
+ const sandbox = p.values["sandbox"] === true;
31177
+ if (sandbox && !kiro) {
31178
+ io.err("--sandbox only makes sense with --kiro (or --shield).");
31179
+ return 2;
31180
+ }
29840
31181
  const binWords = splitCommand(bin);
29841
31182
  const mcpWords = splitCommand(mcpBin);
29842
31183
  if (!binWords) {
@@ -29851,6 +31192,8 @@ ${INIT_HELP}`);
29851
31192
  const onAccessOff = isDefaultBin && MISSING_FROM_DEFAULT_BIN.has("on-access");
29852
31193
  const gateOff = isDefaultBin && MISSING_FROM_DEFAULT_BIN.has("gate");
29853
31194
  const mcpWriteOff = isDefaultBin && MISSING_FROM_DEFAULT_BIN.has("guard-mcp-write");
31195
+ const webFetchOff = isDefaultBin && MISSING_FROM_DEFAULT_BIN.has("guard-web-fetch");
31196
+ const envWriteOff = isDefaultBin && MISSING_FROM_DEFAULT_BIN.has("guard-env-write");
29854
31197
  const files = [
29855
31198
  {
29856
31199
  rel: ".kiro/hooks/exorcist-secrets.json",
@@ -29895,8 +31238,8 @@ ${INIT_HELP}`);
29895
31238
  },
29896
31239
  {
29897
31240
  rel: ".kiro/hooks/exorcist-mcp-write-guard.json",
29898
- summary: mcpWriteOff ? 'PreToolUse on write and shell tools: WRITTEN DISABLED, because the published version in the default command has no guard-mcp-write command (pass --bin with a newer build, then set "enabled": true)' : "PreToolUse on write and shell tools: a person must confirm any agent write to an MCP config",
29899
- body: hook("exorcist-mcp-write-guard", "A person must confirm any agent write to an MCP config. Exit code 2 blocks the write.", {
31241
+ summary: mcpWriteOff ? 'PreToolUse on write and shell tools: WRITTEN DISABLED, because the published version in the default command has no guard-mcp-write command (pass --bin with a newer build, then set "enabled": true)' : "PreToolUse on write and shell tools: a person must confirm any agent write to an MCP config, trusted commands or hook/agent file",
31242
+ body: hook("exorcist-mcp-write-guard", "A person must confirm any agent write to an MCP config, any change that adds a trusted command in .vscode/settings.json, and any change to a file in .kiro/hooks/ or .kiro/agents/. Exit code 2 blocks the write.", {
29900
31243
  trigger: "PreToolUse",
29901
31244
  matcher: "write|shell",
29902
31245
  action: { type: "command", command: `${HOOK_RUNNER} ${bin} guard-mcp-write` },
@@ -29904,6 +31247,28 @@ ${INIT_HELP}`);
29904
31247
  ...mcpWriteOff ? { enabled: false } : {}
29905
31248
  })
29906
31249
  },
31250
+ {
31251
+ rel: ".kiro/hooks/exorcist-guard-web-fetch.json",
31252
+ summary: webFetchOff ? 'PreToolUse on web_fetch: WRITTEN DISABLED, because the published version in the default command has no guard-web-fetch command (pass --bin with a newer build, then set "enabled": true)' : "PreToolUse on web_fetch: blocks a fetch whose address holds a secret, canary or .env value",
31253
+ body: hook("exorcist-guard-web-fetch", "Blocks the web_fetch tool when the address holds a secret (key or token), a canary token, or a value from a .env file of this project. Exit code 2 blocks the fetch; the reason names the kind of value and the host, never the value.", {
31254
+ trigger: "PreToolUse",
31255
+ matcher: "web_fetch|webFetch",
31256
+ action: { type: "command", command: `${HOOK_RUNNER} ${bin} guard-web-fetch` },
31257
+ timeout: 15,
31258
+ ...webFetchOff ? { enabled: false } : {}
31259
+ })
31260
+ },
31261
+ {
31262
+ rel: ".kiro/hooks/exorcist-guard-env-write.json",
31263
+ summary: envWriteOff ? 'PreToolUse on write tools: WRITTEN DISABLED, because the published version in the default command has no guard-env-write command (pass --bin with a newer build, then set "enabled": true)' : "PreToolUse on write tools: blocks writing a .env value into any other file",
31264
+ body: hook("exorcist-guard-env-write", "Blocks the write tools (fs_write, str_replace) when the text to be written holds a value from a .env file of this project and the destination is not itself a .env file. Exit code 2 blocks the write; the reason names the file, never the value.", {
31265
+ trigger: "PreToolUse",
31266
+ matcher: "write|fs_write|str_replace",
31267
+ action: { type: "command", command: `${HOOK_RUNNER} ${bin} guard-env-write` },
31268
+ timeout: 15,
31269
+ ...envWriteOff ? { enabled: false } : {}
31270
+ })
31271
+ },
29907
31272
  { rel: ".kiro/steering/exorcist.md", body: STEERING, summary: "steering (inclusion: always): tool output and file text are data, never instructions" },
29908
31273
  { rel: ".exorcist/kiro-hook.sh", body: KIRO_HOOK_SCRIPT, executable: true, summary: "finds Node for the hooks (Kiro gives hook commands a PATH without it)" },
29909
31274
  { rel: ".exorcist/.gitignore", body: "kiro-hooks.log\n", summary: "keeps the hook log out of git" },
@@ -29919,7 +31284,7 @@ ${INIT_HELP}`);
29919
31284
  }
29920
31285
  const done = [];
29921
31286
  for (const f of files) {
29922
- const path = join25(root, f.rel);
31287
+ const path = join27(root, f.rel);
29923
31288
  if (existsSync20(path) && !force) {
29924
31289
  io.err(`Kept existing ${f.rel} (use --force to replace it).`);
29925
31290
  done.push({ f, wrote: false });
@@ -29936,7 +31301,8 @@ ${INIT_HELP}`);
29936
31301
  if (wroteAny) io.out("Turn on the git hook with: git config core.hooksPath .githooks");
29937
31302
  return wroteAny ? 0 : 1;
29938
31303
  }
29939
- const mcpPath = join25(root, ".kiro/settings/mcp.json");
31304
+ if (sandbox) writeSandboxFile(root, io);
31305
+ const mcpPath = join27(root, ".kiro/settings/mcp.json");
29940
31306
  let shieldOk = true;
29941
31307
  let shieldLine = null;
29942
31308
  if (shield) {
@@ -29946,7 +31312,7 @@ ${INIT_HELP}`);
29946
31312
  shieldOk = false;
29947
31313
  } else {
29948
31314
  const [head, ...rest] = binWords;
29949
- const args = [mcpPath, `--bin=${head}`, ...rest.map((a) => `--bin-arg=${a}`), `--dir=${join25(root, ".exorcist")}`];
31315
+ const args = [mcpPath, `--bin=${head}`, ...rest.map((a) => `--bin-arg=${a}`), `--dir=${join27(root, ".exorcist")}`];
29950
31316
  const notes = [];
29951
31317
  const code3 = await wrapCommand(args, { out: io.out, err: (s) => notes.push(s) }, "wrap");
29952
31318
  for (const n of notes) io.err(n);
@@ -29980,6 +31346,8 @@ ${INIT_HELP}`);
29980
31346
  ` ${mcp.line}`,
29981
31347
  ...mcp.warnings.map((w) => ` ${w}`),
29982
31348
  shield ? ` Shield: ${shieldLine ?? "not applied"}` : " Shield: not applied. To put every server behind it: exorcist init --shield (undo: exorcist unwrap .kiro/settings/mcp.json)",
31349
+ "Sandbox",
31350
+ sandbox ? ` ${SANDBOX_REL}: see the lines above` : " not changed. To turn on Kiro's sandbox for this project: exorcist init --kiro --sandbox",
29983
31351
  "Git",
29984
31352
  ` ${label(".githooks/pre-commit")}
29985
31353
  turn on once per clone: git config core.hooksPath .githooks`,
@@ -29988,7 +31356,7 @@ ${INIT_HELP}`);
29988
31356
  "then reconnect MCP servers in the MCP panel so they start through the Shield."
29989
31357
  ];
29990
31358
  if (isDefaultBin) {
29991
- lines.push("Commands run through npx (@exorcist-98/cli@0.2.0). If Kiro cannot start a wrapped server or a hook cannot find npx,");
31359
+ lines.push("Commands run through npx (@exorcist-98/cli@0.3.0). If Kiro cannot start a wrapped server or a hook cannot find npx,");
29992
31360
  lines.push('rerun with --bin "<absolute path to node> <absolute path to the exorcist CLI>" and --force.');
29993
31361
  }
29994
31362
  io.out(lines.join("\n"));
@@ -29997,8 +31365,8 @@ ${INIT_HELP}`);
29997
31365
  }
29998
31366
 
29999
31367
  // src/commands/lock.ts
30000
- import { existsSync as existsSync21, readFileSync as readFileSync21, writeFileSync as writeFileSync11 } from "node:fs";
30001
- import { isAbsolute as isAbsolute12, join as join26, resolve as resolve24 } from "node:path";
31368
+ import { existsSync as existsSync21, readFileSync as readFileSync24, writeFileSync as writeFileSync11 } from "node:fs";
31369
+ import { isAbsolute as isAbsolute14, join as join28, resolve as resolve24 } from "node:path";
30002
31370
 
30003
31371
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js
30004
31372
  var NEVER2 = Object.freeze({
@@ -37307,7 +38675,7 @@ var StdioClientTransport = class {
37307
38675
  // src/commands/lock.ts
37308
38676
  init_zod();
37309
38677
  var DEFAULT_LOCK_TIMEOUT_MS = 2e4;
37310
- var DEFAULT_CONFIG = join26(".kiro", "settings", "mcp.json");
38678
+ var DEFAULT_CONFIG = join28(".kiro", "settings", "mcp.json");
37311
38679
  var MAX_PAGES = 100;
37312
38680
  var LOCK_HELP = `Usage: exorcist lock [options]
37313
38681
  exorcist lock --check [options]
@@ -37358,7 +38726,7 @@ var EntrySchema2 = external_exports.object({
37358
38726
  function readConfig3(path) {
37359
38727
  let json2;
37360
38728
  try {
37361
- json2 = JSON.parse(readFileSync21(path, "utf8"));
38729
+ json2 = JSON.parse(readFileSync24(path, "utf8"));
37362
38730
  } catch {
37363
38731
  return { ok: false, error: `${path} is not valid JSON.` };
37364
38732
  }
@@ -37371,7 +38739,7 @@ var RawToolsPage = external_exports.object({ tools: external_exports.array(exter
37371
38739
  var firstLine2 = (err) => (err instanceof Error ? err.message : String(err)).split("\n")[0]?.slice(0, 300) ?? "unknown error";
37372
38740
  async function listTools(o) {
37373
38741
  const transport = new StdioClientTransport({ command: o.command, args: o.args, env: o.env, cwd: o.cwd, stderr: "ignore" });
37374
- const client = new Client({ name: "exorcist-lock", version: "0.2.0" }, { capabilities: {} });
38742
+ const client = new Client({ name: "exorcist-lock", version: "0.3.0" }, { capabilities: {} });
37375
38743
  let timer;
37376
38744
  const timedOut = new Promise((res) => {
37377
38745
  timer = setTimeout(() => res({ ok: false, error: `it did not list its tools within ${o.timeoutMs} ms.` }), o.timeoutMs);
@@ -37454,7 +38822,7 @@ async function collectListings(config2, o) {
37454
38822
  if (loaders.length > 0) {
37455
38823
  warnings.push(`HIGH EX-025: "${name}" sets ${loaders.join(", ")} in its env, which changes how its program loads (for example NODE_OPTIONS=--require runs extra code first). Make sure you know why it is there.`);
37456
38824
  }
37457
- const cwd = entry.cwd === void 0 ? o.cwd : isAbsolute12(entry.cwd) ? entry.cwd : resolve24(o.cwd, entry.cwd);
38825
+ const cwd = entry.cwd === void 0 ? o.cwd : isAbsolute14(entry.cwd) ? entry.cwd : resolve24(o.cwd, entry.cwd);
37458
38826
  if (o.static) {
37459
38827
  const old = o.previous && Object.hasOwn(o.previous.servers, name) ? o.previous.servers[name] : void 0;
37460
38828
  kept.push([name, { launch: launchFingerprint(command, entry.args, cwd, void 0, pinEntry).hash, tools: old?.tools ?? {} }]);
@@ -37539,7 +38907,7 @@ ${LOCK_HELP}`);
37539
38907
  if (existsSync21(lockPath2)) {
37540
38908
  let text2;
37541
38909
  try {
37542
- text2 = readFileSync21(lockPath2, "utf8");
38910
+ text2 = readFileSync24(lockPath2, "utf8");
37543
38911
  } catch (err) {
37544
38912
  io.err(`Could not read ${lockPath2}: ${firstLine2(err)}`);
37545
38913
  return 2;
@@ -37613,7 +38981,7 @@ ${LOCK_HELP}`);
37613
38981
  }
37614
38982
 
37615
38983
  // src/commands/map.ts
37616
- import { existsSync as existsSync22, statSync as statSync16 } from "node:fs";
38984
+ import { existsSync as existsSync22, statSync as statSync17 } from "node:fs";
37617
38985
  import { resolve as resolve25 } from "node:path";
37618
38986
  var MAP_HELP = `Usage: exorcist map [dir] [options]
37619
38987
 
@@ -37710,7 +39078,7 @@ ${MAP_HELP}`);
37710
39078
  }
37711
39079
  const target = p.positionals[0] ?? ".";
37712
39080
  const root = resolve25(target);
37713
- if (!existsSync22(root) || !statSync16(root).isDirectory()) {
39081
+ if (!existsSync22(root) || !statSync17(root).isDirectory()) {
37714
39082
  io.err(`Folder not found: ${target}`);
37715
39083
  return 2;
37716
39084
  }
@@ -37732,7 +39100,7 @@ ${MAP_HELP}`);
37732
39100
  }
37733
39101
 
37734
39102
  // src/commands/origin.ts
37735
- import { existsSync as existsSync23, realpathSync as realpathSync5, statSync as statSync17 } from "node:fs";
39103
+ import { existsSync as existsSync23, realpathSync as realpathSync5, statSync as statSync18 } from "node:fs";
37736
39104
  import { posix, relative as relative9, resolve as resolve26, sep as sep2 } from "node:path";
37737
39105
  var ORIGIN_HELP = `Usage: exorcist origin [dir] [options]
37738
39106
 
@@ -37856,7 +39224,7 @@ ${ORIGIN_HELP}`);
37856
39224
  return 2;
37857
39225
  }
37858
39226
  const target = resolve26(p.positionals[0] ?? ".");
37859
- if (!existsSync23(target) || !statSync17(target).isDirectory()) {
39227
+ if (!existsSync23(target) || !statSync18(target).isDirectory()) {
37860
39228
  io.err(`Not a directory: ${target}`);
37861
39229
  return 2;
37862
39230
  }
@@ -38198,7 +39566,7 @@ ${VAULT_HELP}`);
38198
39566
  }
38199
39567
  const vault = vaultPath(stateDir(str4(p.values["dir"])));
38200
39568
  const reason = str4(p.values["reason"]) ?? "quarantined by hand";
38201
- const fail3 = (e) => {
39569
+ const fail4 = (e) => {
38202
39570
  io.err(e);
38203
39571
  return 1;
38204
39572
  };
@@ -38221,7 +39589,7 @@ ${VAULT_HELP}`);
38221
39589
  return 2;
38222
39590
  }
38223
39591
  const r = quarantineServer({ configPath: config2, serverName: server, reason, vaultDir: vault });
38224
- if (!r.ok) return fail3(r.error);
39592
+ if (!r.ok) return fail4(r.error);
38225
39593
  io.out(`Quarantined "${server}". Vault entry: ${r.value.id}
38226
39594
  Restore with: exorcist vault restore ${r.value.id}`);
38227
39595
  return 0;
@@ -38233,7 +39601,7 @@ Restore with: exorcist vault restore ${r.value.id}`);
38233
39601
  return 2;
38234
39602
  }
38235
39603
  const r = quarantineFile({ filePath: file, reason, vaultDir: vault });
38236
- if (!r.ok) return fail3(r.error);
39604
+ if (!r.ok) return fail4(r.error);
38237
39605
  io.out(`Moved ${r.value.target} into the vault. Vault entry: ${r.value.id}
38238
39606
  Restore with: exorcist vault restore ${r.value.id}`);
38239
39607
  return 0;
@@ -38245,7 +39613,7 @@ Restore with: exorcist vault restore ${r.value.id}`);
38245
39613
  return 2;
38246
39614
  }
38247
39615
  const r = diffEntry(vault, id);
38248
- if (!r.ok) return fail3(r.error);
39616
+ if (!r.ok) return fail4(r.error);
38249
39617
  io.out(r.value);
38250
39618
  return 0;
38251
39619
  }
@@ -38256,7 +39624,7 @@ Restore with: exorcist vault restore ${r.value.id}`);
38256
39624
  return 2;
38257
39625
  }
38258
39626
  const r = restoreEntry(vault, id, { force: p.values["force"] === true });
38259
- if (!r.ok) return fail3(r.error);
39627
+ if (!r.ok) return fail4(r.error);
38260
39628
  io.out(`Restored ${r.value.kind === "mcp-server" ? `server "${r.value.serverName}"` : r.value.kind === "exorcise" ? `${r.value.files?.length ?? 0} file(s) in ${r.value.target} to their original bytes` : r.value.target}.`);
38261
39629
  return 0;
38262
39630
  }
@@ -38268,8 +39636,107 @@ ${VAULT_HELP}`);
38268
39636
  }
38269
39637
  }
38270
39638
 
39639
+ // src/commands/verify-log.ts
39640
+ var VERIFY_LOG_HELP = `Usage: exorcist verify-log [--dir <folder>] [--expect <hash | seq:hash>] [--json]
39641
+
39642
+ Checks that the Shield's event log has not been changed, cut short or reordered
39643
+ since it was written. Every event is linked to the one before it, so any edit
39644
+ shows up as the first event that no longer fits.
39645
+
39646
+ --dir <folder> the Shield state folder (default: ${DEFAULT_DIR})
39647
+ --expect <x> a head hash you saved earlier, kept outside the state folder.
39648
+ "<hash>" must be the log's current head; "<seq>:<hash>" must be
39649
+ the hash of event number <seq> (still valid after the log grows).
39650
+ This is what catches a rewrite of the whole folder.
39651
+ --json print the result as one JSON object instead of text
39652
+
39653
+ Exit codes: 0 the log is intact, or has no chain yet ("not chained", an old log);
39654
+ 1 the log is broken, or --expect was given and could not be matched;
39655
+ 2 usage error.
39656
+ `;
39657
+ var HEX643 = /^[0-9a-f]{64}$/;
39658
+ function parseExpect(raw) {
39659
+ const v = raw.trim().toLowerCase();
39660
+ if (HEX643.test(v)) return { kind: "tip", hash: v };
39661
+ const m = /^([1-9][0-9]{0,15}):([0-9a-f]{64})$/.exec(v);
39662
+ if (m === null) return null;
39663
+ const seq2 = Number(m[1]);
39664
+ return Number.isSafeInteger(seq2) ? { kind: "at", seq: seq2, hash: m[2] } : null;
39665
+ }
39666
+ function plain2(s) {
39667
+ return s.replace(/[^\x20-\x7e]/g, "?");
39668
+ }
39669
+ function run(dir, expect) {
39670
+ const opts = expect?.kind === "at" ? { expect: { seq: expect.seq, hash: expect.hash } } : {};
39671
+ const status2 = verifyLogDir(dir, opts);
39672
+ if (expect?.kind === "tip" && status2.status === "intact" && status2.head.hash !== expect.hash) {
39673
+ return { status: "broken", atSeq: status2.head.seq, reason: "expect-mismatch", detail: "the log's head does not match the expected hash" };
39674
+ }
39675
+ return status2;
39676
+ }
39677
+ var REASON = {
39678
+ changed: "an event was changed",
39679
+ removed: "an event was removed",
39680
+ inserted: "an event was inserted",
39681
+ reordered: "events were swapped",
39682
+ "head-mismatch": "the log's end does not match its head record",
39683
+ "expect-mismatch": "the log's head does not match the expected hash"
39684
+ };
39685
+ function describe2(s, expecting) {
39686
+ switch (s.status) {
39687
+ case "intact": {
39688
+ const tail = s.unchained ? ` ${s.unchained} later line${s.unchained === 1 ? " is" : "s are"} not chained and were not checked.` : "";
39689
+ return `The log is intact: ${s.head.seq} events, none changed. Head hash: ${s.head.hash}${tail}`;
39690
+ }
39691
+ case "not-chained":
39692
+ return expecting ? "The log is not chained, so the expected head cannot be matched." : "The log is not chained: it has no hash chain (an old or empty log), so there is nothing to check.";
39693
+ case "broken":
39694
+ return `The log is broken at event ${s.atSeq}: ${REASON[s.reason] ?? s.reason}. ${plain2(s.detail)}`;
39695
+ }
39696
+ }
39697
+ async function verifyLogCommand(argv, io) {
39698
+ const p = parse3(argv, {
39699
+ dir: { type: "string" },
39700
+ expect: { type: "string" },
39701
+ json: { type: "boolean" },
39702
+ help: { type: "boolean", short: "h" }
39703
+ });
39704
+ if (!p.ok) {
39705
+ io.err(`${p.error}
39706
+
39707
+ ${VERIFY_LOG_HELP}`);
39708
+ return 2;
39709
+ }
39710
+ if (p.values["help"] === true) {
39711
+ io.out(VERIFY_LOG_HELP);
39712
+ return 0;
39713
+ }
39714
+ if (p.positionals.length > 0) {
39715
+ io.err(`Unexpected argument "${plain2(p.positionals[0] ?? "")}".
39716
+
39717
+ ${VERIFY_LOG_HELP}`);
39718
+ return 2;
39719
+ }
39720
+ let expect = null;
39721
+ const rawExpect = str4(p.values["expect"]);
39722
+ if (rawExpect !== void 0) {
39723
+ expect = parseExpect(rawExpect);
39724
+ if (expect === null) {
39725
+ io.err(`--expect needs a 64-character hash, or <seq>:<hash>.
39726
+
39727
+ ${VERIFY_LOG_HELP}`);
39728
+ return 2;
39729
+ }
39730
+ }
39731
+ const status2 = run(stateDir(str4(p.values["dir"])), expect);
39732
+ io.out(p.values["json"] === true ? JSON.stringify(status2) : describe2(status2, expect !== null));
39733
+ if (status2.status === "broken") return 1;
39734
+ if (status2.status === "not-chained" && expect !== null) return 1;
39735
+ return 0;
39736
+ }
39737
+
38271
39738
  // src/index.ts
38272
- var VERSION = "0.2.0";
39739
+ var VERSION = "0.3.0";
38273
39740
  var HELP = `Exorcist 98 ${VERSION}: antivirus for AI coding agents
38274
39741
 
38275
39742
  Usage: exorcist <command> [options]
@@ -38294,6 +39761,8 @@ Commands:
38294
39761
  approve <kind> Approve a changed tool, a host, a server or a held session
38295
39762
  (see: exorcist approve --help)
38296
39763
  alerts Show recent shield alerts
39764
+ verify-log Check that the Shield's event log was not changed, cut or reordered
39765
+ (exit 0 intact, 1 broken; --json, --expect <hash>)
38297
39766
  console Open the live, read-only Shield console in your browser
38298
39767
  init [folder] Add hooks and steering to a Kiro project (--kiro: also the
38299
39768
  reviewer agent and a summary; --shield: wrap .kiro/settings/mcp.json)
@@ -38304,6 +39773,8 @@ Commands:
38304
39773
  gate [dir] Fail if this session's changes to agent files add a high or critical
38305
39774
  finding (read-only; run by the Kiro Stop hook)
38306
39775
  guard-mcp-write Hook helper: a person must confirm any agent write to an MCP config
39776
+ guard-web-fetch Hook helper: block a web fetch whose address holds a secret, canary or .env value
39777
+ guard-env-write Hook helper: block writing a .env value into any other file
38307
39778
  guard-commit Hook helper: block git commit while secrets are staged
38308
39779
  hook-scan Hook helper: scan the file named in a Kiro "file saved" event
38309
39780
  check-staged Git pre-commit helper: exit 1 if staged files contain secrets or canary tokens
@@ -38356,6 +39827,8 @@ async function main(argv) {
38356
39827
  return await approveCommand(rest, stdio);
38357
39828
  case "alerts":
38358
39829
  return await alertsCommand(rest, stdio);
39830
+ case "verify-log":
39831
+ return await verifyLogCommand(rest, stdio);
38359
39832
  case "console":
38360
39833
  return await consoleCommand(rest, stdio);
38361
39834
  case "init":
@@ -38376,6 +39849,18 @@ async function main(argv) {
38376
39849
  return 0;
38377
39850
  }
38378
39851
  return await guardMcpWriteCommand(await readStdin(), stdio);
39852
+ case "guard-web-fetch":
39853
+ if (rest.includes("--help") || rest.includes("-h")) {
39854
+ stdio.out(GUARD_WEB_FETCH_HELP);
39855
+ return 0;
39856
+ }
39857
+ return guardWebFetchCommand(await readStdin(), stdio);
39858
+ case "guard-env-write":
39859
+ if (rest.includes("--help") || rest.includes("-h")) {
39860
+ stdio.out(GUARD_ENV_WRITE_HELP);
39861
+ return 0;
39862
+ }
39863
+ return guardEnvWriteCommand(await readStdin(), stdio);
38379
39864
  case "check-staged":
38380
39865
  return await checkStagedCommand(stdio);
38381
39866
  case "guard-commit": {