@akasecurity/ai-tc-codex 0.9.16 → 0.9.17

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.
@@ -1,892 +1,12 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- try {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- } catch (e) {
11
- throw mod = 0, e;
12
- }
13
- };
14
2
  var __export = (target, all) => {
15
3
  for (var name in all)
16
4
  __defProp(target, name, { get: all[name], enumerable: true });
17
5
  };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
-
35
- // ../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js
36
- var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js"(exports, module) {
38
- "use strict";
39
- function makeArray(subject) {
40
- return Array.isArray(subject) ? subject : [subject];
41
- }
42
- var UNDEFINED = void 0;
43
- var EMPTY = "";
44
- var SPACE = " ";
45
- var ESCAPE = "\\";
46
- var REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
47
- var REGEX_TEST_BLANK_LINE = /^\uFEFF? *$/;
48
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
49
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
50
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
51
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
52
- var DOUBLE_SLASH = "//";
53
- var SLASH_CODE = 47;
54
- var DOT_CODE = 46;
55
- var SLASH3 = "/";
56
- var TMP_KEY_IGNORE = "node-ignore";
57
- if (typeof Symbol !== "undefined") {
58
- TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
59
- }
60
- var KEY_IGNORE = TMP_KEY_IGNORE;
61
- var define = (object2, key, value) => {
62
- Object.defineProperty(object2, key, { value });
63
- return value;
64
- };
65
- var RETURN_FALSE = () => false;
66
- var cleanRangeBackSlash = (slashes) => {
67
- const { length } = slashes;
68
- return slashes.slice(0, length - length % 2);
69
- };
70
- var POSIX_CLASSES = {
71
- alnum: "0-9A-Za-z",
72
- alpha: "A-Za-z",
73
- blank: " \\t",
74
- cntrl: "\\x00-\\x1f\\x7f",
75
- digit: "0-9",
76
- graph: "!-.0-~",
77
- lower: "a-z",
78
- print: " -.0-~",
79
- punct: "!-.:-@\\[-`{-~",
80
- // git's `sane-ctype.h` classifies \v and \f as control, not space,
81
- // unlike C's `isspace`
82
- space: " \\t\\n\\r",
83
- upper: "A-Z",
84
- xdigit: "0-9A-Fa-f"
85
- };
86
- var CLASS_MEMBERS_TO_ESCAPE = "\\]^-[";
87
- var escapeMember = (char) => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0 ? char : ESCAPE + char;
88
- var NON_SLASH = "(?!\\/)";
89
- var classSource = (negated, body) => {
90
- if (negated) {
91
- return `[^\\/${body}]`;
92
- }
93
- const source = `[${body}]`;
94
- return new RegExp(source).test("/") ? NON_SLASH + source : source;
95
- };
96
- var scanBracket = (pattern, start) => {
97
- const { length } = pattern;
98
- let index = start + 1;
99
- let negated = EMPTY;
100
- const lead = pattern[index];
101
- if (lead === "!" || lead === "^") {
102
- negated = "^";
103
- index++;
104
- }
105
- let body = EMPTY;
106
- let prev = EMPTY;
107
- for (; ; ) {
108
- const char = pattern[index];
109
- if (char === UNDEFINED) {
110
- return null;
111
- }
112
- if (char === ESCAPE) {
113
- const escaped = pattern[index + 1];
114
- if (escaped === UNDEFINED) {
115
- return null;
116
- }
117
- body += escapeMember(escaped);
118
- prev = escaped;
119
- index++;
120
- } else if (char === "-" && prev && index + 1 < length && pattern[index + 1] !== "]") {
121
- index++;
122
- let to = pattern[index];
123
- if (to === ESCAPE) {
124
- to = pattern[index += 1];
125
- }
126
- if (prev <= to) {
127
- body += `-${escapeMember(to)}`;
128
- }
129
- prev = EMPTY;
130
- } else if (char === "[" && pattern[index + 1] === ":") {
131
- const nameStart = index + 2;
132
- let end = nameStart;
133
- while (end < length && pattern[end] !== "]") {
134
- end++;
135
- }
136
- if (end === length) {
137
- return null;
138
- }
139
- if (end > nameStart && pattern[end - 1] === ":") {
140
- const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)];
141
- if (expanded === UNDEFINED) {
142
- return null;
143
- }
144
- body += expanded;
145
- prev = EMPTY;
146
- index = end;
147
- } else {
148
- body += escapeMember("[");
149
- prev = "[";
150
- index = nameStart - 2;
151
- }
152
- } else {
153
- body += escapeMember(char);
154
- prev = char;
155
- }
156
- index++;
157
- if (pattern[index] === "]") {
158
- return {
159
- end: index,
160
- source: classSource(negated, body)
161
- };
162
- }
163
- }
164
- };
165
- var NEVER_MATCH = "[]";
166
- var PLACEHOLDER = "\0";
167
- var REGEX_RESTORE_PLACEHOLDER = new RegExp(
168
- `${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,
169
- "g"
170
- );
171
- var TRAILING_WILDCARD = "\uE000";
172
- var TRAILING_DOUBLESTAR = "\uE001";
173
- var extractBrackets = (pattern) => {
174
- const sources = [];
175
- const hold = (source) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
176
- const { length } = pattern;
177
- let out = EMPTY;
178
- let index = 0;
179
- while (index < length) {
180
- const char = pattern[index];
181
- if (char === ESCAPE) {
182
- const escaped = pattern[index + 1];
183
- if (escaped === "*" || escaped === "[" || escaped === SPACE || escaped === ESCAPE) {
184
- out += pattern.slice(index, index + 2);
185
- } else {
186
- out += hold(
187
- REGEX_LITERAL_SPECIAL.test(escaped) ? ESCAPE + escaped : escaped
188
- );
189
- }
190
- index += 2;
191
- } else if (char === PLACEHOLDER) {
192
- out += hold(`[${PLACEHOLDER}]`);
193
- index++;
194
- } else if (char === "[") {
195
- const scanned = scanBracket(pattern, index);
196
- if (scanned === null) {
197
- out += hold(NEVER_MATCH);
198
- index = length;
199
- } else {
200
- out += hold(scanned.source);
201
- index = scanned.end + 1;
202
- }
203
- } else {
204
- out += char;
205
- index++;
206
- }
207
- }
208
- return {
209
- source: out,
210
- sources
211
- };
212
- };
213
- var DIRECT = null;
214
- var REGEX_INNER_SLASH = /\/(?!$)/;
215
- var REPLACERS = [
216
- [
217
- // Remove BOM
218
- // TODO:
219
- // Other similar zero-width characters?
220
- /^\uFEFF/,
221
- () => EMPTY,
222
- "\uFEFF"
223
- ],
224
- [
225
- // A trailing line terminator, left on when a whole file's contents are
226
- // added as one pattern rather than split into lines. git never sees one
227
- // -- it reads a `.gitignore` line by line -- so it is not part of the
228
- // pattern and is dropped here, apart from the trailing-space trimming,
229
- // which follows git in touching spaces and nothing else.
230
- /[\r\n]+$/,
231
- () => EMPTY
232
- ],
233
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
234
- [
235
- // Only spaces, never tabs or other whitespace: git trims a trailing run
236
- // of `' '` and nothing else (dir.c, `trim_trailing_spaces`, a single
237
- // `case ' '`), so a pattern ending in a tab keeps it as a literal.
238
- // (a\ ) -> (a )
239
- // (a ) -> (a)
240
- // (a ) -> (a)
241
- // (a \ ) -> (a )
242
- /((?:\\\\)*?)(\\? +)$/,
243
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
244
- ],
245
- // Replace (\ ) with ' '
246
- // Only a space: an escaped tab or other whitespace is already a literal by
247
- // the time it reaches here, and a bare tab must be left as one, not turned
248
- // into a space.
249
- // (\ ) -> ' '
250
- // (\\ ) -> '\\ '
251
- // (\\\ ) -> '\\ '
252
- [
253
- /(\\+?) /g,
254
- (_, m1) => {
255
- const { length } = m1;
256
- return m1.slice(0, length - length % 2) + SPACE;
257
- }
258
- ],
259
- // Escape metacharacters
260
- // which is written down by users but means special for regular expressions.
261
- // > There are 12 characters with special meanings:
262
- // > - the backslash \,
263
- // > - the caret ^,
264
- // > - the dollar sign $,
265
- // > - the period or dot .,
266
- // > - the vertical bar or pipe symbol |,
267
- // > - the question mark ?,
268
- // > - the asterisk or star *,
269
- // > - the plus sign +,
270
- // > - the opening parenthesis (,
271
- // > - the closing parenthesis ),
272
- // > - and the opening square bracket [,
273
- // > - the opening curly brace {,
274
- // > These special characters are often called "metacharacters".
275
- [
276
- /[\\$.|*+(){^]/g,
277
- (match) => `\\${match}`
278
- ],
279
- [
280
- // > a question mark (?) matches a single character
281
- /(?!\\)\?/g,
282
- () => "[^/]",
283
- "?"
284
- ],
285
- // leading slash
286
- [
287
- // > A leading slash matches the beginning of the pathname.
288
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
289
- // A leading slash matches the beginning of the pathname
290
- /^\//,
291
- () => "^",
292
- SLASH3
293
- ],
294
- // replace special metacharacter slash after the leading slash
295
- [
296
- /\//g,
297
- () => "\\/",
298
- SLASH3
299
- ],
300
- [
301
- // > A leading "**" followed by a slash means match in all directories.
302
- // > For example, "**/foo" matches file or directory "foo" anywhere,
303
- // > the same as pattern "foo".
304
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
305
- // > under directory "foo".
306
- // Notice that the '*'s have been replaced as '\\*'
307
- /^\^*(?:\\\*\\\*\\\/)+/,
308
- // '**/foo' <-> 'foo'
309
- () => "^(?:.*\\/)?",
310
- "*"
311
- ],
312
- // starting
313
- [
314
- // there will be no leading '/'
315
- // (which has been replaced by section "leading slash")
316
- // If starts with '**', adding a '^' to the regular expression also works
317
- DIRECT,
318
- (source, pattern) => {
319
- if (!source || source[0] === "^") {
320
- return source;
321
- }
322
- const anchor2 = !REGEX_INNER_SLASH.test(pattern) ? "(?:^|\\/)" : "^";
323
- return anchor2 + source;
324
- }
325
- ],
326
- // two globstars
327
- [
328
- // Use lookahead assertions so that we could match more than one `'/**'`
329
- /\\\/\\\*\\\*(?=\\\/|$)/g,
330
- // Zero, one or several directories
331
- // should not use '*', or it will be replaced by the next replacer
332
- // Check if it is not the last `'/**'`
333
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
334
- "*"
335
- ],
336
- // normal intermediate wildcards
337
- [
338
- // Never replace escaped '*'
339
- // ignore rule '\*' will match the path '*'
340
- // 'abc.*/' -> go
341
- // 'abc.*' -> skip this rule,
342
- // coz trailing single wildcard will be handed by [trailing wildcard]
343
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
344
- // '*.js' matches '.js'
345
- // '*.js' doesn't match 'abc'
346
- (_, p1, p2) => {
347
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
348
- return p1 + unescaped;
349
- },
350
- "*"
351
- ],
352
- // trailing wildcard, held apart from a literal star
353
- [
354
- // The step above leaves a trailing `*` alone, so a single `\*` is all that
355
- // can be left at the end here. Whether it is a wildcard or a literal
356
- // turns on the backslashes the user put in front of it: the escaper has
357
- // since doubled every one, so what stands here is those `2N` doubled
358
- // backslashes and then the star's own escape. An even number of the
359
- // original `N` leaves the star unescaped -- a wildcard -- and an odd
360
- // number escapes it -- a literal. This runs while the two are still
361
- // distinct, before the unescape steps below collapse the literal onto
362
- // the very `\*` a wildcard leaves behind.
363
- /(^|[^\\])((?:\\\\)*)\\\*$/,
364
- (match, p1, p2) => (
365
- // `p2` holds the doubled user backslashes; half of them is `N`.
366
- p2.length / 2 % 2 === 0 ? p1 + p2 + TRAILING_WILDCARD : match
367
- ),
368
- "*"
369
- ],
370
- [
371
- // unescape, revert step 3 except for back slash
372
- // For example, if a user escape a '\\*',
373
- // after step 3, the result will be '\\\\\\*'
374
- /\\\\\\(?=[$.|*+(){^])/g,
375
- () => ESCAPE,
376
- ESCAPE + ESCAPE
377
- ],
378
- [
379
- // '\\\\' -> '\\'
380
- /\\\\/g,
381
- () => ESCAPE,
382
- ESCAPE + ESCAPE
383
- ],
384
- [
385
- // Every real bracket expression -- POSIX classes included -- has already
386
- // been held aside by `extractBrackets`, so the only `[` left in the
387
- // pattern is an escaped, literal one.
388
- // `\` is escaped by step 3
389
- /\\\[([^\]/]*?)(\\*)($|\])/g,
390
- // '\\[bar]' -> '\\\\[bar\\]'
391
- (match, range, endEscape, close) => `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,
392
- "["
393
- ],
394
- // ending
395
- [
396
- // 'js' will not match 'js.'
397
- // 'ab' will not match 'abc'
398
- DIRECT,
399
- // WTF!
400
- // https://git-scm.com/docs/gitignore
401
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
402
- // which re-fixes #24, #38
403
- // > If there is a separator at the end of the pattern then the pattern
404
- // > will only match directories, otherwise the pattern can match both
405
- // > files and directories.
406
- // 'js*' will not match 'a.js'
407
- // 'js/' will not match 'a.js'
408
- // 'js' will match 'a.js' and 'a.js/'
409
- (source) => {
410
- const last = source[source.length - 1];
411
- if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
412
- return source;
413
- }
414
- return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
415
- }
416
- ]
417
- ];
418
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\uE000$/;
419
- var MODE_IGNORE = "regex";
420
- var MODE_CHECK_IGNORE = "checkRegex";
421
- var UNDERSCORE = "_";
422
- var replaceTrailingWildcard = (_, p1) => {
423
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
- return `${prefix}(?=$|\\/$)`;
425
- };
426
- var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
427
- var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
428
- var WILDCARD = "[^\\/]*";
429
- var separatorAfter = (run, at) => {
430
- let separator = EMPTY;
431
- for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
432
- separator += run[index].single;
433
- }
434
- return separator;
435
- };
436
- var pinWildcards = (source) => {
437
- if (source.indexOf(WILDCARD) < 0) {
438
- return source;
439
- }
440
- const tokens = [];
441
- const { length } = source;
442
- let index = 0;
443
- while (index < length) {
444
- const char = source[index];
445
- if (source.startsWith(WILDCARD, index)) {
446
- tokens.push({ wildcard: true });
447
- index += WILDCARD.length;
448
- } else if (char === "[") {
449
- let end = index + 1;
450
- if (source[end] === "^") {
451
- end++;
452
- }
453
- if (source[end] === "]") {
454
- end++;
455
- }
456
- while (end < length && source[end] !== "]") {
457
- end += source[end] === ESCAPE ? 2 : 1;
458
- }
459
- end++;
460
- tokens.push({ single: source.slice(index, end) });
461
- index = end;
462
- } else if (char === ESCAPE) {
463
- tokens.push({ single: source.slice(index, index + 2) });
464
- index += 2;
465
- } else if (char === "(") {
466
- let depth = 0;
467
- let end = index;
468
- do {
469
- if (source[end] === ESCAPE) {
470
- end++;
471
- } else if (source[end] === "(") {
472
- depth++;
473
- } else if (source[end] === ")") {
474
- depth--;
475
- }
476
- end++;
477
- } while (end < length && depth > 0);
478
- if ("*+?".indexOf(source[end]) >= 0) {
479
- end++;
480
- }
481
- tokens.push({ boundary: source.slice(index, end) });
482
- index = end;
483
- } else if (char === "^" || char === "$") {
484
- tokens.push({ boundary: char });
485
- index++;
486
- } else {
487
- tokens.push({ single: char });
488
- index++;
489
- }
490
- }
491
- let out = EMPTY;
492
- let run = [];
493
- const flush = () => {
494
- let lastWildcard;
495
- run.forEach((token, at) => {
496
- if (token.wildcard) {
497
- lastWildcard = at;
498
- }
499
- });
500
- run.forEach((token, at) => {
501
- if (!token.wildcard) {
502
- out += token.single;
503
- return;
504
- }
505
- out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
506
- });
507
- run = [];
508
- };
509
- tokens.forEach((token) => {
510
- if (token.boundary === void 0) {
511
- run.push(token);
512
- return;
513
- }
514
- flush();
515
- out += token.boundary;
516
- });
517
- flush();
518
- return out;
519
- };
520
- var makeRegexPrefix = (pattern) => {
521
- const { source, sources } = extractBrackets(pattern);
522
- const replaced = REPLACERS.reduce(
523
- // A pass whose matcher finds nothing hands back the very string it was
524
- // given, so asking first costs a search and saves a rewrite. Ten of the
525
- // fifteen passes never fire for a typical .gitignore line, and between
526
- // them they were 45% of this chain.
527
- (prev, [matcher, replacer, required2]) => {
528
- if (matcher === DIRECT) {
529
- return replacer(prev, pattern);
530
- }
531
- if (required2 !== UNDEFINED && prev.indexOf(required2) < 0) {
532
- return prev;
533
- }
534
- return matcher.test(prev) ? prev.replace(matcher, replacer.bind(pattern)) : prev;
535
- },
536
- source
537
- );
538
- return sources.length ? replaced.replace(
539
- REGEX_RESTORE_PLACEHOLDER,
540
- (match, index) => sources[index]
541
- ) : replaced;
542
- };
543
- var checkSourceOf = (body, prefix) => {
544
- if (body[body.length - 1] === SLASH3) {
545
- prefix = makeRegexPrefix(body.slice(0, -1));
546
- }
547
- const head = prefix.slice(0, -1);
548
- const last = prefix[prefix.length - 1];
549
- return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
- };
551
- var matchesBasename = (body) => {
552
- const index = body.indexOf(SLASH3);
553
- return index < 0 || index === body.length - 1;
554
- };
555
- var basenameOf = (path) => {
556
- const end = path.length - 1;
557
- const index = path.lastIndexOf(
558
- SLASH3,
559
- path[end] === SLASH3 ? end - 1 : end
560
- );
561
- return index < 0 ? path : path.slice(index + 1);
562
- };
563
- var parentOf = (path) => {
564
- if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
565
- const slices = path.split(SLASH3).filter(Boolean);
566
- slices.pop();
567
- return slices.length ? slices.join(SLASH3) + SLASH3 : EMPTY;
568
- }
569
- const end = path.length - 1;
570
- const cut = path.lastIndexOf(
571
- SLASH3,
572
- path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
573
- );
574
- return cut < 0 ? EMPTY : path.slice(0, cut + 1);
575
- };
576
- var isString = (subject) => typeof subject === "string";
577
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
578
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
579
- var IgnoreRule = class {
580
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
581
- this.pattern = pattern;
582
- this.mark = mark;
583
- this.negative = negative;
584
- define(this, "body", body);
585
- define(this, "ignoreCase", ignoreCase);
586
- define(this, "regexPrefix", prefix);
587
- }
588
- // Worked out on first use and kept behind an own property, the way `regex`
589
- // caches itself in `_regex`. Deciding it in the constructor instead would
590
- // add a fourth `defineProperty` to every rule ever built, which cost 4% of
591
- // every compile -- including the compiles of rules that are never matched
592
- // against anything.
593
- get _basenameOnly() {
594
- return define(this, "_basenameOnly", matchesBasename(this.body));
595
- }
596
- get regex() {
597
- const key = UNDERSCORE + MODE_IGNORE;
598
- if (this[key]) {
599
- return this[key];
600
- }
601
- return this._make(MODE_IGNORE, key);
602
- }
603
- get checkRegex() {
604
- const key = UNDERSCORE + MODE_CHECK_IGNORE;
605
- if (this[key]) {
606
- return this[key];
607
- }
608
- return this._make(MODE_CHECK_IGNORE, key);
609
- }
610
- _make(mode, key) {
611
- const str2 = pinWildcards(
612
- mode === MODE_IGNORE ? this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar) : checkSourceOf(this.body, this.regexPrefix)
613
- );
614
- const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
615
- return define(this, key, regex);
616
- }
617
- };
618
- var createRule = ({
619
- pattern,
620
- mark
621
- }, ignoreCase) => {
622
- let negative = false;
623
- let body = pattern;
624
- if (body.indexOf("!") === 0) {
625
- negative = true;
626
- body = body.substr(1);
627
- }
628
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
629
- const regexPrefix = makeRegexPrefix(body);
630
- return new IgnoreRule(
631
- pattern,
632
- mark,
633
- body,
634
- ignoreCase,
635
- negative,
636
- regexPrefix
637
- );
638
- };
639
- var RuleManager = class {
640
- constructor(ignoreCase) {
641
- this._ignoreCase = ignoreCase;
642
- this._rules = [];
643
- this._basenameCount = 0;
644
- }
645
- _add(pattern) {
646
- if (pattern && pattern[KEY_IGNORE]) {
647
- this._rules = this._rules.concat(pattern._rules._rules);
648
- this._basenameCount += pattern._rules._basenameCount;
649
- this._added = true;
650
- return;
651
- }
652
- if (isString(pattern)) {
653
- pattern = {
654
- pattern
655
- };
656
- }
657
- if (checkPattern(pattern.pattern)) {
658
- const rule = createRule(pattern, this._ignoreCase);
659
- this._added = true;
660
- this._rules.push(rule);
661
- if (matchesBasename(rule.body)) {
662
- this._basenameCount++;
663
- }
664
- }
665
- }
666
- // @param {Array<string> | string | Ignore} pattern
667
- add(pattern) {
668
- this._added = false;
669
- makeArray(
670
- isString(pattern) ? splitPattern(pattern) : pattern
671
- ).forEach(this._add, this);
672
- if (this._added) {
673
- this._literalRules = UNDEFINED;
674
- }
675
- return this._added;
676
- }
677
- // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule
678
- // ending in a wildcard can match it (see `checkSourceOf`), so the rest
679
- // are left out once, rather than tested or compiled for every path.
680
- testLiteral(path) {
681
- const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
- ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
683
- ));
684
- let ignored = false;
685
- let unignored = false;
686
- let matchedRule;
687
- for (let index = rules.length - 1; index >= 0; index--) {
688
- const rule = rules[index];
689
- if (rule.checkRegex.test(path)) {
690
- ignored = !rule.negative;
691
- unignored = rule.negative;
692
- matchedRule = rule.negative ? UNDEFINED : rule;
693
- break;
694
- }
695
- }
696
- const ret = {
697
- ignored,
698
- unignored
699
- };
700
- if (matchedRule) {
701
- ret.rule = matchedRule;
702
- }
703
- return ret;
704
- }
705
- // Test one single path without recursively checking parent directories
706
- //
707
- // - checkUnignored `boolean` whether should check if the path is unignored,
708
- // setting `checkUnignored` to `false` could reduce additional
709
- // path matching.
710
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
711
- // @returns {TestResult} true if a file is ignored
712
- test(path, checkUnignored, mode) {
713
- let ignored = false;
714
- let unignored = false;
715
- let matchedRule;
716
- const rules = this._rules;
717
- const { length } = rules;
718
- const shortcut = this._basenameCount * 2 >= length;
719
- const basename7 = shortcut ? basenameOf(path) : path;
720
- for (let index = 0; index < length; index++) {
721
- const rule = rules[index];
722
- const { negative } = rule;
723
- const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
724
- if (!skip && rule[mode].test(
725
- shortcut && rule._basenameOnly ? basename7 : path
726
- )) {
727
- ignored = !negative;
728
- unignored = negative;
729
- matchedRule = negative ? UNDEFINED : rule;
730
- }
731
- }
732
- const ret = {
733
- ignored,
734
- unignored
735
- };
736
- if (matchedRule) {
737
- ret.rule = matchedRule;
738
- }
739
- return ret;
740
- }
741
- };
742
- var throwError = (message, Ctor) => {
743
- throw new Ctor(message);
744
- };
745
- var checkPath = (path, originalPath, doThrow) => {
746
- if (!isString(path)) {
747
- return doThrow(
748
- `path must be a string, but got \`${originalPath}\``,
749
- TypeError
750
- );
751
- }
752
- if (!path) {
753
- return doThrow(`path must not be empty`, TypeError);
754
- }
755
- if (checkPath.isNotRelative(path)) {
756
- const r = "`path.relative()`d";
757
- return doThrow(
758
- `path should be a ${r} string, but got "${originalPath}"`,
759
- RangeError
760
- );
761
- }
762
- return true;
763
- };
764
- var isNotRelative = (path) => {
765
- const first = path.charCodeAt(0);
766
- if (first === SLASH_CODE) {
767
- return true;
768
- }
769
- if (first !== DOT_CODE) {
770
- return false;
771
- }
772
- if (path.length === 1) {
773
- return true;
774
- }
775
- const second = path.charCodeAt(1);
776
- if (second === SLASH_CODE) {
777
- return true;
778
- }
779
- if (second !== DOT_CODE) {
780
- return false;
781
- }
782
- return path.length === 2 || path.charCodeAt(2) === SLASH_CODE;
783
- };
784
- checkPath.isNotRelative = isNotRelative;
785
- checkPath.convert = (p) => p;
786
- var Ignore = class {
787
- constructor({
788
- ignorecase = true,
789
- ignoreCase = ignorecase,
790
- allowRelativePaths = false
791
- } = {}) {
792
- define(this, KEY_IGNORE, true);
793
- this._rules = new RuleManager(ignoreCase);
794
- this._strictPathCheck = !allowRelativePaths;
795
- this._initCache();
796
- }
797
- _initCache() {
798
- this._ignoreCache = /* @__PURE__ */ Object.create(null);
799
- this._testCache = /* @__PURE__ */ Object.create(null);
800
- }
801
- add(pattern) {
802
- if (this._rules.add(pattern)) {
803
- this._initCache();
804
- }
805
- return this;
806
- }
807
- // legacy
808
- addPattern(pattern) {
809
- return this.add(pattern);
810
- }
811
- // @returns {TestResult}
812
- _test(originalPath, cache, checkUnignored) {
813
- const path = originalPath && checkPath.convert(originalPath);
814
- checkPath(
815
- path,
816
- originalPath,
817
- this._strictPathCheck ? throwError : RETURN_FALSE
818
- );
819
- return this._t(path, cache, checkUnignored);
820
- }
821
- checkIgnore(path) {
822
- if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {
823
- return this.test(path);
824
- }
825
- const dir = this._t(path, this._testCache, true);
826
- if (dir.ignored) {
827
- return dir;
828
- }
829
- const literal2 = this._rules.testLiteral(path);
830
- return literal2.ignored || literal2.unignored ? literal2 : dir;
831
- }
832
- _t(path, cache, checkUnignored) {
833
- if (path in cache) {
834
- return cache[path];
835
- }
836
- const parentPath = parentOf(path);
837
- const parent = parentPath ? this._t(parentPath, cache, checkUnignored) : UNDEFINED;
838
- return cache[path] = parent && parent.ignored ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE);
839
- }
840
- ignores(path) {
841
- return this._test(path, this._ignoreCache, false).ignored;
842
- }
843
- createFilter() {
844
- return (path) => !this.ignores(path);
845
- }
846
- filter(paths) {
847
- return makeArray(paths).filter(this.createFilter());
848
- }
849
- // @returns {TestResult}
850
- test(path) {
851
- return this._test(path, this._testCache, true);
852
- }
853
- };
854
- var factory = (options) => new Ignore(options);
855
- var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
856
- var setupWindows = () => {
857
- const makePosix = (str2) => /^\\\\\?\\/.test(str2) || /["<>|\u0000-\u001F]+/u.test(str2) ? str2 : str2.replace(/\\/g, "/");
858
- checkPath.convert = makePosix;
859
- const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
860
- checkPath.isNotRelative = (path) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
861
- };
862
- if (
863
- // Detect `process` so that it can run in browsers.
864
- typeof process !== "undefined" && process.platform === "win32"
865
- ) {
866
- setupWindows();
867
- }
868
- module.exports = factory;
869
- factory.default = factory;
870
- module.exports.isPathValid = isPathValid;
871
- define(module.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
872
- }
873
- });
874
6
 
