@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,891 +1,14 @@
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 SLASH2 = "/";
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
- SLASH2
293
- ],
294
- // replace special metacharacter slash after the leading slash
295
- [
296
- /\//g,
297
- () => "\\/",
298
- SLASH2
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 === SLASH2 ? `${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] === SLASH2) {
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(SLASH2);
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
- SLASH2,
559
- path[end] === SLASH2 ? 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(SLASH2).filter(Boolean);
566
- slices.pop();
567
- return slices.length ? slices.join(SLASH2) + SLASH2 : EMPTY;
568
- }
569
- const end = path.length - 1;
570
- const cut = path.lastIndexOf(
571
- SLASH2,
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] === SLASH2 ? 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
  // src/apply-suppressions.ts
876
- import { existsSync as existsSync13, readFileSync as readFileSync20 } from "fs";
8
+ import { existsSync as existsSync9, readFileSync as readFileSync14 } from "fs";
877
9
  import { userInfo } from "os";
878
- import { dirname as dirname9, join as join31 } from "path";
879
- import { fileURLToPath as fileURLToPath4 } from "url";
880
-
881
- // ../../packages/persistence/src/attached-derived.ts
882
- import { rmSync } from "fs";
883
- import { join } from "path";
884
- var POLICY_CACHE_FILENAME = "policy-cache.json";
885
-
886
- // ../../packages/persistence/src/control-plane-credential.ts
887
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
888
- import { join as join2 } from "path";
10
+ import { dirname as dirname6, join as join22 } from "path";
11
+ import { fileURLToPath as fileURLToPath3 } from "url";
889
12
 
890
13
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
891
14
  var DEFERRED_MIGRATION_TAGS = [
@@ -1057,6 +180,12 @@ var HOUR_MS = 60 * MINUTE_MS;
1057
180
  var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1058
181
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1059
182
 
183
+ // ../../packages/schema/src/invisible-padding.ts
184
+ 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;
185
+ function stripInvisiblePadding(text) {
186
+ return text.replace(INVISIBLE_PADDING, "");
187
+ }
188
+
1060
189
  // ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
1061
190
  var external_exports = {};
1062
191
  __export(external_exports, {
@@ -3870,9 +2999,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3870
2999
  function stripTabAndNewline(value) {
3871
3000
  return value.replace(asciiTabOrNewline, "");
3872
3001
  }
3873
- function urlHostnameOk(url2, hostname5) {
3874
- hostname5.lastIndex = 0;
3875
- return hostname5.test(url2.hostname);
3002
+ function urlHostnameOk(url2, hostname4) {
3003
+ hostname4.lastIndex = 0;
3004
+ return hostname4.test(url2.hostname);
3876
3005
  }
3877
3006
  function urlProtocolOk(url2, protocol) {
3878
3007
  protocol.lastIndex = 0;
@@ -20792,13 +19921,16 @@ function serviceTierMultiplier(tier) {
20792
19921
  if (tier === void 0) return 1;
20793
19922
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20794
19923
  }
19924
+ function promptTokensOf(usage) {
19925
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19926
+ }
20795
19927
  function costOf(price, usage) {
20796
19928
  const metered = [
20797
19929
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20798
19930
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20799
19931
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20800
19932
  ];
20801
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19933
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20802
19934
  if (band !== null && (band.input === null || band.output === null)) return null;
20803
19935
  const inputRate = band?.input ?? price.input;
20804
19936
  const outputRate = band?.output ?? price.output;
@@ -20871,8 +20003,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20871
20003
  ["ollama", "local"],
20872
20004
  ["local", "local"]
20873
20005
  ]);
20874
- function hostingFor(platform2) {
20875
- return PLATFORM_HOSTING.get(platform2) ?? "api";
20006
+ function hostingFor(platform) {
20007
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20876
20008
  }
20877
20009
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20878
20010
  ["anthropic", "anthropic"],
@@ -20886,8 +20018,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20886
20018
  function firstPartyPlatformFor(vendor2) {
20887
20019
  return FIRST_PARTY.get(vendor2) ?? null;
20888
20020
  }
20889
- function isFirstParty(vendor2, platform2) {
20890
- return FIRST_PARTY.get(vendor2) === platform2;
20021
+ function isFirstParty(vendor2, platform) {
20022
+ return FIRST_PARTY.get(vendor2) === platform;
20891
20023
  }
20892
20024
  var PLATFORM_NAMESPACES = Object.freeze([
20893
20025
  "anthropic",
@@ -20948,14 +20080,14 @@ var ModelVendorBuilder = class {
20948
20080
  );
20949
20081
  }
20950
20082
  for (const ref of spec.on ?? []) {
20951
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20952
- const firstParty = isFirstParty(this.vendor, platform2);
20953
- const hosting = hostingFor(platform2);
20083
+ const { platform, price, retention, region } = normalizeRef(ref);
20084
+ const firstParty = isFirstParty(this.vendor, platform);
20085
+ const hosting = hostingFor(platform);
20954
20086
  const isSelfHosted = hosting === "local";
20955
20087
  platforms.set(
20956
- platform2,
20088
+ platform,
20957
20089
  Object.freeze({
20958
- platform: platform2,
20090
+ platform,
20959
20091
  hosting,
20960
20092
  firstParty,
20961
20093
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21008,35 +20140,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21008
20140
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21009
20141
  var BEDROCK_REVISION_RE = /:\d+$/u;
21010
20142
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21011
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20143
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21012
20144
  function stripPlatformDecorations(model) {
21013
20145
  let id = model.trim();
21014
- let platform2 = null;
20146
+ let platform = null;
21015
20147
  if (GEO_PREFIX_RE.test(id)) {
21016
20148
  id = id.replace(GEO_PREFIX_RE, "");
21017
- platform2 = "bedrock";
20149
+ platform = "bedrock";
21018
20150
  }
21019
20151
  if (NAMESPACE_DOT_RE.test(id)) {
21020
20152
  id = id.replace(NAMESPACE_DOT_RE, "");
21021
- platform2 ??= "bedrock";
20153
+ platform ??= "bedrock";
21022
20154
  }
21023
20155
  if (BEDROCK_VERSION_RE.test(id)) {
21024
20156
  id = id.replace(BEDROCK_VERSION_RE, "");
21025
- platform2 ??= "bedrock";
20157
+ platform ??= "bedrock";
21026
20158
  } else if (BEDROCK_REVISION_RE.test(id)) {
21027
20159
  id = id.replace(BEDROCK_REVISION_RE, "");
21028
- platform2 ??= "bedrock";
20160
+ platform ??= "bedrock";
21029
20161
  }
21030
20162
  if (VERTEX_VERSION_RE.test(id)) {
21031
20163
  id = id.replace(VERTEX_VERSION_RE, "");
21032
- platform2 ??= "vertex";
20164
+ platform ??= "vertex";
21033
20165
  }
21034
20166
  if (NAMESPACE_SLASH_RE.test(id)) {
21035
20167
  id = id.replace(NAMESPACE_SLASH_RE, "");
21036
20168
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21037
20169
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21038
20170
  }
21039
- return { id, platform: platform2 };
20171
+ return { id, platform };
21040
20172
  }
21041
20173
  function buildModelIndex(entries) {
21042
20174
  const byId = /* @__PURE__ */ new Map();
@@ -21053,19 +20185,19 @@ function resolveModel(raw, index) {
21053
20185
  if (exact !== void 0) {
21054
20186
  return { entry: exact, canonicalId: raw, platform: null, raw };
21055
20187
  }
21056
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
20188
+ const { id, platform } = stripPlatformDecorations(raw);
21057
20189
  const stripped = index.byId.get(id);
21058
20190
  if (stripped !== void 0) {
21059
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
20191
+ return { entry: stripped, canonicalId: id, platform, raw };
21060
20192
  }
21061
20193
  if (DATED_SUFFIX_RE.test(id)) {
21062
20194
  const undated = id.replace(DATED_SUFFIX_RE, "");
21063
20195
  const byDate = index.byId.get(undated);
21064
20196
  if (byDate !== void 0) {
21065
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
20197
+ return { entry: byDate, canonicalId: undated, platform, raw };
21066
20198
  }
21067
20199
  }
21068
- return { entry: null, canonicalId: raw, platform: platform2, raw };
20200
+ return { entry: null, canonicalId: raw, platform, raw };
21069
20201
  }
21070
20202
 
21071
20203
  // ../../packages/schema/src/model/catalog.ts
@@ -21158,7 +20290,7 @@ anthropic.model("claude-haiku-4-5", {
21158
20290
  name: "Claude Haiku 4.5",
21159
20291
  ctx: 2e5,
21160
20292
  maxOut: 64e3,
21161
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20293
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21162
20294
  capability: null,
21163
20295
  price: anthropicPrice(1, 5, 0.1),
21164
20296
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21289,6 +20421,11 @@ openai.model("gpt-4o", {
21289
20421
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21290
20422
  on: [...OPENAI_RESELLERS]
21291
20423
  });
20424
+ openai.model("gpt-4o-2024-05-13", {
20425
+ name: "GPT-4o (2024-05-13)",
20426
+ price: tokenPrice(5, 15),
20427
+ on: [...OPENAI_RESELLERS]
20428
+ });
21292
20429
  openai.model("gpt-4o-mini", {
21293
20430
  name: "GPT-4o mini",
21294
20431
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21308,6 +20445,24 @@ openai.model("o3", {
21308
20445
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21309
20446
  on: [...OPENAI_RESELLERS]
21310
20447
  });
20448
+ openai.model("text-embedding-3-small", {
20449
+ name: "text-embedding-3-small",
20450
+ capability: "embedding",
20451
+ price: tokenPrice(0.02, 0),
20452
+ on: [...OPENAI_RESELLERS]
20453
+ });
20454
+ openai.model("text-embedding-3-large", {
20455
+ name: "text-embedding-3-large",
20456
+ capability: "embedding",
20457
+ price: tokenPrice(0.13, 0),
20458
+ on: [...OPENAI_RESELLERS]
20459
+ });
20460
+ openai.model("text-embedding-ada-002", {
20461
+ name: "text-embedding-ada-002",
20462
+ capability: "embedding",
20463
+ price: tokenPrice(0.1, 0),
20464
+ on: [...OPENAI_RESELLERS]
20465
+ });
21311
20466
  openai.model("gpt-oss-120b", {
21312
20467
  name: "GPT-OSS 120B",
21313
20468
  openWeights: true,
@@ -21594,10 +20749,21 @@ var MODEL_ENTRIES = Object.freeze([
21594
20749
  ...alibaba.models(),
21595
20750
  ...amazon.models()
21596
20751
  ]);
20752
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20753
+ [
20754
+ ...new Set(
20755
+ MODEL_ENTRIES.flatMap(
20756
+ (entry) => [...entry.platforms.values()].flatMap(
20757
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20758
+ )
20759
+ )
20760
+ )
20761
+ ].sort((a, b) => a - b)
20762
+ );
21597
20763
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21598
20764
 
21599
20765
  // ../../packages/schema/src/model/governance.ts
21600
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20766
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21601
20767
  var DataRetention = external_exports.enum([
21602
20768
  "zero_retention",
21603
20769
  "no_storage",
@@ -21693,16 +20859,16 @@ function platformForProvider(provider) {
21693
20859
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21694
20860
  }
21695
20861
  function isLocalProvider(provider) {
21696
- const platform2 = platformForProvider(provider);
21697
- return platform2 !== null && hostingFor(platform2) === "local";
20862
+ const platform = platformForProvider(provider);
20863
+ return platform !== null && hostingFor(platform) === "local";
21698
20864
  }
21699
20865
  function priceFor(provider, model) {
21700
20866
  if (isLocalProvider(provider)) return ZERO_PRICE;
21701
20867
  const resolved = resolveModel(model, MODEL_INDEX);
21702
20868
  if (resolved.entry === null) return null;
21703
- const platform2 = resolved.platform ?? platformForProvider(provider);
21704
- if (platform2 === null) return null;
21705
- return resolved.entry.platforms.get(platform2)?.price ?? null;
20869
+ const platform = resolved.platform ?? platformForProvider(provider);
20870
+ if (platform === null) return null;
20871
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21706
20872
  }
21707
20873
  var defaultCostModel = {
21708
20874
  normalizeModelId(provider, model) {
@@ -21728,7 +20894,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21728
20894
 
21729
20895
  // ../../packages/schema/src/token/token-report.ts
21730
20896
  var num = (value) => value ?? 0;
21731
- function costUsageOf(a) {
20897
+ function costUsageOf(a, promptTokens) {
21732
20898
  const usage = {
21733
20899
  inputTokens: num(a.input_tokens),
21734
20900
  outputTokens: num(a.output_tokens),
@@ -21738,11 +20904,12 @@ function costUsageOf(a) {
21738
20904
  webSearchRequests: num(a.web_search_requests)
21739
20905
  };
21740
20906
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20907
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21741
20908
  return usage;
21742
20909
  }
21743
20910
  function buildTokenReports(leaves, costModel) {
21744
20911
  const bySession = /* @__PURE__ */ new Map();
21745
- for (const { sessionId, attributes } of leaves) {
20912
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21746
20913
  const provider = attributes.provider ?? "unknown";
21747
20914
  const model = attributes.model ?? "unknown";
21748
20915
  const key = `${provider} ${model}`;
@@ -21761,7 +20928,8 @@ function buildTokenReports(leaves, costModel) {
21761
20928
  cacheCreation: 0,
21762
20929
  cacheRead: 0,
21763
20930
  costUsd: 0,
21764
- priced: false
20931
+ priced: false,
20932
+ partial: false
21765
20933
  };
21766
20934
  rollups.set(key, acc);
21767
20935
  }
@@ -21769,8 +20937,14 @@ function buildTokenReports(leaves, costModel) {
21769
20937
  acc.output += num(attributes.output_tokens);
21770
20938
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21771
20939
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21772
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21773
- if (leafCost !== null) {
20940
+ const leafCost = costModel.costFor({
20941
+ provider,
20942
+ model,
20943
+ usage: costUsageOf(attributes, promptTokens)
20944
+ });
20945
+ if (leafCost === null) {
20946
+ acc.partial = true;
20947
+ } else {
21774
20948
  acc.costUsd += leafCost;
21775
20949
  acc.priced = true;
21776
20950
  }
@@ -21786,9 +20960,8 @@ function buildTokenReports(leaves, costModel) {
21786
20960
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21787
20961
  totalTokens += rollupTotal;
21788
20962
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21789
- if (estimatedCostUsd === null) {
21790
- anyUnpriced = true;
21791
- } else {
20963
+ if (acc.partial) anyUnpriced = true;
20964
+ if (estimatedCostUsd !== null) {
21792
20965
  anyPriced = true;
21793
20966
  costUsd += estimatedCostUsd;
21794
20967
  }
@@ -21811,7 +20984,7 @@ function buildTokenReports(leaves, costModel) {
21811
20984
  totalTokens,
21812
20985
  // Σ of the PRICED rollups; null when none had a known price.
21813
20986
  estimatedCostUsd: anyPriced ? costUsd : null,
21814
- // Any unknown (provider, model) means the total understates real spend.
20987
+ // Any call priced to null means the total understates real spend.
21815
20988
  costIsPartial: anyUnpriced
21816
20989
  });
21817
20990
  }
@@ -22513,6 +21686,11 @@ var CaptureAttributes = external_exports.object({
22513
21686
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22514
21687
  // repeated rather than referenced because a store reader opens this file.
22515
21688
  redact_degraded_to: ActionTaken.optional(),
21689
+ // Why a capture has no content and no findings: its field was refused
21690
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
21691
+ // whose value this is). Absent on every capture that was scanned, so a
21692
+ // reader can tell a refused row from an empty clean one.
21693
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22516
21694
  // The scope key this capture was stamped with: the canonical repository
22517
21695
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22518
21696
  // against its working directory), else of its own working directory, or a
@@ -22690,8 +21868,9 @@ var SessionTokenReport = external_exports.object({
22690
21868
  totalTokens: external_exports.number().int().nonnegative(),
22691
21869
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22692
21870
  estimatedCostUsd: external_exports.number().nullable(),
22693
- // True whenever any rollup has a null cost (unknown provider/model), so the
22694
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21871
+ // True whenever any call priced to null (an unknown provider/model, or a call
21872
+ // over a long-context threshold whose rate is unpublished), so the total
21873
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22695
21874
  // precise figure rather than silently dropping the unpriced calls.
22696
21875
  costIsPartial: external_exports.boolean()
22697
21876
  });
@@ -23540,7 +22719,15 @@ var StorePostureSnapshot = external_exports.object({
23540
22719
  policyCounts: StorePosturePolicyCounts,
23541
22720
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23542
22721
  // getting its 200 without a payload change.
23543
- plugin: StorePosturePlugin.optional()
22722
+ plugin: StorePosturePlugin.optional(),
22723
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22724
+ // machine attachment omits it, so its body is byte for byte the one it
22725
+ // sent before this member existed. Absent therefore means machine-wide OR
22726
+ // a reporter older than this member, never "scoped". Both values parse, so
22727
+ // a sender that one day spells `machine` breaks no receiver; any other
22728
+ // value fails the whole snapshot, which is why the reporter sends a
22729
+ // constant and never the raw mode.
22730
+ attachmentMode: AttachmentMode.optional()
23544
22731
  }).meta({ id: "StorePostureSnapshot" });
23545
22732
  var CAPTURE_VERSION_PREFIX = "capture/";
23546
22733
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23817,7 +23004,19 @@ var EventMetadata = external_exports.object({
23817
23004
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23818
23005
  // Closing either means moving the reason onto the finding row, which
23819
23006
  // already carries its own action.
23820
- redactDegradedTo: ActionTaken.optional()
23007
+ redactDegradedTo: ActionTaken.optional(),
23008
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23009
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23010
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23011
+ // field instead of letting it through unscanned.
23012
+ //
23013
+ // - 'timeout': the bounded scan ran out of time.
23014
+ // - 'unavailable': no worker could run it.
23015
+ //
23016
+ // A refused row stores '' as its content and has no findings, which is
23017
+ // exactly what a clean, empty capture looks like — this marker is the only
23018
+ // thing that tells the two apart. Absent on every capture that was scanned.
23019
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23821
23020
  }).meta({ id: "EventMetadata" });
23822
23021
  var Event = external_exports.object({
23823
23022
  id: external_exports.guid(),
@@ -23987,7 +23186,7 @@ var Rule = external_exports.strictObject({
23987
23186
  postValidators: external_exports.array(PostValidatorRef).optional(),
23988
23187
  requiresNearby: RequiresNearby.optional(),
23989
23188
  examples: external_exports.array(external_exports.string()).optional(),
23990
- // Whether the matched text is itself sensitive. Absent means 'value'.
23189
+ // Whether the matched text is itself sensitive (see RuleEvidence).
23991
23190
  evidence: RuleEvidence.optional()
23992
23191
  }).meta({ id: "Rule" });
23993
23192
  var Author = external_exports.object({
@@ -24079,7 +23278,13 @@ var DetectionRule = external_exports.object({
24079
23278
  // Representative matching strings the rule author shipped with the rule. The
24080
23279
  // cheapest honest answer to "show me what this rule catches" — every bundled
24081
23280
  // rule has them, and they are already in the stored snapshot.
24082
- examples: external_exports.array(external_exports.string()).optional()
23281
+ examples: external_exports.array(external_exports.string()).optional(),
23282
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23283
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23284
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23285
+ // in a value category (secret/pii/financial/phi) is always 'value',
23286
+ // whatever it declares.
23287
+ evidence: RuleEvidence.optional()
24083
23288
  }).meta({ id: "DetectionRule" });
24084
23289
  var DetectionUpdate = external_exports.object({
24085
23290
  available: external_exports.boolean(),
@@ -24147,8 +23352,10 @@ var ImportDetectionRequest = external_exports.object({
24147
23352
  }).meta({ id: "ImportDetectionRequest" });
24148
23353
 
24149
23354
  // ../../packages/schema/src/zod/detection-build.ts
24150
- function optional2(key, parsed, raw) {
24151
- if (raw === void 0 || !parsed.success || parsed.data === void 0) return {};
23355
+ function optional2(key, raw, parse4) {
23356
+ if (raw === void 0) return {};
23357
+ const parsed = parse4(raw);
23358
+ if (!parsed.success || parsed.data === void 0) return {};
24152
23359
  return { [key]: parsed.data };
24153
23360
  }
24154
23361
  function isStringArray(value) {
@@ -24183,10 +23390,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24183
23390
  category: r.category,
24184
23391
  severity: r.severity,
24185
23392
  matcher: parsed.data,
24186
- // The rest of what decides whether this rule fires. Carried so a consumer
24187
- // re-running the rule (a preview, a tester) evaluates what the engine
24188
- // evaluates rather than a matcher stripped of its guards — half the
24189
- // bundled catalog carries at least one of these.
23393
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23394
+ // decides whether this rule fires. Carried so a consumer re-running the
23395
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23396
+ // than a matcher stripped of its guards — half the bundled catalog
23397
+ // carries at least one of these. `examples` and `evidence` describe the
23398
+ // rule and never gate a match.
24190
23399
  //
24191
23400
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24192
23401
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24196,18 +23405,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24196
23405
  // test should stay exactly what it was, namely a renderable matcher. A
24197
23406
  // field that fails validation is omitted, which reads as "not set" and is
24198
23407
  // the same thing the consumer saw before this change.
24199
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23408
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24200
23409
  ...optional2(
24201
23410
  "postValidators",
24202
- PostValidatorRef.array().safeParse(r.postValidators),
24203
- r.postValidators
23411
+ r.postValidators,
23412
+ (v) => PostValidatorRef.array().safeParse(v)
24204
23413
  ),
24205
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23414
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24206
23415
  ...optional2(
24207
23416
  "examples",
24208
- { success: isStringArray(r.examples), data: r.examples },
24209
- r.examples
24210
- )
23417
+ r.examples,
23418
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23419
+ ),
23420
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24211
23421
  }
24212
23422
  ];
24213
23423
  });
@@ -24900,11 +24110,14 @@ var PolicyBundle = external_exports.object({
24900
24110
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24901
24111
  // Model ids (the raw `model` string a harness reports, e.g.
24902
24112
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24903
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24904
- // one (UserPromptSubmit). Optional so an older backend — and an older
24905
- // on-disk cache — still parses; consumers read `?? []`, which is the
24906
- // unenforced behaviour that predates this field and the safe direction to
24907
- // default.
24113
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24114
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24115
+ // wherever the organization governs the event: everywhere on a
24116
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24117
+ // one (the plugin runtime's `governanceApplies`).
24118
+ // Optional so an older backend — and an older on-disk cache — still
24119
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24120
+ // predates this field and the safe direction to default.
24908
24121
  //
24909
24122
  // Ids, not display names: the governance decision is keyed on the exact
24910
24123
  // string the harness reports (`model_status_override.versionId` in the
@@ -25287,6 +24500,8 @@ var AttachmentScopeEntry = external_exports.object({
25287
24500
  });
25288
24501
  var AttachmentScope = external_exports.object({
25289
24502
  endpoint: external_exports.string().min(1),
24503
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24504
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25290
24505
  entries: external_exports.array(AttachmentScopeEntry)
25291
24506
  });
25292
24507
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25491,6 +24706,7 @@ function toCaptureAttributes(event) {
25491
24706
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25492
24707
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25493
24708
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24709
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25494
24710
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25495
24711
  // has ever populated either), but every legacy metadata key still rides
25496
24712
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25619,6 +24835,27 @@ var ManagedSettings = external_exports.object({
25619
24835
  };
25620
24836
  }).meta({ id: "ManagedSettings" });
25621
24837
 
24838
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24839
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24840
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24841
+ var ModPolicySnapshot = external_exports.object({
24842
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24843
+ generatedAt: external_exports.iso.datetime(),
24844
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24845
+ // user's enabled installed packs (user-modified and custom packs included).
24846
+ // Absent means the store holds no authoritative snapshot, and the reader
24847
+ // scans with the packs it ships — the hook's own fallback.
24848
+ rules: external_exports.array(Rule).optional(),
24849
+ // Rule-targeted actions (first enabled policy per rule wins).
24850
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
24851
+ // The resolved action per detection category.
24852
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
24853
+ // Rules with an active exception grant. Honouring a grant means matching a
24854
+ // keyed fingerprint of the value and consuming a use, which only the hook can
24855
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
24856
+ exceptionRuleIds: external_exports.array(external_exports.string())
24857
+ }).meta({ id: "ModPolicySnapshot" });
24858
+
25622
24859
  // ../../packages/schema/src/zod/project-files.ts
25623
24860
  var ProjectFileInput = external_exports.object({
25624
24861
  path: external_exports.string().min(1),
@@ -25939,7 +25176,16 @@ var AttachInput = external_exports.object({
25939
25176
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
25940
25177
  // renders a longer one usefully.
25941
25178
  label: printable(200).optional(),
25942
- accessKey: external_exports.string()
25179
+ accessKey: external_exports.string(),
25180
+ // How much of this machine the attachment is for: everything, or only the
25181
+ // repositories its user enrolls. Optional, so an input without it still
25182
+ // parses; what an absent mode means is for whatever reads it to decide, not
25183
+ // this shape. This member validates the VALUE rather than leaving that to the
25184
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25185
+ // rejection names the field, so a value that is not a mode is refused as a bad
25186
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25187
+ // it as the mode to attach in.
25188
+ mode: AttachmentMode.optional()
25943
25189
  });
25944
25190
 
25945
25191
  // ../../packages/schema/src/zod/triage.ts
@@ -26225,6 +25471,15 @@ function fromCaptureStatusAttributes(bag) {
26225
25471
  return parsedStatus.success ? parsedStatus.data : null;
26226
25472
  }
26227
25473
 
25474
+ // ../../packages/persistence/src/attached-derived.ts
25475
+ import { rmSync } from "fs";
25476
+ import { join } from "path";
25477
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25478
+
25479
+ // ../../packages/persistence/src/control-plane-credential.ts
25480
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25481
+ import { join as join2 } from "path";
25482
+
26228
25483
  // ../../packages/persistence/src/paths.ts
26229
25484
  import {
26230
25485
  chmodSync,
@@ -26272,10 +25527,30 @@ function tightenFile(file2) {
26272
25527
  function tightenPerms(file2) {
26273
25528
  for (const path of [file2, ...dbSidecars(file2)]) chmodBestEffort(path, DATA_FILE_MODE);
26274
25529
  }
25530
+ function writeExclusiveOwnerOnlySync(file2, data) {
25531
+ writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
25532
+ }
25533
+ function writeOwnerOnlyFileSync(file2, data) {
25534
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
25535
+ try {
25536
+ rmSync2(tmp, { force: true });
25537
+ } catch {
25538
+ }
25539
+ try {
25540
+ writeExclusiveOwnerOnlySync(tmp, data);
25541
+ renameSync(tmp, file2);
25542
+ } finally {
25543
+ try {
25544
+ rmSync2(tmp, { force: true });
25545
+ } catch {
25546
+ }
25547
+ }
25548
+ tightenFile(file2);
25549
+ }
26275
25550
 
26276
25551
  // ../../packages/persistence/src/database.ts
26277
25552
  import { randomUUID as randomUUID11 } from "crypto";
26278
- import { dirname as dirname2, join as join7, sep } from "path";
25553
+ import { dirname as dirname2, join as join8, sep } from "path";
26279
25554
  import { DatabaseSync } from "node:sqlite";
26280
25555
 
26281
25556
  // ../../packages/persistence/src/ids.ts
@@ -26308,6 +25583,7 @@ function captureId(sessionId, contentHash, filePath = null) {
26308
25583
  canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
26309
25584
  );
26310
25585
  }
25586
+ var DOT = ".".charCodeAt(0);
26311
25587
 
26312
25588
  // ../../packages/persistence/src/internal/snapshot.ts
26313
25589
  import { randomUUID } from "crypto";
@@ -26635,6 +25911,25 @@ function scopeKeysParam(scopeKeys) {
26635
25911
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26636
25912
  FROM audit_events AS session_root
26637
25913
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
25914
+ var COUNTED_IN_SCOPE = `
25915
+ AND ${inScope("scope_key")}
25916
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
25917
+ var DRAIN_TOTALS = `SELECT
25918
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25919
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25920
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25921
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25922
+ THEN 1 ELSE 0 END) AS skipped,
25923
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25924
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25925
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25926
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25927
+ FROM audit_events
25928
+ WHERE event_type IN (${TYPE_LIST})`;
25929
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
25930
+ FROM audit_events
25931
+ WHERE synced_at = ${String(SKIPPED)}
25932
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26638
25933
  var ROW_COLUMNS = `id,
26639
25934
  parent_id AS parentId,
26640
25935
  root_session_id AS rootSessionId,
@@ -26710,7 +26005,7 @@ var SqliteHistorySyncRepository = class {
26710
26005
  );
26711
26006
  this.scopedCaptureRowsStmt = db.prepare(
26712
26007
  `SELECT ${ROW_COLUMNS}
26713
- FROM audit_events
26008
+ FROM audit_events INDEXED BY idx_audit_scope_owed
26714
26009
  WHERE synced_at IS NULL
26715
26010
  AND sync_claimed_at IS NULL
26716
26011
  AND outbox_owed = 1
@@ -26763,40 +26058,28 @@ var SqliteHistorySyncRepository = class {
26763
26058
  );
26764
26059
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26765
26060
  FROM audit_events${COUNTED_SCOPE}`);
26061
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26062
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
26766
26063
  this.partitionByKindStmt = db.prepare(
26767
26064
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
26768
26065
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
26769
26066
  GROUP BY event_type`
26770
26067
  );