875
7
  // ../../packages/plugin-sdk/src/config.ts
876
8
  import { existsSync as existsSync8 } from "fs";
877
- import { join as join16 } from "path";
878
-
879
- // ../../packages/persistence/src/attached-derived.ts
880
- import { rmSync } from "fs";
881
- import { join } from "path";
882
- var POLICY_CACHE_FILENAME = "policy-cache.json";
883
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
884
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
885
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
886
-
887
- // ../../packages/persistence/src/control-plane-credential.ts
888
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
889
- import { join as join2 } from "path";
9
+ import { join as join17 } from "path";
890
10
 
891
11
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
892
12
  var DEFERRED_MIGRATION_TAGS = [
@@ -1059,7 +179,7 @@ var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1059
179
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1060
180
 
1061
181
  // ../../packages/schema/src/invisible-padding.ts
1062
- var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
182
+ var INVISIBLE_PADDING = /[\u00AD\u061C\u180E\u200B\u200E\u200F\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\uFFF9-\uFFFB\u{E0001}\u{E0020}-\u{E007F}]/gu;
1063
183
  function stripInvisiblePadding(text) {
1064
184
  return text.replace(INVISIBLE_PADDING, "");
1065
185
  }
@@ -3877,9 +2997,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3877
2997
  function stripTabAndNewline(value) {
3878
2998
  return value.replace(asciiTabOrNewline, "");
3879
2999
  }
3880
- function urlHostnameOk(url2, hostname7) {
3881
- hostname7.lastIndex = 0;
3882
- return hostname7.test(url2.hostname);
3000
+ function urlHostnameOk(url2, hostname6) {
3001
+ hostname6.lastIndex = 0;
3002
+ return hostname6.test(url2.hostname);
3883
3003
  }
3884
3004
  function urlProtocolOk(url2, protocol) {
3885
3005
  protocol.lastIndex = 0;
@@ -20799,13 +19919,16 @@ function serviceTierMultiplier(tier) {
20799
19919
  if (tier === void 0) return 1;
20800
19920
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20801
19921
  }
19922
+ function promptTokensOf(usage) {
19923
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19924
+ }
20802
19925
  function costOf(price, usage) {
20803
19926
  const metered = [
20804
19927
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20805
19928
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20806
19929
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20807
19930
  ];
20808
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19931
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20809
19932
  if (band !== null && (band.input === null || band.output === null)) return null;
20810
19933
  const inputRate = band?.input ?? price.input;
20811
19934
  const outputRate = band?.output ?? price.output;
@@ -20878,8 +20001,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20878
20001
  ["ollama", "local"],
20879
20002
  ["local", "local"]
20880
20003
  ]);
20881
- function hostingFor(platform2) {
20882
- return PLATFORM_HOSTING.get(platform2) ?? "api";
20004
+ function hostingFor(platform) {
20005
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20883
20006
  }
20884
20007
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20885
20008
  ["anthropic", "anthropic"],
@@ -20893,8 +20016,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20893
20016
  function firstPartyPlatformFor(vendor2) {
20894
20017
  return FIRST_PARTY.get(vendor2) ?? null;
20895
20018
  }
20896
- function isFirstParty(vendor2, platform2) {
20897
- return FIRST_PARTY.get(vendor2) === platform2;
20019
+ function isFirstParty(vendor2, platform) {
20020
+ return FIRST_PARTY.get(vendor2) === platform;
20898
20021
  }
20899
20022
  var PLATFORM_NAMESPACES = Object.freeze([
20900
20023
  "anthropic",
@@ -20955,14 +20078,14 @@ var ModelVendorBuilder = class {
20955
20078
  );
20956
20079
  }
20957
20080
  for (const ref of spec.on ?? []) {
20958
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20959
- const firstParty = isFirstParty(this.vendor, platform2);
20960
- const hosting = hostingFor(platform2);
20081
+ const { platform, price, retention, region } = normalizeRef(ref);
20082
+ const firstParty = isFirstParty(this.vendor, platform);
20083
+ const hosting = hostingFor(platform);
20961
20084
  const isSelfHosted = hosting === "local";
20962
20085
  platforms.set(
20963
- platform2,
20086
+ platform,
20964
20087
  Object.freeze({
20965
- platform: platform2,
20088
+ platform,
20966
20089
  hosting,
20967
20090
  firstParty,
20968
20091
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21015,35 +20138,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21015
20138
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21016
20139
  var BEDROCK_REVISION_RE = /:\d+$/u;
21017
20140
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21018
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20141
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21019
20142
  function stripPlatformDecorations(model) {
21020
20143
  let id = model.trim();
21021
- let platform2 = null;
20144
+ let platform = null;
21022
20145
  if (GEO_PREFIX_RE.test(id)) {
21023
20146
  id = id.replace(GEO_PREFIX_RE, "");
21024
- platform2 = "bedrock";
20147
+ platform = "bedrock";
21025
20148
  }
21026
20149
  if (NAMESPACE_DOT_RE.test(id)) {
21027
20150
  id = id.replace(NAMESPACE_DOT_RE, "");
21028
- platform2 ??= "bedrock";
20151
+ platform ??= "bedrock";
21029
20152
  }
21030
20153
  if (BEDROCK_VERSION_RE.test(id)) {
21031
20154
  id = id.replace(BEDROCK_VERSION_RE, "");
21032
- platform2 ??= "bedrock";
20155
+ platform ??= "bedrock";
21033
20156
  } else if (BEDROCK_REVISION_RE.test(id)) {
21034
20157
  id = id.replace(BEDROCK_REVISION_RE, "");
21035
- platform2 ??= "bedrock";
20158
+ platform ??= "bedrock";
21036
20159
  }
21037
20160
  if (VERTEX_VERSION_RE.test(id)) {
21038
20161
  id = id.replace(VERTEX_VERSION_RE, "");
21039
- platform2 ??= "vertex";
20162
+ platform ??= "vertex";
21040
20163
  }
21041
20164
  if (NAMESPACE_SLASH_RE.test(id)) {
21042
20165
  id = id.replace(NAMESPACE_SLASH_RE, "");
21043
20166
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21044
20167
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21045
20168
  }
21046
- return { id, platform: platform2 };
20169
+ return { id, platform };
21047
20170
  }
21048
20171
  function buildModelIndex(entries) {
21049
20172
  const byId = /* @__PURE__ */ new Map();
@@ -21060,19 +20183,19 @@ function resolveModel(raw, index) {
21060
20183
  if (exact !== void 0) {
21061
20184
  return { entry: exact, canonicalId: raw, platform: null, raw };
21062
20185
  }
21063
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
20186
+ const { id, platform } = stripPlatformDecorations(raw);
21064
20187
  const stripped = index.byId.get(id);
21065
20188
  if (stripped !== void 0) {
21066
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
20189
+ return { entry: stripped, canonicalId: id, platform, raw };
21067
20190
  }
21068
20191
  if (DATED_SUFFIX_RE.test(id)) {
21069
20192
  const undated = id.replace(DATED_SUFFIX_RE, "");
21070
20193
  const byDate = index.byId.get(undated);
21071
20194
  if (byDate !== void 0) {
21072
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
20195
+ return { entry: byDate, canonicalId: undated, platform, raw };
21073
20196
  }
21074
20197
  }
21075
- return { entry: null, canonicalId: raw, platform: platform2, raw };
20198
+ return { entry: null, canonicalId: raw, platform, raw };
21076
20199
  }
21077
20200
 
21078
20201
  // ../../packages/schema/src/model/catalog.ts
@@ -21165,7 +20288,7 @@ anthropic.model("claude-haiku-4-5", {
21165
20288
  name: "Claude Haiku 4.5",
21166
20289
  ctx: 2e5,
21167
20290
  maxOut: 64e3,
21168
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20291
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21169
20292
  capability: null,
21170
20293
  price: anthropicPrice(1, 5, 0.1),
21171
20294
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21296,6 +20419,11 @@ openai.model("gpt-4o", {
21296
20419
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21297
20420
  on: [...OPENAI_RESELLERS]
21298
20421
  });
20422
+ openai.model("gpt-4o-2024-05-13", {
20423
+ name: "GPT-4o (2024-05-13)",
20424
+ price: tokenPrice(5, 15),
20425
+ on: [...OPENAI_RESELLERS]
20426
+ });
21299
20427
  openai.model("gpt-4o-mini", {
21300
20428
  name: "GPT-4o mini",
21301
20429
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21315,6 +20443,24 @@ openai.model("o3", {
21315
20443
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21316
20444
  on: [...OPENAI_RESELLERS]
21317
20445
  });
20446
+ openai.model("text-embedding-3-small", {
20447
+ name: "text-embedding-3-small",
20448
+ capability: "embedding",
20449
+ price: tokenPrice(0.02, 0),
20450
+ on: [...OPENAI_RESELLERS]
20451
+ });
20452
+ openai.model("text-embedding-3-large", {
20453
+ name: "text-embedding-3-large",
20454
+ capability: "embedding",
20455
+ price: tokenPrice(0.13, 0),
20456
+ on: [...OPENAI_RESELLERS]
20457
+ });
20458
+ openai.model("text-embedding-ada-002", {
20459
+ name: "text-embedding-ada-002",
20460
+ capability: "embedding",
20461
+ price: tokenPrice(0.1, 0),
20462
+ on: [...OPENAI_RESELLERS]
20463
+ });
21318
20464
  openai.model("gpt-oss-120b", {
21319
20465
  name: "GPT-OSS 120B",
21320
20466
  openWeights: true,
@@ -21601,10 +20747,21 @@ var MODEL_ENTRIES = Object.freeze([
21601
20747
  ...alibaba.models(),
21602
20748
  ...amazon.models()
21603
20749
  ]);
20750
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20751
+ [
20752
+ ...new Set(
20753
+ MODEL_ENTRIES.flatMap(
20754
+ (entry) => [...entry.platforms.values()].flatMap(
20755
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20756
+ )
20757
+ )
20758
+ )
20759
+ ].sort((a, b) => a - b)
20760
+ );
21604
20761
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21605
20762
 
21606
20763
  // ../../packages/schema/src/model/governance.ts
21607
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20764
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21608
20765
  var DataRetention = external_exports.enum([
21609
20766
  "zero_retention",
21610
20767
  "no_storage",
@@ -21700,16 +20857,16 @@ function platformForProvider(provider) {
21700
20857
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21701
20858
  }
21702
20859
  function isLocalProvider(provider) {
21703
- const platform2 = platformForProvider(provider);
21704
- return platform2 !== null && hostingFor(platform2) === "local";
20860
+ const platform = platformForProvider(provider);
20861
+ return platform !== null && hostingFor(platform) === "local";
21705
20862
  }
21706
20863
  function priceFor(provider, model) {
21707
20864
  if (isLocalProvider(provider)) return ZERO_PRICE;
21708
20865
  const resolved = resolveModel(model, MODEL_INDEX);
21709
20866
  if (resolved.entry === null) return null;
21710
- const platform2 = resolved.platform ?? platformForProvider(provider);
21711
- if (platform2 === null) return null;
21712
- return resolved.entry.platforms.get(platform2)?.price ?? null;
20867
+ const platform = resolved.platform ?? platformForProvider(provider);
20868
+ if (platform === null) return null;
20869
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21713
20870
  }
21714
20871
  var defaultCostModel = {
21715
20872
  normalizeModelId(provider, model) {
@@ -21735,7 +20892,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21735
20892
 
21736
20893
  // ../../packages/schema/src/token/token-report.ts
21737
20894
  var num = (value) => value ?? 0;
21738
- function costUsageOf(a) {
20895
+ function costUsageOf(a, promptTokens) {
21739
20896
  const usage = {
21740
20897
  inputTokens: num(a.input_tokens),
21741
20898
  outputTokens: num(a.output_tokens),
@@ -21745,11 +20902,12 @@ function costUsageOf(a) {
21745
20902
  webSearchRequests: num(a.web_search_requests)
21746
20903
  };
21747
20904
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20905
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21748
20906
  return usage;
21749
20907
  }
21750
20908
  function buildTokenReports(leaves, costModel) {
21751
20909
  const bySession = /* @__PURE__ */ new Map();
21752
- for (const { sessionId, attributes } of leaves) {
20910
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21753
20911
  const provider = attributes.provider ?? "unknown";
21754
20912
  const model = attributes.model ?? "unknown";
21755
20913
  const key = `${provider} ${model}`;
@@ -21768,7 +20926,8 @@ function buildTokenReports(leaves, costModel) {
21768
20926
  cacheCreation: 0,
21769
20927
  cacheRead: 0,
21770
20928
  costUsd: 0,
21771
- priced: false
20929
+ priced: false,
20930
+ partial: false
21772
20931
  };
21773
20932
  rollups.set(key, acc);
21774
20933
  }
@@ -21776,8 +20935,14 @@ function buildTokenReports(leaves, costModel) {
21776
20935
  acc.output += num(attributes.output_tokens);
21777
20936
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21778
20937
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21779
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21780
- if (leafCost !== null) {
20938
+ const leafCost = costModel.costFor({
20939
+ provider,
20940
+ model,
20941
+ usage: costUsageOf(attributes, promptTokens)
20942
+ });
20943
+ if (leafCost === null) {
20944
+ acc.partial = true;
20945
+ } else {
21781
20946
  acc.costUsd += leafCost;
21782
20947
  acc.priced = true;
21783
20948
  }
@@ -21793,9 +20958,8 @@ function buildTokenReports(leaves, costModel) {
21793
20958
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21794
20959
  totalTokens += rollupTotal;
21795
20960
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21796
- if (estimatedCostUsd === null) {
21797
- anyUnpriced = true;
21798
- } else {
20961
+ if (acc.partial) anyUnpriced = true;
20962
+ if (estimatedCostUsd !== null) {
21799
20963
  anyPriced = true;
21800
20964
  costUsd += estimatedCostUsd;
21801
20965
  }
@@ -21818,7 +20982,7 @@ function buildTokenReports(leaves, costModel) {
21818
20982
  totalTokens,
21819
20983
  // Σ of the PRICED rollups; null when none had a known price.
21820
20984
  estimatedCostUsd: anyPriced ? costUsd : null,
21821
- // Any unknown (provider, model) means the total understates real spend.
20985
+ // Any call priced to null means the total understates real spend.
21822
20986
  costIsPartial: anyUnpriced
21823
20987
  });
21824
20988
  }
@@ -22520,6 +21684,11 @@ var CaptureAttributes = external_exports.object({
22520
21684
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22521
21685
  // repeated rather than referenced because a store reader opens this file.
22522
21686
  redact_degraded_to: ActionTaken.optional(),
21687
+ // Why a capture has no content and no findings: its field was refused
21688
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
21689
+ // whose value this is). Absent on every capture that was scanned, so a
21690
+ // reader can tell a refused row from an empty clean one.
21691
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22523
21692
  // The scope key this capture was stamped with: the canonical repository
22524
21693
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22525
21694
  // against its working directory), else of its own working directory, or a
@@ -22697,8 +21866,9 @@ var SessionTokenReport = external_exports.object({
22697
21866
  totalTokens: external_exports.number().int().nonnegative(),
22698
21867
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22699
21868
  estimatedCostUsd: external_exports.number().nullable(),
22700
- // True whenever any rollup has a null cost (unknown provider/model), so the
22701
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21869
+ // True whenever any call priced to null (an unknown provider/model, or a call
21870
+ // over a long-context threshold whose rate is unpublished), so the total
21871
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22702
21872
  // precise figure rather than silently dropping the unpriced calls.
22703
21873
  costIsPartial: external_exports.boolean()
22704
21874
  });
@@ -23575,7 +22745,15 @@ var StorePostureSnapshot = external_exports.object({
23575
22745
  policyCounts: StorePosturePolicyCounts,
23576
22746
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23577
22747
  // getting its 200 without a payload change.
23578
- plugin: StorePosturePlugin.optional()
22748
+ plugin: StorePosturePlugin.optional(),
22749
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22750
+ // machine attachment omits it, so its body is byte for byte the one it
22751
+ // sent before this member existed. Absent therefore means machine-wide OR
22752
+ // a reporter older than this member, never "scoped". Both values parse, so
22753
+ // a sender that one day spells `machine` breaks no receiver; any other
22754
+ // value fails the whole snapshot, which is why the reporter sends a
22755
+ // constant and never the raw mode.
22756
+ attachmentMode: AttachmentMode.optional()
23579
22757
  }).meta({ id: "StorePostureSnapshot" });
23580
22758
  var CAPTURE_VERSION_PREFIX = "capture/";
23581
22759
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23852,7 +23030,19 @@ var EventMetadata = external_exports.object({
23852
23030
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23853
23031
  // Closing either means moving the reason onto the finding row, which
23854
23032
  // already carries its own action.
23855
- redactDegradedTo: ActionTaken.optional()
23033
+ redactDegradedTo: ActionTaken.optional(),
23034
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23035
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23036
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23037
+ // field instead of letting it through unscanned.
23038
+ //
23039
+ // - 'timeout': the bounded scan ran out of time.
23040
+ // - 'unavailable': no worker could run it.
23041
+ //
23042
+ // A refused row stores '' as its content and has no findings, which is
23043
+ // exactly what a clean, empty capture looks like — this marker is the only
23044
+ // thing that tells the two apart. Absent on every capture that was scanned.
23045
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23856
23046
  }).meta({ id: "EventMetadata" });
23857
23047
  var Event = external_exports.object({
23858
23048
  id: external_exports.guid(),
@@ -24022,7 +23212,7 @@ var Rule = external_exports.strictObject({
24022
23212
  postValidators: external_exports.array(PostValidatorRef).optional(),
24023
23213
  requiresNearby: RequiresNearby.optional(),
24024
23214
  examples: external_exports.array(external_exports.string()).optional(),
24025
- // Whether the matched text is itself sensitive. Absent means 'value'.
23215
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24026
23216
  evidence: RuleEvidence.optional()
24027
23217
  }).meta({ id: "Rule" });
24028
23218
  var Author = external_exports.object({
@@ -24114,7 +23304,13 @@ var DetectionRule = external_exports.object({
24114
23304
  // Representative matching strings the rule author shipped with the rule. The
24115
23305
  // cheapest honest answer to "show me what this rule catches" — every bundled
24116
23306
  // rule has them, and they are already in the stored snapshot.
24117
- examples: external_exports.array(external_exports.string()).optional()
23307
+ examples: external_exports.array(external_exports.string()).optional(),
23308
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23309
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23310
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23311
+ // in a value category (secret/pii/financial/phi) is always 'value',
23312
+ // whatever it declares.
23313
+ evidence: RuleEvidence.optional()
24118
23314
  }).meta({ id: "DetectionRule" });
24119
23315
  var DetectionUpdate = external_exports.object({
24120
23316
  available: external_exports.boolean(),
@@ -24182,8 +23378,10 @@ var ImportDetectionRequest = external_exports.object({
24182
23378
  }).meta({ id: "ImportDetectionRequest" });
24183
23379
 
24184
23380
  // ../../packages/schema/src/zod/detection-build.ts
24185
- function optional2(key, parsed2, raw) {
24186
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
23381
+ function optional2(key, raw, parse4) {
23382
+ if (raw === void 0) return {};
23383
+ const parsed2 = parse4(raw);
23384
+ if (!parsed2.success || parsed2.data === void 0) return {};
24187
23385
  return { [key]: parsed2.data };
24188
23386
  }
24189
23387
  function isStringArray(value) {
@@ -24218,10 +23416,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24218
23416
  category: r.category,
24219
23417
  severity: r.severity,
24220
23418
  matcher: parsed2.data,
24221
- // The rest of what decides whether this rule fires. Carried so a consumer
24222
- // re-running the rule (a preview, a tester) evaluates what the engine
24223
- // evaluates rather than a matcher stripped of its guards — half the
24224
- // bundled catalog carries at least one of these.
23419
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23420
+ // decides whether this rule fires. Carried so a consumer re-running the
23421
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23422
+ // than a matcher stripped of its guards — half the bundled catalog
23423
+ // carries at least one of these. `examples` and `evidence` describe the
23424
+ // rule and never gate a match.
24225
23425
  //
24226
23426
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24227
23427
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24231,18 +23431,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24231
23431
  // test should stay exactly what it was, namely a renderable matcher. A
24232
23432
  // field that fails validation is omitted, which reads as "not set" and is
24233
23433
  // the same thing the consumer saw before this change.
24234
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23434
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24235
23435
  ...optional2(
24236
23436
  "postValidators",
24237
- PostValidatorRef.array().safeParse(r.postValidators),
24238
- r.postValidators
23437
+ r.postValidators,
23438
+ (v) => PostValidatorRef.array().safeParse(v)
24239
23439
  ),
24240
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23440
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24241
23441
  ...optional2(
24242
23442
  "examples",
24243
- { success: isStringArray(r.examples), data: r.examples },
24244
- r.examples
24245
- )
23443
+ r.examples,
23444
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23445
+ ),
23446
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24246
23447
  }
24247
23448
  ];
24248
23449
  });
@@ -24935,11 +24136,14 @@ var PolicyBundle = external_exports.object({
24935
24136
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24936
24137
  // Model ids (the raw `model` string a harness reports, e.g.
24937
24138
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24938
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24939
- // one (UserPromptSubmit). Optional so an older backend — and an older
24940
- // on-disk cache — still parses; consumers read `?? []`, which is the
24941
- // unenforced behaviour that predates this field and the safe direction to
24942
- // default.
24139
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24140
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24141
+ // wherever the organization governs the event: everywhere on a
24142
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24143
+ // one (the plugin runtime's `governanceApplies`).
24144
+ // Optional so an older backend — and an older on-disk cache — still
24145
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24146
+ // predates this field and the safe direction to default.
24943
24147
  //
24944
24148
  // Ids, not display names: the governance decision is keyed on the exact
24945
24149
  // string the harness reports (`model_status_override.versionId` in the
@@ -25398,6 +24602,8 @@ var AttachmentScopeEntry = external_exports.object({
25398
24602
  });
25399
24603
  var AttachmentScope = external_exports.object({
25400
24604
  endpoint: external_exports.string().min(1),
24605
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24606
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25401
24607
  entries: external_exports.array(AttachmentScopeEntry)
25402
24608
  });
25403
24609
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25410,7 +24616,13 @@ function parseAttachmentScope(raw) {
25410
24616
  const entry = AttachmentScopeEntry.safeParse(candidate);
25411
24617
  if (entry.success) entries.push(entry.data);
25412
24618
  }
25413
- return { endpoint: envelope.data.endpoint, entries };
24619
+ const { endpoint, tenantName, userEmail } = envelope.data;
24620
+ return {
24621
+ endpoint,
24622
+ ...tenantName === void 0 ? {} : { tenantName },
24623
+ ...userEmail === void 0 ? {} : { userEmail },
24624
+ entries
24625
+ };
25414
24626
  } catch {
25415
24627
  return void 0;
25416
24628
  }
@@ -25647,6 +24859,7 @@ function toCaptureAttributes(event) {
25647
24859
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25648
24860
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25649
24861
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24862
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25650
24863
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25651
24864
  // has ever populated either), but every legacy metadata key still rides
25652
24865
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25775,6 +24988,27 @@ var ManagedSettings = external_exports.object({
25775
24988
  };
25776
24989
  }).meta({ id: "ManagedSettings" });
25777
24990
 
24991
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24992
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24993
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24994
+ var ModPolicySnapshot = external_exports.object({
24995
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24996
+ generatedAt: external_exports.iso.datetime(),
24997
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24998
+ // user's enabled installed packs (user-modified and custom packs included).
24999
+ // Absent means the store holds no authoritative snapshot, and the reader
25000
+ // scans with the packs it ships — the hook's own fallback.
25001
+ rules: external_exports.array(Rule).optional(),
25002
+ // Rule-targeted actions (first enabled policy per rule wins).
25003
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25004
+ // The resolved action per detection category.
25005
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25006
+ // Rules with an active exception grant. Honouring a grant means matching a
25007
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25008
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25009
+ exceptionRuleIds: external_exports.array(external_exports.string())
25010
+ }).meta({ id: "ModPolicySnapshot" });
25011
+
25778
25012
  // ../../packages/schema/src/zod/project-files.ts
25779
25013
  var ProjectFileInput = external_exports.object({
25780
25014
  path: external_exports.string().min(1),
@@ -26095,7 +25329,16 @@ var AttachInput = external_exports.object({
26095
25329
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26096
25330
  // renders a longer one usefully.
26097
25331
  label: printable(200).optional(),
26098
- accessKey: external_exports.string()
25332
+ accessKey: external_exports.string(),
25333
+ // How much of this machine the attachment is for: everything, or only the
25334
+ // repositories its user enrolls. Optional, so an input without it still
25335
+ // parses; what an absent mode means is for whatever reads it to decide, not
25336
+ // this shape. This member validates the VALUE rather than leaving that to the
25337
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25338
+ // rejection names the field, so a value that is not a mode is refused as a bad
25339
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25340
+ // it as the mode to attach in.
25341
+ mode: AttachmentMode.optional()
26099
25342
  });
26100
25343
 
26101
25344
  // ../../packages/schema/src/zod/triage.ts
@@ -26381,6 +25624,18 @@ function fromCaptureStatusAttributes(bag) {
26381
25624
  return parsedStatus.success ? parsedStatus.data : null;
26382
25625
  }
26383
25626
 
25627
+ // ../../packages/persistence/src/attached-derived.ts
25628
+ import { rmSync } from "fs";
25629
+ import { join } from "path";
25630
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25631
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25632
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
25633
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
25634
+
25635
+ // ../../packages/persistence/src/control-plane-credential.ts
25636
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25637
+ import { join as join2 } from "path";
25638
+
26384
25639
  // ../../packages/persistence/src/paths.ts
26385
25640
  import {
26386
25641
  chmodSync,
@@ -26527,6 +25782,14 @@ function repairOrRefuseMode(file2) {
26527
25782
  }
26528
25783
  return "ok";
26529
25784
  }
25785
+ function asReadableCredential(value) {
25786
+ const result = AttachedCredentialAny.safeParse(value);
25787
+ if (!result.success) return null;
25788
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25789
+ return null;
25790
+ }
25791
+ return result.data;
25792
+ }
26530
25793
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26531
25794
  const file2 = controlPlaneCredentialPath(settingsDir2);
26532
25795
  let raw;
@@ -26545,20 +25808,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26545
25808
  } catch {
26546
25809
  return { usable: false, reason: "malformed" };
26547
25810
  }
26548
- const result = AttachedCredential.safeParse(parsed2);
26549
- if (!result.success) return { usable: false, reason: "malformed" };
26550
- if (!isSafeEndpoint(result.data.endpoint)) {
25811
+ const credential = asReadableCredential(parsed2);
25812
+ if (credential === null) return { usable: false, reason: "malformed" };
25813
+ if (!isSafeEndpoint(credential.endpoint)) {
26551
25814
  return { usable: false, reason: "unsafe-endpoint" };
26552
25815
  }
26553
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25816
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26554
25817
  return {
26555
25818
  usable: false,
26556
25819
  reason: "endpoint-mismatch",
26557
- credentialEndpoint: result.data.endpoint,
25820
+ credentialEndpoint: credential.endpoint,
26558
25821
  settingsEndpoint: connection.endpoint
26559
25822
  };
26560
25823
  }
26561
- return { usable: true, credential: result.data };
25824
+ return { usable: true, credential };
26562
25825
  }
26563
25826
  function readControlPlaneCredential(settingsDir2, connection) {
26564
25827
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26567,7 +25830,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26567
25830
 
26568
25831
  // ../../packages/persistence/src/database.ts
26569
25832
  import { randomUUID as randomUUID11 } from "crypto";
26570
- import { dirname as dirname2, join as join7, sep } from "path";
25833
+ import { dirname as dirname2, join as join8, sep } from "path";
26571
25834
  import { DatabaseSync } from "node:sqlite";
26572
25835
 
26573
25836
  // ../../packages/persistence/src/ids.ts
@@ -26621,6 +25884,7 @@ function uuidFromDigest(digest) {
26621
25884
  function captureWireId(sessionId, contentHash, filePath = null) {
26622
25885
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26623
25886
  }
25887
+ var DOT = ".".charCodeAt(0);
26624
25888
 
26625
25889
  // ../../packages/persistence/src/internal/snapshot.ts
26626
25890
  import { randomUUID } from "crypto";
@@ -26948,6 +26212,25 @@ function scopeKeysParam(scopeKeys) {
26948
26212
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26949
26213
  FROM audit_events AS session_root
26950
26214
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26215
+ var COUNTED_IN_SCOPE = `
26216
+ AND ${inScope("scope_key")}
26217
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26218
+ var DRAIN_TOTALS = `SELECT
26219
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26220
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26221
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26222
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26223
+ THEN 1 ELSE 0 END) AS skipped,
26224
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26225
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26226
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26227
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26228
+ FROM audit_events
26229
+ WHERE event_type IN (${TYPE_LIST})`;
26230
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26231
+ FROM audit_events
26232
+ WHERE synced_at = ${String(SKIPPED)}
26233
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26951
26234
  var ROW_COLUMNS = `id,
26952
26235
  parent_id AS parentId,
26953
26236
  root_session_id AS rootSessionId,
@@ -27023,7 +26306,7 @@ var SqliteHistorySyncRepository = class {
27023
26306
  );
27024
26307
  this.scopedCaptureRowsStmt = db.prepare(
27025
26308
  `SELECT ${ROW_COLUMNS}
27026
- FROM audit_events
26309
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27027
26310
  WHERE synced_at IS NULL
27028
26311
  AND sync_claimed_at IS NULL
27029
26312
  AND outbox_owed = 1
@@ -27076,40 +26359,28 @@ var SqliteHistorySyncRepository = class {
27076
26359
  );
27077
26360
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27078
26361
  FROM audit_events${COUNTED_SCOPE}`);
26362
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26363
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27079
26364
  this.partitionByKindStmt = db.prepare(
27080
26365
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27081
26366
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27082
26367
  GROUP BY event_type`
27083
26368
  );
27084
- this.countsStmt = db.prepare(
27085
- `SELECT
27086
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27087
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27088
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27089
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27090
- THEN 1 ELSE 0 END) AS skipped,
27091
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27092
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27093
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27094
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27095
- FROM audit_events
27096
- WHERE event_type IN (${TYPE_LIST})`
26369
+ this.scopedPartitionByKindStmt = db.prepare(
26370
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26371
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26372
+ GROUP BY event_type`
27097
26373
  );
27098
- this.captureSkipCountStmt = db.prepare(
27099
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27100
- // way the structural totals are. The split exists because a refusal is
27101
- // terminal only against the deployment that gave it, and the structural
27102
- // re-arm frees it on a change of deployment. The capture lane has no such
27103
- // escape: re-arming a capture would offer one deployment's undelivered
27104
- // prompts, with their text, to a deployment that never saw them, which is
27105
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27106
- // reasons mean the same thing — this row will not be sent — and splitting
27107
- // them would put refused captures in a bucket nothing reads and nothing
27108
- // frees.
27109
- `SELECT COUNT(*) AS skipped
27110
- FROM audit_events
27111
- WHERE synced_at = ${String(SKIPPED)}
27112
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26374
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26375
+ this.scopedCountsStmt = db.prepare(
26376
+ `${DRAIN_TOTALS}
26377
+ AND ${inScope("scope_key")}
26378
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26379
+ );
26380
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26381
+ this.scopedCaptureSkipCountStmt = db.prepare(
26382
+ `${CAPTURE_SKIPS}
26383
+ AND ${inScope("scope_key")}`
27113
26384
  );
27114
26385
  this.fingerprintStmt = db.prepare(
27115
26386
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27223,6 +26494,10 @@ var SqliteHistorySyncRepository = class {
27223
26494
  scopedCaptureRowsStmt;
27224
26495
  scopedCaptureBacklogOwedStmt;
27225
26496
  markScopeCapturesOwedStmt;
26497
+ scopedPartitionStmt;
26498
+ scopedPartitionByKindStmt;
26499
+ scopedCountsStmt;
26500
+ scopedCaptureSkipCountStmt;
27226
26501
  /**
27227
26502
  * The masked detections recorded against one tool call.
27228
26503
  *
@@ -27444,7 +26719,29 @@ var SqliteHistorySyncRepository = class {
27444
26719
  * in" — and a machine that has never attached has no boundary to pass, so
27445
26720
  * requiring one would force a caller to invent one and report the whole store
27446
26721
  * as queued.
26722
+ *
26723
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26724
+ * the rows that pass the drain's reachability rule for that scope
26725
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26726
+ * drain never offers), so a personal repository's rows are in none of them.
26727
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26728
+ * nothing.
27447
26729
  */
26730
+ partition(scopeKeys) {
26731
+ const row = getRow(
26732
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26733
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26734
+ );
26735
+ return {
26736
+ queued: row?.queued ?? 0,
26737
+ inProgress: row?.inProgress ?? 0,
26738
+ synced: row?.synced ?? 0,
26739
+ failed: row?.failed ?? 0,
26740
+ refused: row?.refused ?? 0,
26741
+ detached: row?.detached ?? 0,
26742
+ total: row?.total ?? 0
26743
+ };
26744
+ }
27448
26745
  /**
27449
26746
  * The same partition, one row per kind that a lane carries.
27450
26747
  *
@@ -27454,11 +26751,14 @@ var SqliteHistorySyncRepository = class {
27454
26751
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27455
26752
  * rows", never as "zero sent"; the two look identical in a bar and mean
27456
26753
  * different things.
26754
+ *
26755
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26756
+ * still sum to the scoped aggregate. An empty list returns no rows.
27457
26757
  */
27458
- partitionByKind() {
26758
+ partitionByKind(scopeKeys) {
27459
26759
  return allRows(
27460
- this.partitionByKindStmt,
27461
- {}
26760
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26761
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27462
26762
  ).map((row) => ({
27463
26763
  kind: row.kind,
27464
26764
  queued: row.queued ?? 0,
@@ -27470,22 +26770,25 @@ var SqliteHistorySyncRepository = class {
27470
26770
  total: row.total ?? 0
27471
26771
  }));
27472
26772
  }
27473
- partition() {
27474
- const row = getRow(this.partitionStmt, {});
27475
- return {
27476
- queued: row?.queued ?? 0,
27477
- inProgress: row?.inProgress ?? 0,
27478
- synced: row?.synced ?? 0,
27479
- failed: row?.failed ?? 0,
27480
- refused: row?.refused ?? 0,
27481
- detached: row?.detached ?? 0,
27482
- total: row?.total ?? 0
27483
- };
27484
- }
27485
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27486
- counts(before) {
27487
- const row = getRow(this.countsStmt, { before });
27488
- const captures = getRow(this.captureSkipCountStmt);
26773
+ /**
26774
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26775
+ * and skipped are totals.
26776
+ *
26777
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26778
+ * `capturesSkipped` included: a structural row is counted only when its own
26779
+ * key and its session root's key are among them, a capture when its own key
26780
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26781
+ * under the same keys and boundary. Omitted, this runs the machine
26782
+ * statements, unchanged; an empty list counts nothing.
26783
+ */
26784
+ counts(before, scopeKeys) {
26785
+ const row = getRow(
26786
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26787
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26788
+ );
26789
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26790
+ scopeKeys: scopeKeysParam(scopeKeys)
26791
+ });
27489
26792
  return {
27490
26793
  pending: row?.pending ?? 0,
27491
26794
  sent: row?.sent ?? 0,
@@ -27737,6 +27040,7 @@ function applyMigrations(db, file2, options = {}) {
27737
27040
  }
27738
27041
  ensureSyncedAtColumn(db, "audit_events");
27739
27042
  ensureScopeKeyColumn(db);
27043
+ ensureScopeOwedIndex(db);
27740
27044
  ensureScanLedgerTable(db);
27741
27045
  ensureHistorySyncTable(db);
27742
27046
  ensureBlockedDetectionsTable(db);
@@ -28177,14 +27481,48 @@ function ensureScopeKeyColumn(db) {
28177
27481
  function hasScopeKeyColumn(db) {
28178
27482
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28179
27483
  }
27484
+ var SCOPE_OWED_INDEX_DDL = "CREATE INDEX IF NOT EXISTS idx_audit_scope_owed ON audit_events (scope_key, event_type, started_at) WHERE outbox_owed = 1 AND synced_at IS NULL";
27485
+ function ensureScopeOwedIndex(db) {
27486
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27487
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27488
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27489
+ if (!complete) return;
27490
+ db.exec(SCOPE_OWED_INDEX_DDL);
27491
+ }
28180
27492
  function ensureScanLedgerTable(db) {
28181
27493
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28182
27494
  path TEXT PRIMARY KEY,
28183
27495
  mtime TEXT NOT NULL,
28184
27496
  content_hash TEXT NOT NULL,
28185
27497
  ruleset_hash TEXT NOT NULL,
28186
- scanned_at INTEGER NOT NULL
27498
+ scanned_at INTEGER NOT NULL,
27499
+ scope_key TEXT,
27500
+ scope_root TEXT
28187
27501
  )`);
27502
+ ensureScanLedgerScopeKeyColumn(db);
27503
+ ensureScanLedgerScopeRootColumn(db);
27504
+ }
27505
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27506
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27507
+ function ensureScanLedgerScopeKeyColumn(db) {
27508
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27509
+ }
27510
+ function ensureScanLedgerScopeRootColumn(db) {
27511
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27512
+ }
27513
+ function ensureScanLedgerColumn(db, column, ddl) {
27514
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27515
+ if (hasScanLedgerColumn(db, column)) return;
27516
+ withTransaction(
27517
+ db,
27518
+ () => {
27519
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27520
+ },
27521
+ "IMMEDIATE"
27522
+ );
27523
+ }
27524
+ function hasScanLedgerColumn(db, column) {
27525
+ return columnNames(db, "scan_ledger").includes(column);
28188
27526
  }
28189
27527
  function ensureHistorySyncTable(db) {
28190
27528
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28235,6 +27573,106 @@ function ensureRuleProbeCacheTable(db) {
28235
27573
  )`);
28236
27574
  }
28237
27575
 
27576
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27577
+ import { createHash as createHash2 } from "crypto";
27578
+ import { readFileSync as readFileSync2 } from "fs";
27579
+ import { join as join4 } from "path";
27580
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27581
+ function modPolicySnapshotPath(dataDir2) {
27582
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27583
+ }
27584
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27585
+ const byRule = /* @__PURE__ */ new Map();
27586
+ const byCategory = /* @__PURE__ */ new Map();
27587
+ for (const policy of input2.policies) {
27588
+ if (!policy.enabled) continue;
27589
+ if ("ruleId" in policy.target) {
27590
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27591
+ } else if (!byCategory.has(policy.target.category)) {
27592
+ byCategory.set(policy.target.category, policy.action);
27593
+ }
27594
+ }
27595
+ const categoryActions = {};
27596
+ for (const category of DetectionCategory.options) {
27597
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27598
+ }
27599
+ return {
27600
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27601
+ generatedAt: generatedAt.toISOString(),
27602
+ // `examples` is documentation the mod never reads, and a custom pack's are
27603
+ // whatever its author pasted in, so they stay behind.
27604
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27605
+ ruleActions: Object.fromEntries(byRule),
27606
+ categoryActions,
27607
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27608
+ };
27609
+ }
27610
+ function assignedRuleActionPolicies(installed) {
27611
+ const out = [];
27612
+ for (const [ruleId, action] of installed.ruleActions) {
27613
+ if (installed.assignedRules.has(ruleId))
27614
+ out.push({ target: { ruleId }, action, enabled: true });
27615
+ }
27616
+ return out;
27617
+ }
27618
+ function withoutExamples(rule) {
27619
+ const copy = { ...rule };
27620
+ delete copy.examples;
27621
+ return copy;
27622
+ }
27623
+ function sameContent(a, b) {
27624
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27625
+ }
27626
+ function readModPolicySnapshot(dataDir2) {
27627
+ try {
27628
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27629
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27630
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27631
+ return parsed2.success ? parsed2.data : null;
27632
+ } catch {
27633
+ return null;
27634
+ }
27635
+ }
27636
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27637
+ const text = JSON.stringify(snapshot);
27638
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27639
+ const existing = readModPolicySnapshot(dataDir2);
27640
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27641
+ ensureDataDirSync(dataDir2);
27642
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27643
+ return true;
27644
+ }
27645
+ function regexProbeKey(matcher) {
27646
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27647
+ }
27648
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27649
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27650
+ return rules.filter((rule) => {
27651
+ if (rule.matcher.type !== "regex") return true;
27652
+ const key = regexProbeKey(rule.matcher);
27653
+ const verdict = sources.probeVerdict(key);
27654
+ if (verdict === "quarantined") return false;
27655
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27656
+ });
27657
+ }
27658
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27659
+ const policies = sources.readPolicies();
27660
+ const snapshot = sources.installedRuleset();
27661
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27662
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27663
+ return {
27664
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27665
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27666
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27667
+ };
27668
+ }
27669
+ function refreshModPolicySnapshot(dataDir2, sources) {
27670
+ try {
27671
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27672
+ } catch {
27673
+ }
27674
+ }
27675
+
28238
27676
  // ../../packages/persistence/src/internal/json.ts
28239
27677
  function safeJson(s, fallback) {
28240
27678
  if (s == null) return fallback;
@@ -28409,6 +27847,11 @@ var TIMELINE_COLUMNS = `
28409
27847
  json_extract(attributes, '$.targetId') AS target_id,
28410
27848
  json_extract(attributes, '$.internal') AS internal,
28411
27849
  json_extract(attributes, '$.flagged') AS flagged`;
27850
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27851
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27852
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27853
+ " + "
27854
+ );
28412
27855
  var LLM_USAGE_SELECT = `
28413
27856
  SELECT root_session_id AS sessionId,
28414
27857
  provider,
@@ -28420,9 +27863,10 @@ var LLM_USAGE_SELECT = `
28420
27863
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28421
27864
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28422
27865
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28423
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27866
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27867
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28424
27868
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28425
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27869
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28426
27870
  function usageLeaves(rows) {
28427
27871
  return rows.map((row) => {
28428
27872
  const attributes = {
@@ -28437,7 +27881,7 @@ function usageLeaves(rows) {
28437
27881
  if (row.provider !== null) attributes.provider = row.provider;
28438
27882
  if (row.model !== null) attributes.model = row.model;
28439
27883
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28440
- return { sessionId: row.sessionId, attributes };
27884
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28441
27885
  });
28442
27886
  }
28443
27887
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29771,9 +29215,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29771
29215
  AND conditions IS NULL
29772
29216
  AND ${ACTIVE_PREDICATE}`;
29773
29217
  var SqliteExceptionsRepository = class {
29774
- constructor(db, now = () => Date.now()) {
29218
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29775
29219
  this.db = db;
29776
29220
  this.now = now;
29221
+ this.onChange = onChange;
29777
29222
  this.consumeStmt = db.prepare(
29778
29223
  `UPDATE exceptions
29779
29224
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29792,6 +29237,7 @@ var SqliteExceptionsRepository = class {
29792
29237
  }
29793
29238
  db;
29794
29239
  now;
29240
+ onChange;
29795
29241
  consumeStmt;
29796
29242
  insertBlockedStmt;
29797
29243
  sweepBlockedStmt;
@@ -29807,7 +29253,9 @@ var SqliteExceptionsRepository = class {
29807
29253
  */
29808
29254
  create(input2) {
29809
29255
  try {
29810
- return Promise.resolve(this.createSync(input2));
29256
+ const created = this.createSync(input2);
29257
+ this.onChange();
29258
+ return Promise.resolve(created);
29811
29259
  } catch (err) {
29812
29260
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29813
29261
  }
@@ -29938,6 +29386,7 @@ var SqliteExceptionsRepository = class {
29938
29386
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29939
29387
  WHERE id = :id AND revoked_at IS NULL`
29940
29388
  ).run({ id, revokedBy, reason: reason ?? null, now });
29389
+ if (Number(result.changes) === 1) this.onChange();
29941
29390
  return Promise.resolve(Number(result.changes) === 1);
29942
29391
  }
29943
29392
  /**
@@ -29950,6 +29399,15 @@ var SqliteExceptionsRepository = class {
29950
29399
  const result = this.consumeStmt.run({ id, now });
29951
29400
  return Promise.resolve(Number(result.changes) === 1);
29952
29401
  }
29402
+ /** The rule ids with at least one active grant, under any key version. */
29403
+ activeRuleIds(now = this.now()) {
29404
+ return allRows(
29405
+ this.db.prepare(
29406
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29407
+ ),
29408
+ { now }
29409
+ ).map((row) => row.ruleId);
29410
+ }
29953
29411
  /**
29954
29412
  * The evaluation subset of every active grant under one fingerprint key
29955
29413
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31073,31 +30531,31 @@ var SqliteInspectionFindingsRepository = class {
31073
30531
  };
31074
30532
 
31075
30533
  // ../../packages/persistence/src/repositories/installed-packs.ts
31076
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30534
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31077
30535
 
31078
30536
  // ../../packages/persistence/src/policy-floor.ts
31079
- import { readFileSync as readFileSync5 } from "fs";
31080
- import { join as join6 } from "path";
30537
+ import { readFileSync as readFileSync6 } from "fs";
30538
+ import { join as join7 } from "path";
31081
30539
 
31082
30540
  // ../../packages/persistence/src/local-layout.ts
31083
30541
  import { renameSync as renameSync3 } from "fs";
31084
30542
  import { mkdir } from "fs/promises";
31085
30543
  import { homedir } from "os";
31086
- import { join as join4 } from "path";
30544
+ import { join as join5 } from "path";
31087
30545
  function defaultDataDir() {
31088
- return join4(homedir(), ".aka");
30546
+ return join5(homedir(), ".aka");
31089
30547
  }
31090
30548
  function settingsDir(base = defaultDataDir()) {
31091
- return join4(base, "settings");
30549
+ return join5(base, "settings");
31092
30550
  }
31093
30551
  function dataDir(base = defaultDataDir()) {
31094
- return join4(base, "data");
30552
+ return join5(base, "data");
31095
30553
  }
31096
30554
  function dbPath(base = defaultDataDir()) {
31097
- return join4(dataDir(base), "aka.db");
30555
+ return join5(dataDir(base), "aka.db");
31098
30556
  }
31099
30557
  function keysDir(base = defaultDataDir()) {
31100
- return join4(base, "keys");
30558
+ return join5(base, "keys");
31101
30559
  }
31102
30560
  async function ensureDataDir(dir = defaultDataDir()) {
31103
30561
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31114,8 +30572,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31114
30572
  for (const { name, dest } of moves) {
31115
30573
  try {
31116
30574
  ensureDataDirSync(dest);
31117
- const moved = join4(dest, name);
31118
- renameSync3(join4(base, name), moved);
30575
+ const moved = join5(dest, name);
30576
+ renameSync3(join5(base, name), moved);
31119
30577
  tightenFile(moved);
31120
30578
  } catch {
31121
30579
  }
@@ -31123,8 +30581,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31123
30581
  }
31124
30582
 
31125
30583
  // ../../packages/persistence/src/settings.ts
31126
- import { readFileSync as readFileSync4 } from "fs";
31127
- import { join as join5 } from "path";
30584
+ import { readFileSync as readFileSync5 } from "fs";
30585
+ import { join as join6 } from "path";
31128
30586
 
31129
30587
  // ../../packages/persistence/src/file-lock.ts
31130
30588
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31132,7 +30590,7 @@ import {
31132
30590
  closeSync,
31133
30591
  existsSync as existsSync2,
31134
30592
  openSync,
31135
- readFileSync as readFileSync2,
30593
+ readFileSync as readFileSync3,
31136
30594
  rmSync as rmSync5,
31137
30595
  statSync as statSync3,
31138
30596
  writeFileSync as writeFileSync2
@@ -31141,16 +30599,16 @@ import { hostname as hostname3 } from "os";
31141
30599
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31142
30600
 
31143
30601
  // ../../packages/persistence/src/managed-settings.ts
31144
- import { readFileSync as readFileSync3 } from "fs";
30602
+ import { readFileSync as readFileSync4 } from "fs";
31145
30603
  import { posix, win32 } from "path";
31146
- function managedSettingsPaths(platform2 = process.platform) {
31147
- if (platform2 === "darwin") {
30604
+ function managedSettingsPaths(platform = process.platform) {
30605
+ if (platform === "darwin") {
31148
30606
  return [
31149
30607
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31150
30608
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31151
30609
  ];
31152
30610
  }
31153
- if (platform2 === "win32") {
30611
+ if (platform === "win32") {
31154
30612
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31155
30613
  }
31156
30614
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -31160,7 +30618,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31160
30618
  for (const path of paths) {
31161
30619
  let text;
31162
30620
  try {
31163
- text = readFileSync3(path, "utf8");
30621
+ text = readFileSync4(path, "utf8");
31164
30622
  } catch {
31165
30623
  continue;
31166
30624
  }
@@ -31214,7 +30672,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31214
30672
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31215
30673
  }
31216
30674
  function readUserSettings(base) {
31217
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30675
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31218
30676
  if (!record2) return defaultWorkspaceSettings();
31219
30677
  try {
31220
30678
  return WorkspaceSettings.parse(record2);
@@ -31225,7 +30683,7 @@ function readUserSettings(base) {
31225
30683
  function readJson(file2) {
31226
30684
  let text;
31227
30685
  try {
31228
- text = readFileSync4(file2, "utf8");
30686
+ text = readFileSync5(file2, "utf8");
31229
30687
  } catch {
31230
30688
  return null;
31231
30689
  }
@@ -31265,7 +30723,7 @@ var PolicyFloorError = class extends Error {
31265
30723
  };
31266
30724
  function readCachedPolicyBundle(base = defaultDataDir()) {
31267
30725
  try {
31268
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30726
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31269
30727
  const parsed2 = JSON.parse(raw);
31270
30728
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31271
30729
  return PolicyBundle.parse(parsed2.bundle);
@@ -31389,7 +30847,7 @@ function inventorySignature(packs2) {
31389
30847
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31390
30848
  }
31391
30849
  function hashRules(rulesJson) {
31392
- return createHash2("sha256").update(rulesJson).digest("hex");
30850
+ return createHash3("sha256").update(rulesJson).digest("hex");
31393
30851
  }
31394
30852
  function parseVersion(v) {
31395
30853
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31431,9 +30889,10 @@ var SqliteInstalledPacksRepository = class {
31431
30889
  * from `openLocalDatabase`, which is the single construction site that owns a
31432
30890
  * real `~/.aka`.
31433
30891
  */
31434
- constructor(db, baseDir) {
30892
+ constructor(db, baseDir, onChange = () => void 0) {
31435
30893
  this.db = db;
31436
30894
  this.baseDir = baseDir;
30895
+ this.onChange = onChange;
31437
30896
  this.insertMissingStmt = db.prepare(
31438
30897
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31439
30898
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31462,6 +30921,7 @@ var SqliteInstalledPacksRepository = class {
31462
30921
  }
31463
30922
  db;
31464
30923
  baseDir;
30924
+ onChange;
31465
30925
  insertMissingStmt;
31466
30926
  upsertAvailableStmt;
31467
30927
  signatureStmt;
@@ -31534,6 +30994,7 @@ var SqliteInstalledPacksRepository = class {
31534
30994
  },
31535
30995
  "IMMEDIATE"
31536
30996
  );
30997
+ this.onChange();
31537
30998
  } catch {
31538
30999
  }
31539
31000
  }
@@ -31608,6 +31069,7 @@ var SqliteInstalledPacksRepository = class {
31608
31069
  },
31609
31070
  "IMMEDIATE"
31610
31071
  );
31072
+ if (changed) this.onChange();
31611
31073
  return changed;
31612
31074
  }
31613
31075
  /**
@@ -31849,6 +31311,7 @@ var SqliteInstalledPacksRepository = class {
31849
31311
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31850
31312
  WHERE namespace = :namespace AND pack_id = :packId`
31851
31313
  ).run({ policyId, now: Date.now(), namespace, packId });
31314
+ if (Number(res.changes) > 0) this.onChange();
31852
31315
  return Number(res.changes) > 0;
31853
31316
  }
31854
31317
  /**
@@ -31873,6 +31336,7 @@ var SqliteInstalledPacksRepository = class {
31873
31336
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31874
31337
  WHERE namespace = :namespace AND pack_id = :packId`
31875
31338
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31339
+ if (Number(res.changes) > 0) this.onChange();
31876
31340
  return Number(res.changes) > 0;
31877
31341
  }
31878
31342
  // Fingerprint of the recorded available mirror — compared against the
@@ -32770,13 +32234,19 @@ var SqliteInventoryAssetsRepository = class {
32770
32234
  import { randomUUID as randomUUID6 } from "crypto";
32771
32235
  var SEED_BATCH_WINDOW_MS = 6e4;
32772
32236
  var SqlitePoliciesRepository = class {
32773
- constructor(db) {
32237
+ constructor(db, onChange = () => void 0) {
32774
32238
  this.db = db;
32239
+ this.onChange = onChange;
32775
32240
  }
32776
32241
  db;
32242
+ onChange;
32777
32243
  readPolicies() {
32244
+ return Promise.resolve(this.listPolicies());
32245
+ }
32246
+ /** The synchronous read behind {@link readPolicies}. */
32247
+ listPolicies() {
32778
32248
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32779
- const policies = mapRowsTolerant(rows, (row) => {
32249
+ return mapRowsTolerant(rows, (row) => {
32780
32250
  const target = JSON.parse(row.target);
32781
32251
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32782
32252
  return Policy.parse({
@@ -32788,7 +32258,6 @@ var SqlitePoliciesRepository = class {
32788
32258
  customKeywords
32789
32259
  });
32790
32260
  });
32791
- return Promise.resolve(policies);
32792
32261
  }
32793
32262
  // Seed one policy per bundled category at Monitor so the detection-type config
32794
32263
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32799,7 +32268,7 @@ var SqlitePoliciesRepository = class {
32799
32268
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32800
32269
  if (count > 0) {
32801
32270
  this.markEarlierChoices();
32802
- this.monitorUntouchedSeeds();
32271
+ if (this.monitorUntouchedSeeds()) this.onChange();
32803
32272
  return;
32804
32273
  }
32805
32274
  const stmt = this.db.prepare(
@@ -32816,6 +32285,7 @@ var SqlitePoliciesRepository = class {
32816
32285
  });
32817
32286
  }
32818
32287
  });
32288
+ this.onChange();
32819
32289
  }
32820
32290
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32821
32291
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32881,7 +32351,7 @@ var SqlitePoliciesRepository = class {
32881
32351
  ).filter(
32882
32352
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32883
32353
  );
32884
- if (untouched.length === 0) return;
32354
+ if (untouched.length === 0) return false;
32885
32355
  const stmt = this.db.prepare(
32886
32356
  `UPDATE policies SET action = 'log'
32887
32357
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32892,6 +32362,7 @@ var SqlitePoliciesRepository = class {
32892
32362
  stmt.run({ category: row.category, seeded: row.action });
32893
32363
  }
32894
32364
  });
32365
+ return true;
32895
32366
  }
32896
32367
  // Insert-or-update the single global per-category policy row, keyed on the
32897
32368
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32908,6 +32379,7 @@ var SqlitePoliciesRepository = class {
32908
32379
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32909
32380
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32910
32381
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32382
+ this.onChange();
32911
32383
  }
32912
32384
  // Caps every global per-category policy currently set to block/redact down
32913
32385
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32918,6 +32390,7 @@ var SqlitePoliciesRepository = class {
32918
32390
  WHERE scope='global' AND action IN ('block','redact')
32919
32391
  AND json_extract(target,'$.category') IS NOT NULL`
32920
32392
  ).run({ now: Date.now() });
32393
+ if (Number(info.changes) > 0) this.onChange();
32921
32394
  return Number(info.changes);
32922
32395
  }
32923
32396
  // Whether the category's row was ever written after it was created — by the
@@ -33237,31 +32710,45 @@ var SqliteScanLedgerRepository = class {
33237
32710
  constructor(db) {
33238
32711
  this.db = db;
33239
32712
  this.upsertStmt = db.prepare(
33240
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33241
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32713
+ `INSERT INTO scan_ledger
32714
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32715
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33242
32716
  ON CONFLICT (path) DO UPDATE SET
33243
32717
  mtime = excluded.mtime,
33244
32718
  content_hash = excluded.content_hash,
33245
32719
  ruleset_hash = excluded.ruleset_hash,
32720
+ scope_key = excluded.scope_key,
32721
+ scope_root = excluded.scope_root,
33246
32722
  scanned_at = excluded.scanned_at`
33247
32723
  );
33248
32724
  this.readStmt = db.prepare(
33249
- `SELECT path, mtime, content_hash AS contentHash
32725
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32726
+ scope_root AS scopeRoot
33250
32727
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33251
32728
  );
33252
32729
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32730
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33253
32731
  }
33254
32732
  db;
33255
32733
  upsertStmt;
33256
32734
  readStmt;
33257
32735
  pathsStmt;
32736
+ pathKeysStmt;
33258
32737
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33259
32738
  // older ruleset are simply absent, which reads as "never scanned".
33260
32739
  entriesForRuleset(rulesetHash) {
33261
- const rows = allRows(this.readStmt, {
33262
- rulesetHash
33263
- });
33264
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32740
+ const rows = allRows(this.readStmt, { rulesetHash });
32741
+ return new Map(
32742
+ rows.map((r) => [
32743
+ r.path,
32744
+ {
32745
+ mtime: r.mtime,
32746
+ contentHash: r.contentHash,
32747
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32748
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32749
+ }
32750
+ ])
32751
+ );
33265
32752
  }
33266
32753
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33267
32754
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33270,6 +32757,14 @@ var SqliteScanLedgerRepository = class {
33270
32757
  allPaths() {
33271
32758
  return allRows(this.pathsStmt).map((r) => r.path);
33272
32759
  }
32760
+ // Every ledgered path with the repository it was in when it was last read,
32761
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32762
+ // which repository a vanished file belonged to. `undefined` for a row with no
32763
+ // key, which is every row written before the column existed.
32764
+ pathKeys() {
32765
+ const rows = allRows(this.pathKeysStmt);
32766
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32767
+ }
33273
32768
  upsertEntries(entries) {
33274
32769
  if (entries.length === 0) return;
33275
32770
  const scannedAt = Date.now();
@@ -33280,6 +32775,8 @@ var SqliteScanLedgerRepository = class {
33280
32775
  mtime: entry.mtime,
33281
32776
  contentHash: entry.contentHash,
33282
32777
  rulesetHash: entry.rulesetHash,
32778
+ scopeKey: entry.scopeKey ?? null,
32779
+ scopeRoot: entry.scopeRoot ?? null,
33283
32780
  scannedAt
33284
32781
  });
33285
32782
  }
@@ -34367,6 +33864,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34367
33864
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34368
33865
  };
34369
33866
  }
33867
+ function withoutTrailingSlashes(path) {
33868
+ let end = path.length;
33869
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33870
+ return path.slice(0, end);
33871
+ }
34370
33872
  function toEndpointSummary(row) {
34371
33873
  return {
34372
33874
  id: row.id,
@@ -34654,7 +34156,7 @@ var SqliteSharesRepository = class {
34654
34156
  */
34655
34157
  reconcileCallSites(projectKey, reconcile) {
34656
34158
  if (reconcile.mode === "walk") {
34657
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
34159
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34658
34160
  this.db.prepare(
34659
34161
  `DELETE FROM share_call_site
34660
34162
  WHERE project_key = :key
@@ -35222,7 +34724,7 @@ function backupLegacyStore(db, file2) {
35222
34724
  discardStore(file2, backup);
35223
34725
  return backup;
35224
34726
  }
35225
- function openAndInitialize(file2, base, skipTags) {
34727
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35226
34728
  let db = openWithPragmas(file2);
35227
34729
  try {
35228
34730
  if (isForeignSqliteLineage(db)) {
@@ -35234,8 +34736,15 @@ function openAndInitialize(file2, base, skipTags) {
35234
34736
  }
35235
34737
  applyMigrations(db, file2, { skipTags });
35236
34738
  tightenPerms(file2);
35237
- const policies = new SqlitePoliciesRepository(db);
35238
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34739
+ const modPolicy = {};
34740
+ const onPolicyStateChange = () => {
34741
+ if (modPolicy.current !== void 0)
34742
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34743
+ };
34744
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34745
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34746
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34747
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35239
34748
  const repositories = {
35240
34749
  events: new SqliteEventsRepository(db),
35241
34750
  findings: new SqliteFindingsRepository(db),
@@ -35244,9 +34753,9 @@ function openAndInitialize(file2, base, skipTags) {
35244
34753
  scanLedger: new SqliteScanLedgerRepository(db),
35245
34754
  historySync: new SqliteHistorySyncRepository(db),
35246
34755
  secretVault: new SqliteSecretVaultRepository(db),
35247
- exceptions: new SqliteExceptionsRepository(db),
34756
+ exceptions,
35248
34757
  resolutions: new SqliteResolutionsRepository(db),
35249
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34758
+ ruleProbeCache,
35250
34759
  bodyRetention: new SqliteBodyRetentionRepository(db),
35251
34760
  security: new SqliteSecurityRepository(db),
35252
34761
  detections: new SqliteDetectionsRepository(db),
@@ -35264,6 +34773,13 @@ function openAndInitialize(file2, base, skipTags) {
35264
34773
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35265
34774
  configInventory: new SqliteConfigInventoryRepository(db)
35266
34775
  };
34776
+ modPolicy.current = {
34777
+ installedRuleset: () => installedPacks.installedRuleset(),
34778
+ readPolicies: () => policies.listPolicies(),
34779
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34780
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34781
+ bundledRegexMatchers: () => shippedRegexMatchers2
34782
+ };
35267
34783
  policies.seedDefaults();
35268
34784
  return { db, ...repositories };
35269
34785
  } catch (err) {
@@ -35275,7 +34791,7 @@ function openAndInitialize(file2, base, skipTags) {
35275
34791
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35276
34792
  function openLocalDatabase(dir, options = {}) {
35277
34793
  ensureDataDirSync(dir);
35278
- const file2 = join7(dir, DB_FILENAME);
34794
+ const file2 = join8(dir, DB_FILENAME);
35279
34795
  reapStalePartials(file2);
35280
34796
  const {
35281
34797
  db,
@@ -35311,7 +34827,8 @@ function openLocalDatabase(dir, options = {}) {
35311
34827
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35312
34828
  // settings/ and data/, and the pack-policy floor needs both halves.
35313
34829
  dirname2(dir),
35314
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34830
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34831
+ options.shippedRegexMatchers ?? []
35315
34832
  );
35316
34833
  function captureRowId(event) {
35317
34834
  return captureId(
@@ -35576,7 +35093,7 @@ function openLocalDatabase(dir, options = {}) {
35576
35093
  }
35577
35094
 
35578
35095
  // ../../packages/persistence/src/egress-wire.ts
35579
- import { createHash as createHash3 } from "crypto";
35096
+ import { createHash as createHash4 } from "crypto";
35580
35097
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35581
35098
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35582
35099
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35608,7 +35125,7 @@ function canonicalGitUrl(url2) {
35608
35125
  }
35609
35126
  function hashProjectKey(projectKey) {
35610
35127
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35611
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35128
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35612
35129
  }
35613
35130
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35614
35131
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35673,24 +35190,23 @@ function toEgressIngestRequest(input2) {
35673
35190
  }
35674
35191
 
35675
35192
  // ../../packages/persistence/src/finding-key.ts
35676
- import { createHash as createHash4 } from "crypto";
35193
+ import { createHash as createHash5 } from "crypto";
35677
35194
  function normalizeFilePath(filePath) {
35678
35195
  return filePath.replaceAll("\\", "/");
35679
35196
  }
35680
35197
  function computeFindingKey(input2) {
35681
35198
  const normalizedPath = normalizeFilePath(input2.filePath);
35682
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35199
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35683
35200
  }
35684
35201
 
35685
35202
  // ../../packages/persistence/src/fingerprint.ts
35686
35203
  import { createHmac, randomBytes } from "crypto";
35687
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35688
- import { join as join8 } from "path";
35689
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35204
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
35205
+ import { join as join9 } from "path";
35690
35206
  var EXCEPTION_KEY_FILENAME = "exception.key";
35691
35207
  var KEY_MATERIAL_BYTES = 32;
35692
35208
  function keyFilePath(dataDir2) {
35693
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
35209
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35694
35210
  }
35695
35211
  function parseKeyFile(raw) {
35696
35212
  const parsed2 = JSON.parse(raw);
@@ -35717,6 +35233,12 @@ var KEY_VERSION_COLUMNS = {
35717
35233
  };
35718
35234
  var SQLITE_ERROR2 = 1;
35719
35235
  var FLOOR_BUSY_TIMEOUT_MS = 250;
35236
+ function openReadOnly(file2) {
35237
+ const host = process;
35238
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
35239
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
35240
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
35241
+ }
35720
35242
  var FloorUnreadableError = class extends Error {
35721
35243
  code = "floor-unreadable";
35722
35244
  constructor(cause) {
@@ -35728,11 +35250,11 @@ var FloorUnreadableError = class extends Error {
35728
35250
  }
35729
35251
  };
35730
35252
  function storedKeyVersionFloor(dataDir2) {
35731
- const file2 = join8(dataDir2, DB_FILENAME);
35253
+ const file2 = join9(dataDir2, DB_FILENAME);
35732
35254
  if (!existsSync3(file2)) return 0;
35733
35255
  let db;
35734
35256
  try {
35735
- db = new DatabaseSync2(file2, { readOnly: true });
35257
+ db = openReadOnly(file2);
35736
35258
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35737
35259
  let floor = 0;
35738
35260
  for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35783,7 +35305,7 @@ function occupantMessage(file2, kind) {
35783
35305
  function readFingerprintKey(dataDir2) {
35784
35306
  let raw;
35785
35307
  try {
35786
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
35308
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35787
35309
  } catch (err) {
35788
35310
  if (err.code === "ENOENT") return null;
35789
35311
  throw err instanceof Error ? err : new Error(String(err));
@@ -35809,8 +35331,8 @@ function exactFingerprintValue(key, raw) {
35809
35331
  }
35810
35332
 
35811
35333
  // ../../packages/persistence/src/forward-health.ts
35812
- import { readFileSync as readFileSync7 } from "fs";
35813
- import { join as join9 } from "path";
35334
+ import { readFileSync as readFileSync8 } from "fs";
35335
+ import { join as join10 } from "path";
35814
35336
  var BREAKER_COOLDOWN_MS = 3e4;
35815
35337
  function parseForwardHealth(raw, nowMs) {
35816
35338
  try {
@@ -35834,20 +35356,21 @@ function isForwardPaused(health, nowMs) {
35834
35356
 
35835
35357
  // ../../packages/persistence/src/history-backfill.ts
35836
35358
  import { existsSync as existsSync4 } from "fs";
35837
- import { join as join10 } from "path";
35359
+ import { join as join11 } from "path";
35838
35360
 
35839
35361
  // ../../packages/persistence/src/history-preview.ts
35840
35362
  import { existsSync as existsSync5 } from "fs";
35841
- import { join as join11 } from "path";
35842
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
35363
+ import { join as join12 } from "path";
35364
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35843
35365
 
35844
35366
  // ../../packages/persistence/src/history-sync-state.ts
35845
- import { readFileSync as readFileSync8 } from "fs";
35846
- import { join as join12 } from "path";
35367
+ import { readFileSync as readFileSync9 } from "fs";
35368
+ import { join as join13 } from "path";
35369
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35847
35370
 
35848
35371
  // ../../packages/persistence/src/store-symlinks.ts
35849
35372
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35850
- import { dirname as dirname3, join as join13, resolve } from "path";
35373
+ import { dirname as dirname3, join as join14, resolve } from "path";
35851
35374
  var STORE_DB = "the store database (including the prompt corpus)";
35852
35375
  var STORE_SETTINGS = "your settings file";
35853
35376
  function storeContents(home) {
@@ -35856,11 +35379,11 @@ function storeContents(home) {
35856
35379
  [settingsDir(home), STORE_SETTINGS],
35857
35380
  [dataDir(home), STORE_DB],
35858
35381
  [keysDir(home), "the vault key"],
35859
- [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
35382
+ [join14(settingsDir(home), "settings.json"), STORE_SETTINGS],
35860
35383
  [dbPath(home), STORE_DB]
35861
35384
  ]);
35862
35385
  }
35863
- function symlinkedStorePaths(home, platform2 = process.platform) {
35386
+ function symlinkedStorePaths(home, platform = process.platform) {
35864
35387
  return [...storeContents(home)].flatMap(([path, holds]) => {
35865
35388
  try {
35866
35389
  if (!lstatSync3(path).isSymbolicLink()) return [];
@@ -35872,7 +35395,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
35872
35395
  // existsSync follows the link, so a target that is gone reads as
35873
35396
  // absent here while lstat above still sees the link itself.
35874
35397
  missing: !existsSync6(path),
35875
- mode: targetMode(path, platform2)
35398
+ mode: targetMode(path, platform)
35876
35399
  }
35877
35400
  ];
35878
35401
  } catch {
@@ -35887,8 +35410,8 @@ function linkTarget(path) {
35887
35410
  return resolve(dirname3(path), readlinkSync(path));
35888
35411
  }
35889
35412
  }
35890
- function targetMode(path, platform2) {
35891
- if (platform2 === "win32") return void 0;
35413
+ function targetMode(path, platform) {
35414
+ if (platform === "win32") return void 0;
35892
35415
  try {
35893
35416
  return statSync4(path).mode & 511;
35894
35417
  } catch {
@@ -35908,19 +35431,19 @@ import {
35908
35431
  // ../../packages/persistence/src/vault/key-provider.ts
35909
35432
  import { execFileSync } from "child_process";
35910
35433
  import { randomBytes as randomBytes2 } from "crypto";
35911
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35912
- import { join as join14 } from "path";
35434
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35435
+ import { join as join15 } from "path";
35913
35436
 
35914
35437
  // ../../packages/persistence/src/vault/vault.ts
35915
35438
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35916
35439
 
35917
35440
  // ../../packages/persistence/src/warn-era-cap.ts
35918
35441
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35919
- import { join as join15 } from "path";
35442
+ import { join as join16 } from "path";
35920
35443
  var MARKER = "warn-era-capped";
35921
35444
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35922
35445
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35923
- const marker = join15(dataDir2, MARKER);
35446
+ const marker = join16(dataDir2, MARKER);
35924
35447
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35925
35448
  const capped = db.policies.capCategoryActions();
35926
35449
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35980,7 +35503,7 @@ function resolveProvider() {
35980
35503
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
35981
35504
  try {
35982
35505
  ensureLayoutDirSync(base);
35983
- const settingsFile = join16(settingsDir(base), "settings.json");
35506
+ const settingsFile = join17(settingsDir(base), "settings.json");
35984
35507
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
35985
35508
  } catch {
35986
35509
  }
@@ -36003,11 +35526,6 @@ function resolveProviderSafe(resolveProviderFn) {
36003
35526
  }
36004
35527
  }
36005
35528
 
36006
- // ../../packages/plugin-sdk/src/config-inventory.ts
36007
- import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
36008
- import { homedir as homedir2 } from "os";
36009
- import { basename as basename3, join as join18 } from "path";
36010
-
36011
35529
  // ../../packages/detections/src/egress/registry.ts
36012
35530
  var EXTRACTOR_VERSION = "3";
36013
35531
  var PROVIDER_REGISTRY = [
@@ -36771,12 +36289,12 @@ var RegexMatcher2 = class {
36771
36289
  rule.matcher,
36772
36290
  () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
36773
36291
  );
36774
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
36292
+ const scanText = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
36775
36293
  const spans = [];
36776
36294
  let m;
36777
- const maxIterations = scanText2.length + 1;
36295
+ const maxIterations = scanText.length + 1;
36778
36296
  let iterations = 0;
36779
- while ((m = re.exec(scanText2)) !== null) {
36297
+ while ((m = re.exec(scanText)) !== null) {
36780
36298
  if (++iterations > maxIterations) break;
36781
36299
  const group = captureGroup != null ? m[captureGroup] : m[0];
36782
36300
  if (m[0].length === 0) re.lastIndex++;
@@ -37118,17 +36636,18 @@ function ruleEvidence(rule) {
37118
36636
 
37119
36637
  // ../../packages/detections/src/mask.ts
37120
36638
  function maskMatch(raw) {
37121
- if (raw.length <= 5) return "***";
37122
- const atIndex = raw.indexOf("@");
37123
- if (atIndex > 0 && atIndex < raw.length - 1) {
37124
- const domain2 = raw.slice(atIndex + 1);
36639
+ const visible = stripInvisiblePadding(raw);
36640
+ if (visible.length <= 5) return "***";
36641
+ const atIndex = visible.indexOf("@");
36642
+ if (atIndex > 0 && atIndex < visible.length - 1) {
36643
+ const domain2 = visible.slice(atIndex + 1);
37125
36644
  if (domain2.includes(".")) {
37126
- const local = raw.slice(0, atIndex);
36645
+ const local = visible.slice(0, atIndex);
37127
36646
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
37128
36647
  return `${maskedLocal}@${domain2}`;
37129
36648
  }
37130
36649
  }
37131
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
36650
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
37132
36651
  }
37133
36652
 
37134
36653
  // ../../packages/detections/src/pointer-shield.ts
@@ -37364,6 +36883,38 @@ function worstProbeMs(rule, now = wallClock, corroborate) {
37364
36883
  }
37365
36884
  var CPU_CORROBORATION_SHARE = 0.2;
37366
36885
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36886
+ function repeatTo(unit, length) {
36887
+ return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
36888
+ }
36889
+ function joinTo(length, open3, close, item) {
36890
+ const parts = [];
36891
+ let size = open3.length;
36892
+ for (let i = 0; size < length; i++) {
36893
+ const next = (i === 0 ? "" : ",") + item(i);
36894
+ parts.push(next);
36895
+ size += next.length;
36896
+ }
36897
+ return (open3 + parts.join("") + close).slice(0, length);
36898
+ }
36899
+ var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
36900
+ var GROWTH_CORPORA = [
36901
+ {
36902
+ name: "one-line JSON dictionary",
36903
+ build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
36904
+ },
36905
+ {
36906
+ name: "JSON array of quoted SQL keywords",
36907
+ build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
36908
+ },
36909
+ { name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
36910
+ { name: "double-quote run", build: (length) => repeatTo('"', length) },
36911
+ { name: "space run", build: (length) => repeatTo(" ", length) },
36912
+ { name: "newline run", build: (length) => repeatTo("\n", length) },
36913
+ ...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
36914
+ name: `unit run ${JSON.stringify(unit)}`,
36915
+ build: (length) => repeatTo(unit, length)
36916
+ }))
36917
+ ];
37367
36918
  function checkRuleTiming(rule, corroborate) {
37368
36919
  const { ms, probe, corroboratedMs } = worstProbeMs(rule, wallClock, corroborate);
37369
36920
  const work = corroboratedMs ?? 0;
@@ -37390,7 +36941,12 @@ var MIN_RAW_LEN = 4;
37390
36941
  var RAW_RUN_LEN = 8;
37391
36942
  function carriesRawRun(text, rawValues) {
37392
36943
  let windows = null;
37393
- for (const raw of new Set(rawValues)) {
36944
+ const values = /* @__PURE__ */ new Set();
36945
+ for (const raw of rawValues) {
36946
+ values.add(raw);
36947
+ values.add(stripInvisiblePadding(raw));
36948
+ }
36949
+ for (const raw of values) {
37394
36950
  if (raw.length < MIN_RAW_LEN) continue;
37395
36951
  if (raw.length < RAW_RUN_LEN) {
37396
36952
  if (text.includes(raw)) return true;
@@ -37414,11 +36970,16 @@ function carriesRawRun(text, rawValues) {
37414
36970
  return false;
37415
36971
  }
37416
36972
  function safeMaskedMatch(rawMatch) {
37417
- const masked = maskMatch(rawMatch);
37418
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37419
- return "***";
36973
+ const visible = stripInvisiblePadding(rawMatch);
36974
+ const masked = maskMatch(visible);
36975
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
36976
+ if (!reveals(masked)) return masked;
36977
+ const atIndex = masked.indexOf("@");
36978
+ if (atIndex > 0 && atIndex < masked.length - 1) {
36979
+ const emailFallback = `*${masked.slice(atIndex)}`;
36980
+ if (!reveals(emailFallback)) return emailFallback;
37420
36981
  }
37421
- return masked;
36982
+ return "***";
37422
36983
  }
37423
36984
  function assertRawFree(text, rawValues) {
37424
36985
  if (carriesRawRun(text, rawValues)) {
@@ -37655,7 +37216,7 @@ var auth_jwt_no_verify_default = {
37655
37216
  severity: "critical",
37656
37217
  matcher: {
37657
37218
  type: "regex",
37658
- pattern: "(verify\\s*=\\s*false|verify_signature.*false|algorithms\\s*=\\s*\\[\\])",
37219
+ pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
37659
37220
  flags: "gi"
37660
37221
  },
37661
37222
  requiresNearby: {
@@ -37743,7 +37304,7 @@ var cmd_inject_shell_default = {
37743
37304
  severity: "critical",
37744
37305
  matcher: {
37745
37306
  type: "regex",
37746
- pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
37307
+ pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
37747
37308
  flags: "gi"
37748
37309
  },
37749
37310
  requiresNearby: {
@@ -37872,7 +37433,7 @@ var deser_yaml_unsafe_default = {
37872
37433
  severity: "high",
37873
37434
  matcher: {
37874
37435
  type: "regex",
37875
- pattern: "\\byaml\\.load\\s*\\((?![^)]*SafeLoader|[^)]*safe_load)",
37436
+ pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
37876
37437
  flags: "gi"
37877
37438
  },
37878
37439
  examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
@@ -38089,7 +37650,7 @@ var sql_inject_concat_dot_default = {
38089
37650
  severity: "high",
38090
37651
  matcher: {
38091
37652
  type: "regex",
38092
- pattern: `["'][^\\n]*?(select|insert|update|delete|drop|where)[^\\n]*?["']\\s*\\.`,
37653
+ pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
38093
37654
  flags: "gi"
38094
37655
  },
38095
37656
  appliesTo: {
@@ -38107,7 +37668,7 @@ var sql_inject_concat_default = {
38107
37668
  severity: "high",
38108
37669
  matcher: {
38109
37670
  type: "regex",
38110
- pattern: `["']\\s*(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?["']\\s*\\+`,
37671
+ pattern: `(["'])\\s*(?=(select\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?=))\\2(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?["']\\s*\\+`,
38111
37672
  flags: "gi"
38112
37673
  },
38113
37674
  examples: ['"SELECT * FROM users WHERE id = " + userId']
@@ -38122,7 +37683,7 @@ var sql_inject_format_default = {
38122
37683
  severity: "high",
38123
37684
  matcher: {
38124
37685
  type: "regex",
38125
- pattern: "\\b(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?(?:[%][sd]|\\{[^}]+\\})",
37686
+ pattern: "\\b(?=(select\\b(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))\\1(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})|\\b(?=(where\\b(?:(?!\\bwhere\\b)[^\\n])*?=))\\2(?:(?!\\bwhere\\b)[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})",
38126
37687
  flags: "gi"
38127
37688
  },
38128
37689
  examples: [
@@ -38140,7 +37701,7 @@ var sql_inject_interp_default = {
38140
37701
  severity: "high",
38141
37702
  matcher: {
38142
37703
  type: "regex",
38143
- pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
37704
+ pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
38144
37705
  flags: "gi"
38145
37706
  },
38146
37707
  examples: [
@@ -38515,7 +38076,7 @@ var stack_trace_default = {
38515
38076
  severity: "low",
38516
38077
  matcher: {
38517
38078
  type: "regex",
38518
- pattern: "(?:^|\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38079
+ pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38519
38080
  flags: "g"
38520
38081
  },
38521
38082
  examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
@@ -39673,7 +39234,7 @@ var BUNDLED_PACKS = [
39673
39234
  {
39674
39235
  packId: "code-flaws",
39675
39236
  name: "Code Security Flaws",
39676
- version: "0.1.0",
39237
+ version: "0.1.1",
39677
39238
  rawRules: [
39678
39239
  sql_inject_concat_default,
39679
39240
  sql_inject_concat_dot_default,
@@ -39723,7 +39284,7 @@ var BUNDLED_PACKS = [
39723
39284
  {
39724
39285
  packId: "core-code-context",
39725
39286
  name: "Code Context",
39726
- version: "0.2.1",
39287
+ version: "0.2.2",
39727
39288
  rawRules: [
39728
39289
  internal_ip_default,
39729
39290
  localhost_ref_default,
@@ -39860,6 +39421,11 @@ function bundledDetections() {
39860
39421
  }));
39861
39422
  return cachedDetections;
39862
39423
  }
39424
+ function shippedRegexMatchers() {
39425
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
39426
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
39427
+ );
39428
+ }
39863
39429
  function uniqueRuleIds(findings) {
39864
39430
  return [...new Set(findings.map((f) => f.ruleId))].join(", ");
39865
39431
  }
@@ -39884,13 +39450,14 @@ function bundledMaskingRules() {
39884
39450
  }
39885
39451
 
39886
39452
  // ../../packages/plugin-sdk/src/repo.ts
39887
- import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
39888
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
39453
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
39454
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
39889
39455
  var ATTRIBUTION_MEMO_LIMIT = 64;
39890
39456
  var attributionMemo = /* @__PURE__ */ new Map();
39891
39457
  var NO_ATTRIBUTION = Object.freeze({});
39892
- function resolveRepoAttribution(cwd) {
39458
+ function resolveRepoAttribution(cwd, options) {
39893
39459
  try {
39460
+ if (options?.cache === false) return attributeRepo(cwd);
39894
39461
  const remembered = attributionMemo.get(cwd);
39895
39462
  if (remembered !== void 0) return remembered;
39896
39463
  const attribution = attributeRepo(cwd);
@@ -39914,36 +39481,36 @@ function attributeRepo(cwd) {
39914
39481
  function findGitRoot(start) {
39915
39482
  let dir = start;
39916
39483
  for (; ; ) {
39917
- if (existsSync9(join17(dir, ".git"))) return dir;
39484
+ if (existsSync9(join18(dir, ".git"))) return dir;
39918
39485
  const parent = dirname4(dir);
39919
39486
  if (parent === dir) return void 0;
39920
39487
  dir = parent;
39921
39488
  }
39922
39489
  }
39923
39490
  function resolveGitContext(root) {
39924
- const dotGit = join17(root, ".git");
39491
+ const dotGit = join18(root, ".git");
39925
39492
  try {
39926
39493
  if (statSync6(dotGit).isDirectory()) {
39927
- return { configPath: join17(dotGit, "config"), headRoot: root };
39494
+ return { configPath: join18(dotGit, "config"), headRoot: root };
39928
39495
  }
39929
39496
  } catch {
39930
39497
  return void 0;
39931
39498
  }
39932
39499
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
39933
39500
  if (!target) return void 0;
39934
- const gitdir = isAbsolute(target) ? target : join17(root, target);
39935
- if (existsSync9(join17(gitdir, "config"))) {
39936
- return { configPath: join17(gitdir, "config"), headRoot: root };
39501
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
39502
+ if (existsSync9(join18(gitdir, "config"))) {
39503
+ return { configPath: join18(gitdir, "config"), headRoot: root };
39937
39504
  }
39938
- const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
39505
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
39939
39506
  if (!commonRaw) return void 0;
39940
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
39507
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
39941
39508
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
39942
- return { configPath: join17(commonGitDir, "config"), headRoot };
39509
+ return { configPath: join18(commonGitDir, "config"), headRoot };
39943
39510
  }
39944
39511
  function safeRead(path) {
39945
39512
  try {
39946
- return readFileSync10(path, "utf8");
39513
+ return readFileSync11(path, "utf8");
39947
39514
  } catch {
39948
39515
  return void 0;
39949
39516
  }
@@ -39990,9 +39557,9 @@ function slugFromUrl(url2) {
39990
39557
  }
39991
39558
 
39992
39559
  // ../../packages/plugin-sdk/src/events.ts
39993
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39560
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
39994
39561
  function contentHashOf(text) {
39995
- return createHash5("sha256").update(text).digest("hex");
39562
+ return createHash6("sha256").update(text).digest("hex");
39996
39563
  }
39997
39564
  function buildIngestEvent(input2) {
39998
39565
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -40167,9 +39734,10 @@ function createIsolatedScanner(data, opts = {}) {
40167
39734
  if (job.timer !== void 0) return;
40168
39735
  job.startedAt = performance.now();
40169
39736
  job.progressAt = job.startedAt;
39737
+ const budget = job.deadlineAt === void 0 ? job.budgetMs : Math.max(0, Math.min(job.budgetMs, job.deadlineAt - job.startedAt));
40170
39738
  job.timer = setTimeout(() => {
40171
39739
  onDeadline(job);
40172
- }, job.budgetMs);
39740
+ }, budget);
40173
39741
  }
40174
39742
  function runOne(spec, fail) {
40175
39743
  if (closed) {
@@ -40180,6 +39748,12 @@ function createIsolatedScanner(data, opts = {}) {
40180
39748
  fail({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
40181
39749
  return;
40182
39750
  }
39751
+ const now = performance.now();
39752
+ const deadlineAt = spec.deadlineAt;
39753
+ if (deadlineAt !== void 0 && deadlineAt <= now) {
39754
+ fail({ status: "timeout", culpritIndex: void 0, elapsedMs: 0 });
39755
+ return;
39756
+ }
40183
39757
  const started = ensureWorker();
40184
39758
  if (!(started instanceof Worker)) {
40185
39759
  broken = started.error;
@@ -40187,11 +39761,11 @@ function createIsolatedScanner(data, opts = {}) {
40187
39761
  return;
40188
39762
  }
40189
39763
  const id = nextJobId++;
40190
- const now = performance.now();
40191
39764
  const job = {
40192
39765
  id,
40193
39766
  worker: started,
40194
39767
  budgetMs: spec.budgetMs,
39768
+ deadlineAt,
40195
39769
  startedAt: now,
40196
39770
  progressIndex: -1,
40197
39771
  progressAt: now,
@@ -40205,14 +39779,19 @@ function createIsolatedScanner(data, opts = {}) {
40205
39779
  if (readyWorker === started) {
40206
39780
  beginDeadline(job);
40207
39781
  } else {
39782
+ const startBudget = spec.startBudgetMs ?? startBudgetMs;
39783
+ const callerLimited = deadlineAt !== void 0 && deadlineAt - now < startBudget;
39784
+ const startWaitMs = callerLimited ? deadlineAt - now : startBudget;
40208
39785
  job.startupTimer = setTimeout(() => {
40209
39786
  if (pending !== job) return;
40210
39787
  kill(job.worker);
40211
- failPending({
40212
- status: "unavailable",
40213
- reason: `the scan worker did not start within ${String(startBudgetMs)}ms`
40214
- });
40215
- }, startBudgetMs);
39788
+ failPending(
39789
+ callerLimited ? { status: "timeout", culpritIndex: void 0, elapsedMs: performance.now() - now } : {
39790
+ status: "unavailable",
39791
+ reason: `the scan worker did not start within ${String(startBudget)}ms`
39792
+ }
39793
+ );
39794
+ }, startWaitMs);
40216
39795
  }
40217
39796
  try {
40218
39797
  started.postMessage(spec.build(id));
@@ -40241,7 +39820,9 @@ function createIsolatedScanner(data, opts = {}) {
40241
39820
  return enqueue((resolve3) => {
40242
39821
  runOne(
40243
39822
  {
40244
- budgetMs,
39823
+ budgetMs: scanOpts?.budgetMs ?? budgetMs,
39824
+ startBudgetMs: scanOpts?.startBudgetMs,
39825
+ deadlineAt: scanOpts?.deadlineAt,
40245
39826
  build: (id) => ({
40246
39827
  kind: "scan",
40247
39828
  id,
@@ -40435,6 +40016,9 @@ function createGuardedScanner(partition, gateway, opts) {
40435
40016
  let unverified = partition.unverified;
40436
40017
  let isolated = unverified.length > 0 ? createIsolatedScanner({ verified, unverified }, opts) : void 0;
40437
40018
  let retired = false;
40019
+ let bounded;
40020
+ let boundedWarned = false;
40021
+ let closed = false;
40438
40022
  function inProcess(text, context) {
40439
40023
  return scan(text, verified, context);
40440
40024
  }
@@ -40496,11 +40080,48 @@ function createGuardedScanner(partition, gateway, opts) {
40496
40080
  await degrade();
40497
40081
  return inProcess(text, context);
40498
40082
  }
40083
+ async function scanBounded(text, context, bound) {
40084
+ const remainingMs = bound.remainingMs;
40085
+ let outcome;
40086
+ if (closed) {
40087
+ outcome = { status: "unavailable", reason: "the scan worker is closed" };
40088
+ } else if (remainingMs !== void 0 && !(remainingMs > 0)) {
40089
+ outcome = { status: "timeout", culpritIndex: void 0, elapsedMs: 0 };
40090
+ } else {
40091
+ bounded ??= createIsolatedScanner({ verified, unverified }, opts);
40092
+ const deadlineAt = remainingMs === void 0 ? void 0 : performance.now() + remainingMs;
40093
+ try {
40094
+ outcome = await bounded.scan(text, context, {
40095
+ budgetMs: bound.budgetMs,
40096
+ startBudgetMs: bound.startBudgetMs,
40097
+ deadlineAt
40098
+ });
40099
+ } catch (error62) {
40100
+ outcome = {
40101
+ status: "unavailable",
40102
+ reason: error62 instanceof Error ? error62.message : "the scan worker failed unexpectedly"
40103
+ };
40104
+ }
40105
+ }
40106
+ if (outcome.status !== "ok" && !boundedWarned) {
40107
+ boundedWarned = true;
40108
+ process.stderr.write(
40109
+ outcome.status === "timeout" ? `[aka] a large input could not be scanned within its time limit and was refused.
40110
+ ` : `[aka] a large input could not be scanned and was refused: ${outcome.reason}.
40111
+ `
40112
+ );
40113
+ }
40114
+ return outcome;
40115
+ }
40499
40116
  return {
40500
40117
  scan: guardedScan,
40118
+ scanBounded,
40501
40119
  degraded: () => retired,
40502
40120
  async close() {
40503
- await retire();
40121
+ closed = true;
40122
+ const live = bounded;
40123
+ bounded = void 0;
40124
+ await Promise.all([retire(), live?.close()]);
40504
40125
  }
40505
40126
  };
40506
40127
  }
@@ -40543,10 +40164,6 @@ function isPositiveSafeInteger(value) {
40543
40164
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
40544
40165
  }
40545
40166
 
40546
- // ../../packages/plugin-sdk/src/host-floor.ts
40547
- import { readFileSync as readFileSync14 } from "fs";
40548
- import { join as join21 } from "path";
40549
-
40550
40167
  // ../../packages/plugin-sdk/src/model-governance.ts
40551
40168
  import {
40552
40169
  closeSync as closeSync2,
@@ -40684,54 +40301,18 @@ function buildModelRefusalEvent(input2) {
40684
40301
  };
40685
40302
  }
40686
40303
 
40687
- // ../../packages/plugin-sdk/src/host-floor.ts
40688
- var HOST_FEATURE = {
40689
- ModelSwitch: "model-switch",
40690
- VaultPointerDisplay: "vault-pointer-display"
40691
- };
40692
- var HOST_FLOORS = {
40693
- [HOST_FEATURE.ModelSwitch]: {
40694
- label: "model-switch protection",
40695
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
40696
- since: "2.1.251"
40697
- },
40698
- [HOST_FEATURE.VaultPointerDisplay]: {
40699
- label: "vault pointer display",
40700
- hookEvents: ["MessageDisplay"],
40701
- since: "2.1.152"
40702
- }
40703
- };
40704
- var ANTIGRAVITY_HOST_FEATURE = {
40705
- EndOfTurnCapture: "end-of-turn-capture"
40706
- };
40707
- var ANTIGRAVITY_HOST_FLOORS = {
40708
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
40709
- label: "end-of-turn history capture",
40710
- hookEvents: ["Stop"],
40711
- since: "1.1.10"
40712
- }
40713
- };
40714
-
40715
- // ../../packages/plugin-sdk/src/ignore-layers.ts
40716
- var import_ignore = __toESM(require_ignore(), 1);
40717
- import { readFileSync as readFileSync15 } from "fs";
40718
- import { join as join22 } from "path";
40719
-
40720
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
40721
- import { arch, hostname as hostname4, platform, release } from "os";
40722
-
40723
40304
  // ../../packages/plugin-sdk/src/nudge.ts
40724
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
40725
- import { join as join23 } from "path";
40305
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
40306
+ import { join as join21 } from "path";
40726
40307
  var NUDGE_MARKER = "nudge-last-session";
40727
40308
  function claimOnboardingNudge(dataDir2, sessionId) {
40728
40309
  return claimOncePerSession(dataDir2, NUDGE_MARKER, sessionId);
40729
40310
  }
40730
40311
  function claimOncePerSession(dataDir2, marker, sessionId) {
40731
40312
  if (!sessionId) return true;
40732
- const path = join23(dataDir2, marker);
40313
+ const path = join21(dataDir2, marker);
40733
40314
  try {
40734
- if (readFileSync16(path, "utf8") === sessionId) return false;
40315
+ if (readFileSync14(path, "utf8") === sessionId) return false;
40735
40316
  } catch {
40736
40317
  }
40737
40318
  try {
@@ -40742,10 +40323,6 @@ function claimOncePerSession(dataDir2, marker, sessionId) {
40742
40323
  return true;
40743
40324
  }
40744
40325
 
40745
- // ../../packages/plugin-sdk/src/paths.ts
40746
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
40747
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
40748
-
40749
40326
  // ../../packages/plugin-sdk/src/policy-resolver.ts
40750
40327
  import { randomUUID as randomUUID14 } from "crypto";
40751
40328
  function createPolicyResolver(bundle) {
@@ -40790,36 +40367,6 @@ function assignedRulePolicies(installed) {
40790
40367
  return out;
40791
40368
  }
40792
40369
 
40793
- // ../../packages/plugin-sdk/src/project-files.ts
40794
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
40795
- import { basename as basename5, join as join24 } from "path";
40796
-
40797
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
40798
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
40799
- if (typeof v === "string" && v.trim() === "") return void 0;
40800
- return v;
40801
- }, external_exports.string().optional()).catch(void 0);
40802
- var optionalFlag = external_exports.preprocess((v) => {
40803
- if (typeof v !== "string") return false;
40804
- const normalized = v.trim().toLowerCase();
40805
- return normalized !== "" && normalized !== "0" && normalized !== "false";
40806
- }, external_exports.boolean()).catch(false);
40807
- var antigravityProviderEnvShape = {
40808
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
40809
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
40810
- };
40811
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
40812
-
40813
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
40814
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
40815
- if (typeof v === "string" && v.trim() === "") return void 0;
40816
- return v;
40817
- }, external_exports.string().optional()).catch(void 0);
40818
- var codexProviderEnvShape = {
40819
- OPENAI_BASE_URL: optionalBaseUrl3
40820
- };
40821
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
40822
-
40823
40370
  // ../../packages/plugin-sdk/src/runtime.ts
40824
40371
  import { randomUUID as randomUUID15 } from "crypto";
40825
40372
  var ENFORCEMENT_CEILING_ENABLED = false;
@@ -40860,6 +40407,19 @@ function conditionsMatch(conditions, ctx) {
40860
40407
  if (conditions.provider !== void 0) return false;
40861
40408
  return true;
40862
40409
  }
40410
+ var LARGE_INPUT_THRESHOLD_CHARS = 32768;
40411
+ var LARGE_INPUT_SCAN_BUDGET_MS = 2e3;
40412
+ var LARGE_INPUT_START_BUDGET_MS = 1500;
40413
+ function readRemainingMs(largeInput) {
40414
+ const read = largeInput.remainingMs;
40415
+ if (read === void 0) return void 0;
40416
+ try {
40417
+ const remaining = read();
40418
+ return typeof remaining !== "number" || Number.isNaN(remaining) ? 0 : remaining;
40419
+ } catch {
40420
+ return 0;
40421
+ }
40422
+ }
40863
40423
  var bundlesPacked = false;
40864
40424
  function createPluginRuntime(gateway, settings, opts) {
40865
40425
  if (!bundlesPacked) {
@@ -40869,6 +40429,7 @@ function createPluginRuntime(gateway, settings, opts) {
40869
40429
  const policyMode = settings.policy;
40870
40430
  let redactFallback = settings.redactFallback;
40871
40431
  const dataDir2 = opts?.dataDir;
40432
+ const largeInput = opts?.largeInput;
40872
40433
  let rules = [];
40873
40434
  let evidenceOf = evidenceLookup(rules);
40874
40435
  let scanner;
@@ -41081,7 +40642,24 @@ function createPluginRuntime(gateway, settings, opts) {
41081
40642
  await ensureInitialized();
41082
40643
  if (!scanner) throw new Error("the runtime initialized without a scanner");
41083
40644
  const shielded = shieldPointers(text);
41084
- const matched = await scanner.scan(shielded.text, context);
40645
+ let matched;
40646
+ if (largeInput !== void 0 && shielded.text.length >= largeInput.thresholdChars) {
40647
+ const outcome = await scanner.scanBounded(shielded.text, context, {
40648
+ budgetMs: largeInput.budgetMs,
40649
+ startBudgetMs: largeInput.startBudgetMs,
40650
+ remainingMs: readRemainingMs(largeInput)
40651
+ });
40652
+ if (outcome.status !== "ok") {
40653
+ return {
40654
+ decision: { action: "block", text: null, findings: [], scanIncomplete: outcome.status },
40655
+ excepted: /* @__PURE__ */ new Set(),
40656
+ exceptionIds: []
40657
+ };
40658
+ }
40659
+ matched = outcome.findings;
40660
+ } else {
40661
+ matched = await scanner.scan(shielded.text, context);
40662
+ }
41085
40663
  const findings = dropShieldedFindings(matched, shielded.spans);
41086
40664
  const fpCache = /* @__PURE__ */ new Map();
41087
40665
  const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
@@ -41106,12 +40684,11 @@ function createPluginRuntime(gateway, settings, opts) {
41106
40684
  async function processText(text, context, opts2 = {}) {
41107
40685
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
41108
40686
  }
41109
- async function capture(input2, opts2 = {}) {
40687
+ async function evaluateCapture(input2, opts2) {
41110
40688
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
41111
- const filePath = input2.metadata?.filePath;
41112
40689
  const { decision, excepted, exceptionIds } = await evaluate(
41113
40690
  input2.text,
41114
- { filePath, eventKind: input2.kind },
40691
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
41115
40692
  {
41116
40693
  sourceTool: input2.sourceTool,
41117
40694
  metadata: input2.metadata,
@@ -41119,20 +40696,28 @@ function createPluginRuntime(gateway, settings, opts) {
41119
40696
  },
41120
40697
  opts2.rewritable
41121
40698
  );
41122
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
40699
+ return { decision, excepted, exceptionIds, timingStartedAt };
40700
+ }
40701
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
40702
+ const filePath = input2.metadata?.filePath;
40703
+ if (opts2.persist === "with-findings" && decision.findings.length === 0 && decision.scanIncomplete === void 0) {
40704
+ return;
40705
+ }
41123
40706
  try {
41124
40707
  const contentHash = contentHashOf(input2.text);
41125
40708
  const maskedFindings = decision.findings.filter(
41126
40709
  (match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
41127
40710
  );
41128
- const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
40711
+ const storedContent = decision.scanIncomplete !== void 0 ? "" : maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
41129
40712
  const inspectionMs = elapsedMs(timingStartedAt);
41130
40713
  const redactDegradedTo = decision.redactDegradedTo;
41131
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
40714
+ const scanIncomplete = decision.scanIncomplete;
40715
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 || scanIncomplete !== void 0 ? {
41132
40716
  ...input2.metadata,
41133
40717
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
41134
40718
  ...inspectionMs !== void 0 ? { inspectionMs } : {},
41135
- ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
40719
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {},
40720
+ ...scanIncomplete !== void 0 ? { scanIncomplete } : {}
41136
40721
  } : input2.metadata;
41137
40722
  const event = buildIngestEvent({
41138
40723
  kind: input2.kind,
@@ -41162,6 +40747,8 @@ function createPluginRuntime(gateway, settings, opts) {
41162
40747
  // exceptions/blocked_detections when a key is available;
41163
40748
  // falls back to the masked match so at-rest findings still get
41164
40749
  // a stable (if weaker) identity on a workspace with no dataDir.
40750
+ // Both ignore the same invisible padding, so a clean and a
40751
+ // padded occurrence of one secret key alike on either path.
41165
40752
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
41166
40753
  }) : void 0;
41167
40754
  return {
@@ -41189,7 +40776,37 @@ function createPluginRuntime(gateway, settings, opts) {
41189
40776
  }
41190
40777
  } catch {
41191
40778
  }
41192
- return decision;
40779
+ }
40780
+ async function enforcedIn(text, context) {
40781
+ try {
40782
+ await ensureInitialized();
40783
+ if (!scanner) return [];
40784
+ const shielded = shieldPointers(text);
40785
+ const matched = await scanner.scan(shielded.text, context);
40786
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
40787
+ const action = resolveAction(finding.ruleId, finding.category);
40788
+ return action === "block" || action === "redact";
40789
+ });
40790
+ } catch {
40791
+ return [];
40792
+ }
40793
+ }
40794
+ async function capture(input2, opts2 = {}) {
40795
+ const evaluated = await evaluateCapture(input2, opts2);
40796
+ await persistCapture(input2, opts2, evaluated);
40797
+ return evaluated.decision;
40798
+ }
40799
+ async function captureDeferred(input2, opts2 = {}) {
40800
+ const evaluated = await evaluateCapture(input2, opts2);
40801
+ let recorded = false;
40802
+ return {
40803
+ result: evaluated.decision,
40804
+ record: async () => {
40805
+ if (recorded) return;
40806
+ recorded = true;
40807
+ await persistCapture(input2, opts2, evaluated);
40808
+ }
40809
+ };
41193
40810
  }
41194
40811
  async function rulesetFingerprint() {
41195
40812
  try {
@@ -41210,187 +40827,30 @@ function createPluginRuntime(gateway, settings, opts) {
41210
40827
  }
41211
40828
  await gateway.close();
41212
40829
  }
41213
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
41214
- }
41215
-
41216
- // ../../packages/plugin-sdk/src/scope-key.ts
41217
- import { existsSync as existsSync12 } from "fs";
41218
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join25, normalize } from "path";
41219
-
41220
- // ../../packages/plugin-sdk/src/suppressions.ts
41221
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
41222
-
41223
- // ../../packages/plugin-sdk/src/throttle.ts
41224
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
41225
- import { join as join26 } from "path";
41226
-
41227
- // src/present.ts
41228
- var fg = (hex3) => (text) => {
41229
- const r = Number.parseInt(hex3.slice(1, 3), 16);
41230
- const g = Number.parseInt(hex3.slice(3, 5), 16);
41231
- const b = Number.parseInt(hex3.slice(5, 7), 16);
41232
- return `\x1B[38;2;${String(r)};${String(g)};${String(b)}m${text}\x1B[0m`;
41233
- };
41234
- var paint = {
41235
- brand: fg("#33e6c6"),
41236
- // --color-brand · ▸▸ AKA wordmark (accent text)
41237
- dim: fg("#838995"),
41238
- // --color-text-3 · separators · "/100" · the "unreviewed" label
41239
- bold: (text) => `\x1B[1m${text}\x1B[0m`,
41240
- // the health score number
41241
- ok: fg("#0db15f"),
41242
- // --color-ok · healthy ● dot
41243
- critical: fg("#e63448"),
41244
- // --color-sev-critical · ■ and the open-findings flag
41245
- high: fg("#e97a0a"),
41246
- // --color-sev-high · ■ and the mid-health dot
41247
- medium: fg("#f7bd00"),
41248
- // --color-sev-medium · ■
41249
- low: fg("#0581d4")
41250
- // --color-sev-low · ■ (azure blue, not purple)
41251
- };
41252
-
41253
- // src/exception-guidance.ts
41254
- function blockMessage(input2) {
41255
- const preview = input2.blockedRef ? ` (${input2.blockedRef.maskedValue})` : "";
41256
- const commands = input2.blockedRef ? [
41257
- ` aka exception approve ${input2.blockedRef.reference} (asks for scope + reason, then resubmit)`,
41258
- " aka exception approve <value> (same flow, pasting the blocked value itself)"
41259
- ] : [" aka exception approve (asks for scope + reason, then resubmit)"];
41260
- const note = input2.note ? ` ${input2.note}` : "";
41261
- return [
41262
- `AKA blocked this ${input2.subject} \u2014 flagged ${input2.ruleIds}${preview}.${note} Remove the flagged content and resubmit.`,
41263
- "If this is intentional and you accept the risk, grant an exception:",
41264
- ...commands,
41265
- "More: aka exception --help"
41266
- ].join("\n");
41267
- }
41268
- function exceptionPointer(references) {
41269
- const ref = references?.[0];
41270
- if (ref === void 0) return "";
41271
- return ` To allow this exact value intentionally, run: aka exception approve ${ref.reference}.`;
40830
+ return {
40831
+ processText,
40832
+ capture,
40833
+ captureDeferred,
40834
+ enforcedIn,
40835
+ rulesetFingerprint,
40836
+ scanIsolationDegraded,
40837
+ close
40838
+ };
41272
40839
  }
41273
40840
 
41274
- // src/hooks/model-guard.ts
41275
- import { randomUUID as randomUUID16 } from "crypto";
41276
-
41277
- // src/hooks/shared.ts
41278
- import { isAbsolute as isAbsolute3, normalize as normalize2, resolve as resolvePath } from "path";
41279
- async function readStdin() {
41280
- return new Promise((resolve3) => {
41281
- let data = "";
41282
- let settled = false;
41283
- const finish = () => {
41284
- if (settled) return;
41285
- settled = true;
41286
- clearTimeout(timer);
41287
- process.stdin.removeListener("data", onData);
41288
- process.stdin.removeListener("end", finish);
41289
- resolve3(data);
41290
- };
41291
- const onData = (chunk) => {
41292
- data += chunk;
41293
- };
41294
- const timer = setTimeout(finish, 5e3);
41295
- process.stdin.setEncoding("utf8");
41296
- process.stdin.on("data", onData);
41297
- process.stdin.on("end", finish);
41298
- process.stdin.on("error", finish);
41299
- });
41300
- }
41301
- function parseJson(raw) {
41302
- try {
41303
- const parsed2 = JSON.parse(raw);
41304
- return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
41305
- } catch {
41306
- return null;
41307
- }
41308
- }
41309
- function getString(record2, key) {
41310
- const value = record2[key];
41311
- return typeof value === "string" ? value : void 0;
41312
- }
41313
- function emit(output2) {
41314
- return new Promise((resolve3) => {
41315
- let settled = false;
41316
- const finish = () => {
41317
- if (settled) return;
41318
- settled = true;
41319
- resolve3();
41320
- };
41321
- process.stdout.on("error", finish);
41322
- process.stdout.write(JSON.stringify(output2), finish);
41323
- });
41324
- }
41325
- function baseMetadata(input2) {
41326
- const metadata = {};
41327
- const sessionId = getString(input2, "session_id");
41328
- if (sessionId) metadata.sessionId = sessionId;
41329
- const repo = resolveRepoAttribution(getString(input2, "cwd") ?? process.cwd()).repo;
41330
- if (repo) metadata.repo = repo;
41331
- return Object.keys(metadata).length > 0 ? metadata : void 0;
41332
- }
41333
- function captureScopeKey(input2, filePath) {
41334
- try {
41335
- if (filePath === void 0 || filePath === "") {
41336
- return resolveRepoAttribution(getString(input2, "cwd") ?? process.cwd()).scopeKey;
41337
- }
41338
- if (isAbsolute3(filePath)) return resolveRepoAttribution(normalize2(filePath)).scopeKey;
41339
- const cwd = getString(input2, "cwd") ?? process.cwd();
41340
- if (!isAbsolute3(cwd)) return void 0;
41341
- return resolveRepoAttribution(resolvePath(cwd, filePath)).scopeKey;
41342
- } catch {
41343
- return void 0;
41344
- }
41345
- }
41346
- function countFailOpen(base) {
41347
- try {
41348
- recordHookFailOpen(dataDir(base), Date.now());
41349
- } catch {
41350
- }
40841
+ // src/hooks/large-input.ts
40842
+ var HOOK_SCAN_DEADLINE_MS = 6e3;
40843
+ function largeInputBound(deadlineAt, now = () => performance.now()) {
40844
+ return {
40845
+ thresholdChars: LARGE_INPUT_THRESHOLD_CHARS,
40846
+ budgetMs: LARGE_INPUT_SCAN_BUDGET_MS,
40847
+ startBudgetMs: LARGE_INPUT_START_BUDGET_MS,
40848
+ remainingMs: () => deadlineAt - now()
40849
+ };
41351
40850
  }
41352
40851
 
41353
40852
  // src/hooks/model-guard.ts
41354
- function resolveCodexSessionModel(dataDir2, sessionId, transcriptPath) {
41355
- return readSessionModel(dataDir2, sessionId) ?? modelFromTranscriptTail(transcriptPath, codexModelFromRecord);
41356
- }
41357
- async function refuseProhibitedTurn(gateway, dataDir2, sessionId, transcriptPath) {
41358
- try {
41359
- const { prohibitedModels } = await gateway.getPolicyBundle();
41360
- if (prohibitedModels === void 0 || prohibitedModels.length === 0) return null;
41361
- const model = resolveCodexSessionModel(dataDir2, sessionId, transcriptPath);
41362
- const decision = decideProhibitedModelTurn(model, prohibitedModels);
41363
- return decision === null || model === void 0 ? null : { decision, model };
41364
- } catch {
41365
- return null;
41366
- }
41367
- }
41368
- async function handleProhibitedTurn(gateway, dataDir2, sessionId, transcriptPath, cwd, emit2) {
41369
- const blocked = await refuseProhibitedTurn(gateway, dataDir2, sessionId, transcriptPath);
41370
- if (blocked === null) return false;
41371
- try {
41372
- await gateway.recordAuditEvent(
41373
- buildModelRefusalEvent({
41374
- id: randomUUID16(),
41375
- sessionId,
41376
- model: blocked.model,
41377
- seam: "turn",
41378
- sourceTool: SOURCE_TOOL.Codex,
41379
- occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
41380
- // Total by contract, so it cannot cost the record it stamps.
41381
- scopeKey: captureScopeKey({ cwd })
41382
- })
41383
- );
41384
- } catch {
41385
- }
41386
- await gateway.close();
41387
- await emit2(blocked.decision);
41388
- return true;
41389
- }
41390
-
41391
- // src/hooks/store-health.ts
41392
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
41393
- import { dirname as dirname8, join as join34 } from "path";
40853
+ import { randomUUID as randomUUID20 } from "crypto";
41394
40854
 
41395
40855
  // ../../packages/remote/src/http.ts
41396
40856
  import { request as httpRequest } from "http";
@@ -41768,11 +41228,11 @@ function withTimeout(promise2, ms) {
41768
41228
  }
41769
41229
 
41770
41230
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
41771
- import { readFileSync as readFileSync17 } from "fs";
41772
- import { join as join27 } from "path";
41231
+ import { readFileSync as readFileSync15 } from "fs";
41232
+ import { join as join22 } from "path";
41773
41233
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
41774
41234
  function forwardDropsPath(dataDir2) {
41775
- return join27(dataDir2, FORWARD_DROPS_FILENAME);
41235
+ return join22(dataDir2, FORWARD_DROPS_FILENAME);
41776
41236
  }
41777
41237
  function recordForwardDrops(dataDir2, count, nowMs) {
41778
41238
  if (count <= 0) return;
@@ -41790,7 +41250,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
41790
41250
  }
41791
41251
  function readForwardDrops(dataDir2) {
41792
41252
  try {
41793
- const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
41253
+ const parsed2 = JSON.parse(readFileSync15(forwardDropsPath(dataDir2), "utf8"));
41794
41254
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
41795
41255
  const record2 = parsed2;
41796
41256
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -41807,9 +41267,9 @@ function readForwardDrops(dataDir2) {
41807
41267
  }
41808
41268
 
41809
41269
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
41810
- import { randomUUID as randomUUID17 } from "crypto";
41270
+ import { randomUUID as randomUUID16 } from "crypto";
41811
41271
  import { readFile, rename, writeFile } from "fs/promises";
41812
- import { join as join28 } from "path";
41272
+ import { join as join23 } from "path";
41813
41273
  function isInvalidRequest(err) {
41814
41274
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
41815
41275
  }
@@ -41828,7 +41288,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
41828
41288
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
41829
41289
  function createForwardPolicy(deps) {
41830
41290
  const now = deps.now ?? (() => Date.now());
41831
- const file2 = join28(deps.dir, STATE_FILENAME);
41291
+ const file2 = join23(deps.dir, STATE_FILENAME);
41832
41292
  let state = null;
41833
41293
  let loading = null;
41834
41294
  async function readState() {
@@ -41853,7 +41313,7 @@ function createForwardPolicy(deps) {
41853
41313
  state = next;
41854
41314
  try {
41855
41315
  await ensureDataDir(deps.dir);
41856
- const tmp = `${file2}.${randomUUID17()}.tmp`;
41316
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
41857
41317
  await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
41858
41318
  await rename(tmp, file2);
41859
41319
  } catch {
@@ -41994,6 +41454,9 @@ var AttachedDataGateway = class {
41994
41454
  *
41995
41455
  * Machine mode answers before any key is read, so a machine attachment pays
41996
41456
  * nothing for scoping and forwards exactly what it always has.
41457
+ *
41458
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
41459
+ * forwarding key for key.
41997
41460
  */
41998
41461
  verdictFor(keyOf) {
41999
41462
  try {
@@ -42010,24 +41473,27 @@ var AttachedDataGateway = class {
42010
41473
  * the key its row holds in the local store, recorded per root (see
42011
41474
  * `rootVerdict`), not the key on the root event just handed in: roots are
42012
41475
  * first-write-wins in the store, so when two producers record a root for one
42013
- * session (the session-start hook, then a reconcile pass) the second leaves
42014
- * the stored row as it was, and the history drain decides that row, not this
42015
- * event. Whether this root EVENT is itself sent takes both keys: the stored
42016
- * one AND its own. The event's attributes (cwd, project, repo) describe where
42017
- * it was recorded from, so a root event keyed to a personal directory is never
42018
- * sent under an enrolled stored root, though the enrolled leaves still forward
42019
- * under it: the instance that wrote the stored root is expected to have
42020
- * forwarded it. If it did not (the root was written while standalone or under
42021
- * another attachment, or its forward failed), the plane refuses those leaves
42022
- * and the history drain ships the root first. Any other row with a root
42023
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
42024
- * is in scope AND this instance recorded an in-scope verdict for that root.
42025
- * The audit-event route has real foreign keys on both columns and stubs no
42026
- * missing root, so a leaf sent after its root was kept local is refused
42027
- * there, and a refused forward counts toward the breaker that guards every
42028
- * other one. A root this instance never recorded is therefore `'local'`: the
42029
- * only answer that cannot orphan a row. A row with no root reference at all
42030
- * has nothing to orphan, and is decided by its own key.
41476
+ * session (the session-start hook, then a reconcile pass) the second leaves the
41477
+ * stored row as it was. That stored row, not this event, is what a history
41478
+ * drain pass would decide, if the root started before the attach; the drain
41479
+ * never offers one that started after it (`started_at < backlogBefore`).
41480
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
41481
+ * its own. The event's attributes (cwd, project, repo) describe where it was
41482
+ * recorded from, so a root event keyed to a personal directory is never sent
41483
+ * under an enrolled stored root, though the enrolled leaves still forward under
41484
+ * it: the instance that wrote the stored root is expected to have forwarded it.
41485
+ * If it did not (the root was written while standalone or under another
41486
+ * attachment, or its forward failed), the plane refuses those leaves. A root
41487
+ * that started before the attach is shipped, ahead of its leaves, by the
41488
+ * history drain; one that started after it is never offered by the drain. Any
41489
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
41490
+ * only when its own key is in scope AND this instance recorded an in-scope
41491
+ * verdict for that root. The audit-event route has real foreign keys on both
41492
+ * columns and stubs no missing root, so a leaf sent after its root was kept
41493
+ * local is refused there, and a refused forward counts toward the breaker that
41494
+ * guards every other one. A root this instance never recorded is therefore
41495
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
41496
+ * reference at all has nothing to orphan, and is decided by its own key.
42031
41497
  *
42032
41498
  * What this costs is stated rather than discovered. A session whose stored
42033
41499
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -42098,6 +41564,87 @@ var AttachedDataGateway = class {
42098
41564
  return [];
42099
41565
  }
42100
41566
  }
41567
+ /**
41568
+ * The verdict for the repositories nested in a scanned project, answered
41569
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
41570
+ *
41571
+ * A walk descends into a nested clone or submodule and folds its files into
41572
+ * the project it is walking, so one register can carry several
41573
+ * repositories' call sites under one project key. Each of them must be in
41574
+ * scope for it to forward. One key out of scope, or a nested repository with
41575
+ * no remote (an `undefined` key), keeps the whole register local.
41576
+ *
41577
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
41578
+ * what is nested in it, and every scan passes the list, empty when nothing
41579
+ * is nested. A register nobody vouched for is not one a scoped attachment
41580
+ * may send.
41581
+ *
41582
+ * Machine mode answers before reading the context, so a machine attachment
41583
+ * forwards exactly what it always has.
41584
+ */
41585
+ nestedVerdict(context) {
41586
+ try {
41587
+ if (this.deps.attachment.mode === "machine") return "forward";
41588
+ const keys = context?.nestedScopeKeys;
41589
+ if (keys === void 0) return "local";
41590
+ for (const key of keys) {
41591
+ if (this.verdictFor(() => key) === "local") return "local";
41592
+ }
41593
+ return "forward";
41594
+ } catch {
41595
+ return "local";
41596
+ }
41597
+ }
41598
+ /**
41599
+ * The register a scoped attachment sends, once the project and the repositories
41600
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
41601
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
41602
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
41603
+ *
41604
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
41605
+ * and the ledger holds every file the scanner ever read under the root, nested
41606
+ * clones' included. So a clone that was removed, or one an ignore file now
41607
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
41608
+ * paths come back as deleted. The scan names the repository of each deleted
41609
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
41610
+ * and each is held to the same verdict as any other key. A path whose key is
41611
+ * absent, or out of scope, is not sent.
41612
+ *
41613
+ * The list is asked for here, and only here: it is an async read of the scan
41614
+ * ledger that the scan makes on being called, so a machine attachment, which
41615
+ * returns before this, and a register already kept local never cause it.
41616
+ *
41617
+ * Anything the scan did not vouch for sends no deleted path, and the register
41618
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
41619
+ * list whose length is not the register's. Deleting is the only thing a dropped
41620
+ * path could have done on the server, so the cost of a refusal is a stored row
41621
+ * that stays, never a path that leaves.
41622
+ *
41623
+ * Machine mode returns `input` itself, the same object and unread, so a machine
41624
+ * attachment's request is exactly what it was. A register that lists no deleted
41625
+ * path, or that is not a ledger register, has nothing to cut and is returned
41626
+ * as it came, with the list unread.
41627
+ */
41628
+ async registerForWire(input2, context) {
41629
+ try {
41630
+ if (this.deps.attachment.mode === "machine") return input2;
41631
+ const { reconcile } = input2;
41632
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
41633
+ const deleted = reconcile.deletedFiles;
41634
+ let kept = [];
41635
+ try {
41636
+ const keys = await context?.deletedFileKeys?.();
41637
+ if (keys?.length === deleted.length) {
41638
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
41639
+ }
41640
+ } catch {
41641
+ kept = [];
41642
+ }
41643
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
41644
+ } catch {
41645
+ return void 0;
41646
+ }
41647
+ }
42101
41648
  /**
42102
41649
  * The event `recordCapture` sends for a capture the verdict let through, or
42103
41650
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -42423,12 +41970,24 @@ var AttachedDataGateway = class {
42423
41970
  * payload onto the wire-boundary-safe shape (no snippet, hashed
42424
41971
  * projectKey), and its result is discarded: `forward.run` never throws or
42425
41972
  * rejects, so there is nothing here to act on.
41973
+ *
41974
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
41975
+ * not say: the key of every repository nested below the scan root, whose
41976
+ * files the walk folded into this register. On a scoped attachment the
41977
+ * register is forwarded only when the project's own key AND every one of
41978
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
41979
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
41980
+ * `registerForWire`). Machine mode never reads either, and the local write
41981
+ * never receives the context and gets the register whole.
42426
41982
  */
42427
- async recordProjectEgress(input2) {
41983
+ async recordProjectEgress(input2, context) {
42428
41984
  const summary = await this.deps.local.recordProjectEgress(input2);
42429
41985
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
41986
+ if (this.nestedVerdict(context) === "local") return summary;
41987
+ const register = await this.registerForWire(input2, context);
41988
+ if (register === void 0) return summary;
42430
41989
  await this.deps.forward.run(
42431
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
41990
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
42432
41991
  );
42433
41992
  return summary;
42434
41993
  }
@@ -42482,6 +42041,11 @@ var AttachedDataGateway = class {
42482
42041
  async scanLedgerPaths() {
42483
42042
  return this.deps.local.scanLedgerPaths();
42484
42043
  }
42044
+ // Delegated, like the path list. An inner gateway that cannot say answers an
42045
+ // empty map, which gives every deleted path no key.
42046
+ async scanLedgerPathKeys() {
42047
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
42048
+ }
42485
42049
  async recordScanned(entries) {
42486
42050
  return this.deps.local.recordScanned(entries);
42487
42051
  }
@@ -42548,6 +42112,12 @@ var AttachedDataGateway = class {
42548
42112
  // and the spread above would otherwise drop the field silently — which is
42549
42113
  // exactly what it did, leaving the whole control inert on every device
42550
42114
  // while every test around it stayed green.
42115
+ //
42116
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
42117
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
42118
+ // reads this bundle once to build detection, so the detections it carries
42119
+ // apply to every event on the machine. Where a prohibition applies is
42120
+ // answered per event by `governanceAppliesTo` below.
42551
42121
  prohibitedModels: cached2.prohibitedModels,
42552
42122
  // NAMED for the same reason as the line above, and it is the same defect
42553
42123
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -42607,6 +42177,30 @@ var AttachedDataGateway = class {
42607
42177
  };
42608
42178
  }
42609
42179
  // ---------------------------------------------------------------------
42180
+ // GovernanceScope — where the organization's model policy applies
42181
+ // ---------------------------------------------------------------------
42182
+ /**
42183
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
42184
+ * the question a model-guard site asks once it has decided to refuse.
42185
+ *
42186
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
42187
+ * with the same key would be forwarded. A machine-wide attachment governs
42188
+ * every event, keyless included, exactly as before. A scoped one governs an
42189
+ * event only when its key names an enrolled repository. An event in a
42190
+ * personal repository, in no repository, with an empty key, or met by a fault
42191
+ * is not governed.
42192
+ *
42193
+ * The event's OWN key, never its session root's. The root rule in
42194
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
42195
+ * this decides whether a refusal applies, which is a question about where the
42196
+ * event happened.
42197
+ *
42198
+ * Answered from memory: no store read, no bundle read, nothing sent.
42199
+ */
42200
+ governanceAppliesTo(scopeKey) {
42201
+ return this.verdictFor(() => scopeKey) === "forward";
42202
+ }
42203
+ // ---------------------------------------------------------------------
42610
42204
  // LocalStoreMaintenance — by delegation (D3).
42611
42205
  //
42612
42206
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -42715,14 +42309,15 @@ function toWireInspection(insp) {
42715
42309
  }
42716
42310
 
42717
42311
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42718
- import { createHash as createHash6 } from "crypto";
42719
- import { hostname as hostname5 } from "os";
42312
+ import { createHash as createHash7 } from "crypto";
42313
+ import { hostname as hostname4 } from "os";
42720
42314
 
42721
42315
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
42722
42316
  var CORRELATION_ID = EventMetadata.shape.correlationId;
42723
42317
  var TRACE_ID = EventMetadata.shape.traceId;
42724
42318
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
42725
42319
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
42320
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
42726
42321
 
42727
42322
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42728
42323
  var CAPTURE_BATCH_BYTES = 1024 * 1024;
@@ -42734,17 +42329,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
42734
42329
 
42735
42330
  // ../../packages/plugin-runtime/src/attached/install-record.ts
42736
42331
  import { readFile as readFile2, stat } from "fs/promises";
42737
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
42332
+ import { basename as basename3, dirname as dirname5, join as join24, resolve as resolve2 } from "path";
42738
42333
  async function readInstalledVersion(installRoot) {
42739
42334
  try {
42740
42335
  const versionDir = resolve2(installRoot);
42741
- const pluginDir = dirname7(versionDir);
42742
- const marketplaceDir = dirname7(pluginDir);
42743
- const cacheDir = dirname7(marketplaceDir);
42744
- if (basename6(cacheDir) !== "cache") return null;
42745
- const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
42336
+ const pluginDir = dirname5(versionDir);
42337
+ const marketplaceDir = dirname5(pluginDir);
42338
+ const cacheDir = dirname5(marketplaceDir);
42339
+ if (basename3(cacheDir) !== "cache") return null;
42340
+ const key = `${basename3(pluginDir)}@${basename3(marketplaceDir)}`;
42746
42341
  const record2 = JSON.parse(
42747
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
42342
+ await readFile2(join24(dirname5(cacheDir), "installed_plugins.json"), "utf8")
42748
42343
  );
42749
42344
  const plugins = record2?.plugins;
42750
42345
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -42776,7 +42371,7 @@ async function exists(path) {
42776
42371
  }
42777
42372
 
42778
42373
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
42779
- import { readFileSync as readFileSync18 } from "fs";
42374
+ import { readFileSync as readFileSync16 } from "fs";
42780
42375
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
42781
42376
  function createPluginBlock(build, policyStore) {
42782
42377
  return async () => {
@@ -42804,9 +42399,9 @@ async function readInstalledVersionBounded(installRoot) {
42804
42399
  }
42805
42400
 
42806
42401
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42807
- import { randomUUID as randomUUID18 } from "crypto";
42402
+ import { randomUUID as randomUUID17 } from "crypto";
42808
42403
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42809
- import { join as join30 } from "path";
42404
+ import { join as join25 } from "path";
42810
42405
 
42811
42406
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
42812
42407
  import { rename as rename2 } from "fs/promises";
@@ -42835,7 +42430,7 @@ async function publishByRename(tmp, file2, move = rename2) {
42835
42430
 
42836
42431
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42837
42432
  function createPolicyStore(dir = dataDir()) {
42838
- const file2 = join30(dir, "policy-cache.json");
42433
+ const file2 = join25(dir, "policy-cache.json");
42839
42434
  async function read() {
42840
42435
  try {
42841
42436
  const raw = await readFile3(file2, "utf8");
@@ -42867,7 +42462,7 @@ function createPolicyStore(dir = dataDir()) {
42867
42462
  }
42868
42463
  }
42869
42464
  async function publishRecord(record2) {
42870
- const tmp = `${file2}.${randomUUID18()}.tmp`;
42465
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
42871
42466
  try {
42872
42467
  await writeFile2(tmp, JSON.stringify(record2), {
42873
42468
  encoding: "utf8",
@@ -42905,8 +42500,8 @@ function createPolicyStore(dir = dataDir()) {
42905
42500
  }
42906
42501
 
42907
42502
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
42908
- import { readFileSync as readFileSync19 } from "fs";
42909
- import { join as join31 } from "path";
42503
+ import { readFileSync as readFileSync17 } from "fs";
42504
+ import { join as join26 } from "path";
42910
42505
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
42911
42506
  var OUTCOME_KEYS = {
42912
42507
  ok: true,
@@ -42920,7 +42515,7 @@ var OUTCOME_KEYS = {
42920
42515
  };
42921
42516
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
42922
42517
  function postureReportStatePath(dataDir2) {
42923
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42518
+ return join26(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42924
42519
  }
42925
42520
  function writePostureReportState(dataDir2, state) {
42926
42521
  try {
@@ -42961,10 +42556,19 @@ function createPostureReporter(deps) {
42961
42556
  hostname: deps.hostname(),
42962
42557
  capturedAt: nowMs,
42963
42558
  ...measurement,
42964
- // Omit the key rather than spread an explicit `undefined` —
42965
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
42966
- // factory.ts keys on presence.
42967
- ...plugin === void 0 ? {} : { plugin }
42559
+ // Omit the key rather than spread an explicit `undefined`. The type
42560
+ // admits `undefined` here (the schema's optional member), and
42561
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
42562
+ // in-memory object free of an explicit `undefined` member, which the
42563
+ // tests pin by key presence.
42564
+ ...plugin === void 0 ? {} : { plugin },
42565
+ // LAST, and only for a scoped attachment. A machine attachment omits
42566
+ // the key the same way, so its body is byte for byte the one it sent
42567
+ // before the member existed. Anything but exactly `machine` reports the
42568
+ // constant `scoped`, never the raw value: that is resolveScope's own
42569
+ // fail direction, and a value outside the wire's vocabulary would fail
42570
+ // the whole snapshot at the receiver, the wipe signal with it.
42571
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
42968
42572
  };
42969
42573
  } catch {
42970
42574
  return null;
@@ -42987,8 +42591,8 @@ function createPostureReporter(deps) {
42987
42591
  }
42988
42592
 
42989
42593
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
42990
- import { statSync as statSync9 } from "fs";
42991
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
42594
+ import { statSync as statSync7 } from "fs";
42595
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
42992
42596
 
42993
42597
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
42994
42598
  function emptyActionCounts() {
@@ -43018,7 +42622,7 @@ function emptyReadout(readError = false) {
43018
42622
  }
43019
42623
  function readStorePosture(dbPath2) {
43020
42624
  try {
43021
- statSync9(dbPath2);
42625
+ statSync7(dbPath2);
43022
42626
  } catch (err) {
43023
42627
  const code = err.code;
43024
42628
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -43046,7 +42650,7 @@ function readStorePosture(dbPath2) {
43046
42650
  readError: false
43047
42651
  });
43048
42652
  try {
43049
- db = new DatabaseSync4(dbPath2, { readOnly: true });
42653
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
43050
42654
  db.exec("PRAGMA busy_timeout = 2000");
43051
42655
  version2 = db.prepare("PRAGMA user_version").get().user_version;
43052
42656
  try {
@@ -43098,16 +42702,16 @@ function readStorePosture(dbPath2) {
43098
42702
  }
43099
42703
 
43100
42704
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
43101
- import { randomUUID as randomUUID19 } from "crypto";
42705
+ import { randomUUID as randomUUID18 } from "crypto";
43102
42706
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
43103
- import { join as join32 } from "path";
42707
+ import { join as join27 } from "path";
43104
42708
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
43105
42709
  function createPostureStore(dir = settingsDir(), legacyDir) {
43106
- const file2 = join32(dir, "posture-state.json");
43107
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
42710
+ const file2 = join27(dir, "posture-state.json");
42711
+ const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
43108
42712
  async function persist(state) {
43109
42713
  await ensureDataDir(dir);
43110
- const tmp = `${file2}.${randomUUID19()}.tmp`;
42714
+ const tmp = `${file2}.${randomUUID18()}.tmp`;
43111
42715
  try {
43112
42716
  await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
43113
42717
  await publishByRename(tmp, file2);
@@ -43149,7 +42753,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
43149
42753
  }
43150
42754
  return legacy;
43151
42755
  }
43152
- const fresh = { deviceId: randomUUID19(), lastAttemptedAtMs: 0 };
42756
+ const fresh = { deviceId: randomUUID18(), lastAttemptedAtMs: 0 };
43153
42757
  try {
43154
42758
  await ensureDataDir(dir);
43155
42759
  if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
@@ -43172,8 +42776,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
43172
42776
  }
43173
42777
 
43174
42778
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
43175
- import { readFileSync as readFileSync20 } from "fs";
43176
- import { join as join33 } from "path";
42779
+ import { readFileSync as readFileSync18 } from "fs";
42780
+ import { join as join28 } from "path";
43177
42781
 
43178
42782
  // ../../packages/plugin-runtime/src/attached/status.ts
43179
42783
  var REFUSAL_LINES = {
@@ -43202,8 +42806,22 @@ import { spawn as spawn3 } from "child_process";
43202
42806
  import { fileURLToPath as fileURLToPath4 } from "url";
43203
42807
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
43204
42808
 
42809
+ // ../../packages/plugin-runtime/src/governance-scope.ts
42810
+ function offersGovernanceScope(gateway) {
42811
+ return typeof gateway.governanceAppliesTo === "function";
42812
+ }
42813
+ function governanceApplies(gateway, scopeKey) {
42814
+ try {
42815
+ if (!offersGovernanceScope(gateway)) return true;
42816
+ const answer = gateway.governanceAppliesTo(scopeKey);
42817
+ return answer === true;
42818
+ } catch {
42819
+ return false;
42820
+ }
42821
+ }
42822
+
43205
42823
  // ../../packages/plugin-runtime/src/attached/factory.ts
43206
- import { hostname as hostname6 } from "os";
42824
+ import { hostname as hostname5 } from "os";
43207
42825
 
43208
42826
  // ../../packages/plugin-runtime/src/recorder.ts
43209
42827
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -43216,7 +42834,7 @@ var StandaloneDataGateway = class {
43216
42834
  // One notice per gateway — see warnRulesetDiscarded.
43217
42835
  warnedRulesetDiscarded = false;
43218
42836
  constructor(dataDir2, detections = [], meta4) {
43219
- this.db = openLocalDatabase(dataDir2);
42837
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
43220
42838
  this.dataDir = dataDir2;
43221
42839
  this.db.installedPacks.recordInventory(detections, meta4);
43222
42840
  }
@@ -43565,6 +43183,9 @@ var StandaloneDataGateway = class {
43565
43183
  scanLedgerPaths() {
43566
43184
  return Promise.resolve(this.db.scanLedger.allPaths());
43567
43185
  }
43186
+ scanLedgerPathKeys() {
43187
+ return Promise.resolve(this.db.scanLedger.pathKeys());
43188
+ }
43568
43189
  recordScanned(entries) {
43569
43190
  this.db.scanLedger.upsertEntries(entries);
43570
43191
  return Promise.resolve();
@@ -43650,13 +43271,17 @@ function resolveGatewayForConfig(config2, meta4) {
43650
43271
  },
43651
43272
  store: postureStore,
43652
43273
  readStore: () => readStorePosture(config2.dbPath),
43653
- hostname: () => hostname6(),
43274
+ hostname: () => hostname5(),
43654
43275
  now: () => Date.now(),
43276
+ // The mode THIS gateway enforces, from the attachment resolved above,
43277
+ // so the report cannot name a mode the forward paths are not using.
43278
+ attachmentMode: attachment.mode,
43655
43279
  // The reporting build's identity, when the caller knows it (the plugin
43656
43280
  // adapters do; an embedder or a test may not). Composed with the SAME
43657
43281
  // policy store the sync child writes, so the block names the bundle
43658
- // actually in force. Key omitted rather than set undefined — the
43659
- // reporter keys on presence.
43282
+ // actually in force. The dependency key is omitted when no build is
43283
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
43284
+ // then adds no block.
43660
43285
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
43661
43286
  })
43662
43287
  });
@@ -43673,10 +43298,127 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
43673
43298
  }
43674
43299
 
43675
43300
  // ../../packages/plugin-runtime/src/handle-session-start.ts
43676
- import { randomUUID as randomUUID20 } from "crypto";
43301
+ import { randomUUID as randomUUID19 } from "crypto";
43677
43302
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
43678
43303
 
43304
+ // src/hooks/shared.ts
43305
+ import { isAbsolute as isAbsolute2, normalize, resolve as resolvePath } from "path";
43306
+ async function readStdin() {
43307
+ return new Promise((resolve3) => {
43308
+ let data = "";
43309
+ let settled = false;
43310
+ const finish = () => {
43311
+ if (settled) return;
43312
+ settled = true;
43313
+ clearTimeout(timer);
43314
+ process.stdin.removeListener("data", onData);
43315
+ process.stdin.removeListener("end", finish);
43316
+ resolve3(data);
43317
+ };
43318
+ const onData = (chunk) => {
43319
+ data += chunk;
43320
+ };
43321
+ const timer = setTimeout(finish, 5e3);
43322
+ process.stdin.setEncoding("utf8");
43323
+ process.stdin.on("data", onData);
43324
+ process.stdin.on("end", finish);
43325
+ process.stdin.on("error", finish);
43326
+ });
43327
+ }
43328
+ function parseJson(raw) {
43329
+ try {
43330
+ const parsed2 = JSON.parse(raw);
43331
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
43332
+ } catch {
43333
+ return null;
43334
+ }
43335
+ }
43336
+ function getString(record2, key) {
43337
+ const value = record2[key];
43338
+ return typeof value === "string" ? value : void 0;
43339
+ }
43340
+ function emit(output2) {
43341
+ return new Promise((resolve3) => {
43342
+ let settled = false;
43343
+ const finish = () => {
43344
+ if (settled) return;
43345
+ settled = true;
43346
+ resolve3();
43347
+ };
43348
+ process.stdout.on("error", finish);
43349
+ process.stdout.write(JSON.stringify(output2), finish);
43350
+ });
43351
+ }
43352
+ function baseMetadata(input2) {
43353
+ const metadata = {};
43354
+ const sessionId = getString(input2, "session_id");
43355
+ if (sessionId) metadata.sessionId = sessionId;
43356
+ const repo = resolveRepoAttribution(getString(input2, "cwd") ?? process.cwd()).repo;
43357
+ if (repo) metadata.repo = repo;
43358
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
43359
+ }
43360
+ function captureScopeKey(input2, filePath) {
43361
+ try {
43362
+ if (filePath === void 0 || filePath === "") {
43363
+ return resolveRepoAttribution(getString(input2, "cwd") ?? process.cwd()).scopeKey;
43364
+ }
43365
+ if (isAbsolute2(filePath)) return resolveRepoAttribution(normalize(filePath)).scopeKey;
43366
+ const cwd = getString(input2, "cwd") ?? process.cwd();
43367
+ if (!isAbsolute2(cwd)) return void 0;
43368
+ return resolveRepoAttribution(resolvePath(cwd, filePath)).scopeKey;
43369
+ } catch {
43370
+ return void 0;
43371
+ }
43372
+ }
43373
+ function countFailOpen(base) {
43374
+ try {
43375
+ recordHookFailOpen(dataDir(base), Date.now());
43376
+ } catch {
43377
+ }
43378
+ }
43379
+
43380
+ // src/hooks/model-guard.ts
43381
+ function resolveCodexSessionModel(dataDir2, sessionId, transcriptPath) {
43382
+ return readSessionModel(dataDir2, sessionId) ?? modelFromTranscriptTail(transcriptPath, codexModelFromRecord);
43383
+ }
43384
+ async function refuseProhibitedTurn(gateway, dataDir2, sessionId, transcriptPath) {
43385
+ try {
43386
+ const { prohibitedModels } = await gateway.getPolicyBundle();
43387
+ if (prohibitedModels === void 0 || prohibitedModels.length === 0) return null;
43388
+ const model = resolveCodexSessionModel(dataDir2, sessionId, transcriptPath);
43389
+ const decision = decideProhibitedModelTurn(model, prohibitedModels);
43390
+ return decision === null || model === void 0 ? null : { decision, model };
43391
+ } catch {
43392
+ return null;
43393
+ }
43394
+ }
43395
+ async function handleProhibitedTurn(gateway, dataDir2, sessionId, transcriptPath, cwd, emit2) {
43396
+ const blocked = await refuseProhibitedTurn(gateway, dataDir2, sessionId, transcriptPath);
43397
+ if (blocked === null) return false;
43398
+ const scopeKey = captureScopeKey({ cwd });
43399
+ if (!governanceApplies(gateway, scopeKey)) return false;
43400
+ try {
43401
+ await gateway.recordAuditEvent(
43402
+ buildModelRefusalEvent({
43403
+ id: randomUUID20(),
43404
+ sessionId,
43405
+ model: blocked.model,
43406
+ seam: "turn",
43407
+ sourceTool: SOURCE_TOOL.Codex,
43408
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
43409
+ scopeKey
43410
+ })
43411
+ );
43412
+ } catch {
43413
+ }
43414
+ await gateway.close();
43415
+ await emit2(blocked.decision);
43416
+ return true;
43417
+ }
43418
+
43679
43419
  // src/hooks/store-health.ts
43420
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync19, writeFileSync as writeFileSync7 } from "fs";
43421
+ import { dirname as dirname6, join as join29 } from "path";
43680
43422
  var STORE_WARNING_MARKER = "store-warning-last-session";
43681
43423
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
43682
43424
  function openGateway(config2) {
@@ -43703,12 +43445,12 @@ function claimStoreUnavailableWarning(dataDir2, sessionId) {
43703
43445
  return true;
43704
43446
  }
43705
43447
  function markerDirs(dataDir2) {
43706
- return [dataDir2, dirname8(dataDir2)];
43448
+ return [dataDir2, dirname6(dataDir2)];
43707
43449
  }
43708
43450
  function alreadyClaimed(dirs, marker, sessionId) {
43709
43451
  return dirs.some((dir) => {
43710
43452
  try {
43711
- return readFileSync21(join34(dir, marker), "utf8") === sessionId;
43453
+ return readFileSync19(join29(dir, marker), "utf8") === sessionId;
43712
43454
  } catch {
43713
43455
  return false;
43714
43456
  }
@@ -43717,14 +43459,14 @@ function alreadyClaimed(dirs, marker, sessionId) {
43717
43459
  function recordClaim(dirs, marker, sessionId) {
43718
43460
  for (const dir of dirs) {
43719
43461
  try {
43720
- mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
43721
- writeFileSync8(join34(dir, marker), sessionId, { mode: DATA_FILE_MODE });
43462
+ mkdirSync4(dir, { recursive: true, mode: DATA_DIR_MODE });
43463
+ writeFileSync7(join29(dir, marker), sessionId, { mode: DATA_FILE_MODE });
43722
43464
  return;
43723
43465
  } catch {
43724
43466
  }
43725
43467
  }
43726
43468
  }
43727
- function storeRedirectedMessage(paths, platform2 = process.platform) {
43469
+ function storeRedirectedMessage(paths, platform = process.platform) {
43728
43470
  const where = paths.map(({ path, target, holds, missing, mode }) => {
43729
43471
  if (missing) return `${path} -> ${target} (which does not exist; ${holds} cannot land there)`;
43730
43472
  const loose = mode !== void 0 && (mode & 63) !== 0 ? ", NOT owner-only" : "";
@@ -43734,7 +43476,7 @@ function storeRedirectedMessage(paths, platform2 = process.platform) {
43734
43476
  const subject = paths.length === 1 ? "a store path is a symlink" : `${String(paths.length)} store paths are symlinks`;
43735
43477
  const anyResolves = paths.some(({ missing }) => !missing);
43736
43478
  const lead = anyResolves ? `${subject}, so AKA is writing into the target instead: ${where}. ` : `${subject} resolving nowhere, so AKA cannot write there: ${where}. `;
43737
- const kept = anyResolves && platform2 !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
43479
+ const kept = anyResolves && platform !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
43738
43480
  return `[aka] ${lead}${kept}If you did not create that link, treat it as untrusted and run \`aka init\` for the full report.
43739
43481
  `;
43740
43482
  }
@@ -43743,7 +43485,7 @@ function formatMode(mode) {
43743
43485
  }
43744
43486
  function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
43745
43487
  try {
43746
- const paths = symlinkedStorePaths(dirname8(config2.dataDir));
43488
+ const paths = symlinkedStorePaths(dirname6(config2.dataDir));
43747
43489
  if (paths.length === 0) return;
43748
43490
  if (!sessionId) {
43749
43491
  write(storeRedirectedMessage(paths));
@@ -43757,6 +43499,79 @@ function warnIfStoreRedirected(config2, sessionId, write = (message) => void pro
43757
43499
  }
43758
43500
  }
43759
43501
 
43502
+ // src/present.ts
43503
+ var fg = (hex3) => (text) => {
43504
+ const r = Number.parseInt(hex3.slice(1, 3), 16);
43505
+ const g = Number.parseInt(hex3.slice(3, 5), 16);
43506
+ const b = Number.parseInt(hex3.slice(5, 7), 16);
43507
+ return `\x1B[38;2;${String(r)};${String(g)};${String(b)}m${text}\x1B[0m`;
43508
+ };
43509
+ var paint = {
43510
+ brand: fg("#33e6c6"),
43511
+ // --color-brand · ▸▸ AKA wordmark (accent text)
43512
+ dim: fg("#838995"),
43513
+ // --color-text-3 · separators · "/100" · the "unreviewed" label
43514
+ bold: (text) => `\x1B[1m${text}\x1B[0m`,
43515
+ // the health score number
43516
+ ok: fg("#0db15f"),
43517
+ // --color-ok · healthy ● dot
43518
+ critical: fg("#e63448"),
43519
+ // --color-sev-critical · ■ and the open-findings flag
43520
+ high: fg("#e97a0a"),
43521
+ // --color-sev-high · ■ and the mid-health dot
43522
+ medium: fg("#f7bd00"),
43523
+ // --color-sev-medium · ■
43524
+ low: fg("#0581d4")
43525
+ // --color-sev-low · ■ (azure blue, not purple)
43526
+ };
43527
+
43528
+ // src/exception-guidance.ts
43529
+ function blockMessage(input2) {
43530
+ const preview = input2.blockedRef ? ` (${input2.blockedRef.maskedValue})` : "";
43531
+ const commands = input2.blockedRef ? [
43532
+ ` aka exception approve ${input2.blockedRef.reference} (asks for scope + reason, then resubmit)`,
43533
+ " aka exception approve <value> (same flow, pasting the blocked value itself)"
43534
+ ] : [" aka exception approve (asks for scope + reason, then resubmit)"];
43535
+ const note = input2.note ? ` ${input2.note}` : "";
43536
+ return [
43537
+ `AKA blocked this ${input2.subject} \u2014 flagged ${input2.ruleIds}${preview}.${note} Remove the flagged content and resubmit.`,
43538
+ "If this is intentional and you accept the risk, grant an exception:",
43539
+ ...commands,
43540
+ "More: aka exception --help"
43541
+ ].join("\n");
43542
+ }
43543
+ function tooLargeToScanMessage(subject) {
43544
+ return `This ${subject} is too large for AKA to scan within the time limit, so it was blocked. Shorten it or send it in smaller parts.`;
43545
+ }
43546
+ function exceptionPointer(references) {
43547
+ const ref = references?.[0];
43548
+ if (ref === void 0) return "";
43549
+ return ` To allow this exact value intentionally, run: aka exception approve ${ref.reference}.`;
43550
+ }
43551
+
43552
+ // src/hooks/user-prompt-submit-decision.ts
43553
+ function decideUserPromptSubmit(result) {
43554
+ if (result.scanIncomplete !== void 0) {
43555
+ return { decision: "block", reason: tooLargeToScanMessage("prompt") };
43556
+ }
43557
+ if (result.action === "block" || result.action === "redact") {
43558
+ return {
43559
+ decision: "block",
43560
+ reason: blockMessage({
43561
+ subject: "prompt",
43562
+ ruleIds: uniqueRuleIds(result.findings),
43563
+ blockedRef: result.blockedReferences?.[0]
43564
+ })
43565
+ };
43566
+ }
43567
+ if (result.action === "warn") {
43568
+ return {
43569
+ systemMessage: `AKA flagged sensitive content (${uniqueRuleIds(result.findings)}) \u2014 sent unchanged.${exceptionPointer(result.blockedReferences)}`
43570
+ };
43571
+ }
43572
+ return null;
43573
+ }
43574
+
43760
43575
  // src/hooks/user-prompt-submit.ts
43761
43576
  async function main() {
43762
43577
  const input2 = parseJson(await readStdin());
@@ -43785,7 +43600,10 @@ async function main() {
43785
43600
  )) {
43786
43601
  return;
43787
43602
  }
43788
- const runtime = createPluginRuntime(gateway, config2.settings, { dataDir: config2.dataDir });
43603
+ const runtime = createPluginRuntime(gateway, config2.settings, {
43604
+ dataDir: config2.dataDir,
43605
+ largeInput: largeInputBound(HOOK_SCAN_DEADLINE_MS)
43606
+ });
43789
43607
  let result;
43790
43608
  try {
43791
43609
  result = await runtime.capture({
@@ -43798,21 +43616,9 @@ async function main() {
43798
43616
  } finally {
43799
43617
  await runtime.close();
43800
43618
  }
43801
- if (result.action === "block" || result.action === "redact") {
43802
- await emit({
43803
- decision: "block",
43804
- reason: blockMessage({
43805
- subject: "prompt",
43806
- ruleIds: uniqueRuleIds(result.findings),
43807
- blockedRef: result.blockedReferences?.[0]
43808
- })
43809
- });
43810
- return;
43811
- }
43812
- if (result.action === "warn") {
43813
- await emit({
43814
- systemMessage: `AKA flagged sensitive content (${uniqueRuleIds(result.findings)}) \u2014 sent unchanged.${exceptionPointer(result.blockedReferences)}`
43815
- });
43619
+ const decision = decideUserPromptSubmit(result);
43620
+ if (decision !== null) {
43621
+ await emit(decision);
43816
43622
  return;
43817
43623
  }
43818
43624
  if (!config2.onboarded && claimOnboardingNudge(config2.dataDir, sessionId)) {