26771
- this.countsStmt = db.prepare(
26772
- `SELECT
26773
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26774
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26775
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26776
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26777
- THEN 1 ELSE 0 END) AS skipped,
26778
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26779
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26780
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26781
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26782
- FROM audit_events
26783
- WHERE event_type IN (${TYPE_LIST})`
26068
+ this.scopedPartitionByKindStmt = db.prepare(
26069
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26070
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26071
+ GROUP BY event_type`
26784
26072
  );
26785
- this.captureSkipCountStmt = db.prepare(
26786
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
26787
- // way the structural totals are. The split exists because a refusal is
26788
- // terminal only against the deployment that gave it, and the structural
26789
- // re-arm frees it on a change of deployment. The capture lane has no such
26790
- // escape: re-arming a capture would offer one deployment's undelivered
26791
- // prompts, with their text, to a deployment that never saw them, which is
26792
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
26793
- // reasons mean the same thing — this row will not be sent — and splitting
26794
- // them would put refused captures in a bucket nothing reads and nothing
26795
- // frees.
26796
- `SELECT COUNT(*) AS skipped
26797
- FROM audit_events
26798
- WHERE synced_at = ${String(SKIPPED)}
26799
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26073
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26074
+ this.scopedCountsStmt = db.prepare(
26075
+ `${DRAIN_TOTALS}
26076
+ AND ${inScope("scope_key")}
26077
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26078
+ );
26079
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26080
+ this.scopedCaptureSkipCountStmt = db.prepare(
26081
+ `${CAPTURE_SKIPS}
26082
+ AND ${inScope("scope_key")}`
26800
26083
  );
26801
26084
  this.fingerprintStmt = db.prepare(
26802
26085
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -26910,6 +26193,10 @@ var SqliteHistorySyncRepository = class {
26910
26193
  scopedCaptureRowsStmt;
26911
26194
  scopedCaptureBacklogOwedStmt;
26912
26195
  markScopeCapturesOwedStmt;
26196
+ scopedPartitionStmt;
26197
+ scopedPartitionByKindStmt;
26198
+ scopedCountsStmt;
26199
+ scopedCaptureSkipCountStmt;
26913
26200
  /**
26914
26201
  * The masked detections recorded against one tool call.
26915
26202
  *
@@ -27131,7 +26418,29 @@ var SqliteHistorySyncRepository = class {
27131
26418
  * in" — and a machine that has never attached has no boundary to pass, so
27132
26419
  * requiring one would force a caller to invent one and report the whole store
27133
26420
  * as queued.
26421
+ *
26422
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26423
+ * the rows that pass the drain's reachability rule for that scope
26424
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26425
+ * drain never offers), so a personal repository's rows are in none of them.
26426
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26427
+ * nothing.
27134
26428
  */
26429
+ partition(scopeKeys) {
26430
+ const row = getRow(
26431
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26432
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26433
+ );
26434
+ return {
26435
+ queued: row?.queued ?? 0,
26436
+ inProgress: row?.inProgress ?? 0,
26437
+ synced: row?.synced ?? 0,
26438
+ failed: row?.failed ?? 0,
26439
+ refused: row?.refused ?? 0,
26440
+ detached: row?.detached ?? 0,
26441
+ total: row?.total ?? 0
26442
+ };
26443
+ }
27135
26444
  /**
27136
26445
  * The same partition, one row per kind that a lane carries.
27137
26446
  *
@@ -27141,11 +26450,14 @@ var SqliteHistorySyncRepository = class {
27141
26450
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27142
26451
  * rows", never as "zero sent"; the two look identical in a bar and mean
27143
26452
  * different things.
26453
+ *
26454
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26455
+ * still sum to the scoped aggregate. An empty list returns no rows.
27144
26456
  */
27145
- partitionByKind() {
26457
+ partitionByKind(scopeKeys) {
27146
26458
  return allRows(
27147
- this.partitionByKindStmt,
27148
- {}
26459
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26460
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27149
26461
  ).map((row) => ({
27150
26462
  kind: row.kind,
27151
26463
  queued: row.queued ?? 0,
@@ -27157,22 +26469,25 @@ var SqliteHistorySyncRepository = class {
27157
26469
  total: row.total ?? 0
27158
26470
  }));
27159
26471
  }
27160
- partition() {
27161
- const row = getRow(this.partitionStmt, {});
27162
- return {
27163
- queued: row?.queued ?? 0,
27164
- inProgress: row?.inProgress ?? 0,
27165
- synced: row?.synced ?? 0,
27166
- failed: row?.failed ?? 0,
27167
- refused: row?.refused ?? 0,
27168
- detached: row?.detached ?? 0,
27169
- total: row?.total ?? 0
27170
- };
27171
- }
27172
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27173
- counts(before) {
27174
- const row = getRow(this.countsStmt, { before });
27175
- const captures = getRow(this.captureSkipCountStmt);
26472
+ /**
26473
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26474
+ * and skipped are totals.
26475
+ *
26476
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26477
+ * `capturesSkipped` included: a structural row is counted only when its own
26478
+ * key and its session root's key are among them, a capture when its own key
26479
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26480
+ * under the same keys and boundary. Omitted, this runs the machine
26481
+ * statements, unchanged; an empty list counts nothing.
26482
+ */
26483
+ counts(before, scopeKeys) {
26484
+ const row = getRow(
26485
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26486
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26487
+ );
26488
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26489
+ scopeKeys: scopeKeysParam(scopeKeys)
26490
+ });
27176
26491
  return {
27177
26492
  pending: row?.pending ?? 0,
27178
26493
  sent: row?.sent ?? 0,
@@ -27424,6 +26739,7 @@ function applyMigrations(db, file2, options = {}) {
27424
26739
  }
27425
26740
  ensureSyncedAtColumn(db, "audit_events");
27426
26741
  ensureScopeKeyColumn(db);
26742
+ ensureScopeOwedIndex(db);
27427
26743
  ensureScanLedgerTable(db);
27428
26744
  ensureHistorySyncTable(db);
27429
26745
  ensureBlockedDetectionsTable(db);
@@ -27864,14 +27180,48 @@ function ensureScopeKeyColumn(db) {
27864
27180
  function hasScopeKeyColumn(db) {
27865
27181
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
27866
27182
  }
27183
+ 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";
27184
+ function ensureScopeOwedIndex(db) {
27185
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27186
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27187
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27188
+ if (!complete) return;
27189
+ db.exec(SCOPE_OWED_INDEX_DDL);
27190
+ }
27867
27191
  function ensureScanLedgerTable(db) {
27868
27192
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27869
27193
  path TEXT PRIMARY KEY,
27870
27194
  mtime TEXT NOT NULL,
27871
27195
  content_hash TEXT NOT NULL,
27872
27196
  ruleset_hash TEXT NOT NULL,
27873
- scanned_at INTEGER NOT NULL
27197
+ scanned_at INTEGER NOT NULL,
27198
+ scope_key TEXT,
27199
+ scope_root TEXT
27874
27200
  )`);
27201
+ ensureScanLedgerScopeKeyColumn(db);
27202
+ ensureScanLedgerScopeRootColumn(db);
27203
+ }
27204
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27205
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27206
+ function ensureScanLedgerScopeKeyColumn(db) {
27207
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27208
+ }
27209
+ function ensureScanLedgerScopeRootColumn(db) {
27210
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27211
+ }
27212
+ function ensureScanLedgerColumn(db, column, ddl) {
27213
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27214
+ if (hasScanLedgerColumn(db, column)) return;
27215
+ withTransaction(
27216
+ db,
27217
+ () => {
27218
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27219
+ },
27220
+ "IMMEDIATE"
27221
+ );
27222
+ }
27223
+ function hasScanLedgerColumn(db, column) {
27224
+ return columnNames(db, "scan_ledger").includes(column);
27875
27225
  }
27876
27226
  function ensureHistorySyncTable(db) {
27877
27227
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -27922,6 +27272,106 @@ function ensureRuleProbeCacheTable(db) {
27922
27272
  )`);
27923
27273
  }
27924
27274
 
27275
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27276
+ import { createHash as createHash2 } from "crypto";
27277
+ import { readFileSync as readFileSync2 } from "fs";
27278
+ import { join as join4 } from "path";
27279
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27280
+ function modPolicySnapshotPath(dataDir2) {
27281
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27282
+ }
27283
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27284
+ const byRule = /* @__PURE__ */ new Map();
27285
+ const byCategory = /* @__PURE__ */ new Map();
27286
+ for (const policy of input2.policies) {
27287
+ if (!policy.enabled) continue;
27288
+ if ("ruleId" in policy.target) {
27289
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27290
+ } else if (!byCategory.has(policy.target.category)) {
27291
+ byCategory.set(policy.target.category, policy.action);
27292
+ }
27293
+ }
27294
+ const categoryActions = {};
27295
+ for (const category of DetectionCategory.options) {
27296
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27297
+ }
27298
+ return {
27299
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27300
+ generatedAt: generatedAt.toISOString(),
27301
+ // `examples` is documentation the mod never reads, and a custom pack's are
27302
+ // whatever its author pasted in, so they stay behind.
27303
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27304
+ ruleActions: Object.fromEntries(byRule),
27305
+ categoryActions,
27306
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27307
+ };
27308
+ }
27309
+ function assignedRuleActionPolicies(installed) {
27310
+ const out = [];
27311
+ for (const [ruleId, action] of installed.ruleActions) {
27312
+ if (installed.assignedRules.has(ruleId))
27313
+ out.push({ target: { ruleId }, action, enabled: true });
27314
+ }
27315
+ return out;
27316
+ }
27317
+ function withoutExamples(rule) {
27318
+ const copy = { ...rule };
27319
+ delete copy.examples;
27320
+ return copy;
27321
+ }
27322
+ function sameContent(a, b) {
27323
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27324
+ }
27325
+ function readModPolicySnapshot(dataDir2) {
27326
+ try {
27327
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27328
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27329
+ const parsed = ModPolicySnapshot.safeParse(JSON.parse(text));
27330
+ return parsed.success ? parsed.data : null;
27331
+ } catch {
27332
+ return null;
27333
+ }
27334
+ }
27335
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27336
+ const text = JSON.stringify(snapshot);
27337
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27338
+ const existing = readModPolicySnapshot(dataDir2);
27339
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27340
+ ensureDataDirSync(dataDir2);
27341
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27342
+ return true;
27343
+ }
27344
+ function regexProbeKey(matcher) {
27345
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27346
+ }
27347
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27348
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27349
+ return rules.filter((rule) => {
27350
+ if (rule.matcher.type !== "regex") return true;
27351
+ const key = regexProbeKey(rule.matcher);
27352
+ const verdict = sources.probeVerdict(key);
27353
+ if (verdict === "quarantined") return false;
27354
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27355
+ });
27356
+ }
27357
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27358
+ const policies = sources.readPolicies();
27359
+ const snapshot = sources.installedRuleset();
27360
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27361
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27362
+ return {
27363
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27364
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27365
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27366
+ };
27367
+ }
27368
+ function refreshModPolicySnapshot(dataDir2, sources) {
27369
+ try {
27370
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27371
+ } catch {
27372
+ }
27373
+ }
27374
+
27925
27375
  // ../../packages/persistence/src/internal/json.ts
27926
27376
  function safeJson(s, fallback) {
27927
27377
  if (s == null) return fallback;
@@ -28096,6 +27546,11 @@ var TIMELINE_COLUMNS = `
28096
27546
  json_extract(attributes, '$.targetId') AS target_id,
28097
27547
  json_extract(attributes, '$.internal') AS internal,
28098
27548
  json_extract(attributes, '$.flagged') AS flagged`;
27549
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27550
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27551
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27552
+ " + "
27553
+ );
28099
27554
  var LLM_USAGE_SELECT = `
28100
27555
  SELECT root_session_id AS sessionId,
28101
27556
  provider,
@@ -28107,9 +27562,10 @@ var LLM_USAGE_SELECT = `
28107
27562
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28108
27563
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28109
27564
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28110
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27565
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27566
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28111
27567
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28112
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27568
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28113
27569
  function usageLeaves(rows) {
28114
27570
  return rows.map((row) => {
28115
27571
  const attributes = {
@@ -28124,7 +27580,7 @@ function usageLeaves(rows) {
28124
27580
  if (row.provider !== null) attributes.provider = row.provider;
28125
27581
  if (row.model !== null) attributes.model = row.model;
28126
27582
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28127
- return { sessionId: row.sessionId, attributes };
27583
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28128
27584
  });
28129
27585
  }
28130
27586
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29458,9 +28914,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29458
28914
  AND conditions IS NULL
29459
28915
  AND ${ACTIVE_PREDICATE}`;
29460
28916
  var SqliteExceptionsRepository = class {
29461
- constructor(db, now = () => Date.now()) {
28917
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29462
28918
  this.db = db;
29463
28919
  this.now = now;
28920
+ this.onChange = onChange;
29464
28921
  this.consumeStmt = db.prepare(
29465
28922
  `UPDATE exceptions
29466
28923
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29479,6 +28936,7 @@ var SqliteExceptionsRepository = class {
29479
28936
  }
29480
28937
  db;
29481
28938
  now;
28939
+ onChange;
29482
28940
  consumeStmt;
29483
28941
  insertBlockedStmt;
29484
28942
  sweepBlockedStmt;
@@ -29494,7 +28952,9 @@ var SqliteExceptionsRepository = class {
29494
28952
  */
29495
28953
  create(input2) {
29496
28954
  try {
29497
- return Promise.resolve(this.createSync(input2));
28955
+ const created = this.createSync(input2);
28956
+ this.onChange();
28957
+ return Promise.resolve(created);
29498
28958
  } catch (err) {
29499
28959
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29500
28960
  }
@@ -29625,6 +29085,7 @@ var SqliteExceptionsRepository = class {
29625
29085
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29626
29086
  WHERE id = :id AND revoked_at IS NULL`
29627
29087
  ).run({ id, revokedBy, reason: reason ?? null, now });
29088
+ if (Number(result.changes) === 1) this.onChange();
29628
29089
  return Promise.resolve(Number(result.changes) === 1);
29629
29090
  }
29630
29091
  /**
@@ -29637,6 +29098,15 @@ var SqliteExceptionsRepository = class {
29637
29098
  const result = this.consumeStmt.run({ id, now });
29638
29099
  return Promise.resolve(Number(result.changes) === 1);
29639
29100
  }
29101
+ /** The rule ids with at least one active grant, under any key version. */
29102
+ activeRuleIds(now = this.now()) {
29103
+ return allRows(
29104
+ this.db.prepare(
29105
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29106
+ ),
29107
+ { now }
29108
+ ).map((row) => row.ruleId);
29109
+ }
29640
29110
  /**
29641
29111
  * The evaluation subset of every active grant under one fingerprint key
29642
29112
  * version — what rides the policy bundle to the hook. Grants written under
@@ -30760,28 +30230,28 @@ var SqliteInspectionFindingsRepository = class {
30760
30230
  };
30761
30231
 
30762
30232
  // ../../packages/persistence/src/repositories/installed-packs.ts
30763
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30233
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
30764
30234
 
30765
30235
  // ../../packages/persistence/src/policy-floor.ts
30766
- import { readFileSync as readFileSync5 } from "fs";
30767
- import { join as join6 } from "path";
30236
+ import { readFileSync as readFileSync6 } from "fs";
30237
+ import { join as join7 } from "path";
30768
30238
 
30769
30239
  // ../../packages/persistence/src/local-layout.ts
30770
30240
  import { renameSync as renameSync3 } from "fs";
30771
30241
  import { mkdir } from "fs/promises";
30772
30242
  import { homedir } from "os";
30773
- import { join as join4 } from "path";
30243
+ import { join as join5 } from "path";
30774
30244
  function defaultDataDir() {
30775
- return join4(homedir(), ".aka");
30245
+ return join5(homedir(), ".aka");
30776
30246
  }
30777
30247
  function settingsDir(base = defaultDataDir()) {
30778
- return join4(base, "settings");
30248
+ return join5(base, "settings");
30779
30249
  }
30780
30250
  function dataDir(base = defaultDataDir()) {
30781
- return join4(base, "data");
30251
+ return join5(base, "data");
30782
30252
  }
30783
30253
  function dbPath(base = defaultDataDir()) {
30784
- return join4(dataDir(base), "aka.db");
30254
+ return join5(dataDir(base), "aka.db");
30785
30255
  }
30786
30256
  function ensureLayoutDirSync(dir = defaultDataDir()) {
30787
30257
  ensureDataDirSync(dir);
@@ -30794,8 +30264,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
30794
30264
  for (const { name, dest } of moves) {
30795
30265
  try {
30796
30266
  ensureDataDirSync(dest);
30797
- const moved = join4(dest, name);
30798
- renameSync3(join4(base, name), moved);
30267
+ const moved = join5(dest, name);
30268
+ renameSync3(join5(base, name), moved);
30799
30269
  tightenFile(moved);
30800
30270
  } catch {
30801
30271
  }
@@ -30803,8 +30273,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
30803
30273
  }
30804
30274
 
30805
30275
  // ../../packages/persistence/src/settings.ts
30806
- import { readFileSync as readFileSync4 } from "fs";
30807
- import { join as join5 } from "path";
30276
+ import { readFileSync as readFileSync5 } from "fs";
30277
+ import { join as join6 } from "path";
30808
30278
 
30809
30279
  // ../../packages/persistence/src/file-lock.ts
30810
30280
  import { randomUUID as randomUUID3 } from "crypto";
@@ -30812,7 +30282,7 @@ import {
30812
30282
  closeSync,
30813
30283
  existsSync as existsSync2,
30814
30284
  openSync,
30815
- readFileSync as readFileSync2,
30285
+ readFileSync as readFileSync3,
30816
30286
  rmSync as rmSync5,
30817
30287
  statSync as statSync3,
30818
30288
  writeFileSync as writeFileSync2
@@ -30821,16 +30291,16 @@ import { hostname as hostname3 } from "os";
30821
30291
  var PARK = new Int32Array(new SharedArrayBuffer(4));
30822
30292
 
30823
30293
  // ../../packages/persistence/src/managed-settings.ts
30824
- import { readFileSync as readFileSync3 } from "fs";
30294
+ import { readFileSync as readFileSync4 } from "fs";
30825
30295
  import { posix, win32 } from "path";
30826
- function managedSettingsPaths(platform2 = process.platform) {
30827
- if (platform2 === "darwin") {
30296
+ function managedSettingsPaths(platform = process.platform) {
30297
+ if (platform === "darwin") {
30828
30298
  return [
30829
30299
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
30830
30300
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
30831
30301
  ];
30832
30302
  }
30833
- if (platform2 === "win32") {
30303
+ if (platform === "win32") {
30834
30304
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
30835
30305
  }
30836
30306
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -30840,7 +30310,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
30840
30310
  for (const path of paths) {
30841
30311
  let text;
30842
30312
  try {
30843
- text = readFileSync3(path, "utf8");
30313
+ text = readFileSync4(path, "utf8");
30844
30314
  } catch {
30845
30315
  continue;
30846
30316
  }
@@ -30894,7 +30364,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
30894
30364
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
30895
30365
  }
30896
30366
  function readUserSettings(base) {
30897
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30367
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
30898
30368
  if (!record2) return defaultWorkspaceSettings();
30899
30369
  try {
30900
30370
  return WorkspaceSettings.parse(record2);
@@ -30905,7 +30375,7 @@ function readUserSettings(base) {
30905
30375
  function readJson(file2) {
30906
30376
  let text;
30907
30377
  try {
30908
- text = readFileSync4(file2, "utf8");
30378
+ text = readFileSync5(file2, "utf8");
30909
30379
  } catch {
30910
30380
  return null;
30911
30381
  }
@@ -30945,7 +30415,7 @@ var PolicyFloorError = class extends Error {
30945
30415
  };
30946
30416
  function readCachedPolicyBundle(base = defaultDataDir()) {
30947
30417
  try {
30948
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30418
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30949
30419
  const parsed = JSON.parse(raw);
30950
30420
  if (typeof parsed !== "object" || parsed === null) return null;
30951
30421
  return PolicyBundle.parse(parsed.bundle);
@@ -31069,7 +30539,7 @@ function inventorySignature(packs2) {
31069
30539
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31070
30540
  }
31071
30541
  function hashRules(rulesJson) {
31072
- return createHash2("sha256").update(rulesJson).digest("hex");
30542
+ return createHash3("sha256").update(rulesJson).digest("hex");
31073
30543
  }
31074
30544
  function parseVersion(v) {
31075
30545
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31111,9 +30581,10 @@ var SqliteInstalledPacksRepository = class {
31111
30581
  * from `openLocalDatabase`, which is the single construction site that owns a
31112
30582
  * real `~/.aka`.
31113
30583
  */
31114
- constructor(db, baseDir) {
30584
+ constructor(db, baseDir, onChange = () => void 0) {
31115
30585
  this.db = db;
31116
30586
  this.baseDir = baseDir;
30587
+ this.onChange = onChange;
31117
30588
  this.insertMissingStmt = db.prepare(
31118
30589
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31119
30590
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31142,6 +30613,7 @@ var SqliteInstalledPacksRepository = class {
31142
30613
  }
31143
30614
  db;
31144
30615
  baseDir;
30616
+ onChange;
31145
30617
  insertMissingStmt;
31146
30618
  upsertAvailableStmt;
31147
30619
  signatureStmt;
@@ -31214,6 +30686,7 @@ var SqliteInstalledPacksRepository = class {
31214
30686
  },
31215
30687
  "IMMEDIATE"
31216
30688
  );
30689
+ this.onChange();
31217
30690
  } catch {
31218
30691
  }
31219
30692
  }
@@ -31288,6 +30761,7 @@ var SqliteInstalledPacksRepository = class {
31288
30761
  },
31289
30762
  "IMMEDIATE"
31290
30763
  );
30764
+ if (changed) this.onChange();
31291
30765
  return changed;
31292
30766
  }
31293
30767
  /**
@@ -31529,6 +31003,7 @@ var SqliteInstalledPacksRepository = class {
31529
31003
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31530
31004
  WHERE namespace = :namespace AND pack_id = :packId`
31531
31005
  ).run({ policyId, now: Date.now(), namespace, packId });
31006
+ if (Number(res.changes) > 0) this.onChange();
31532
31007
  return Number(res.changes) > 0;
31533
31008
  }
31534
31009
  /**
@@ -31553,6 +31028,7 @@ var SqliteInstalledPacksRepository = class {
31553
31028
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31554
31029
  WHERE namespace = :namespace AND pack_id = :packId`
31555
31030
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31031
+ if (Number(res.changes) > 0) this.onChange();
31556
31032
  return Number(res.changes) > 0;
31557
31033
  }
31558
31034
  // Fingerprint of the recorded available mirror — compared against the
@@ -32450,13 +31926,19 @@ var SqliteInventoryAssetsRepository = class {
32450
31926
  import { randomUUID as randomUUID6 } from "crypto";
32451
31927
  var SEED_BATCH_WINDOW_MS = 6e4;
32452
31928
  var SqlitePoliciesRepository = class {
32453
- constructor(db) {
31929
+ constructor(db, onChange = () => void 0) {
32454
31930
  this.db = db;
31931
+ this.onChange = onChange;
32455
31932
  }
32456
31933
  db;
31934
+ onChange;
32457
31935
  readPolicies() {
31936
+ return Promise.resolve(this.listPolicies());
31937
+ }
31938
+ /** The synchronous read behind {@link readPolicies}. */
31939
+ listPolicies() {
32458
31940
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32459
- const policies = mapRowsTolerant(rows, (row) => {
31941
+ return mapRowsTolerant(rows, (row) => {
32460
31942
  const target = JSON.parse(row.target);
32461
31943
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32462
31944
  return Policy.parse({
@@ -32468,7 +31950,6 @@ var SqlitePoliciesRepository = class {
32468
31950
  customKeywords
32469
31951
  });
32470
31952
  });
32471
- return Promise.resolve(policies);
32472
31953
  }
32473
31954
  // Seed one policy per bundled category at Monitor so the detection-type config
32474
31955
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32479,7 +31960,7 @@ var SqlitePoliciesRepository = class {
32479
31960
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32480
31961
  if (count > 0) {
32481
31962
  this.markEarlierChoices();
32482
- this.monitorUntouchedSeeds();
31963
+ if (this.monitorUntouchedSeeds()) this.onChange();
32483
31964
  return;
32484
31965
  }
32485
31966
  const stmt = this.db.prepare(
@@ -32496,6 +31977,7 @@ var SqlitePoliciesRepository = class {
32496
31977
  });
32497
31978
  }
32498
31979
  });
31980
+ this.onChange();
32499
31981
  }
32500
31982
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32501
31983
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32561,7 +32043,7 @@ var SqlitePoliciesRepository = class {
32561
32043
  ).filter(
32562
32044
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32563
32045
  );
32564
- if (untouched.length === 0) return;
32046
+ if (untouched.length === 0) return false;
32565
32047
  const stmt = this.db.prepare(
32566
32048
  `UPDATE policies SET action = 'log'
32567
32049
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32572,6 +32054,7 @@ var SqlitePoliciesRepository = class {
32572
32054
  stmt.run({ category: row.category, seeded: row.action });
32573
32055
  }
32574
32056
  });
32057
+ return true;
32575
32058
  }
32576
32059
  // Insert-or-update the single global per-category policy row, keyed on the
32577
32060
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32588,6 +32071,7 @@ var SqlitePoliciesRepository = class {
32588
32071
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32589
32072
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32590
32073
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32074
+ this.onChange();
32591
32075
  }
32592
32076
  // Caps every global per-category policy currently set to block/redact down
32593
32077
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32598,6 +32082,7 @@ var SqlitePoliciesRepository = class {
32598
32082
  WHERE scope='global' AND action IN ('block','redact')
32599
32083
  AND json_extract(target,'$.category') IS NOT NULL`
32600
32084
  ).run({ now: Date.now() });
32085
+ if (Number(info.changes) > 0) this.onChange();
32601
32086
  return Number(info.changes);
32602
32087
  }
32603
32088
  // Whether the category's row was ever written after it was created — by the
@@ -32917,31 +32402,45 @@ var SqliteScanLedgerRepository = class {
32917
32402
  constructor(db) {
32918
32403
  this.db = db;
32919
32404
  this.upsertStmt = db.prepare(
32920
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
32921
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32405
+ `INSERT INTO scan_ledger
32406
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32407
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
32922
32408
  ON CONFLICT (path) DO UPDATE SET
32923
32409
  mtime = excluded.mtime,
32924
32410
  content_hash = excluded.content_hash,
32925
32411
  ruleset_hash = excluded.ruleset_hash,
32412
+ scope_key = excluded.scope_key,
32413
+ scope_root = excluded.scope_root,
32926
32414
  scanned_at = excluded.scanned_at`
32927
32415
  );
32928
32416
  this.readStmt = db.prepare(
32929
- `SELECT path, mtime, content_hash AS contentHash
32417
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32418
+ scope_root AS scopeRoot
32930
32419
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
32931
32420
  );
32932
32421
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32422
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
32933
32423
  }
32934
32424
  db;
32935
32425
  upsertStmt;
32936
32426
  readStmt;
32937
32427
  pathsStmt;
32428
+ pathKeysStmt;
32938
32429
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
32939
32430
  // older ruleset are simply absent, which reads as "never scanned".
32940
32431
  entriesForRuleset(rulesetHash) {
32941
- const rows = allRows(this.readStmt, {
32942
- rulesetHash
32943
- });
32944
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32432
+ const rows = allRows(this.readStmt, { rulesetHash });
32433
+ return new Map(
32434
+ rows.map((r) => [
32435
+ r.path,
32436
+ {
32437
+ mtime: r.mtime,
32438
+ contentHash: r.contentHash,
32439
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32440
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32441
+ }
32442
+ ])
32443
+ );
32945
32444
  }
32946
32445
  // Every ledgered path, whatever ruleset it was scanned under — the set a
32947
32446
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -32950,6 +32449,14 @@ var SqliteScanLedgerRepository = class {
32950
32449
  allPaths() {
32951
32450
  return allRows(this.pathsStmt).map((r) => r.path);
32952
32451
  }
32452
+ // Every ledgered path with the repository it was in when it was last read,
32453
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32454
+ // which repository a vanished file belonged to. `undefined` for a row with no
32455
+ // key, which is every row written before the column existed.
32456
+ pathKeys() {
32457
+ const rows = allRows(this.pathKeysStmt);
32458
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32459
+ }
32953
32460
  upsertEntries(entries) {
32954
32461
  if (entries.length === 0) return;
32955
32462
  const scannedAt = Date.now();
@@ -32960,6 +32467,8 @@ var SqliteScanLedgerRepository = class {
32960
32467
  mtime: entry.mtime,
32961
32468
  contentHash: entry.contentHash,
32962
32469
  rulesetHash: entry.rulesetHash,
32470
+ scopeKey: entry.scopeKey ?? null,
32471
+ scopeRoot: entry.scopeRoot ?? null,
32963
32472
  scannedAt
32964
32473
  });
32965
32474
  }
@@ -34047,6 +33556,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34047
33556
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34048
33557
  };
34049
33558
  }
33559
+ function withoutTrailingSlashes(path) {
33560
+ let end = path.length;
33561
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33562
+ return path.slice(0, end);
33563
+ }
34050
33564
  function toEndpointSummary(row) {
34051
33565
  return {
34052
33566
  id: row.id,
@@ -34334,7 +33848,7 @@ var SqliteSharesRepository = class {
34334
33848
  */
34335
33849
  reconcileCallSites(projectKey, reconcile) {
34336
33850
  if (reconcile.mode === "walk") {
34337
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
33851
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34338
33852
  this.db.prepare(
34339
33853
  `DELETE FROM share_call_site
34340
33854
  WHERE project_key = :key
@@ -34902,7 +34416,7 @@ function backupLegacyStore(db, file2) {
34902
34416
  discardStore(file2, backup);
34903
34417
  return backup;
34904
34418
  }
34905
- function openAndInitialize(file2, base, skipTags) {
34419
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
34906
34420
  let db = openWithPragmas(file2);
34907
34421
  try {
34908
34422
  if (isForeignSqliteLineage(db)) {
@@ -34914,8 +34428,15 @@ function openAndInitialize(file2, base, skipTags) {
34914
34428
  }
34915
34429
  applyMigrations(db, file2, { skipTags });
34916
34430
  tightenPerms(file2);
34917
- const policies = new SqlitePoliciesRepository(db);
34918
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34431
+ const modPolicy = {};
34432
+ const onPolicyStateChange = () => {
34433
+ if (modPolicy.current !== void 0)
34434
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34435
+ };
34436
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34437
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34438
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34439
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
34919
34440
  const repositories = {
34920
34441
  events: new SqliteEventsRepository(db),
34921
34442
  findings: new SqliteFindingsRepository(db),
@@ -34924,9 +34445,9 @@ function openAndInitialize(file2, base, skipTags) {
34924
34445
  scanLedger: new SqliteScanLedgerRepository(db),
34925
34446
  historySync: new SqliteHistorySyncRepository(db),
34926
34447
  secretVault: new SqliteSecretVaultRepository(db),
34927
- exceptions: new SqliteExceptionsRepository(db),
34448
+ exceptions,
34928
34449
  resolutions: new SqliteResolutionsRepository(db),
34929
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34450
+ ruleProbeCache,
34930
34451
  bodyRetention: new SqliteBodyRetentionRepository(db),
34931
34452
  security: new SqliteSecurityRepository(db),
34932
34453
  detections: new SqliteDetectionsRepository(db),
@@ -34944,6 +34465,13 @@ function openAndInitialize(file2, base, skipTags) {
34944
34465
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
34945
34466
  configInventory: new SqliteConfigInventoryRepository(db)
34946
34467
  };
34468
+ modPolicy.current = {
34469
+ installedRuleset: () => installedPacks.installedRuleset(),
34470
+ readPolicies: () => policies.listPolicies(),
34471
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34472
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34473
+ bundledRegexMatchers: () => shippedRegexMatchers2
34474
+ };
34947
34475
  policies.seedDefaults();
34948
34476
  return { db, ...repositories };
34949
34477
  } catch (err) {
@@ -34955,7 +34483,7 @@ function openAndInitialize(file2, base, skipTags) {
34955
34483
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
34956
34484
  function openLocalDatabase(dir, options = {}) {
34957
34485
  ensureDataDirSync(dir);
34958
- const file2 = join7(dir, DB_FILENAME);
34486
+ const file2 = join8(dir, DB_FILENAME);
34959
34487
  reapStalePartials(file2);
34960
34488
  const {
34961
34489
  db,
@@ -34991,7 +34519,8 @@ function openLocalDatabase(dir, options = {}) {
34991
34519
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
34992
34520
  // settings/ and data/, and the pack-policy floor needs both halves.
34993
34521
  dirname2(dir),
34994
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34522
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34523
+ options.shippedRegexMatchers ?? []
34995
34524
  );
34996
34525
  function captureRowId(event) {
34997
34526
  return captureId(
@@ -35256,39 +34785,39 @@ function openLocalDatabase(dir, options = {}) {
35256
34785
  }
35257
34786
 
35258
34787
  // ../../packages/persistence/src/egress-wire.ts
35259
- import { createHash as createHash3 } from "crypto";
34788
+ import { createHash as createHash4 } from "crypto";
35260
34789
  var SLASH = "/".charCodeAt(0);
35261
34790
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35262
34791
 
35263
34792
  // ../../packages/persistence/src/finding-key.ts
35264
- import { createHash as createHash4 } from "crypto";
34793
+ import { createHash as createHash5 } from "crypto";
35265
34794
 
35266
34795
  // ../../packages/persistence/src/fingerprint.ts
35267
34796
  import { createHmac, randomBytes } from "crypto";
35268
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35269
- import { join as join8 } from "path";
35270
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34797
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
34798
+ import { join as join9 } from "path";
35271
34799
 
35272
34800
  // ../../packages/persistence/src/forward-health.ts
35273
- import { readFileSync as readFileSync7 } from "fs";
35274
- import { join as join9 } from "path";
34801
+ import { readFileSync as readFileSync8 } from "fs";
34802
+ import { join as join10 } from "path";
35275
34803
 
35276
34804
  // ../../packages/persistence/src/history-backfill.ts
35277
34805
  import { existsSync as existsSync4 } from "fs";
35278
- import { join as join10 } from "path";
34806
+ import { join as join11 } from "path";
35279
34807
 
35280
34808
  // ../../packages/persistence/src/history-preview.ts
35281
34809
  import { existsSync as existsSync5 } from "fs";
35282
- import { join as join11 } from "path";
35283
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
34810
+ import { join as join12 } from "path";
34811
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35284
34812
 
35285
34813
  // ../../packages/persistence/src/history-sync-state.ts
35286
- import { readFileSync as readFileSync8 } from "fs";
35287
- import { join as join12 } from "path";
34814
+ import { readFileSync as readFileSync9 } from "fs";
34815
+ import { join as join13 } from "path";
34816
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35288
34817
 
35289
34818
  // ../../packages/persistence/src/store-symlinks.ts
35290
34819
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35291
- import { dirname as dirname3, join as join13, resolve } from "path";
34820
+ import { dirname as dirname3, join as join14, resolve } from "path";
35292
34821
 
35293
34822
  // ../../packages/persistence/src/vault/crypto.ts
35294
34823
  import {
@@ -35302,19 +34831,19 @@ import {
35302
34831
  // ../../packages/persistence/src/vault/key-provider.ts
35303
34832
  import { execFileSync } from "child_process";
35304
34833
  import { randomBytes as randomBytes2 } from "crypto";
35305
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35306
- import { join as join14 } from "path";
34834
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
34835
+ import { join as join15 } from "path";
35307
34836
 
35308
34837
  // ../../packages/persistence/src/vault/vault.ts
35309
34838
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35310
34839
 
35311
34840
  // ../../packages/persistence/src/warn-era-cap.ts
35312
34841
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35313
- import { join as join15 } from "path";
34842
+ import { join as join16 } from "path";
35314
34843
 
35315
34844
  // ../../packages/plugin-sdk/src/config.ts
35316
34845
  import { existsSync as existsSync8 } from "fs";
35317
- import { join as join16 } from "path";
34846
+ import { join as join17 } from "path";
35318
34847
 
35319
34848
  // ../../packages/plugin-sdk/src/provider-env.ts
35320
34849
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -35368,7 +34897,7 @@ function resolveProvider() {
35368
34897
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
35369
34898
  try {
35370
34899
  ensureLayoutDirSync(base);
35371
- const settingsFile = join16(settingsDir(base), "settings.json");
34900
+ const settingsFile = join17(settingsDir(base), "settings.json");
35372
34901
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
35373
34902
  } catch {
35374
34903
  }
@@ -35391,11 +34920,6 @@ function resolveProviderSafe(resolveProviderFn) {
35391
34920
  }
35392
34921
  }
35393
34922
 
35394
- // ../../packages/plugin-sdk/src/config-inventory.ts
35395
- import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
35396
- import { homedir as homedir2 } from "os";
35397
- import { basename as basename3, join as join18 } from "path";
35398
-
35399
34923
  // ../../packages/detections/src/egress/registry.ts
35400
34924
  var EXTRACTOR_VERSION = "3";
35401
34925
  var PROVIDER_REGISTRY = [
@@ -36506,17 +36030,18 @@ function ruleEvidence(rule) {
36506
36030
 
36507
36031
  // ../../packages/detections/src/mask.ts
36508
36032
  function maskMatch(raw) {
36509
- if (raw.length <= 5) return "***";
36510
- const atIndex = raw.indexOf("@");
36511
- if (atIndex > 0 && atIndex < raw.length - 1) {
36512
- const domain2 = raw.slice(atIndex + 1);
36033
+ const visible = stripInvisiblePadding(raw);
36034
+ if (visible.length <= 5) return "***";
36035
+ const atIndex = visible.indexOf("@");
36036
+ if (atIndex > 0 && atIndex < visible.length - 1) {
36037
+ const domain2 = visible.slice(atIndex + 1);
36513
36038
  if (domain2.includes(".")) {
36514
- const local = raw.slice(0, atIndex);
36039
+ const local = visible.slice(0, atIndex);
36515
36040
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
36516
36041
  return `${maskedLocal}@${domain2}`;
36517
36042
  }
36518
36043
  }
36519
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
36044
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
36520
36045
  }
36521
36046
 
36522
36047
  // ../../packages/detections/src/pointer-shield.ts
@@ -36671,6 +36196,38 @@ var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].m
36671
36196
  );
36672
36197
  var CPU_CORROBORATION_SHARE = 0.2;
36673
36198
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36199
+ function repeatTo(unit, length) {
36200
+ return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
36201
+ }
36202
+ function joinTo(length, open3, close, item) {
36203
+ const parts = [];
36204
+ let size = open3.length;
36205
+ for (let i = 0; size < length; i++) {
36206
+ const next = (i === 0 ? "" : ",") + item(i);
36207
+ parts.push(next);
36208
+ size += next.length;
36209
+ }
36210
+ return (open3 + parts.join("") + close).slice(0, length);
36211
+ }
36212
+ var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
36213
+ var GROWTH_CORPORA = [
36214
+ {
36215
+ name: "one-line JSON dictionary",
36216
+ build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
36217
+ },
36218
+ {
36219
+ name: "JSON array of quoted SQL keywords",
36220
+ build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
36221
+ },
36222
+ { name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
36223
+ { name: "double-quote run", build: (length) => repeatTo('"', length) },
36224
+ { name: "space run", build: (length) => repeatTo(" ", length) },
36225
+ { name: "newline run", build: (length) => repeatTo("\n", length) },
36226
+ ...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
36227
+ name: `unit run ${JSON.stringify(unit)}`,
36228
+ build: (length) => repeatTo(unit, length)
36229
+ }))
36230
+ ];
36674
36231
 
36675
36232
  // ../../packages/plugin-sdk/src/raw-egress.ts
36676
36233
  var RawEgressError = class extends Error {
@@ -36691,7 +36248,12 @@ var MIN_RAW_LEN = 4;
36691
36248
  var RAW_RUN_LEN = 8;
36692
36249
  function carriesRawRun(text, rawValues) {
36693
36250
  let windows = null;
36694
- for (const raw of new Set(rawValues)) {
36251
+ const values = /* @__PURE__ */ new Set();
36252
+ for (const raw of rawValues) {
36253
+ values.add(raw);
36254
+ values.add(stripInvisiblePadding(raw));
36255
+ }
36256
+ for (const raw of values) {
36695
36257
  if (raw.length < MIN_RAW_LEN) continue;
36696
36258
  if (raw.length < RAW_RUN_LEN) {
36697
36259
  if (text.includes(raw)) return true;
@@ -36765,11 +36327,16 @@ function maskContextSlice(slice, sliceStart, hits) {
36765
36327
  return masked;
36766
36328
  }
36767
36329
  function safeMaskedMatch(rawMatch) {
36768
- const masked = maskMatch(rawMatch);
36769
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
36770
- return "***";
36330
+ const visible = stripInvisiblePadding(rawMatch);
36331
+ const masked = maskMatch(visible);
36332
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
36333
+ if (!reveals(masked)) return masked;
36334
+ const atIndex = masked.indexOf("@");
36335
+ if (atIndex > 0 && atIndex < masked.length - 1) {
36336
+ const emailFallback = `*${masked.slice(atIndex)}`;
36337
+ if (!reveals(emailFallback)) return emailFallback;
36771
36338
  }
36772
- return masked;
36339
+ return "***";
36773
36340
  }
36774
36341
  function assertRawFree(text, rawValues) {
36775
36342
  if (carriesRawRun(text, rawValues)) {
@@ -37006,7 +36573,7 @@ var auth_jwt_no_verify_default = {
37006
36573
  severity: "critical",
37007
36574
  matcher: {
37008
36575
  type: "regex",
37009
- pattern: "(verify\\s*=\\s*false|verify_signature.*false|algorithms\\s*=\\s*\\[\\])",
36576
+ pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
37010
36577
  flags: "gi"
37011
36578
  },
37012
36579
  requiresNearby: {
@@ -37094,7 +36661,7 @@ var cmd_inject_shell_default = {
37094
36661
  severity: "critical",
37095
36662
  matcher: {
37096
36663
  type: "regex",
37097
- pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
36664
+ pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
37098
36665
  flags: "gi"
37099
36666
  },
37100
36667
  requiresNearby: {
@@ -37223,7 +36790,7 @@ var deser_yaml_unsafe_default = {
37223
36790
  severity: "high",
37224
36791
  matcher: {
37225
36792
  type: "regex",
37226
- pattern: "\\byaml\\.load\\s*\\((?![^)]*SafeLoader|[^)]*safe_load)",
36793
+ pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
37227
36794
  flags: "gi"
37228
36795
  },
37229
36796
  examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
@@ -37440,7 +37007,7 @@ var sql_inject_concat_dot_default = {
37440
37007
  severity: "high",
37441
37008
  matcher: {
37442
37009
  type: "regex",
37443
- pattern: `["'][^\\n]*?(select|insert|update|delete|drop|where)[^\\n]*?["']\\s*\\.`,
37010
+ pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
37444
37011
  flags: "gi"
37445
37012
  },
37446
37013
  appliesTo: {
@@ -37458,7 +37025,7 @@ var sql_inject_concat_default = {
37458
37025
  severity: "high",
37459
37026
  matcher: {
37460
37027
  type: "regex",
37461
- 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*\\+`,
37028
+ 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*\\+`,
37462
37029
  flags: "gi"
37463
37030
  },
37464
37031
  examples: ['"SELECT * FROM users WHERE id = " + userId']
@@ -37473,7 +37040,7 @@ var sql_inject_format_default = {
37473
37040
  severity: "high",
37474
37041
  matcher: {
37475
37042
  type: "regex",
37476
- 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]|\\{[^}]+\\})",
37043
+ 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]+\\})",
37477
37044
  flags: "gi"
37478
37045
  },
37479
37046
  examples: [
@@ -37491,7 +37058,7 @@ var sql_inject_interp_default = {
37491
37058
  severity: "high",
37492
37059
  matcher: {
37493
37060
  type: "regex",
37494
- pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
37061
+ pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
37495
37062
  flags: "gi"
37496
37063
  },
37497
37064
  examples: [
@@ -37866,7 +37433,7 @@ var stack_trace_default = {
37866
37433
  severity: "low",
37867
37434
  matcher: {
37868
37435
  type: "regex",
37869
- pattern: "(?:^|\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
37436
+ pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
37870
37437
  flags: "g"
37871
37438
  },
37872
37439
  examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
@@ -39024,7 +38591,7 @@ var BUNDLED_PACKS = [
39024
38591
  {
39025
38592
  packId: "code-flaws",
39026
38593
  name: "Code Security Flaws",
39027
- version: "0.1.0",
38594
+ version: "0.1.1",
39028
38595
  rawRules: [
39029
38596
  sql_inject_concat_default,
39030
38597
  sql_inject_concat_dot_default,
@@ -39074,7 +38641,7 @@ var BUNDLED_PACKS = [
39074
38641
  {
39075
38642
  packId: "core-code-context",
39076
38643
  name: "Code Context",
39077
- version: "0.2.1",
38644
+ version: "0.2.2",
39078
38645
  rawRules: [
39079
38646
  internal_ip_default,
39080
38647
  localhost_ref_default,
@@ -39191,6 +38758,7 @@ var BUNDLED_PACKS = [
39191
38758
  ];
39192
38759
 
39193
38760
  // ../../packages/plugin-sdk/src/rule-packs.ts
38761
+ var BUNDLED_NAMESPACE = "aka";
39194
38762
  function registerRulePack(packId, rawRules) {
39195
38763
  const rules = rawRules.map((raw) => Rule.parse(raw));
39196
38764
  registerPack({ id: packId, rules });
@@ -39198,6 +38766,23 @@ function registerRulePack(packId, rawRules) {
39198
38766
  function registerBundledPacks() {
39199
38767
  for (const pack of BUNDLED_PACKS) registerRulePack(pack.packId, pack.rawRules);
39200
38768
  }
38769
+ var cachedDetections;
38770
+ function bundledDetections() {
38771
+ cachedDetections ??= BUNDLED_PACKS.map((pack) => ({
38772
+ namespace: BUNDLED_NAMESPACE,
38773
+ packId: pack.packId,
38774
+ version: pack.version,
38775
+ name: pack.name,
38776
+ rules: pack.rawRules.map((raw) => Rule.parse(raw)),
38777
+ defaultPolicyId: pack.defaultPolicy
38778
+ }));
38779
+ return cachedDetections;
38780
+ }
38781
+ function shippedRegexMatchers() {
38782
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
38783
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
38784
+ );
38785
+ }
39201
38786
 
39202
38787
  // ../../packages/plugin-sdk/src/mask.ts
39203
38788
  var packsReady = false;
@@ -39252,87 +38837,6 @@ function maskText(text) {
39252
38837
  return scanText(text).masked;
39253
38838
  }
39254
38839
 
39255
- // ../../packages/plugin-sdk/src/repo.ts
39256
- import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
39257
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
39258
- var NO_ATTRIBUTION = Object.freeze({});
39259
-
39260
- // ../../packages/plugin-sdk/src/events.ts
39261
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39262
-
39263
- // ../../packages/plugin-sdk/src/isolated-scan.ts
39264
- import { existsSync as existsSync10 } from "fs";
39265
- import { fileURLToPath } from "url";
39266
- import { Worker } from "worker_threads";
39267
-
39268
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
39269
- import { readFileSync as readFileSync12 } from "fs";
39270
- import { join as join19 } from "path";
39271
-
39272
- // ../../packages/plugin-sdk/src/host-floor.ts
39273
- import { readFileSync as readFileSync14 } from "fs";
39274
- import { join as join21 } from "path";
39275
-
39276
- // ../../packages/plugin-sdk/src/model-governance.ts
39277
- import {
39278
- closeSync as closeSync2,
39279
- fstatSync,
39280
- mkdirSync as mkdirSync2,
39281
- openSync as openSync2,
39282
- readFileSync as readFileSync13,
39283
- readSync,
39284
- writeFileSync as writeFileSync5
39285
- } from "fs";
39286
- import { join as join20 } from "path";
39287
- var TAIL_BYTES = 256 * 1024;
39288
-
39289
- // ../../packages/plugin-sdk/src/host-floor.ts
39290
- var HOST_FEATURE = {
39291
- ModelSwitch: "model-switch",
39292
- VaultPointerDisplay: "vault-pointer-display"
39293
- };
39294
- var HOST_FLOORS = {
39295
- [HOST_FEATURE.ModelSwitch]: {
39296
- label: "model-switch protection",
39297
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
39298
- since: "2.1.251"
39299
- },
39300
- [HOST_FEATURE.VaultPointerDisplay]: {
39301
- label: "vault pointer display",
39302
- hookEvents: ["MessageDisplay"],
39303
- since: "2.1.152"
39304
- }
39305
- };
39306
- var ANTIGRAVITY_HOST_FEATURE = {
39307
- EndOfTurnCapture: "end-of-turn-capture"
39308
- };
39309
- var ANTIGRAVITY_HOST_FLOORS = {
39310
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
39311
- label: "end-of-turn history capture",
39312
- hookEvents: ["Stop"],
39313
- since: "1.1.10"
39314
- }
39315
- };
39316
-
39317
- // ../../packages/plugin-sdk/src/ignore-layers.ts
39318
- var import_ignore = __toESM(require_ignore(), 1);
39319
- import { readFileSync as readFileSync15 } from "fs";
39320
- import { join as join22 } from "path";
39321
-
39322
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
39323
- import { arch, hostname as hostname4, platform, release } from "os";
39324
-
39325
- // ../../packages/plugin-sdk/src/nudge.ts
39326
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
39327
- import { join as join23 } from "path";
39328
-
39329
- // ../../packages/plugin-sdk/src/paths.ts
39330
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
39331
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
39332
-
39333
- // ../../packages/plugin-sdk/src/policy-resolver.ts
39334
- import { randomUUID as randomUUID14 } from "crypto";
39335
-
39336
38840
  // ../../packages/plugin-sdk/src/posture.ts
39337
38841
  function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
39338
38842
  for (const category of Object.keys(posture)) {
@@ -39346,43 +38850,6 @@ function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
39346
38850
  }
39347
38851
  }
39348
38852
 
39349
- // ../../packages/plugin-sdk/src/project-files.ts
39350
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
39351
- import { basename as basename5, join as join24 } from "path";
39352
-
39353
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
39354
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
39355
- if (typeof v === "string" && v.trim() === "") return void 0;
39356
- return v;
39357
- }, external_exports.string().optional()).catch(void 0);
39358
- var optionalFlag = external_exports.preprocess((v) => {
39359
- if (typeof v !== "string") return false;
39360
- const normalized = v.trim().toLowerCase();
39361
- return normalized !== "" && normalized !== "0" && normalized !== "false";
39362
- }, external_exports.boolean()).catch(false);
39363
- var antigravityProviderEnvShape = {
39364
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
39365
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
39366
- };
39367
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
39368
-
39369
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
39370
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
39371
- if (typeof v === "string" && v.trim() === "") return void 0;
39372
- return v;
39373
- }, external_exports.string().optional()).catch(void 0);
39374
- var codexProviderEnvShape = {
39375
- OPENAI_BASE_URL: optionalBaseUrl3
39376
- };
39377
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
39378
-
39379
- // ../../packages/plugin-sdk/src/runtime.ts
39380
- import { randomUUID as randomUUID15 } from "crypto";
39381
-
39382
- // ../../packages/plugin-sdk/src/scope-key.ts
39383
- import { existsSync as existsSync12 } from "fs";
39384
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join25, normalize } from "path";
39385
-
39386
38853
  // ../../packages/plugin-sdk/src/suppressions.ts
39387
38854
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
39388
38855
  function isDuplicateActive(err) {
@@ -39420,13 +38887,9 @@ async function applySetupTriageSuppressions(entries, writer, opts) {
39420
38887
  return { written, skippedDuplicate };
39421
38888
  }
39422
38889
 
39423
- // ../../packages/plugin-sdk/src/throttle.ts
39424
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
39425
- import { join as join26 } from "path";
39426
-
39427
38890
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
39428
- import { writeFileSync as writeFileSync8 } from "fs";
39429
- import { join as join27 } from "path";
38891
+ import { writeFileSync as writeFileSync5 } from "fs";
38892
+ import { join as join18 } from "path";
39430
38893
 
39431
38894
  // ../../packages/setup-wizard/src/triage/dedupe.ts
39432
38895
  function dedupeKey(hit) {
@@ -39481,12 +38944,12 @@ function deriveFalsePositivePatterns(hits, rec, plan) {
39481
38944
  }
39482
38945
 
39483
38946
  // ../../packages/setup-wizard/src/triage/gate-display.ts
39484
- function findContext(entry, join32) {
39485
- const byFingerprint = join32.find(
38947
+ function findContext(entry, join23) {
38948
+ const byFingerprint = join23.find(
39486
38949
  (j) => j.valueFingerprint !== void 0 && j.valueFingerprint === entry.valueFingerprint
39487
38950
  );
39488
38951
  if (byFingerprint) return byFingerprint.maskedContext;
39489
- const byRuleAndMask = join32.find(
38952
+ const byRuleAndMask = join23.find(
39490
38953
  (j) => j.ruleId === entry.ruleId && j.maskedMatch === entry.maskedValue
39491
38954
  );
39492
38955
  return byRuleAndMask?.maskedContext;
@@ -39557,13 +39020,13 @@ function renderShowcase(showcase) {
39557
39020
 
39558
39021
  ${blocks.join("\n\n")}`;
39559
39022
  }
39560
- function renderSuppressionGate(entries, join32) {
39023
+ function renderSuppressionGate(entries, join23) {
39561
39024
  if (entries.length === 0) {
39562
39025
  return "No false-positive suppressions to confirm \u2014 nothing will be written.";
39563
39026
  }
39564
39027
  const header = entries.length === 1 ? "This looks like a false positive \u2014 take a look before I suppress it:" : `These ${String(entries.length)} look like false positives \u2014 take a look before I suppress them:`;
39565
39028
  const blocks = entries.map((entry, i) => {
39566
- const context = findContext(entry, join32);
39029
+ const context = findContext(entry, join23);
39567
39030
  const lines = [
39568
39031
  `${String(i + 1)}. ${entry.ruleId} [${entry.category}]`,
39569
39032
  ` value: ${entry.maskedValue}`,
@@ -39649,9 +39112,9 @@ function mergeRecommendations(verdicts) {
39649
39112
  }
39650
39113
 
39651
39114
  // ../../packages/setup-wizard/src/triage/plan-file.ts
39652
- import { mkdtempSync, readFileSync as readFileSync17, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
39115
+ import { mkdtempSync, readFileSync as readFileSync11, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "fs";
39653
39116
  import { tmpdir } from "os";
39654
- import { basename as basename6, dirname as dirname7, join as join28 } from "path";
39117
+ import { basename as basename2, dirname as dirname4, join as join19 } from "path";
39655
39118
  var SuppressionEntrySchema = external_exports.object({
39656
39119
  ruleId: external_exports.string(),
39657
39120
  category: DetectionCategory,
@@ -39706,20 +39169,20 @@ function serializePlan(plan, current) {
39706
39169
  function writePlanFile(plan, current, rawValues, deps = {}) {
39707
39170
  const serialized = serializePlan(plan, current);
39708
39171
  assertRawFree(serialized, rawValues);
39709
- const dir = (deps.mkTempDir ?? (() => mkdtempSync(join28(tmpdir(), "aka-plan-"))))();
39710
- const path = join28(dir, "setup-plan.json");
39711
- writeFileSync9(path, serialized, { encoding: "utf8", mode: 384 });
39172
+ const dir = (deps.mkTempDir ?? (() => mkdtempSync(join19(tmpdir(), "aka-plan-"))))();
39173
+ const path = join19(dir, "setup-plan.json");
39174
+ writeFileSync6(path, serialized, { encoding: "utf8", mode: 384 });
39712
39175
  return path;
39713
39176
  }
39714
39177
  function readPlanFile(path) {
39715
- const text = readFileSync17(path, "utf8");
39178
+ const text = readFileSync11(path, "utf8");
39716
39179
  const json2 = JSON.parse(text);
39717
39180
  return PersistedPlanSchema.parse(json2);
39718
39181
  }
39719
39182
  function deletePlanFile(path) {
39720
39183
  rmSync7(path, { force: true });
39721
- const dir = dirname7(path);
39722
- if (!basename6(dir).startsWith("aka-plan-")) return;
39184
+ const dir = dirname4(path);
39185
+ if (!basename2(dir).startsWith("aka-plan-")) return;
39723
39186
  try {
39724
39187
  rmdirSync(dir);
39725
39188
  } catch {
@@ -39787,8 +39250,8 @@ function buildJoinEntries(hits) {
39787
39250
  }
39788
39251
 
39789
39252
  // ../../packages/setup-wizard/src/triage/resolve.ts
39790
- function resolveSuppressions(rec, join32) {
39791
- const byId = new Map(join32.map((e) => [e.id, e]));
39253
+ function resolveSuppressions(rec, join23) {
39254
+ const byId = new Map(join23.map((e) => [e.id, e]));
39792
39255
  const entries = [];
39793
39256
  const skipped = [];
39794
39257
  for (const cat of rec.perCategory) {
@@ -39890,7 +39353,7 @@ function parseTriageStream(text) {
39890
39353
  return { hits, status: "complete" };
39891
39354
  }
39892
39355
  function planTriageWriteback(hits, rec) {
39893
- const join32 = buildJoinEntries(hits);
39356
+ const join23 = buildJoinEntries(hits);
39894
39357
  const rawValues = hits.map((h) => h.rawMatch);
39895
39358
  const skipped = [];
39896
39359
  const posture = {};
@@ -39930,7 +39393,7 @@ function planTriageWriteback(hits, rec) {
39930
39393
  }
39931
39394
  const { entries, skipped: resolveSkips } = resolveSuppressions(
39932
39395
  { perCategory: safeCategories, notes: rec.notes },
39933
- join32
39396
+ join23
39934
39397
  );
39935
39398
  skipped.push(...resolveSkips);
39936
39399
  let notes = rec.notes;
@@ -39940,7 +39403,7 @@ function planTriageWriteback(hits, rec) {
39940
39403
  if (err instanceof RawEgressError) notes = SCRUBBED_NOTES;
39941
39404
  else throw err;
39942
39405
  }
39943
- return { entries, posture, showcase, join: join32, notes, skipped };
39406
+ return { entries, posture, showcase, join: join23, notes, skipped };
39944
39407
  }
39945
39408
  function recommendedPosture(evidence) {
39946
39409
  return { ...severityFloorPosture(), ...evidence };
@@ -40199,24 +39662,35 @@ async function runConfirm(deps, planIO) {
40199
39662
  }
40200
39663
 
40201
39664
  // ../../packages/setup-wizard/src/triage/parse-verdict.ts
40202
- var FENCE_RE = /```json\s*([\s\S]*?)```/g;
39665
+ var FENCE_OPEN = "```json";
39666
+ var FENCE_CLOSE = "```";
40203
39667
  function parseRecommendation(text) {
40204
- const fences = [...text.matchAll(FENCE_RE)];
40205
- const lastFence = fences.at(-1);
40206
- const raw = lastFence?.[1] ?? text;
39668
+ const raw = lastFenceBody(text) ?? text;
40207
39669
  return TriageRecommendation.parse(JSON.parse(raw.trim()));
40208
39670
  }
39671
+ function lastFenceBody(text) {
39672
+ let body;
39673
+ let open3 = text.indexOf(FENCE_OPEN);
39674
+ while (open3 !== -1) {
39675
+ const start = open3 + FENCE_OPEN.length;
39676
+ const close = text.indexOf(FENCE_CLOSE, start);
39677
+ if (close === -1) break;
39678
+ body = text.slice(start, close);
39679
+ open3 = text.indexOf(FENCE_OPEN, close + FENCE_CLOSE.length);
39680
+ }
39681
+ return body;
39682
+ }
40209
39683
 
40210
39684
  // src/triage/judge.ts
40211
39685
  import { execFileSync as execFileSync2 } from "child_process";
40212
- import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync18, rmSync as rmSync8 } from "fs";
39686
+ import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync12, rmSync as rmSync8 } from "fs";
40213
39687
  import { tmpdir as tmpdir2 } from "os";
40214
- import { dirname as dirname8, join as join29 } from "path";
40215
- import { fileURLToPath as fileURLToPath2 } from "url";
39688
+ import { dirname as dirname5, join as join20 } from "path";
39689
+ import { fileURLToPath } from "url";
40216
39690
 
40217
39691
  // ../../packages/plugin-sdk/src/bare-command.ts
40218
39692
  import { spawnSync } from "child_process";
40219
- import { homedir as homedir3 } from "os";
39693
+ import { homedir as homedir2 } from "os";
40220
39694
  import { win32 as win322 } from "path";
40221
39695
  var CMD_LINE_MAX = 8191;
40222
39696
  var CMD_WRAPPER_ALLOWANCE = 64;
@@ -40297,11 +39771,11 @@ function isDirectlyExecutable(file2) {
40297
39771
  return DIRECT_EXTENSIONS.has(win322.extname(file2).toLowerCase());
40298
39772
  }
40299
39773
  function planBareCommand(command, args, deps = {}) {
40300
- const platform2 = deps.platform ?? process.platform;
40301
- if (platform2 !== "win32") {
39774
+ const platform = deps.platform ?? process.platform;
39775
+ if (platform !== "win32") {
40302
39776
  return { file: command, args, options: {}, viaShell: false, resolved: void 0 };
40303
39777
  }
40304
- const home = deps.home ?? homedir3();
39778
+ const home = deps.home ?? homedir2();
40305
39779
  const resolve2 = deps.resolve ?? resolveWindowsCommand;
40306
39780
  const resolved = resolve2(command, deps.env, home);
40307
39781
  if (resolved !== void 0 && isDirectlyExecutable(resolved)) {
@@ -40322,8 +39796,8 @@ function planBareCommand(command, args, deps = {}) {
40322
39796
  }
40323
39797
 
40324
39798
  // src/triage/judge.ts
40325
- var TRIAGE_DIR = dirname8(fileURLToPath2(import.meta.url));
40326
- var DEFAULT_RUBRIC_PATH = join29(
39799
+ var TRIAGE_DIR = dirname5(fileURLToPath(import.meta.url));
39800
+ var DEFAULT_RUBRIC_PATH = join20(
40327
39801
  TRIAGE_DIR,
40328
39802
  "..",
40329
39803
  "..",
@@ -40379,7 +39853,7 @@ function runJudge(hits, deps) {
40379
39853
  if (typeof deps.spawn !== "function") {
40380
39854
  throw new TypeError("runJudge requires deps.spawn \u2014 there is no live-spawn fallback");
40381
39855
  }
40382
- const rubric = deps.loadRubric?.() ?? readFileSync18(DEFAULT_RUBRIC_PATH, "utf8");
39856
+ const rubric = deps.loadRubric?.() ?? readFileSync12(DEFAULT_RUBRIC_PATH, "utf8");
40383
39857
  const hitsJsonl = hits.map((h) => JSON.stringify(toJudgePayload(h))).join("\n");
40384
39858
  const fullPrompt = `${rubric}
40385
39859
 
@@ -40389,8 +39863,8 @@ function runJudge(hits, deps) {
40389
39863
  ${hitsJsonl}
40390
39864
  \`\`\`
40391
39865
  `;
40392
- const outDir = mkdtempSync2(join29(tmpdir2(), "aka-judge-"));
40393
- const outFile = join29(outDir, "last-message.txt");
39866
+ const outDir = mkdtempSync2(join20(tmpdir2(), "aka-judge-"));
39867
+ const outFile = join20(outDir, "last-message.txt");
40394
39868
  const argv = [
40395
39869
  "exec",
40396
39870
  "--ephemeral",
@@ -40407,7 +39881,7 @@ ${hitsJsonl}
40407
39881
  }
40408
39882
  let lastMessage;
40409
39883
  try {
40410
- lastMessage = readFileSync18(outFile, "utf8");
39884
+ lastMessage = readFileSync12(outFile, "utf8");
40411
39885
  } catch {
40412
39886
  throw new Error("codex exec wrote no last-message file");
40413
39887
  }
@@ -40488,8 +39962,8 @@ function table(headers, rows, opts = {}) {
40488
39962
  const widths = headers.map(
40489
39963
  (h, i) => Math.max(visibleLength(h), ...rows.map((r) => visibleLength(r[i] ?? "")))
40490
39964
  );
40491
- const sep4 = " ".repeat(gap);
40492
- const fmt = (cells) => cells.map((cell, i) => padEnd(cell, widths[i] ?? 0)).join(sep4);
39965
+ const sep2 = " ".repeat(gap);
39966
+ const fmt = (cells) => cells.map((cell, i) => padEnd(cell, widths[i] ?? 0)).join(sep2);
40493
39967
  const headerLine = fmt(headers.map((h) => h.toUpperCase()));
40494
39968
  if (opts.rowSep === true) {
40495
39969
  const fullWidth = widths.reduce((n, w) => n + w, 0) + gap * Math.max(0, widths.length - 1);
@@ -40501,7 +39975,7 @@ function table(headers, rows, opts = {}) {
40501
39975
  });
40502
39976
  return [headerLine, rule, ...body].join("\n");
40503
39977
  }
40504
- const ruleLine = widths.map((w) => "\u2500".repeat(w)).join(sep4);
39978
+ const ruleLine = widths.map((w) => "\u2500".repeat(w)).join(sep2);
40505
39979
  return [headerLine, ruleLine, ...rows.map(fmt)].join("\n");
40506
39980
  }
40507
39981
  function fenced(body) {
@@ -40514,10 +39988,10 @@ function show(body) {
40514
39988
  }
40515
39989
 
40516
39990
  // src/skills-registry.ts
40517
- import { readdirSync as readdirSync5, readFileSync as readFileSync19 } from "fs";
40518
- import { join as join30 } from "path";
40519
- import { fileURLToPath as fileURLToPath3 } from "url";
40520
- var SKILLS_DIR = fileURLToPath3(new URL("../skills", import.meta.url));
39991
+ import { readdirSync as readdirSync2, readFileSync as readFileSync13 } from "fs";
39992
+ import { join as join21 } from "path";
39993
+ import { fileURLToPath as fileURLToPath2 } from "url";
39994
+ var SKILLS_DIR = fileURLToPath2(new URL("../skills", import.meta.url));
40521
39995
  function frontmatterName(content) {
40522
39996
  const block = /^---\n([\s\S]*?)\n---/.exec(content);
40523
39997
  if (block === null) return void 0;
@@ -40525,10 +39999,10 @@ function frontmatterName(content) {
40525
39999
  return name?.[1];
40526
40000
  }
40527
40001
  function readRegisteredSkills() {
40528
- return readdirSync5(SKILLS_DIR, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
40002
+ return readdirSync2(SKILLS_DIR, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
40529
40003
  let content;
40530
40004
  try {
40531
- content = readFileSync19(join30(SKILLS_DIR, entry.name, "SKILL.md"), "utf8");
40005
+ content = readFileSync13(join21(SKILLS_DIR, entry.name, "SKILL.md"), "utf8");
40532
40006
  } catch {
40533
40007
  return [];
40534
40008
  }
@@ -40679,11 +40153,11 @@ function resolveCreatedBy() {
40679
40153
  }
40680
40154
  }
40681
40155
  function loadRubric() {
40682
- const here = dirname9(fileURLToPath4(import.meta.url));
40683
- const shipped = join31(here, "triage-rubric.md");
40684
- if (existsSync13(shipped)) return readFileSync20(shipped, "utf8");
40685
- return readFileSync20(
40686
- join31(here, "..", "..", "..", "packages", "setup-wizard", "assets", "triage-rubric.md"),
40156
+ const here = dirname6(fileURLToPath3(import.meta.url));
40157
+ const shipped = join22(here, "triage-rubric.md");
40158
+ if (existsSync9(shipped)) return readFileSync14(shipped, "utf8");
40159
+ return readFileSync14(
40160
+ join22(here, "..", "..", "..", "packages", "setup-wizard", "assets", "triage-rubric.md"),
40687
40161
  "utf8"
40688
40162
  );
40689
40163
  }
@@ -40693,10 +40167,12 @@ async function main() {
40693
40167
  argv,
40694
40168
  // fd 0 = stdin; the wizard pipes `backfill.js --triage` into this on preview.
40695
40169
  // Called only on the preview path — the confirm path never reads a stream.
40696
- readStream: (streamPath) => streamPath !== void 0 ? readFileSync20(streamPath, "utf8") : readFileSync20(0, "utf8"),
40170
+ readStream: (streamPath) => streamPath !== void 0 ? readFileSync14(streamPath, "utf8") : readFileSync14(0, "utf8"),
40697
40171
  runJudge: (hits) => runJudge(hits, { spawn: spawnCodex, loadRubric }),
40698
40172
  openDb: () => {
40699
- const db = openLocalDatabase(loadConfig().dataDir);
40173
+ const db = openLocalDatabase(loadConfig().dataDir, {
40174
+ shippedRegexMatchers: shippedRegexMatchers()
40175
+ });
40700
40176
  return {
40701
40177
  policies: db.policies,
40702
40178
  exceptions: db.exceptions,