@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,895 +1,15 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- try {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- } catch (e) {
11
- throw mod = 0, e;
12
- }
13
- };
14
2
  var __export = (target, all) => {
15
3
  for (var name in all)
16
4
  __defProp(target, name, { get: all[name], enumerable: true });
17
5
  };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
-
35
- // ../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js
36
- var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js"(exports, module) {
38
- "use strict";
39
- function makeArray(subject) {
40
- return Array.isArray(subject) ? subject : [subject];
41
- }
42
- var UNDEFINED = void 0;
43
- var EMPTY = "";
44
- var SPACE = " ";
45
- var ESCAPE = "\\";
46
- var REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
47
- var REGEX_TEST_BLANK_LINE = /^\uFEFF? *$/;
48
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
49
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
50
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
51
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
52
- var DOUBLE_SLASH = "//";
53
- var SLASH_CODE = 47;
54
- var DOT_CODE = 46;
55
- var SLASH3 = "/";
56
- var TMP_KEY_IGNORE = "node-ignore";
57
- if (typeof Symbol !== "undefined") {
58
- TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
59
- }
60
- var KEY_IGNORE = TMP_KEY_IGNORE;
61
- var define = (object2, key, value) => {
62
- Object.defineProperty(object2, key, { value });
63
- return value;
64
- };
65
- var RETURN_FALSE = () => false;
66
- var cleanRangeBackSlash = (slashes) => {
67
- const { length } = slashes;
68
- return slashes.slice(0, length - length % 2);
69
- };
70
- var POSIX_CLASSES = {
71
- alnum: "0-9A-Za-z",
72
- alpha: "A-Za-z",
73
- blank: " \\t",
74
- cntrl: "\\x00-\\x1f\\x7f",
75
- digit: "0-9",
76
- graph: "!-.0-~",
77
- lower: "a-z",
78
- print: " -.0-~",
79
- punct: "!-.:-@\\[-`{-~",
80
- // git's `sane-ctype.h` classifies \v and \f as control, not space,
81
- // unlike C's `isspace`
82
- space: " \\t\\n\\r",
83
- upper: "A-Z",
84
- xdigit: "0-9A-Fa-f"
85
- };
86
- var CLASS_MEMBERS_TO_ESCAPE = "\\]^-[";
87
- var escapeMember = (char) => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0 ? char : ESCAPE + char;
88
- var NON_SLASH = "(?!\\/)";
89
- var classSource = (negated, body) => {
90
- if (negated) {
91
- return `[^\\/${body}]`;
92
- }
93
- const source = `[${body}]`;
94
- return new RegExp(source).test("/") ? NON_SLASH + source : source;
95
- };
96
- var scanBracket = (pattern, start) => {
97
- const { length } = pattern;
98
- let index = start + 1;
99
- let negated = EMPTY;
100
- const lead = pattern[index];
101
- if (lead === "!" || lead === "^") {
102
- negated = "^";
103
- index++;
104
- }
105
- let body = EMPTY;
106
- let prev = EMPTY;
107
- for (; ; ) {
108
- const char = pattern[index];
109
- if (char === UNDEFINED) {
110
- return null;
111
- }
112
- if (char === ESCAPE) {
113
- const escaped = pattern[index + 1];
114
- if (escaped === UNDEFINED) {
115
- return null;
116
- }
117
- body += escapeMember(escaped);
118
- prev = escaped;
119
- index++;
120
- } else if (char === "-" && prev && index + 1 < length && pattern[index + 1] !== "]") {
121
- index++;
122
- let to = pattern[index];
123
- if (to === ESCAPE) {
124
- to = pattern[index += 1];
125
- }
126
- if (prev <= to) {
127
- body += `-${escapeMember(to)}`;
128
- }
129
- prev = EMPTY;
130
- } else if (char === "[" && pattern[index + 1] === ":") {
131
- const nameStart = index + 2;
132
- let end = nameStart;
133
- while (end < length && pattern[end] !== "]") {
134
- end++;
135
- }
136
- if (end === length) {
137
- return null;
138
- }
139
- if (end > nameStart && pattern[end - 1] === ":") {
140
- const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)];
141
- if (expanded === UNDEFINED) {
142
- return null;
143
- }
144
- body += expanded;
145
- prev = EMPTY;
146
- index = end;
147
- } else {
148
- body += escapeMember("[");
149
- prev = "[";
150
- index = nameStart - 2;
151
- }
152
- } else {
153
- body += escapeMember(char);
154
- prev = char;
155
- }
156
- index++;
157
- if (pattern[index] === "]") {
158
- return {
159
- end: index,
160
- source: classSource(negated, body)
161
- };
162
- }
163
- }
164
- };
165
- var NEVER_MATCH = "[]";
166
- var PLACEHOLDER = "\0";
167
- var REGEX_RESTORE_PLACEHOLDER = new RegExp(
168
- `${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,
169
- "g"
170
- );
171
- var TRAILING_WILDCARD = "\uE000";
172
- var TRAILING_DOUBLESTAR = "\uE001";
173
- var extractBrackets = (pattern) => {
174
- const sources = [];
175
- const hold = (source) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
176
- const { length } = pattern;
177
- let out = EMPTY;
178
- let index = 0;
179
- while (index < length) {
180
- const char = pattern[index];
181
- if (char === ESCAPE) {
182
- const escaped = pattern[index + 1];
183
- if (escaped === "*" || escaped === "[" || escaped === SPACE || escaped === ESCAPE) {
184
- out += pattern.slice(index, index + 2);
185
- } else {
186
- out += hold(
187
- REGEX_LITERAL_SPECIAL.test(escaped) ? ESCAPE + escaped : escaped
188
- );
189
- }
190
- index += 2;
191
- } else if (char === PLACEHOLDER) {
192
- out += hold(`[${PLACEHOLDER}]`);
193
- index++;
194
- } else if (char === "[") {
195
- const scanned = scanBracket(pattern, index);
196
- if (scanned === null) {
197
- out += hold(NEVER_MATCH);
198
- index = length;
199
- } else {
200
- out += hold(scanned.source);
201
- index = scanned.end + 1;
202
- }
203
- } else {
204
- out += char;
205
- index++;
206
- }
207
- }
208
- return {
209
- source: out,
210
- sources
211
- };
212
- };
213
- var DIRECT = null;
214
- var REGEX_INNER_SLASH = /\/(?!$)/;
215
- var REPLACERS = [
216
- [
217
- // Remove BOM
218
- // TODO:
219
- // Other similar zero-width characters?
220
- /^\uFEFF/,
221
- () => EMPTY,
222
- "\uFEFF"
223
- ],
224
- [
225
- // A trailing line terminator, left on when a whole file's contents are
226
- // added as one pattern rather than split into lines. git never sees one
227
- // -- it reads a `.gitignore` line by line -- so it is not part of the
228
- // pattern and is dropped here, apart from the trailing-space trimming,
229
- // which follows git in touching spaces and nothing else.
230
- /[\r\n]+$/,
231
- () => EMPTY
232
- ],
233
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
234
- [
235
- // Only spaces, never tabs or other whitespace: git trims a trailing run
236
- // of `' '` and nothing else (dir.c, `trim_trailing_spaces`, a single
237
- // `case ' '`), so a pattern ending in a tab keeps it as a literal.
238
- // (a\ ) -> (a )
239
- // (a ) -> (a)
240
- // (a ) -> (a)
241
- // (a \ ) -> (a )
242
- /((?:\\\\)*?)(\\? +)$/,
243
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
244
- ],
245
- // Replace (\ ) with ' '
246
- // Only a space: an escaped tab or other whitespace is already a literal by
247
- // the time it reaches here, and a bare tab must be left as one, not turned
248
- // into a space.
249
- // (\ ) -> ' '
250
- // (\\ ) -> '\\ '
251
- // (\\\ ) -> '\\ '
252
- [
253
- /(\\+?) /g,
254
- (_, m1) => {
255
- const { length } = m1;
256
- return m1.slice(0, length - length % 2) + SPACE;
257
- }
258
- ],
259
- // Escape metacharacters
260
- // which is written down by users but means special for regular expressions.
261
- // > There are 12 characters with special meanings:
262
- // > - the backslash \,
263
- // > - the caret ^,
264
- // > - the dollar sign $,
265
- // > - the period or dot .,
266
- // > - the vertical bar or pipe symbol |,
267
- // > - the question mark ?,
268
- // > - the asterisk or star *,
269
- // > - the plus sign +,
270
- // > - the opening parenthesis (,
271
- // > - the closing parenthesis ),
272
- // > - and the opening square bracket [,
273
- // > - the opening curly brace {,
274
- // > These special characters are often called "metacharacters".
275
- [
276
- /[\\$.|*+(){^]/g,
277
- (match) => `\\${match}`
278
- ],
279
- [
280
- // > a question mark (?) matches a single character
281
- /(?!\\)\?/g,
282
- () => "[^/]",
283
- "?"
284
- ],
285
- // leading slash
286
- [
287
- // > A leading slash matches the beginning of the pathname.
288
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
289
- // A leading slash matches the beginning of the pathname
290
- /^\//,
291
- () => "^",
292
- SLASH3
293
- ],
294
- // replace special metacharacter slash after the leading slash
295
- [
296
- /\//g,
297
- () => "\\/",
298
- SLASH3
299
- ],
300
- [
301
- // > A leading "**" followed by a slash means match in all directories.
302
- // > For example, "**/foo" matches file or directory "foo" anywhere,
303
- // > the same as pattern "foo".
304
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
305
- // > under directory "foo".
306
- // Notice that the '*'s have been replaced as '\\*'
307
- /^\^*(?:\\\*\\\*\\\/)+/,
308
- // '**/foo' <-> 'foo'
309
- () => "^(?:.*\\/)?",
310
- "*"
311
- ],
312
- // starting
313
- [
314
- // there will be no leading '/'
315
- // (which has been replaced by section "leading slash")
316
- // If starts with '**', adding a '^' to the regular expression also works
317
- DIRECT,
318
- (source, pattern) => {
319
- if (!source || source[0] === "^") {
320
- return source;
321
- }
322
- const anchor2 = !REGEX_INNER_SLASH.test(pattern) ? "(?:^|\\/)" : "^";
323
- return anchor2 + source;
324
- }
325
- ],
326
- // two globstars
327
- [
328
- // Use lookahead assertions so that we could match more than one `'/**'`
329
- /\\\/\\\*\\\*(?=\\\/|$)/g,
330
- // Zero, one or several directories
331
- // should not use '*', or it will be replaced by the next replacer
332
- // Check if it is not the last `'/**'`
333
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
334
- "*"
335
- ],
336
- // normal intermediate wildcards
337
- [
338
- // Never replace escaped '*'
339
- // ignore rule '\*' will match the path '*'
340
- // 'abc.*/' -> go
341
- // 'abc.*' -> skip this rule,
342
- // coz trailing single wildcard will be handed by [trailing wildcard]
343
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
344
- // '*.js' matches '.js'
345
- // '*.js' doesn't match 'abc'
346
- (_, p1, p2) => {
347
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
348
- return p1 + unescaped;
349
- },
350
- "*"
351
- ],
352
- // trailing wildcard, held apart from a literal star
353
- [
354
- // The step above leaves a trailing `*` alone, so a single `\*` is all that
355
- // can be left at the end here. Whether it is a wildcard or a literal
356
- // turns on the backslashes the user put in front of it: the escaper has
357
- // since doubled every one, so what stands here is those `2N` doubled
358
- // backslashes and then the star's own escape. An even number of the
359
- // original `N` leaves the star unescaped -- a wildcard -- and an odd
360
- // number escapes it -- a literal. This runs while the two are still
361
- // distinct, before the unescape steps below collapse the literal onto
362
- // the very `\*` a wildcard leaves behind.
363
- /(^|[^\\])((?:\\\\)*)\\\*$/,
364
- (match, p1, p2) => (
365
- // `p2` holds the doubled user backslashes; half of them is `N`.
366
- p2.length / 2 % 2 === 0 ? p1 + p2 + TRAILING_WILDCARD : match
367
- ),
368
- "*"
369
- ],
370
- [
371
- // unescape, revert step 3 except for back slash
372
- // For example, if a user escape a '\\*',
373
- // after step 3, the result will be '\\\\\\*'
374
- /\\\\\\(?=[$.|*+(){^])/g,
375
- () => ESCAPE,
376
- ESCAPE + ESCAPE
377
- ],
378
- [
379
- // '\\\\' -> '\\'
380
- /\\\\/g,
381
- () => ESCAPE,
382
- ESCAPE + ESCAPE
383
- ],
384
- [
385
- // Every real bracket expression -- POSIX classes included -- has already
386
- // been held aside by `extractBrackets`, so the only `[` left in the
387
- // pattern is an escaped, literal one.
388
- // `\` is escaped by step 3
389
- /\\\[([^\]/]*?)(\\*)($|\])/g,
390
- // '\\[bar]' -> '\\\\[bar\\]'
391
- (match, range, endEscape, close) => `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,
392
- "["
393
- ],
394
- // ending
395
- [
396
- // 'js' will not match 'js.'
397
- // 'ab' will not match 'abc'
398
- DIRECT,
399
- // WTF!
400
- // https://git-scm.com/docs/gitignore
401
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
402
- // which re-fixes #24, #38
403
- // > If there is a separator at the end of the pattern then the pattern
404
- // > will only match directories, otherwise the pattern can match both
405
- // > files and directories.
406
- // 'js*' will not match 'a.js'
407
- // 'js/' will not match 'a.js'
408
- // 'js' will match 'a.js' and 'a.js/'
409
- (source) => {
410
- const last = source[source.length - 1];
411
- if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
412
- return source;
413
- }
414
- return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
415
- }
416
- ]
417
- ];
418
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\uE000$/;
419
- var MODE_IGNORE = "regex";
420
- var MODE_CHECK_IGNORE = "checkRegex";
421
- var UNDERSCORE = "_";
422
- var replaceTrailingWildcard = (_, p1) => {
423
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
- return `${prefix}(?=$|\\/$)`;
425
- };
426
- var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
427
- var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
428
- var WILDCARD = "[^\\/]*";
429
- var separatorAfter = (run, at) => {
430
- let separator = EMPTY;
431
- for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
432
- separator += run[index].single;
433
- }
434
- return separator;
435
- };
436
- var pinWildcards = (source) => {
437
- if (source.indexOf(WILDCARD) < 0) {
438
- return source;
439
- }
440
- const tokens = [];
441
- const { length } = source;
442
- let index = 0;
443
- while (index < length) {
444
- const char = source[index];
445
- if (source.startsWith(WILDCARD, index)) {
446
- tokens.push({ wildcard: true });
447
- index += WILDCARD.length;
448
- } else if (char === "[") {
449
- let end = index + 1;
450
- if (source[end] === "^") {
451
- end++;
452
- }
453
- if (source[end] === "]") {
454
- end++;
455
- }
456
- while (end < length && source[end] !== "]") {
457
- end += source[end] === ESCAPE ? 2 : 1;
458
- }
459
- end++;
460
- tokens.push({ single: source.slice(index, end) });
461
- index = end;
462
- } else if (char === ESCAPE) {
463
- tokens.push({ single: source.slice(index, index + 2) });
464
- index += 2;
465
- } else if (char === "(") {
466
- let depth = 0;
467
- let end = index;
468
- do {
469
- if (source[end] === ESCAPE) {
470
- end++;
471
- } else if (source[end] === "(") {
472
- depth++;
473
- } else if (source[end] === ")") {
474
- depth--;
475
- }
476
- end++;
477
- } while (end < length && depth > 0);
478
- if ("*+?".indexOf(source[end]) >= 0) {
479
- end++;
480
- }
481
- tokens.push({ boundary: source.slice(index, end) });
482
- index = end;
483
- } else if (char === "^" || char === "$") {
484
- tokens.push({ boundary: char });
485
- index++;
486
- } else {
487
- tokens.push({ single: char });
488
- index++;
489
- }
490
- }
491
- let out = EMPTY;
492
- let run = [];
493
- const flush = () => {
494
- let lastWildcard;
495
- run.forEach((token, at) => {
496
- if (token.wildcard) {
497
- lastWildcard = at;
498
- }
499
- });
500
- run.forEach((token, at) => {
501
- if (!token.wildcard) {
502
- out += token.single;
503
- return;
504
- }
505
- out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
506
- });
507
- run = [];
508
- };
509
- tokens.forEach((token) => {
510
- if (token.boundary === void 0) {
511
- run.push(token);
512
- return;
513
- }
514
- flush();
515
- out += token.boundary;
516
- });
517
- flush();
518
- return out;
519
- };
520
- var makeRegexPrefix = (pattern) => {
521
- const { source, sources } = extractBrackets(pattern);
522
- const replaced = REPLACERS.reduce(
523
- // A pass whose matcher finds nothing hands back the very string it was
524
- // given, so asking first costs a search and saves a rewrite. Ten of the
525
- // fifteen passes never fire for a typical .gitignore line, and between
526
- // them they were 45% of this chain.
527
- (prev, [matcher, replacer, required2]) => {
528
- if (matcher === DIRECT) {
529
- return replacer(prev, pattern);
530
- }
531
- if (required2 !== UNDEFINED && prev.indexOf(required2) < 0) {
532
- return prev;
533
- }
534
- return matcher.test(prev) ? prev.replace(matcher, replacer.bind(pattern)) : prev;
535
- },
536
- source
537
- );
538
- return sources.length ? replaced.replace(
539
- REGEX_RESTORE_PLACEHOLDER,
540
- (match, index) => sources[index]
541
- ) : replaced;
542
- };
543
- var checkSourceOf = (body, prefix) => {
544
- if (body[body.length - 1] === SLASH3) {
545
- prefix = makeRegexPrefix(body.slice(0, -1));
546
- }
547
- const head = prefix.slice(0, -1);
548
- const last = prefix[prefix.length - 1];
549
- return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
- };
551
- var matchesBasename = (body) => {
552
- const index = body.indexOf(SLASH3);
553
- return index < 0 || index === body.length - 1;
554
- };
555
- var basenameOf = (path) => {
556
- const end = path.length - 1;
557
- const index = path.lastIndexOf(
558
- SLASH3,
559
- path[end] === SLASH3 ? end - 1 : end
560
- );
561
- return index < 0 ? path : path.slice(index + 1);
562
- };
563
- var parentOf = (path) => {
564
- if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
565
- const slices = path.split(SLASH3).filter(Boolean);
566
- slices.pop();
567
- return slices.length ? slices.join(SLASH3) + SLASH3 : EMPTY;
568
- }
569
- const end = path.length - 1;
570
- const cut = path.lastIndexOf(
571
- SLASH3,
572
- path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
573
- );
574
- return cut < 0 ? EMPTY : path.slice(0, cut + 1);
575
- };
576
- var isString = (subject) => typeof subject === "string";
577
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
578
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
579
- var IgnoreRule = class {
580
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
581
- this.pattern = pattern;
582
- this.mark = mark;
583
- this.negative = negative;
584
- define(this, "body", body);
585
- define(this, "ignoreCase", ignoreCase);
586
- define(this, "regexPrefix", prefix);
587
- }
588
- // Worked out on first use and kept behind an own property, the way `regex`
589
- // caches itself in `_regex`. Deciding it in the constructor instead would
590
- // add a fourth `defineProperty` to every rule ever built, which cost 4% of
591
- // every compile -- including the compiles of rules that are never matched
592
- // against anything.
593
- get _basenameOnly() {
594
- return define(this, "_basenameOnly", matchesBasename(this.body));
595
- }
596
- get regex() {
597
- const key = UNDERSCORE + MODE_IGNORE;
598
- if (this[key]) {
599
- return this[key];
600
- }
601
- return this._make(MODE_IGNORE, key);
602
- }
603
- get checkRegex() {
604
- const key = UNDERSCORE + MODE_CHECK_IGNORE;
605
- if (this[key]) {
606
- return this[key];
607
- }
608
- return this._make(MODE_CHECK_IGNORE, key);
609
- }
610
- _make(mode, key) {
611
- const str2 = pinWildcards(
612
- mode === MODE_IGNORE ? this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar) : checkSourceOf(this.body, this.regexPrefix)
613
- );
614
- const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
615
- return define(this, key, regex);
616
- }
617
- };
618
- var createRule = ({
619
- pattern,
620
- mark
621
- }, ignoreCase) => {
622
- let negative = false;
623
- let body = pattern;
624
- if (body.indexOf("!") === 0) {
625
- negative = true;
626
- body = body.substr(1);
627
- }
628
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
629
- const regexPrefix = makeRegexPrefix(body);
630
- return new IgnoreRule(
631
- pattern,
632
- mark,
633
- body,
634
- ignoreCase,
635
- negative,
636
- regexPrefix
637
- );
638
- };
639
- var RuleManager = class {
640
- constructor(ignoreCase) {
641
- this._ignoreCase = ignoreCase;
642
- this._rules = [];
643
- this._basenameCount = 0;
644
- }
645
- _add(pattern) {
646
- if (pattern && pattern[KEY_IGNORE]) {
647
- this._rules = this._rules.concat(pattern._rules._rules);
648
- this._basenameCount += pattern._rules._basenameCount;
649
- this._added = true;
650
- return;
651
- }
652
- if (isString(pattern)) {
653
- pattern = {
654
- pattern
655
- };
656
- }
657
- if (checkPattern(pattern.pattern)) {
658
- const rule = createRule(pattern, this._ignoreCase);
659
- this._added = true;
660
- this._rules.push(rule);
661
- if (matchesBasename(rule.body)) {
662
- this._basenameCount++;
663
- }
664
- }
665
- }
666
- // @param {Array<string> | string | Ignore} pattern
667
- add(pattern) {
668
- this._added = false;
669
- makeArray(
670
- isString(pattern) ? splitPattern(pattern) : pattern
671
- ).forEach(this._add, this);
672
- if (this._added) {
673
- this._literalRules = UNDEFINED;
674
- }
675
- return this._added;
676
- }
677
- // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule
678
- // ending in a wildcard can match it (see `checkSourceOf`), so the rest
679
- // are left out once, rather than tested or compiled for every path.
680
- testLiteral(path) {
681
- const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
- ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
683
- ));
684
- let ignored = false;
685
- let unignored = false;
686
- let matchedRule;
687
- for (let index = rules.length - 1; index >= 0; index--) {
688
- const rule = rules[index];
689
- if (rule.checkRegex.test(path)) {
690
- ignored = !rule.negative;
691
- unignored = rule.negative;
692
- matchedRule = rule.negative ? UNDEFINED : rule;
693
- break;
694
- }
695
- }
696
- const ret = {
697
- ignored,
698
- unignored
699
- };
700
- if (matchedRule) {
701
- ret.rule = matchedRule;
702
- }
703
- return ret;
704
- }
705
- // Test one single path without recursively checking parent directories
706
- //
707
- // - checkUnignored `boolean` whether should check if the path is unignored,
708
- // setting `checkUnignored` to `false` could reduce additional
709
- // path matching.
710
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
711
- // @returns {TestResult} true if a file is ignored
712
- test(path, checkUnignored, mode) {
713
- let ignored = false;
714
- let unignored = false;
715
- let matchedRule;
716
- const rules = this._rules;
717
- const { length } = rules;
718
- const shortcut = this._basenameCount * 2 >= length;
719
- const basename8 = 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 ? basename8 : 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/backfill.ts
876
8
  import { fileURLToPath as fileURLToPath5 } from "url";
877
9
 
878
10
  // ../../packages/plugin-sdk/src/config.ts
879
11
  import { existsSync as existsSync8 } from "fs";
880
- import { join as join16 } from "path";
881
-
882
- // ../../packages/persistence/src/attached-derived.ts
883
- import { rmSync } from "fs";
884
- import { join } from "path";
885
- var POLICY_CACHE_FILENAME = "policy-cache.json";
886
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
887
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
888
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
889
-
890
- // ../../packages/persistence/src/control-plane-credential.ts
891
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
892
- import { join as join2 } from "path";
12
+ import { join as join17 } from "path";
893
13
 
894
14
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
895
15
  var DEFERRED_MIGRATION_TAGS = [
@@ -1062,7 +182,7 @@ var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1062
182
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1063
183
 
1064
184
  // ../../packages/schema/src/invisible-padding.ts
1065
- var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
185
+ 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;
1066
186
  function stripInvisiblePadding(text) {
1067
187
  return text.replace(INVISIBLE_PADDING, "");
1068
188
  }
@@ -20802,13 +19922,16 @@ function serviceTierMultiplier(tier) {
20802
19922
  if (tier === void 0) return 1;
20803
19923
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20804
19924
  }
19925
+ function promptTokensOf(usage) {
19926
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19927
+ }
20805
19928
  function costOf(price, usage) {
20806
19929
  const metered = [
20807
19930
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20808
19931
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20809
19932
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20810
19933
  ];
20811
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19934
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20812
19935
  if (band !== null && (band.input === null || band.output === null)) return null;
20813
19936
  const inputRate = band?.input ?? price.input;
20814
19937
  const outputRate = band?.output ?? price.output;
@@ -21018,7 +20141,7 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21018
20141
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21019
20142
  var BEDROCK_REVISION_RE = /:\d+$/u;
21020
20143
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21021
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20144
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21022
20145
  function stripPlatformDecorations(model) {
21023
20146
  let id = model.trim();
21024
20147
  let platform2 = null;
@@ -21168,7 +20291,7 @@ anthropic.model("claude-haiku-4-5", {
21168
20291
  name: "Claude Haiku 4.5",
21169
20292
  ctx: 2e5,
21170
20293
  maxOut: 64e3,
21171
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20294
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21172
20295
  capability: null,
21173
20296
  price: anthropicPrice(1, 5, 0.1),
21174
20297
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21299,6 +20422,11 @@ openai.model("gpt-4o", {
21299
20422
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21300
20423
  on: [...OPENAI_RESELLERS]
21301
20424
  });
20425
+ openai.model("gpt-4o-2024-05-13", {
20426
+ name: "GPT-4o (2024-05-13)",
20427
+ price: tokenPrice(5, 15),
20428
+ on: [...OPENAI_RESELLERS]
20429
+ });
21302
20430
  openai.model("gpt-4o-mini", {
21303
20431
  name: "GPT-4o mini",
21304
20432
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21318,6 +20446,24 @@ openai.model("o3", {
21318
20446
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21319
20447
  on: [...OPENAI_RESELLERS]
21320
20448
  });
20449
+ openai.model("text-embedding-3-small", {
20450
+ name: "text-embedding-3-small",
20451
+ capability: "embedding",
20452
+ price: tokenPrice(0.02, 0),
20453
+ on: [...OPENAI_RESELLERS]
20454
+ });
20455
+ openai.model("text-embedding-3-large", {
20456
+ name: "text-embedding-3-large",
20457
+ capability: "embedding",
20458
+ price: tokenPrice(0.13, 0),
20459
+ on: [...OPENAI_RESELLERS]
20460
+ });
20461
+ openai.model("text-embedding-ada-002", {
20462
+ name: "text-embedding-ada-002",
20463
+ capability: "embedding",
20464
+ price: tokenPrice(0.1, 0),
20465
+ on: [...OPENAI_RESELLERS]
20466
+ });
21321
20467
  openai.model("gpt-oss-120b", {
21322
20468
  name: "GPT-OSS 120B",
21323
20469
  openWeights: true,
@@ -21604,10 +20750,21 @@ var MODEL_ENTRIES = Object.freeze([
21604
20750
  ...alibaba.models(),
21605
20751
  ...amazon.models()
21606
20752
  ]);
20753
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20754
+ [
20755
+ ...new Set(
20756
+ MODEL_ENTRIES.flatMap(
20757
+ (entry) => [...entry.platforms.values()].flatMap(
20758
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20759
+ )
20760
+ )
20761
+ )
20762
+ ].sort((a, b) => a - b)
20763
+ );
21607
20764
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21608
20765
 
21609
20766
  // ../../packages/schema/src/model/governance.ts
21610
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20767
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21611
20768
  var DataRetention = external_exports.enum([
21612
20769
  "zero_retention",
21613
20770
  "no_storage",
@@ -21738,7 +20895,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21738
20895
 
21739
20896
  // ../../packages/schema/src/token/token-report.ts
21740
20897
  var num = (value) => value ?? 0;
21741
- function costUsageOf(a) {
20898
+ function costUsageOf(a, promptTokens) {
21742
20899
  const usage = {
21743
20900
  inputTokens: num(a.input_tokens),
21744
20901
  outputTokens: num(a.output_tokens),
@@ -21748,11 +20905,12 @@ function costUsageOf(a) {
21748
20905
  webSearchRequests: num(a.web_search_requests)
21749
20906
  };
21750
20907
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20908
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21751
20909
  return usage;
21752
20910
  }
21753
20911
  function buildTokenReports(leaves, costModel) {
21754
20912
  const bySession = /* @__PURE__ */ new Map();
21755
- for (const { sessionId, attributes } of leaves) {
20913
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21756
20914
  const provider = attributes.provider ?? "unknown";
21757
20915
  const model = attributes.model ?? "unknown";
21758
20916
  const key = `${provider} ${model}`;
@@ -21771,7 +20929,8 @@ function buildTokenReports(leaves, costModel) {
21771
20929
  cacheCreation: 0,
21772
20930
  cacheRead: 0,
21773
20931
  costUsd: 0,
21774
- priced: false
20932
+ priced: false,
20933
+ partial: false
21775
20934
  };
21776
20935
  rollups.set(key, acc);
21777
20936
  }
@@ -21779,8 +20938,14 @@ function buildTokenReports(leaves, costModel) {
21779
20938
  acc.output += num(attributes.output_tokens);
21780
20939
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21781
20940
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21782
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21783
- if (leafCost !== null) {
20941
+ const leafCost = costModel.costFor({
20942
+ provider,
20943
+ model,
20944
+ usage: costUsageOf(attributes, promptTokens)
20945
+ });
20946
+ if (leafCost === null) {
20947
+ acc.partial = true;
20948
+ } else {
21784
20949
  acc.costUsd += leafCost;
21785
20950
  acc.priced = true;
21786
20951
  }
@@ -21796,9 +20961,8 @@ function buildTokenReports(leaves, costModel) {
21796
20961
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21797
20962
  totalTokens += rollupTotal;
21798
20963
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21799
- if (estimatedCostUsd === null) {
21800
- anyUnpriced = true;
21801
- } else {
20964
+ if (acc.partial) anyUnpriced = true;
20965
+ if (estimatedCostUsd !== null) {
21802
20966
  anyPriced = true;
21803
20967
  costUsd += estimatedCostUsd;
21804
20968
  }
@@ -21821,7 +20985,7 @@ function buildTokenReports(leaves, costModel) {
21821
20985
  totalTokens,
21822
20986
  // Σ of the PRICED rollups; null when none had a known price.
21823
20987
  estimatedCostUsd: anyPriced ? costUsd : null,
21824
- // Any unknown (provider, model) means the total understates real spend.
20988
+ // Any call priced to null means the total understates real spend.
21825
20989
  costIsPartial: anyUnpriced
21826
20990
  });
21827
20991
  }
@@ -22526,6 +21690,11 @@ var CaptureAttributes = external_exports.object({
22526
21690
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22527
21691
  // repeated rather than referenced because a store reader opens this file.
22528
21692
  redact_degraded_to: ActionTaken.optional(),
21693
+ // Why a capture has no content and no findings: its field was refused
21694
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
21695
+ // whose value this is). Absent on every capture that was scanned, so a
21696
+ // reader can tell a refused row from an empty clean one.
21697
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22529
21698
  // The scope key this capture was stamped with: the canonical repository
22530
21699
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22531
21700
  // against its working directory), else of its own working directory, or a
@@ -22703,8 +21872,9 @@ var SessionTokenReport = external_exports.object({
22703
21872
  totalTokens: external_exports.number().int().nonnegative(),
22704
21873
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22705
21874
  estimatedCostUsd: external_exports.number().nullable(),
22706
- // True whenever any rollup has a null cost (unknown provider/model), so the
22707
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21875
+ // True whenever any call priced to null (an unknown provider/model, or a call
21876
+ // over a long-context threshold whose rate is unpublished), so the total
21877
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22708
21878
  // precise figure rather than silently dropping the unpriced calls.
22709
21879
  costIsPartial: external_exports.boolean()
22710
21880
  });
@@ -23581,7 +22751,15 @@ var StorePostureSnapshot = external_exports.object({
23581
22751
  policyCounts: StorePosturePolicyCounts,
23582
22752
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23583
22753
  // getting its 200 without a payload change.
23584
- plugin: StorePosturePlugin.optional()
22754
+ plugin: StorePosturePlugin.optional(),
22755
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22756
+ // machine attachment omits it, so its body is byte for byte the one it
22757
+ // sent before this member existed. Absent therefore means machine-wide OR
22758
+ // a reporter older than this member, never "scoped". Both values parse, so
22759
+ // a sender that one day spells `machine` breaks no receiver; any other
22760
+ // value fails the whole snapshot, which is why the reporter sends a
22761
+ // constant and never the raw mode.
22762
+ attachmentMode: AttachmentMode.optional()
23585
22763
  }).meta({ id: "StorePostureSnapshot" });
23586
22764
  var CAPTURE_VERSION_PREFIX = "capture/";
23587
22765
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23858,7 +23036,19 @@ var EventMetadata = external_exports.object({
23858
23036
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23859
23037
  // Closing either means moving the reason onto the finding row, which
23860
23038
  // already carries its own action.
23861
- redactDegradedTo: ActionTaken.optional()
23039
+ redactDegradedTo: ActionTaken.optional(),
23040
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23041
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23042
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23043
+ // field instead of letting it through unscanned.
23044
+ //
23045
+ // - 'timeout': the bounded scan ran out of time.
23046
+ // - 'unavailable': no worker could run it.
23047
+ //
23048
+ // A refused row stores '' as its content and has no findings, which is
23049
+ // exactly what a clean, empty capture looks like — this marker is the only
23050
+ // thing that tells the two apart. Absent on every capture that was scanned.
23051
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23862
23052
  }).meta({ id: "EventMetadata" });
23863
23053
  var Event = external_exports.object({
23864
23054
  id: external_exports.guid(),
@@ -24028,7 +23218,7 @@ var Rule = external_exports.strictObject({
24028
23218
  postValidators: external_exports.array(PostValidatorRef).optional(),
24029
23219
  requiresNearby: RequiresNearby.optional(),
24030
23220
  examples: external_exports.array(external_exports.string()).optional(),
24031
- // Whether the matched text is itself sensitive. Absent means 'value'.
23221
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24032
23222
  evidence: RuleEvidence.optional()
24033
23223
  }).meta({ id: "Rule" });
24034
23224
  var Author = external_exports.object({
@@ -24120,7 +23310,13 @@ var DetectionRule = external_exports.object({
24120
23310
  // Representative matching strings the rule author shipped with the rule. The
24121
23311
  // cheapest honest answer to "show me what this rule catches" — every bundled
24122
23312
  // rule has them, and they are already in the stored snapshot.
24123
- examples: external_exports.array(external_exports.string()).optional()
23313
+ examples: external_exports.array(external_exports.string()).optional(),
23314
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23315
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23316
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23317
+ // in a value category (secret/pii/financial/phi) is always 'value',
23318
+ // whatever it declares.
23319
+ evidence: RuleEvidence.optional()
24124
23320
  }).meta({ id: "DetectionRule" });
24125
23321
  var DetectionUpdate = external_exports.object({
24126
23322
  available: external_exports.boolean(),
@@ -24188,8 +23384,10 @@ var ImportDetectionRequest = external_exports.object({
24188
23384
  }).meta({ id: "ImportDetectionRequest" });
24189
23385
 
24190
23386
  // ../../packages/schema/src/zod/detection-build.ts
24191
- function optional2(key, parsed2, raw) {
24192
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
23387
+ function optional2(key, raw, parse4) {
23388
+ if (raw === void 0) return {};
23389
+ const parsed2 = parse4(raw);
23390
+ if (!parsed2.success || parsed2.data === void 0) return {};
24193
23391
  return { [key]: parsed2.data };
24194
23392
  }
24195
23393
  function isStringArray(value) {
@@ -24224,10 +23422,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24224
23422
  category: r.category,
24225
23423
  severity: r.severity,
24226
23424
  matcher: parsed2.data,
24227
- // The rest of what decides whether this rule fires. Carried so a consumer
24228
- // re-running the rule (a preview, a tester) evaluates what the engine
24229
- // evaluates rather than a matcher stripped of its guards — half the
24230
- // bundled catalog carries at least one of these.
23425
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23426
+ // decides whether this rule fires. Carried so a consumer re-running the
23427
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23428
+ // than a matcher stripped of its guards — half the bundled catalog
23429
+ // carries at least one of these. `examples` and `evidence` describe the
23430
+ // rule and never gate a match.
24231
23431
  //
24232
23432
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24233
23433
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24237,18 +23437,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24237
23437
  // test should stay exactly what it was, namely a renderable matcher. A
24238
23438
  // field that fails validation is omitted, which reads as "not set" and is
24239
23439
  // the same thing the consumer saw before this change.
24240
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23440
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24241
23441
  ...optional2(
24242
23442
  "postValidators",
24243
- PostValidatorRef.array().safeParse(r.postValidators),
24244
- r.postValidators
23443
+ r.postValidators,
23444
+ (v) => PostValidatorRef.array().safeParse(v)
24245
23445
  ),
24246
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23446
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24247
23447
  ...optional2(
24248
23448
  "examples",
24249
- { success: isStringArray(r.examples), data: r.examples },
24250
- r.examples
24251
- )
23449
+ r.examples,
23450
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23451
+ ),
23452
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24252
23453
  }
24253
23454
  ];
24254
23455
  });
@@ -24941,11 +24142,14 @@ var PolicyBundle = external_exports.object({
24941
24142
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24942
24143
  // Model ids (the raw `model` string a harness reports, e.g.
24943
24144
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24944
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24945
- // one (UserPromptSubmit). Optional so an older backend — and an older
24946
- // on-disk cache — still parses; consumers read `?? []`, which is the
24947
- // unenforced behaviour that predates this field and the safe direction to
24948
- // default.
24145
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24146
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24147
+ // wherever the organization governs the event: everywhere on a
24148
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24149
+ // one (the plugin runtime's `governanceApplies`).
24150
+ // Optional so an older backend — and an older on-disk cache — still
24151
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24152
+ // predates this field and the safe direction to default.
24949
24153
  //
24950
24154
  // Ids, not display names: the governance decision is keyed on the exact
24951
24155
  // string the harness reports (`model_status_override.versionId` in the
@@ -25404,6 +24608,8 @@ var AttachmentScopeEntry = external_exports.object({
25404
24608
  });
25405
24609
  var AttachmentScope = external_exports.object({
25406
24610
  endpoint: external_exports.string().min(1),
24611
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24612
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25407
24613
  entries: external_exports.array(AttachmentScopeEntry)
25408
24614
  });
25409
24615
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25416,7 +24622,13 @@ function parseAttachmentScope(raw) {
25416
24622
  const entry = AttachmentScopeEntry.safeParse(candidate);
25417
24623
  if (entry.success) entries.push(entry.data);
25418
24624
  }
25419
- return { endpoint: envelope.data.endpoint, entries };
24625
+ const { endpoint, tenantName, userEmail } = envelope.data;
24626
+ return {
24627
+ endpoint,
24628
+ ...tenantName === void 0 ? {} : { tenantName },
24629
+ ...userEmail === void 0 ? {} : { userEmail },
24630
+ entries
24631
+ };
25420
24632
  } catch {
25421
24633
  return void 0;
25422
24634
  }
@@ -25653,6 +24865,7 @@ function toCaptureAttributes(event) {
25653
24865
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25654
24866
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25655
24867
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24868
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25656
24869
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25657
24870
  // has ever populated either), but every legacy metadata key still rides
25658
24871
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25781,6 +24994,27 @@ var ManagedSettings = external_exports.object({
25781
24994
  };
25782
24995
  }).meta({ id: "ManagedSettings" });
25783
24996
 
24997
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24998
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24999
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
25000
+ var ModPolicySnapshot = external_exports.object({
25001
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
25002
+ generatedAt: external_exports.iso.datetime(),
25003
+ // The complete effective ruleset, as the hook's runtime scans with it: the
25004
+ // user's enabled installed packs (user-modified and custom packs included).
25005
+ // Absent means the store holds no authoritative snapshot, and the reader
25006
+ // scans with the packs it ships — the hook's own fallback.
25007
+ rules: external_exports.array(Rule).optional(),
25008
+ // Rule-targeted actions (first enabled policy per rule wins).
25009
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25010
+ // The resolved action per detection category.
25011
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25012
+ // Rules with an active exception grant. Honouring a grant means matching a
25013
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25014
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25015
+ exceptionRuleIds: external_exports.array(external_exports.string())
25016
+ }).meta({ id: "ModPolicySnapshot" });
25017
+
25784
25018
  // ../../packages/schema/src/zod/project-files.ts
25785
25019
  var ProjectFileInput = external_exports.object({
25786
25020
  path: external_exports.string().min(1),
@@ -26101,7 +25335,16 @@ var AttachInput = external_exports.object({
26101
25335
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26102
25336
  // renders a longer one usefully.
26103
25337
  label: printable(200).optional(),
26104
- accessKey: external_exports.string()
25338
+ accessKey: external_exports.string(),
25339
+ // How much of this machine the attachment is for: everything, or only the
25340
+ // repositories its user enrolls. Optional, so an input without it still
25341
+ // parses; what an absent mode means is for whatever reads it to decide, not
25342
+ // this shape. This member validates the VALUE rather than leaving that to the
25343
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25344
+ // rejection names the field, so a value that is not a mode is refused as a bad
25345
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25346
+ // it as the mode to attach in.
25347
+ mode: AttachmentMode.optional()
26105
25348
  });
26106
25349
 
26107
25350
  // ../../packages/schema/src/zod/triage.ts
@@ -26387,6 +25630,18 @@ function fromCaptureStatusAttributes(bag) {
26387
25630
  return parsedStatus.success ? parsedStatus.data : null;
26388
25631
  }
26389
25632
 
25633
+ // ../../packages/persistence/src/attached-derived.ts
25634
+ import { rmSync } from "fs";
25635
+ import { join } from "path";
25636
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25637
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25638
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
25639
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
25640
+
25641
+ // ../../packages/persistence/src/control-plane-credential.ts
25642
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25643
+ import { join as join2 } from "path";
25644
+
26390
25645
  // ../../packages/persistence/src/paths.ts
26391
25646
  import {
26392
25647
  chmodSync,
@@ -26533,6 +25788,14 @@ function repairOrRefuseMode(file2) {
26533
25788
  }
26534
25789
  return "ok";
26535
25790
  }
25791
+ function asReadableCredential(value) {
25792
+ const result = AttachedCredentialAny.safeParse(value);
25793
+ if (!result.success) return null;
25794
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25795
+ return null;
25796
+ }
25797
+ return result.data;
25798
+ }
26536
25799
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26537
25800
  const file2 = controlPlaneCredentialPath(settingsDir2);
26538
25801
  let raw;
@@ -26551,20 +25814,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26551
25814
  } catch {
26552
25815
  return { usable: false, reason: "malformed" };
26553
25816
  }
26554
- const result = AttachedCredential.safeParse(parsed2);
26555
- if (!result.success) return { usable: false, reason: "malformed" };
26556
- if (!isSafeEndpoint(result.data.endpoint)) {
25817
+ const credential = asReadableCredential(parsed2);
25818
+ if (credential === null) return { usable: false, reason: "malformed" };
25819
+ if (!isSafeEndpoint(credential.endpoint)) {
26557
25820
  return { usable: false, reason: "unsafe-endpoint" };
26558
25821
  }
26559
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25822
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26560
25823
  return {
26561
25824
  usable: false,
26562
25825
  reason: "endpoint-mismatch",
26563
- credentialEndpoint: result.data.endpoint,
25826
+ credentialEndpoint: credential.endpoint,
26564
25827
  settingsEndpoint: connection.endpoint
26565
25828
  };
26566
25829
  }
26567
- return { usable: true, credential: result.data };
25830
+ return { usable: true, credential };
26568
25831
  }
26569
25832
  function readControlPlaneCredential(settingsDir2, connection) {
26570
25833
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26573,7 +25836,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26573
25836
 
26574
25837
  // ../../packages/persistence/src/database.ts
26575
25838
  import { randomUUID as randomUUID11 } from "crypto";
26576
- import { dirname as dirname2, join as join7, sep } from "path";
25839
+ import { dirname as dirname2, join as join8, sep } from "path";
26577
25840
  import { DatabaseSync } from "node:sqlite";
26578
25841
 
26579
25842
  // ../../packages/persistence/src/ids.ts
@@ -26627,6 +25890,7 @@ function uuidFromDigest(digest) {
26627
25890
  function captureWireId(sessionId, contentHash, filePath = null) {
26628
25891
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26629
25892
  }
25893
+ var DOT = ".".charCodeAt(0);
26630
25894
 
26631
25895
  // ../../packages/persistence/src/internal/snapshot.ts
26632
25896
  import { randomUUID } from "crypto";
@@ -26954,6 +26218,25 @@ function scopeKeysParam(scopeKeys) {
26954
26218
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26955
26219
  FROM audit_events AS session_root
26956
26220
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26221
+ var COUNTED_IN_SCOPE = `
26222
+ AND ${inScope("scope_key")}
26223
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26224
+ var DRAIN_TOTALS = `SELECT
26225
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26226
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26227
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26228
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26229
+ THEN 1 ELSE 0 END) AS skipped,
26230
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26231
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26232
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26233
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26234
+ FROM audit_events
26235
+ WHERE event_type IN (${TYPE_LIST})`;
26236
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26237
+ FROM audit_events
26238
+ WHERE synced_at = ${String(SKIPPED)}
26239
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26957
26240
  var ROW_COLUMNS = `id,
26958
26241
  parent_id AS parentId,
26959
26242
  root_session_id AS rootSessionId,
@@ -27029,7 +26312,7 @@ var SqliteHistorySyncRepository = class {
27029
26312
  );
27030
26313
  this.scopedCaptureRowsStmt = db.prepare(
27031
26314
  `SELECT ${ROW_COLUMNS}
27032
- FROM audit_events
26315
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27033
26316
  WHERE synced_at IS NULL
27034
26317
  AND sync_claimed_at IS NULL
27035
26318
  AND outbox_owed = 1
@@ -27082,40 +26365,28 @@ var SqliteHistorySyncRepository = class {
27082
26365
  );
27083
26366
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27084
26367
  FROM audit_events${COUNTED_SCOPE}`);
26368
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26369
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27085
26370
  this.partitionByKindStmt = db.prepare(
27086
26371
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27087
26372
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27088
26373
  GROUP BY event_type`
27089
26374
  );
27090
- this.countsStmt = db.prepare(
27091
- `SELECT
27092
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27093
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27094
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27095
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27096
- THEN 1 ELSE 0 END) AS skipped,
27097
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27098
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27099
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27100
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27101
- FROM audit_events
27102
- WHERE event_type IN (${TYPE_LIST})`
26375
+ this.scopedPartitionByKindStmt = db.prepare(
26376
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26377
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26378
+ GROUP BY event_type`
27103
26379
  );
27104
- this.captureSkipCountStmt = db.prepare(
27105
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27106
- // way the structural totals are. The split exists because a refusal is
27107
- // terminal only against the deployment that gave it, and the structural
27108
- // re-arm frees it on a change of deployment. The capture lane has no such
27109
- // escape: re-arming a capture would offer one deployment's undelivered
27110
- // prompts, with their text, to a deployment that never saw them, which is
27111
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27112
- // reasons mean the same thing — this row will not be sent — and splitting
27113
- // them would put refused captures in a bucket nothing reads and nothing
27114
- // frees.
27115
- `SELECT COUNT(*) AS skipped
27116
- FROM audit_events
27117
- WHERE synced_at = ${String(SKIPPED)}
27118
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26380
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26381
+ this.scopedCountsStmt = db.prepare(
26382
+ `${DRAIN_TOTALS}
26383
+ AND ${inScope("scope_key")}
26384
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26385
+ );
26386
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26387
+ this.scopedCaptureSkipCountStmt = db.prepare(
26388
+ `${CAPTURE_SKIPS}
26389
+ AND ${inScope("scope_key")}`
27119
26390
  );
27120
26391
  this.fingerprintStmt = db.prepare(
27121
26392
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27229,6 +26500,10 @@ var SqliteHistorySyncRepository = class {
27229
26500
  scopedCaptureRowsStmt;
27230
26501
  scopedCaptureBacklogOwedStmt;
27231
26502
  markScopeCapturesOwedStmt;
26503
+ scopedPartitionStmt;
26504
+ scopedPartitionByKindStmt;
26505
+ scopedCountsStmt;
26506
+ scopedCaptureSkipCountStmt;
27232
26507
  /**
27233
26508
  * The masked detections recorded against one tool call.
27234
26509
  *
@@ -27450,7 +26725,29 @@ var SqliteHistorySyncRepository = class {
27450
26725
  * in" — and a machine that has never attached has no boundary to pass, so
27451
26726
  * requiring one would force a caller to invent one and report the whole store
27452
26727
  * as queued.
26728
+ *
26729
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26730
+ * the rows that pass the drain's reachability rule for that scope
26731
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26732
+ * drain never offers), so a personal repository's rows are in none of them.
26733
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26734
+ * nothing.
27453
26735
  */
26736
+ partition(scopeKeys) {
26737
+ const row = getRow(
26738
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26739
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26740
+ );
26741
+ return {
26742
+ queued: row?.queued ?? 0,
26743
+ inProgress: row?.inProgress ?? 0,
26744
+ synced: row?.synced ?? 0,
26745
+ failed: row?.failed ?? 0,
26746
+ refused: row?.refused ?? 0,
26747
+ detached: row?.detached ?? 0,
26748
+ total: row?.total ?? 0
26749
+ };
26750
+ }
27454
26751
  /**
27455
26752
  * The same partition, one row per kind that a lane carries.
27456
26753
  *
@@ -27460,11 +26757,14 @@ var SqliteHistorySyncRepository = class {
27460
26757
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27461
26758
  * rows", never as "zero sent"; the two look identical in a bar and mean
27462
26759
  * different things.
26760
+ *
26761
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26762
+ * still sum to the scoped aggregate. An empty list returns no rows.
27463
26763
  */
27464
- partitionByKind() {
26764
+ partitionByKind(scopeKeys) {
27465
26765
  return allRows(
27466
- this.partitionByKindStmt,
27467
- {}
26766
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26767
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27468
26768
  ).map((row) => ({
27469
26769
  kind: row.kind,
27470
26770
  queued: row.queued ?? 0,
@@ -27476,22 +26776,25 @@ var SqliteHistorySyncRepository = class {
27476
26776
  total: row.total ?? 0
27477
26777
  }));
27478
26778
  }
27479
- partition() {
27480
- const row = getRow(this.partitionStmt, {});
27481
- return {
27482
- queued: row?.queued ?? 0,
27483
- inProgress: row?.inProgress ?? 0,
27484
- synced: row?.synced ?? 0,
27485
- failed: row?.failed ?? 0,
27486
- refused: row?.refused ?? 0,
27487
- detached: row?.detached ?? 0,
27488
- total: row?.total ?? 0
27489
- };
27490
- }
27491
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27492
- counts(before) {
27493
- const row = getRow(this.countsStmt, { before });
27494
- const captures = getRow(this.captureSkipCountStmt);
26779
+ /**
26780
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26781
+ * and skipped are totals.
26782
+ *
26783
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26784
+ * `capturesSkipped` included: a structural row is counted only when its own
26785
+ * key and its session root's key are among them, a capture when its own key
26786
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26787
+ * under the same keys and boundary. Omitted, this runs the machine
26788
+ * statements, unchanged; an empty list counts nothing.
26789
+ */
26790
+ counts(before, scopeKeys) {
26791
+ const row = getRow(
26792
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26793
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26794
+ );
26795
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26796
+ scopeKeys: scopeKeysParam(scopeKeys)
26797
+ });
27495
26798
  return {
27496
26799
  pending: row?.pending ?? 0,
27497
26800
  sent: row?.sent ?? 0,
@@ -27743,6 +27046,7 @@ function applyMigrations(db, file2, options = {}) {
27743
27046
  }
27744
27047
  ensureSyncedAtColumn(db, "audit_events");
27745
27048
  ensureScopeKeyColumn(db);
27049
+ ensureScopeOwedIndex(db);
27746
27050
  ensureScanLedgerTable(db);
27747
27051
  ensureHistorySyncTable(db);
27748
27052
  ensureBlockedDetectionsTable(db);
@@ -28183,14 +27487,48 @@ function ensureScopeKeyColumn(db) {
28183
27487
  function hasScopeKeyColumn(db) {
28184
27488
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28185
27489
  }
27490
+ 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";
27491
+ function ensureScopeOwedIndex(db) {
27492
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27493
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27494
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27495
+ if (!complete) return;
27496
+ db.exec(SCOPE_OWED_INDEX_DDL);
27497
+ }
28186
27498
  function ensureScanLedgerTable(db) {
28187
27499
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28188
27500
  path TEXT PRIMARY KEY,
28189
27501
  mtime TEXT NOT NULL,
28190
27502
  content_hash TEXT NOT NULL,
28191
27503
  ruleset_hash TEXT NOT NULL,
28192
- scanned_at INTEGER NOT NULL
27504
+ scanned_at INTEGER NOT NULL,
27505
+ scope_key TEXT,
27506
+ scope_root TEXT
28193
27507
  )`);
27508
+ ensureScanLedgerScopeKeyColumn(db);
27509
+ ensureScanLedgerScopeRootColumn(db);
27510
+ }
27511
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27512
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27513
+ function ensureScanLedgerScopeKeyColumn(db) {
27514
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27515
+ }
27516
+ function ensureScanLedgerScopeRootColumn(db) {
27517
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27518
+ }
27519
+ function ensureScanLedgerColumn(db, column, ddl) {
27520
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27521
+ if (hasScanLedgerColumn(db, column)) return;
27522
+ withTransaction(
27523
+ db,
27524
+ () => {
27525
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27526
+ },
27527
+ "IMMEDIATE"
27528
+ );
27529
+ }
27530
+ function hasScanLedgerColumn(db, column) {
27531
+ return columnNames(db, "scan_ledger").includes(column);
28194
27532
  }
28195
27533
  function ensureHistorySyncTable(db) {
28196
27534
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28241,6 +27579,106 @@ function ensureRuleProbeCacheTable(db) {
28241
27579
  )`);
28242
27580
  }
28243
27581
 
27582
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27583
+ import { createHash as createHash2 } from "crypto";
27584
+ import { readFileSync as readFileSync2 } from "fs";
27585
+ import { join as join4 } from "path";
27586
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27587
+ function modPolicySnapshotPath(dataDir2) {
27588
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27589
+ }
27590
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27591
+ const byRule = /* @__PURE__ */ new Map();
27592
+ const byCategory = /* @__PURE__ */ new Map();
27593
+ for (const policy of input2.policies) {
27594
+ if (!policy.enabled) continue;
27595
+ if ("ruleId" in policy.target) {
27596
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27597
+ } else if (!byCategory.has(policy.target.category)) {
27598
+ byCategory.set(policy.target.category, policy.action);
27599
+ }
27600
+ }
27601
+ const categoryActions = {};
27602
+ for (const category of DetectionCategory.options) {
27603
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27604
+ }
27605
+ return {
27606
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27607
+ generatedAt: generatedAt.toISOString(),
27608
+ // `examples` is documentation the mod never reads, and a custom pack's are
27609
+ // whatever its author pasted in, so they stay behind.
27610
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27611
+ ruleActions: Object.fromEntries(byRule),
27612
+ categoryActions,
27613
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27614
+ };
27615
+ }
27616
+ function assignedRuleActionPolicies(installed) {
27617
+ const out = [];
27618
+ for (const [ruleId, action] of installed.ruleActions) {
27619
+ if (installed.assignedRules.has(ruleId))
27620
+ out.push({ target: { ruleId }, action, enabled: true });
27621
+ }
27622
+ return out;
27623
+ }
27624
+ function withoutExamples(rule) {
27625
+ const copy = { ...rule };
27626
+ delete copy.examples;
27627
+ return copy;
27628
+ }
27629
+ function sameContent(a, b) {
27630
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27631
+ }
27632
+ function readModPolicySnapshot(dataDir2) {
27633
+ try {
27634
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27635
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27636
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27637
+ return parsed2.success ? parsed2.data : null;
27638
+ } catch {
27639
+ return null;
27640
+ }
27641
+ }
27642
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27643
+ const text = JSON.stringify(snapshot);
27644
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27645
+ const existing = readModPolicySnapshot(dataDir2);
27646
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27647
+ ensureDataDirSync(dataDir2);
27648
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27649
+ return true;
27650
+ }
27651
+ function regexProbeKey(matcher) {
27652
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27653
+ }
27654
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27655
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27656
+ return rules.filter((rule) => {
27657
+ if (rule.matcher.type !== "regex") return true;
27658
+ const key = regexProbeKey(rule.matcher);
27659
+ const verdict = sources.probeVerdict(key);
27660
+ if (verdict === "quarantined") return false;
27661
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27662
+ });
27663
+ }
27664
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27665
+ const policies = sources.readPolicies();
27666
+ const snapshot = sources.installedRuleset();
27667
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27668
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27669
+ return {
27670
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27671
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27672
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27673
+ };
27674
+ }
27675
+ function refreshModPolicySnapshot(dataDir2, sources) {
27676
+ try {
27677
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27678
+ } catch {
27679
+ }
27680
+ }
27681
+
28244
27682
  // ../../packages/persistence/src/internal/json.ts
28245
27683
  function safeJson(s, fallback) {
28246
27684
  if (s == null) return fallback;
@@ -28415,6 +27853,11 @@ var TIMELINE_COLUMNS = `
28415
27853
  json_extract(attributes, '$.targetId') AS target_id,
28416
27854
  json_extract(attributes, '$.internal') AS internal,
28417
27855
  json_extract(attributes, '$.flagged') AS flagged`;
27856
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27857
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27858
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27859
+ " + "
27860
+ );
28418
27861
  var LLM_USAGE_SELECT = `
28419
27862
  SELECT root_session_id AS sessionId,
28420
27863
  provider,
@@ -28426,9 +27869,10 @@ var LLM_USAGE_SELECT = `
28426
27869
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28427
27870
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28428
27871
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28429
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27872
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27873
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28430
27874
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28431
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27875
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28432
27876
  function usageLeaves(rows) {
28433
27877
  return rows.map((row) => {
28434
27878
  const attributes = {
@@ -28443,7 +27887,7 @@ function usageLeaves(rows) {
28443
27887
  if (row.provider !== null) attributes.provider = row.provider;
28444
27888
  if (row.model !== null) attributes.model = row.model;
28445
27889
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28446
- return { sessionId: row.sessionId, attributes };
27890
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28447
27891
  });
28448
27892
  }
28449
27893
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29777,9 +29221,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29777
29221
  AND conditions IS NULL
29778
29222
  AND ${ACTIVE_PREDICATE}`;
29779
29223
  var SqliteExceptionsRepository = class {
29780
- constructor(db, now = () => Date.now()) {
29224
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29781
29225
  this.db = db;
29782
29226
  this.now = now;
29227
+ this.onChange = onChange;
29783
29228
  this.consumeStmt = db.prepare(
29784
29229
  `UPDATE exceptions
29785
29230
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29798,6 +29243,7 @@ var SqliteExceptionsRepository = class {
29798
29243
  }
29799
29244
  db;
29800
29245
  now;
29246
+ onChange;
29801
29247
  consumeStmt;
29802
29248
  insertBlockedStmt;
29803
29249
  sweepBlockedStmt;
@@ -29813,7 +29259,9 @@ var SqliteExceptionsRepository = class {
29813
29259
  */
29814
29260
  create(input2) {
29815
29261
  try {
29816
- return Promise.resolve(this.createSync(input2));
29262
+ const created = this.createSync(input2);
29263
+ this.onChange();
29264
+ return Promise.resolve(created);
29817
29265
  } catch (err) {
29818
29266
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29819
29267
  }
@@ -29944,6 +29392,7 @@ var SqliteExceptionsRepository = class {
29944
29392
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29945
29393
  WHERE id = :id AND revoked_at IS NULL`
29946
29394
  ).run({ id, revokedBy, reason: reason ?? null, now });
29395
+ if (Number(result.changes) === 1) this.onChange();
29947
29396
  return Promise.resolve(Number(result.changes) === 1);
29948
29397
  }
29949
29398
  /**
@@ -29956,6 +29405,15 @@ var SqliteExceptionsRepository = class {
29956
29405
  const result = this.consumeStmt.run({ id, now });
29957
29406
  return Promise.resolve(Number(result.changes) === 1);
29958
29407
  }
29408
+ /** The rule ids with at least one active grant, under any key version. */
29409
+ activeRuleIds(now = this.now()) {
29410
+ return allRows(
29411
+ this.db.prepare(
29412
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29413
+ ),
29414
+ { now }
29415
+ ).map((row) => row.ruleId);
29416
+ }
29959
29417
  /**
29960
29418
  * The evaluation subset of every active grant under one fingerprint key
29961
29419
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31079,28 +30537,28 @@ var SqliteInspectionFindingsRepository = class {
31079
30537
  };
31080
30538
 
31081
30539
  // ../../packages/persistence/src/repositories/installed-packs.ts
31082
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30540
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31083
30541
 
31084
30542
  // ../../packages/persistence/src/policy-floor.ts
31085
- import { readFileSync as readFileSync5 } from "fs";
31086
- import { join as join6 } from "path";
30543
+ import { readFileSync as readFileSync6 } from "fs";
30544
+ import { join as join7 } from "path";
31087
30545
 
31088
30546
  // ../../packages/persistence/src/local-layout.ts
31089
30547
  import { renameSync as renameSync3 } from "fs";
31090
30548
  import { mkdir } from "fs/promises";
31091
30549
  import { homedir } from "os";
31092
- import { join as join4 } from "path";
30550
+ import { join as join5 } from "path";
31093
30551
  function defaultDataDir() {
31094
- return join4(homedir(), ".aka");
30552
+ return join5(homedir(), ".aka");
31095
30553
  }
31096
30554
  function settingsDir(base = defaultDataDir()) {
31097
- return join4(base, "settings");
30555
+ return join5(base, "settings");
31098
30556
  }
31099
30557
  function dataDir(base = defaultDataDir()) {
31100
- return join4(base, "data");
30558
+ return join5(base, "data");
31101
30559
  }
31102
30560
  function dbPath(base = defaultDataDir()) {
31103
- return join4(dataDir(base), "aka.db");
30561
+ return join5(dataDir(base), "aka.db");
31104
30562
  }
31105
30563
  async function ensureDataDir(dir = defaultDataDir()) {
31106
30564
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31117,8 +30575,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31117
30575
  for (const { name, dest } of moves) {
31118
30576
  try {
31119
30577
  ensureDataDirSync(dest);
31120
- const moved = join4(dest, name);
31121
- renameSync3(join4(base, name), moved);
30578
+ const moved = join5(dest, name);
30579
+ renameSync3(join5(base, name), moved);
31122
30580
  tightenFile(moved);
31123
30581
  } catch {
31124
30582
  }
@@ -31126,8 +30584,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31126
30584
  }
31127
30585
 
31128
30586
  // ../../packages/persistence/src/settings.ts
31129
- import { readFileSync as readFileSync4 } from "fs";
31130
- import { join as join5 } from "path";
30587
+ import { readFileSync as readFileSync5 } from "fs";
30588
+ import { join as join6 } from "path";
31131
30589
 
31132
30590
  // ../../packages/persistence/src/file-lock.ts
31133
30591
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31135,7 +30593,7 @@ import {
31135
30593
  closeSync,
31136
30594
  existsSync as existsSync2,
31137
30595
  openSync,
31138
- readFileSync as readFileSync2,
30596
+ readFileSync as readFileSync3,
31139
30597
  rmSync as rmSync5,
31140
30598
  statSync as statSync3,
31141
30599
  writeFileSync as writeFileSync2
@@ -31144,7 +30602,7 @@ import { hostname as hostname3 } from "os";
31144
30602
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31145
30603
 
31146
30604
  // ../../packages/persistence/src/managed-settings.ts
31147
- import { readFileSync as readFileSync3 } from "fs";
30605
+ import { readFileSync as readFileSync4 } from "fs";
31148
30606
  import { posix, win32 } from "path";
31149
30607
  function managedSettingsPaths(platform2 = process.platform) {
31150
30608
  if (platform2 === "darwin") {
@@ -31163,7 +30621,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31163
30621
  for (const path of paths) {
31164
30622
  let text;
31165
30623
  try {
31166
- text = readFileSync3(path, "utf8");
30624
+ text = readFileSync4(path, "utf8");
31167
30625
  } catch {
31168
30626
  continue;
31169
30627
  }
@@ -31217,7 +30675,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31217
30675
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31218
30676
  }
31219
30677
  function readUserSettings(base) {
31220
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30678
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31221
30679
  if (!record2) return defaultWorkspaceSettings();
31222
30680
  try {
31223
30681
  return WorkspaceSettings.parse(record2);
@@ -31228,7 +30686,7 @@ function readUserSettings(base) {
31228
30686
  function readJson(file2) {
31229
30687
  let text;
31230
30688
  try {
31231
- text = readFileSync4(file2, "utf8");
30689
+ text = readFileSync5(file2, "utf8");
31232
30690
  } catch {
31233
30691
  return null;
31234
30692
  }
@@ -31268,7 +30726,7 @@ var PolicyFloorError = class extends Error {
31268
30726
  };
31269
30727
  function readCachedPolicyBundle(base = defaultDataDir()) {
31270
30728
  try {
31271
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30729
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31272
30730
  const parsed2 = JSON.parse(raw);
31273
30731
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31274
30732
  return PolicyBundle.parse(parsed2.bundle);
@@ -31392,7 +30850,7 @@ function inventorySignature(packs2) {
31392
30850
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31393
30851
  }
31394
30852
  function hashRules(rulesJson) {
31395
- return createHash2("sha256").update(rulesJson).digest("hex");
30853
+ return createHash3("sha256").update(rulesJson).digest("hex");
31396
30854
  }
31397
30855
  function parseVersion(v) {
31398
30856
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31434,9 +30892,10 @@ var SqliteInstalledPacksRepository = class {
31434
30892
  * from `openLocalDatabase`, which is the single construction site that owns a
31435
30893
  * real `~/.aka`.
31436
30894
  */
31437
- constructor(db, baseDir) {
30895
+ constructor(db, baseDir, onChange = () => void 0) {
31438
30896
  this.db = db;
31439
30897
  this.baseDir = baseDir;
30898
+ this.onChange = onChange;
31440
30899
  this.insertMissingStmt = db.prepare(
31441
30900
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31442
30901
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31465,6 +30924,7 @@ var SqliteInstalledPacksRepository = class {
31465
30924
  }
31466
30925
  db;
31467
30926
  baseDir;
30927
+ onChange;
31468
30928
  insertMissingStmt;
31469
30929
  upsertAvailableStmt;
31470
30930
  signatureStmt;
@@ -31537,6 +30997,7 @@ var SqliteInstalledPacksRepository = class {
31537
30997
  },
31538
30998
  "IMMEDIATE"
31539
30999
  );
31000
+ this.onChange();
31540
31001
  } catch {
31541
31002
  }
31542
31003
  }
@@ -31611,6 +31072,7 @@ var SqliteInstalledPacksRepository = class {
31611
31072
  },
31612
31073
  "IMMEDIATE"
31613
31074
  );
31075
+ if (changed) this.onChange();
31614
31076
  return changed;
31615
31077
  }
31616
31078
  /**
@@ -31852,6 +31314,7 @@ var SqliteInstalledPacksRepository = class {
31852
31314
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31853
31315
  WHERE namespace = :namespace AND pack_id = :packId`
31854
31316
  ).run({ policyId, now: Date.now(), namespace, packId });
31317
+ if (Number(res.changes) > 0) this.onChange();
31855
31318
  return Number(res.changes) > 0;
31856
31319
  }
31857
31320
  /**
@@ -31876,6 +31339,7 @@ var SqliteInstalledPacksRepository = class {
31876
31339
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31877
31340
  WHERE namespace = :namespace AND pack_id = :packId`
31878
31341
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31342
+ if (Number(res.changes) > 0) this.onChange();
31879
31343
  return Number(res.changes) > 0;
31880
31344
  }
31881
31345
  // Fingerprint of the recorded available mirror — compared against the
@@ -32773,13 +32237,19 @@ var SqliteInventoryAssetsRepository = class {
32773
32237
  import { randomUUID as randomUUID6 } from "crypto";
32774
32238
  var SEED_BATCH_WINDOW_MS = 6e4;
32775
32239
  var SqlitePoliciesRepository = class {
32776
- constructor(db) {
32240
+ constructor(db, onChange = () => void 0) {
32777
32241
  this.db = db;
32242
+ this.onChange = onChange;
32778
32243
  }
32779
32244
  db;
32245
+ onChange;
32780
32246
  readPolicies() {
32247
+ return Promise.resolve(this.listPolicies());
32248
+ }
32249
+ /** The synchronous read behind {@link readPolicies}. */
32250
+ listPolicies() {
32781
32251
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32782
- const policies = mapRowsTolerant(rows, (row) => {
32252
+ return mapRowsTolerant(rows, (row) => {
32783
32253
  const target = JSON.parse(row.target);
32784
32254
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32785
32255
  return Policy.parse({
@@ -32791,7 +32261,6 @@ var SqlitePoliciesRepository = class {
32791
32261
  customKeywords
32792
32262
  });
32793
32263
  });
32794
- return Promise.resolve(policies);
32795
32264
  }
32796
32265
  // Seed one policy per bundled category at Monitor so the detection-type config
32797
32266
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32802,7 +32271,7 @@ var SqlitePoliciesRepository = class {
32802
32271
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32803
32272
  if (count > 0) {
32804
32273
  this.markEarlierChoices();
32805
- this.monitorUntouchedSeeds();
32274
+ if (this.monitorUntouchedSeeds()) this.onChange();
32806
32275
  return;
32807
32276
  }
32808
32277
  const stmt = this.db.prepare(
@@ -32819,6 +32288,7 @@ var SqlitePoliciesRepository = class {
32819
32288
  });
32820
32289
  }
32821
32290
  });
32291
+ this.onChange();
32822
32292
  }
32823
32293
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32824
32294
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32884,7 +32354,7 @@ var SqlitePoliciesRepository = class {
32884
32354
  ).filter(
32885
32355
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32886
32356
  );
32887
- if (untouched.length === 0) return;
32357
+ if (untouched.length === 0) return false;
32888
32358
  const stmt = this.db.prepare(
32889
32359
  `UPDATE policies SET action = 'log'
32890
32360
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32895,6 +32365,7 @@ var SqlitePoliciesRepository = class {
32895
32365
  stmt.run({ category: row.category, seeded: row.action });
32896
32366
  }
32897
32367
  });
32368
+ return true;
32898
32369
  }
32899
32370
  // Insert-or-update the single global per-category policy row, keyed on the
32900
32371
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32911,6 +32382,7 @@ var SqlitePoliciesRepository = class {
32911
32382
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32912
32383
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32913
32384
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32385
+ this.onChange();
32914
32386
  }
32915
32387
  // Caps every global per-category policy currently set to block/redact down
32916
32388
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32921,6 +32393,7 @@ var SqlitePoliciesRepository = class {
32921
32393
  WHERE scope='global' AND action IN ('block','redact')
32922
32394
  AND json_extract(target,'$.category') IS NOT NULL`
32923
32395
  ).run({ now: Date.now() });
32396
+ if (Number(info.changes) > 0) this.onChange();
32924
32397
  return Number(info.changes);
32925
32398
  }
32926
32399
  // Whether the category's row was ever written after it was created — by the
@@ -33240,31 +32713,45 @@ var SqliteScanLedgerRepository = class {
33240
32713
  constructor(db) {
33241
32714
  this.db = db;
33242
32715
  this.upsertStmt = db.prepare(
33243
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33244
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32716
+ `INSERT INTO scan_ledger
32717
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32718
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33245
32719
  ON CONFLICT (path) DO UPDATE SET
33246
32720
  mtime = excluded.mtime,
33247
32721
  content_hash = excluded.content_hash,
33248
32722
  ruleset_hash = excluded.ruleset_hash,
32723
+ scope_key = excluded.scope_key,
32724
+ scope_root = excluded.scope_root,
33249
32725
  scanned_at = excluded.scanned_at`
33250
32726
  );
33251
32727
  this.readStmt = db.prepare(
33252
- `SELECT path, mtime, content_hash AS contentHash
32728
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32729
+ scope_root AS scopeRoot
33253
32730
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33254
32731
  );
33255
32732
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32733
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33256
32734
  }
33257
32735
  db;
33258
32736
  upsertStmt;
33259
32737
  readStmt;
33260
32738
  pathsStmt;
32739
+ pathKeysStmt;
33261
32740
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33262
32741
  // older ruleset are simply absent, which reads as "never scanned".
33263
32742
  entriesForRuleset(rulesetHash) {
33264
- const rows = allRows(this.readStmt, {
33265
- rulesetHash
33266
- });
33267
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32743
+ const rows = allRows(this.readStmt, { rulesetHash });
32744
+ return new Map(
32745
+ rows.map((r) => [
32746
+ r.path,
32747
+ {
32748
+ mtime: r.mtime,
32749
+ contentHash: r.contentHash,
32750
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32751
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32752
+ }
32753
+ ])
32754
+ );
33268
32755
  }
33269
32756
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33270
32757
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33273,6 +32760,14 @@ var SqliteScanLedgerRepository = class {
33273
32760
  allPaths() {
33274
32761
  return allRows(this.pathsStmt).map((r) => r.path);
33275
32762
  }
32763
+ // Every ledgered path with the repository it was in when it was last read,
32764
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32765
+ // which repository a vanished file belonged to. `undefined` for a row with no
32766
+ // key, which is every row written before the column existed.
32767
+ pathKeys() {
32768
+ const rows = allRows(this.pathKeysStmt);
32769
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32770
+ }
33276
32771
  upsertEntries(entries) {
33277
32772
  if (entries.length === 0) return;
33278
32773
  const scannedAt = Date.now();
@@ -33283,6 +32778,8 @@ var SqliteScanLedgerRepository = class {
33283
32778
  mtime: entry.mtime,
33284
32779
  contentHash: entry.contentHash,
33285
32780
  rulesetHash: entry.rulesetHash,
32781
+ scopeKey: entry.scopeKey ?? null,
32782
+ scopeRoot: entry.scopeRoot ?? null,
33286
32783
  scannedAt
33287
32784
  });
33288
32785
  }
@@ -34370,6 +33867,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34370
33867
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34371
33868
  };
34372
33869
  }
33870
+ function withoutTrailingSlashes(path) {
33871
+ let end = path.length;
33872
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33873
+ return path.slice(0, end);
33874
+ }
34373
33875
  function toEndpointSummary(row) {
34374
33876
  return {
34375
33877
  id: row.id,
@@ -34657,7 +34159,7 @@ var SqliteSharesRepository = class {
34657
34159
  */
34658
34160
  reconcileCallSites(projectKey, reconcile) {
34659
34161
  if (reconcile.mode === "walk") {
34660
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
34162
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34661
34163
  this.db.prepare(
34662
34164
  `DELETE FROM share_call_site
34663
34165
  WHERE project_key = :key
@@ -35225,7 +34727,7 @@ function backupLegacyStore(db, file2) {
35225
34727
  discardStore(file2, backup);
35226
34728
  return backup;
35227
34729
  }
35228
- function openAndInitialize(file2, base, skipTags) {
34730
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35229
34731
  let db = openWithPragmas(file2);
35230
34732
  try {
35231
34733
  if (isForeignSqliteLineage(db)) {
@@ -35237,8 +34739,15 @@ function openAndInitialize(file2, base, skipTags) {
35237
34739
  }
35238
34740
  applyMigrations(db, file2, { skipTags });
35239
34741
  tightenPerms(file2);
35240
- const policies = new SqlitePoliciesRepository(db);
35241
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34742
+ const modPolicy = {};
34743
+ const onPolicyStateChange = () => {
34744
+ if (modPolicy.current !== void 0)
34745
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34746
+ };
34747
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34748
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34749
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34750
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35242
34751
  const repositories = {
35243
34752
  events: new SqliteEventsRepository(db),
35244
34753
  findings: new SqliteFindingsRepository(db),
@@ -35247,9 +34756,9 @@ function openAndInitialize(file2, base, skipTags) {
35247
34756
  scanLedger: new SqliteScanLedgerRepository(db),
35248
34757
  historySync: new SqliteHistorySyncRepository(db),
35249
34758
  secretVault: new SqliteSecretVaultRepository(db),
35250
- exceptions: new SqliteExceptionsRepository(db),
34759
+ exceptions,
35251
34760
  resolutions: new SqliteResolutionsRepository(db),
35252
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34761
+ ruleProbeCache,
35253
34762
  bodyRetention: new SqliteBodyRetentionRepository(db),
35254
34763
  security: new SqliteSecurityRepository(db),
35255
34764
  detections: new SqliteDetectionsRepository(db),
@@ -35267,6 +34776,13 @@ function openAndInitialize(file2, base, skipTags) {
35267
34776
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35268
34777
  configInventory: new SqliteConfigInventoryRepository(db)
35269
34778
  };
34779
+ modPolicy.current = {
34780
+ installedRuleset: () => installedPacks.installedRuleset(),
34781
+ readPolicies: () => policies.listPolicies(),
34782
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34783
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34784
+ bundledRegexMatchers: () => shippedRegexMatchers2
34785
+ };
35270
34786
  policies.seedDefaults();
35271
34787
  return { db, ...repositories };
35272
34788
  } catch (err) {
@@ -35278,7 +34794,7 @@ function openAndInitialize(file2, base, skipTags) {
35278
34794
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35279
34795
  function openLocalDatabase(dir, options = {}) {
35280
34796
  ensureDataDirSync(dir);
35281
- const file2 = join7(dir, DB_FILENAME);
34797
+ const file2 = join8(dir, DB_FILENAME);
35282
34798
  reapStalePartials(file2);
35283
34799
  const {
35284
34800
  db,
@@ -35314,7 +34830,8 @@ function openLocalDatabase(dir, options = {}) {
35314
34830
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35315
34831
  // settings/ and data/, and the pack-policy floor needs both halves.
35316
34832
  dirname2(dir),
35317
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34833
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34834
+ options.shippedRegexMatchers ?? []
35318
34835
  );
35319
34836
  function captureRowId(event) {
35320
34837
  return captureId(
@@ -35579,7 +35096,7 @@ function openLocalDatabase(dir, options = {}) {
35579
35096
  }
35580
35097
 
35581
35098
  // ../../packages/persistence/src/egress-wire.ts
35582
- import { createHash as createHash3 } from "crypto";
35099
+ import { createHash as createHash4 } from "crypto";
35583
35100
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35584
35101
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35585
35102
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35611,7 +35128,7 @@ function canonicalGitUrl(url2) {
35611
35128
  }
35612
35129
  function hashProjectKey(projectKey) {
35613
35130
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35614
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35131
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35615
35132
  }
35616
35133
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35617
35134
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35676,24 +35193,23 @@ function toEgressIngestRequest(input2) {
35676
35193
  }
35677
35194
 
35678
35195
  // ../../packages/persistence/src/finding-key.ts
35679
- import { createHash as createHash4 } from "crypto";
35196
+ import { createHash as createHash5 } from "crypto";
35680
35197
  function normalizeFilePath(filePath) {
35681
35198
  return filePath.replaceAll("\\", "/");
35682
35199
  }
35683
35200
  function computeFindingKey(input2) {
35684
35201
  const normalizedPath = normalizeFilePath(input2.filePath);
35685
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35202
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35686
35203
  }
35687
35204
 
35688
35205
  // ../../packages/persistence/src/fingerprint.ts
35689
35206
  import { createHmac, randomBytes } from "crypto";
35690
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35691
- import { join as join8 } from "path";
35692
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35207
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
35208
+ import { join as join9 } from "path";
35693
35209
  var EXCEPTION_KEY_FILENAME = "exception.key";
35694
35210
  var KEY_MATERIAL_BYTES = 32;
35695
35211
  function keyFilePath(dataDir2) {
35696
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
35212
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35697
35213
  }
35698
35214
  function parseKeyFile(raw) {
35699
35215
  const parsed2 = JSON.parse(raw);
@@ -35720,6 +35236,12 @@ var KEY_VERSION_COLUMNS = {
35720
35236
  };
35721
35237
  var SQLITE_ERROR2 = 1;
35722
35238
  var FLOOR_BUSY_TIMEOUT_MS = 250;
35239
+ function openReadOnly(file2) {
35240
+ const host = process;
35241
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
35242
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
35243
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
35244
+ }
35723
35245
  var FloorUnreadableError = class extends Error {
35724
35246
  code = "floor-unreadable";
35725
35247
  constructor(cause) {
@@ -35731,11 +35253,11 @@ var FloorUnreadableError = class extends Error {
35731
35253
  }
35732
35254
  };
35733
35255
  function storedKeyVersionFloor(dataDir2) {
35734
- const file2 = join8(dataDir2, DB_FILENAME);
35256
+ const file2 = join9(dataDir2, DB_FILENAME);
35735
35257
  if (!existsSync3(file2)) return 0;
35736
35258
  let db;
35737
35259
  try {
35738
- db = new DatabaseSync2(file2, { readOnly: true });
35260
+ db = openReadOnly(file2);
35739
35261
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35740
35262
  let floor = 0;
35741
35263
  for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35786,7 +35308,7 @@ function occupantMessage(file2, kind) {
35786
35308
  function readFingerprintKey(dataDir2) {
35787
35309
  let raw;
35788
35310
  try {
35789
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
35311
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35790
35312
  } catch (err) {
35791
35313
  if (err.code === "ENOENT") return null;
35792
35314
  throw err instanceof Error ? err : new Error(String(err));
@@ -35812,8 +35334,8 @@ function exactFingerprintValue(key, raw) {
35812
35334
  }
35813
35335
 
35814
35336
  // ../../packages/persistence/src/forward-health.ts
35815
- import { readFileSync as readFileSync7 } from "fs";
35816
- import { join as join9 } from "path";
35337
+ import { readFileSync as readFileSync8 } from "fs";
35338
+ import { join as join10 } from "path";
35817
35339
  var BREAKER_COOLDOWN_MS = 3e4;
35818
35340
  function parseForwardHealth(raw, nowMs) {
35819
35341
  try {
@@ -35837,20 +35359,21 @@ function isForwardPaused(health, nowMs) {
35837
35359
 
35838
35360
  // ../../packages/persistence/src/history-backfill.ts
35839
35361
  import { existsSync as existsSync4 } from "fs";
35840
- import { join as join10 } from "path";
35362
+ import { join as join11 } from "path";
35841
35363
 
35842
35364
  // ../../packages/persistence/src/history-preview.ts
35843
35365
  import { existsSync as existsSync5 } from "fs";
35844
- import { join as join11 } from "path";
35845
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
35366
+ import { join as join12 } from "path";
35367
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35846
35368
 
35847
35369
  // ../../packages/persistence/src/history-sync-state.ts
35848
- import { readFileSync as readFileSync8 } from "fs";
35849
- import { join as join12 } from "path";
35370
+ import { readFileSync as readFileSync9 } from "fs";
35371
+ import { join as join13 } from "path";
35372
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35850
35373
 
35851
35374
  // ../../packages/persistence/src/store-symlinks.ts
35852
35375
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35853
- import { dirname as dirname3, join as join13, resolve } from "path";
35376
+ import { dirname as dirname3, join as join14, resolve } from "path";
35854
35377
 
35855
35378
  // ../../packages/persistence/src/vault/crypto.ts
35856
35379
  import {
@@ -35864,19 +35387,19 @@ import {
35864
35387
  // ../../packages/persistence/src/vault/key-provider.ts
35865
35388
  import { execFileSync } from "child_process";
35866
35389
  import { randomBytes as randomBytes2 } from "crypto";
35867
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35868
- import { join as join14 } from "path";
35390
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35391
+ import { join as join15 } from "path";
35869
35392
 
35870
35393
  // ../../packages/persistence/src/vault/vault.ts
35871
35394
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35872
35395
 
35873
35396
  // ../../packages/persistence/src/warn-era-cap.ts
35874
35397
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35875
- import { join as join15 } from "path";
35398
+ import { join as join16 } from "path";
35876
35399
  var MARKER = "warn-era-capped";
35877
35400
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35878
35401
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35879
- const marker = join15(dataDir2, MARKER);
35402
+ const marker = join16(dataDir2, MARKER);
35880
35403
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35881
35404
  const capped = db.policies.capCategoryActions();
35882
35405
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35936,7 +35459,7 @@ function resolveProvider() {
35936
35459
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
35937
35460
  try {
35938
35461
  ensureLayoutDirSync(base);
35939
- const settingsFile = join16(settingsDir(base), "settings.json");
35462
+ const settingsFile = join17(settingsDir(base), "settings.json");
35940
35463
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
35941
35464
  } catch {
35942
35465
  }
@@ -35959,11 +35482,6 @@ function resolveProviderSafe(resolveProviderFn) {
35959
35482
  }
35960
35483
  }
35961
35484
 
35962
- // ../../packages/plugin-sdk/src/config-inventory.ts
35963
- import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
35964
- import { homedir as homedir2 } from "os";
35965
- import { basename as basename3, join as join18 } from "path";
35966
-
35967
35485
  // ../../packages/detections/src/egress/registry.ts
35968
35486
  var EXTRACTOR_VERSION = "3";
35969
35487
  var PROVIDER_REGISTRY = [
@@ -37074,17 +36592,18 @@ function ruleEvidence(rule) {
37074
36592
 
37075
36593
  // ../../packages/detections/src/mask.ts
37076
36594
  function maskMatch(raw) {
37077
- if (raw.length <= 5) return "***";
37078
- const atIndex = raw.indexOf("@");
37079
- if (atIndex > 0 && atIndex < raw.length - 1) {
37080
- const domain2 = raw.slice(atIndex + 1);
36595
+ const visible = stripInvisiblePadding(raw);
36596
+ if (visible.length <= 5) return "***";
36597
+ const atIndex = visible.indexOf("@");
36598
+ if (atIndex > 0 && atIndex < visible.length - 1) {
36599
+ const domain2 = visible.slice(atIndex + 1);
37081
36600
  if (domain2.includes(".")) {
37082
- const local = raw.slice(0, atIndex);
36601
+ const local = visible.slice(0, atIndex);
37083
36602
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
37084
36603
  return `${maskedLocal}@${domain2}`;
37085
36604
  }
37086
36605
  }
37087
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
36606
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
37088
36607
  }
37089
36608
 
37090
36609
  // ../../packages/detections/src/pointer-shield.ts
@@ -37320,6 +36839,38 @@ function worstProbeMs(rule, now = wallClock, corroborate) {
37320
36839
  }
37321
36840
  var CPU_CORROBORATION_SHARE = 0.2;
37322
36841
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36842
+ function repeatTo(unit, length) {
36843
+ return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
36844
+ }
36845
+ function joinTo(length, open3, close, item) {
36846
+ const parts = [];
36847
+ let size = open3.length;
36848
+ for (let i = 0; size < length; i++) {
36849
+ const next = (i === 0 ? "" : ",") + item(i);
36850
+ parts.push(next);
36851
+ size += next.length;
36852
+ }
36853
+ return (open3 + parts.join("") + close).slice(0, length);
36854
+ }
36855
+ var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
36856
+ var GROWTH_CORPORA = [
36857
+ {
36858
+ name: "one-line JSON dictionary",
36859
+ build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
36860
+ },
36861
+ {
36862
+ name: "JSON array of quoted SQL keywords",
36863
+ build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
36864
+ },
36865
+ { name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
36866
+ { name: "double-quote run", build: (length) => repeatTo('"', length) },
36867
+ { name: "space run", build: (length) => repeatTo(" ", length) },
36868
+ { name: "newline run", build: (length) => repeatTo("\n", length) },
36869
+ ...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
36870
+ name: `unit run ${JSON.stringify(unit)}`,
36871
+ build: (length) => repeatTo(unit, length)
36872
+ }))
36873
+ ];
37323
36874
  function checkRuleTiming(rule, corroborate) {
37324
36875
  const { ms, probe, corroboratedMs } = worstProbeMs(rule, wallClock, corroborate);
37325
36876
  const work = corroboratedMs ?? 0;
@@ -37346,7 +36897,12 @@ var MIN_RAW_LEN = 4;
37346
36897
  var RAW_RUN_LEN = 8;
37347
36898
  function carriesRawRun(text, rawValues) {
37348
36899
  let windows = null;
37349
- for (const raw of new Set(rawValues)) {
36900
+ const values = /* @__PURE__ */ new Set();
36901
+ for (const raw of rawValues) {
36902
+ values.add(raw);
36903
+ values.add(stripInvisiblePadding(raw));
36904
+ }
36905
+ for (const raw of values) {
37350
36906
  if (raw.length < MIN_RAW_LEN) continue;
37351
36907
  if (raw.length < RAW_RUN_LEN) {
37352
36908
  if (text.includes(raw)) return true;
@@ -37393,11 +36949,16 @@ function maskContextSlice(slice, sliceStart, hits) {
37393
36949
  return masked;
37394
36950
  }
37395
36951
  function safeMaskedMatch(rawMatch) {
37396
- const masked = maskMatch(rawMatch);
37397
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37398
- return "***";
36952
+ const visible = stripInvisiblePadding(rawMatch);
36953
+ const masked = maskMatch(visible);
36954
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
36955
+ if (!reveals(masked)) return masked;
36956
+ const atIndex = masked.indexOf("@");
36957
+ if (atIndex > 0 && atIndex < masked.length - 1) {
36958
+ const emailFallback = `*${masked.slice(atIndex)}`;
36959
+ if (!reveals(emailFallback)) return emailFallback;
37399
36960
  }
37400
- return masked;
36961
+ return "***";
37401
36962
  }
37402
36963
  function assertRawFree(text, rawValues) {
37403
36964
  if (carriesRawRun(text, rawValues)) {
@@ -37634,7 +37195,7 @@ var auth_jwt_no_verify_default = {
37634
37195
  severity: "critical",
37635
37196
  matcher: {
37636
37197
  type: "regex",
37637
- pattern: "(verify\\s*=\\s*false|verify_signature.*false|algorithms\\s*=\\s*\\[\\])",
37198
+ pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
37638
37199
  flags: "gi"
37639
37200
  },
37640
37201
  requiresNearby: {
@@ -37722,7 +37283,7 @@ var cmd_inject_shell_default = {
37722
37283
  severity: "critical",
37723
37284
  matcher: {
37724
37285
  type: "regex",
37725
- pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
37286
+ pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
37726
37287
  flags: "gi"
37727
37288
  },
37728
37289
  requiresNearby: {
@@ -37851,7 +37412,7 @@ var deser_yaml_unsafe_default = {
37851
37412
  severity: "high",
37852
37413
  matcher: {
37853
37414
  type: "regex",
37854
- pattern: "\\byaml\\.load\\s*\\((?![^)]*SafeLoader|[^)]*safe_load)",
37415
+ pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
37855
37416
  flags: "gi"
37856
37417
  },
37857
37418
  examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
@@ -38068,7 +37629,7 @@ var sql_inject_concat_dot_default = {
38068
37629
  severity: "high",
38069
37630
  matcher: {
38070
37631
  type: "regex",
38071
- pattern: `["'][^\\n]*?(select|insert|update|delete|drop|where)[^\\n]*?["']\\s*\\.`,
37632
+ pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
38072
37633
  flags: "gi"
38073
37634
  },
38074
37635
  appliesTo: {
@@ -38086,7 +37647,7 @@ var sql_inject_concat_default = {
38086
37647
  severity: "high",
38087
37648
  matcher: {
38088
37649
  type: "regex",
38089
- 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*\\+`,
37650
+ 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*\\+`,
38090
37651
  flags: "gi"
38091
37652
  },
38092
37653
  examples: ['"SELECT * FROM users WHERE id = " + userId']
@@ -38101,7 +37662,7 @@ var sql_inject_format_default = {
38101
37662
  severity: "high",
38102
37663
  matcher: {
38103
37664
  type: "regex",
38104
- 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]|\\{[^}]+\\})",
37665
+ 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]+\\})",
38105
37666
  flags: "gi"
38106
37667
  },
38107
37668
  examples: [
@@ -38119,7 +37680,7 @@ var sql_inject_interp_default = {
38119
37680
  severity: "high",
38120
37681
  matcher: {
38121
37682
  type: "regex",
38122
- pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
37683
+ pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
38123
37684
  flags: "gi"
38124
37685
  },
38125
37686
  examples: [
@@ -38494,7 +38055,7 @@ var stack_trace_default = {
38494
38055
  severity: "low",
38495
38056
  matcher: {
38496
38057
  type: "regex",
38497
- pattern: "(?:^|\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38058
+ pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38498
38059
  flags: "g"
38499
38060
  },
38500
38061
  examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
@@ -39652,7 +39213,7 @@ var BUNDLED_PACKS = [
39652
39213
  {
39653
39214
  packId: "code-flaws",
39654
39215
  name: "Code Security Flaws",
39655
- version: "0.1.0",
39216
+ version: "0.1.1",
39656
39217
  rawRules: [
39657
39218
  sql_inject_concat_default,
39658
39219
  sql_inject_concat_dot_default,
@@ -39702,7 +39263,7 @@ var BUNDLED_PACKS = [
39702
39263
  {
39703
39264
  packId: "core-code-context",
39704
39265
  name: "Code Context",
39705
- version: "0.2.1",
39266
+ version: "0.2.2",
39706
39267
  rawRules: [
39707
39268
  internal_ip_default,
39708
39269
  localhost_ref_default,
@@ -39839,6 +39400,11 @@ function bundledDetections() {
39839
39400
  }));
39840
39401
  return cachedDetections;
39841
39402
  }
39403
+ function shippedRegexMatchers() {
39404
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
39405
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
39406
+ );
39407
+ }
39842
39408
 
39843
39409
  // ../../packages/plugin-sdk/src/mask.ts
39844
39410
  var packsReady = false;
@@ -39894,8 +39460,8 @@ function scanText(text, ruleVersions, options = {}) {
39894
39460
  }
39895
39461
 
39896
39462
  // ../../packages/plugin-sdk/src/repo.ts
39897
- import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
39898
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
39463
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
39464
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
39899
39465
  function resolveRepoIdentity(cwd) {
39900
39466
  try {
39901
39467
  const location = locateRepo(cwd);
@@ -39914,8 +39480,9 @@ function resolveRepoIdentity(cwd) {
39914
39480
  var ATTRIBUTION_MEMO_LIMIT = 64;
39915
39481
  var attributionMemo = /* @__PURE__ */ new Map();
39916
39482
  var NO_ATTRIBUTION = Object.freeze({});
39917
- function resolveRepoAttribution(cwd) {
39483
+ function resolveRepoAttribution(cwd, options) {
39918
39484
  try {
39485
+ if (options?.cache === false) return attributeRepo(cwd);
39919
39486
  const remembered = attributionMemo.get(cwd);
39920
39487
  if (remembered !== void 0) return remembered;
39921
39488
  const attribution = attributeRepo(cwd);
@@ -39939,36 +39506,36 @@ function attributeRepo(cwd) {
39939
39506
  function findGitRoot(start) {
39940
39507
  let dir = start;
39941
39508
  for (; ; ) {
39942
- if (existsSync9(join17(dir, ".git"))) return dir;
39509
+ if (existsSync9(join18(dir, ".git"))) return dir;
39943
39510
  const parent = dirname4(dir);
39944
39511
  if (parent === dir) return void 0;
39945
39512
  dir = parent;
39946
39513
  }
39947
39514
  }
39948
39515
  function resolveGitContext(root) {
39949
- const dotGit = join17(root, ".git");
39516
+ const dotGit = join18(root, ".git");
39950
39517
  try {
39951
39518
  if (statSync6(dotGit).isDirectory()) {
39952
- return { configPath: join17(dotGit, "config"), headRoot: root };
39519
+ return { configPath: join18(dotGit, "config"), headRoot: root };
39953
39520
  }
39954
39521
  } catch {
39955
39522
  return void 0;
39956
39523
  }
39957
39524
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
39958
39525
  if (!target) return void 0;
39959
- const gitdir = isAbsolute(target) ? target : join17(root, target);
39960
- if (existsSync9(join17(gitdir, "config"))) {
39961
- return { configPath: join17(gitdir, "config"), headRoot: root };
39526
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
39527
+ if (existsSync9(join18(gitdir, "config"))) {
39528
+ return { configPath: join18(gitdir, "config"), headRoot: root };
39962
39529
  }
39963
- const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
39530
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
39964
39531
  if (!commonRaw) return void 0;
39965
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
39532
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
39966
39533
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
39967
- return { configPath: join17(commonGitDir, "config"), headRoot };
39534
+ return { configPath: join18(commonGitDir, "config"), headRoot };
39968
39535
  }
39969
39536
  function safeRead(path) {
39970
39537
  try {
39971
- return readFileSync10(path, "utf8");
39538
+ return readFileSync11(path, "utf8");
39972
39539
  } catch {
39973
39540
  return void 0;
39974
39541
  }
@@ -40015,9 +39582,9 @@ function slugFromUrl(url2) {
40015
39582
  }
40016
39583
 
40017
39584
  // ../../packages/plugin-sdk/src/events.ts
40018
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39585
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
40019
39586
  function contentHashOf(text) {
40020
- return createHash5("sha256").update(text).digest("hex");
39587
+ return createHash6("sha256").update(text).digest("hex");
40021
39588
  }
40022
39589
  function buildIngestEvent(input2) {
40023
39590
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -40192,9 +39759,10 @@ function createIsolatedScanner(data, opts = {}) {
40192
39759
  if (job.timer !== void 0) return;
40193
39760
  job.startedAt = performance.now();
40194
39761
  job.progressAt = job.startedAt;
39762
+ const budget = job.deadlineAt === void 0 ? job.budgetMs : Math.max(0, Math.min(job.budgetMs, job.deadlineAt - job.startedAt));
40195
39763
  job.timer = setTimeout(() => {
40196
39764
  onDeadline(job);
40197
- }, job.budgetMs);
39765
+ }, budget);
40198
39766
  }
40199
39767
  function runOne(spec, fail) {
40200
39768
  if (closed) {
@@ -40205,6 +39773,12 @@ function createIsolatedScanner(data, opts = {}) {
40205
39773
  fail({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
40206
39774
  return;
40207
39775
  }
39776
+ const now = performance.now();
39777
+ const deadlineAt = spec.deadlineAt;
39778
+ if (deadlineAt !== void 0 && deadlineAt <= now) {
39779
+ fail({ status: "timeout", culpritIndex: void 0, elapsedMs: 0 });
39780
+ return;
39781
+ }
40208
39782
  const started = ensureWorker();
40209
39783
  if (!(started instanceof Worker)) {
40210
39784
  broken = started.error;
@@ -40212,11 +39786,11 @@ function createIsolatedScanner(data, opts = {}) {
40212
39786
  return;
40213
39787
  }
40214
39788
  const id = nextJobId++;
40215
- const now = performance.now();
40216
39789
  const job = {
40217
39790
  id,
40218
39791
  worker: started,
40219
39792
  budgetMs: spec.budgetMs,
39793
+ deadlineAt,
40220
39794
  startedAt: now,
40221
39795
  progressIndex: -1,
40222
39796
  progressAt: now,
@@ -40230,14 +39804,19 @@ function createIsolatedScanner(data, opts = {}) {
40230
39804
  if (readyWorker === started) {
40231
39805
  beginDeadline(job);
40232
39806
  } else {
39807
+ const startBudget = spec.startBudgetMs ?? startBudgetMs;
39808
+ const callerLimited = deadlineAt !== void 0 && deadlineAt - now < startBudget;
39809
+ const startWaitMs = callerLimited ? deadlineAt - now : startBudget;
40233
39810
  job.startupTimer = setTimeout(() => {
40234
39811
  if (pending !== job) return;
40235
39812
  kill(job.worker);
40236
- failPending({
40237
- status: "unavailable",
40238
- reason: `the scan worker did not start within ${String(startBudgetMs)}ms`
40239
- });
40240
- }, startBudgetMs);
39813
+ failPending(
39814
+ callerLimited ? { status: "timeout", culpritIndex: void 0, elapsedMs: performance.now() - now } : {
39815
+ status: "unavailable",
39816
+ reason: `the scan worker did not start within ${String(startBudget)}ms`
39817
+ }
39818
+ );
39819
+ }, startWaitMs);
40241
39820
  }
40242
39821
  try {
40243
39822
  started.postMessage(spec.build(id));
@@ -40266,7 +39845,9 @@ function createIsolatedScanner(data, opts = {}) {
40266
39845
  return enqueue((resolve3) => {
40267
39846
  runOne(
40268
39847
  {
40269
- budgetMs,
39848
+ budgetMs: scanOpts?.budgetMs ?? budgetMs,
39849
+ startBudgetMs: scanOpts?.startBudgetMs,
39850
+ deadlineAt: scanOpts?.deadlineAt,
40270
39851
  build: (id) => ({
40271
39852
  kind: "scan",
40272
39853
  id,
@@ -40460,6 +40041,9 @@ function createGuardedScanner(partition, gateway, opts) {
40460
40041
  let unverified = partition.unverified;
40461
40042
  let isolated = unverified.length > 0 ? createIsolatedScanner({ verified, unverified }, opts) : void 0;
40462
40043
  let retired = false;
40044
+ let bounded;
40045
+ let boundedWarned = false;
40046
+ let closed = false;
40463
40047
  function inProcess(text, context) {
40464
40048
  return scan(text, verified, context);
40465
40049
  }
@@ -40521,69 +40105,52 @@ function createGuardedScanner(partition, gateway, opts) {
40521
40105
  await degrade();
40522
40106
  return inProcess(text, context);
40523
40107
  }
40108
+ async function scanBounded(text, context, bound) {
40109
+ const remainingMs = bound.remainingMs;
40110
+ let outcome;
40111
+ if (closed) {
40112
+ outcome = { status: "unavailable", reason: "the scan worker is closed" };
40113
+ } else if (remainingMs !== void 0 && !(remainingMs > 0)) {
40114
+ outcome = { status: "timeout", culpritIndex: void 0, elapsedMs: 0 };
40115
+ } else {
40116
+ bounded ??= createIsolatedScanner({ verified, unverified }, opts);
40117
+ const deadlineAt = remainingMs === void 0 ? void 0 : performance.now() + remainingMs;
40118
+ try {
40119
+ outcome = await bounded.scan(text, context, {
40120
+ budgetMs: bound.budgetMs,
40121
+ startBudgetMs: bound.startBudgetMs,
40122
+ deadlineAt
40123
+ });
40124
+ } catch (error62) {
40125
+ outcome = {
40126
+ status: "unavailable",
40127
+ reason: error62 instanceof Error ? error62.message : "the scan worker failed unexpectedly"
40128
+ };
40129
+ }
40130
+ }
40131
+ if (outcome.status !== "ok" && !boundedWarned) {
40132
+ boundedWarned = true;
40133
+ process.stderr.write(
40134
+ outcome.status === "timeout" ? `[aka] a large input could not be scanned within its time limit and was refused.
40135
+ ` : `[aka] a large input could not be scanned and was refused: ${outcome.reason}.
40136
+ `
40137
+ );
40138
+ }
40139
+ return outcome;
40140
+ }
40524
40141
  return {
40525
40142
  scan: guardedScan,
40143
+ scanBounded,
40526
40144
  degraded: () => retired,
40527
40145
  async close() {
40528
- await retire();
40146
+ closed = true;
40147
+ const live = bounded;
40148
+ bounded = void 0;
40149
+ await Promise.all([retire(), live?.close()]);
40529
40150
  }
40530
40151
  };
40531
40152
  }
40532
40153
 
40533
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
40534
- import { readFileSync as readFileSync12 } from "fs";
40535
- import { join as join19 } from "path";
40536
-
40537
- // ../../packages/plugin-sdk/src/host-floor.ts
40538
- import { readFileSync as readFileSync14 } from "fs";
40539
- import { join as join21 } from "path";
40540
-
40541
- // ../../packages/plugin-sdk/src/model-governance.ts
40542
- import {
40543
- closeSync as closeSync2,
40544
- fstatSync,
40545
- mkdirSync as mkdirSync2,
40546
- openSync as openSync2,
40547
- readFileSync as readFileSync13,
40548
- readSync,
40549
- writeFileSync as writeFileSync5
40550
- } from "fs";
40551
- import { join as join20 } from "path";
40552
- var TAIL_BYTES = 256 * 1024;
40553
-
40554
- // ../../packages/plugin-sdk/src/host-floor.ts
40555
- var HOST_FEATURE = {
40556
- ModelSwitch: "model-switch",
40557
- VaultPointerDisplay: "vault-pointer-display"
40558
- };
40559
- var HOST_FLOORS = {
40560
- [HOST_FEATURE.ModelSwitch]: {
40561
- label: "model-switch protection",
40562
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
40563
- since: "2.1.251"
40564
- },
40565
- [HOST_FEATURE.VaultPointerDisplay]: {
40566
- label: "vault pointer display",
40567
- hookEvents: ["MessageDisplay"],
40568
- since: "2.1.152"
40569
- }
40570
- };
40571
- var ANTIGRAVITY_HOST_FEATURE = {
40572
- EndOfTurnCapture: "end-of-turn-capture"
40573
- };
40574
- var ANTIGRAVITY_HOST_FLOORS = {
40575
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
40576
- label: "end-of-turn history capture",
40577
- hookEvents: ["Stop"],
40578
- since: "1.1.10"
40579
- }
40580
- };
40581
-
40582
- // ../../packages/plugin-sdk/src/ignore-layers.ts
40583
- var import_ignore = __toESM(require_ignore(), 1);
40584
- import { readFileSync as readFileSync15 } from "fs";
40585
- import { join as join22 } from "path";
40586
-
40587
40154
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
40588
40155
  import { arch, hostname as hostname4, platform, release } from "os";
40589
40156
  function resolveInventoryContext(input2) {
@@ -40613,14 +40180,6 @@ function resolveInventoryContext(input2) {
40613
40180
  return ctx;
40614
40181
  }
40615
40182
 
40616
- // ../../packages/plugin-sdk/src/nudge.ts
40617
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
40618
- import { join as join23 } from "path";
40619
-
40620
- // ../../packages/plugin-sdk/src/paths.ts
40621
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
40622
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
40623
-
40624
40183
  // ../../packages/plugin-sdk/src/policy-resolver.ts
40625
40184
  import { randomUUID as randomUUID14 } from "crypto";
40626
40185
  function createPolicyResolver(bundle) {
@@ -40665,36 +40224,6 @@ function assignedRulePolicies(installed) {
40665
40224
  return out;
40666
40225
  }
40667
40226
 
40668
- // ../../packages/plugin-sdk/src/project-files.ts
40669
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
40670
- import { basename as basename5, join as join24 } from "path";
40671
-
40672
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
40673
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
40674
- if (typeof v === "string" && v.trim() === "") return void 0;
40675
- return v;
40676
- }, external_exports.string().optional()).catch(void 0);
40677
- var optionalFlag = external_exports.preprocess((v) => {
40678
- if (typeof v !== "string") return false;
40679
- const normalized = v.trim().toLowerCase();
40680
- return normalized !== "" && normalized !== "0" && normalized !== "false";
40681
- }, external_exports.boolean()).catch(false);
40682
- var antigravityProviderEnvShape = {
40683
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
40684
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
40685
- };
40686
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
40687
-
40688
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
40689
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
40690
- if (typeof v === "string" && v.trim() === "") return void 0;
40691
- return v;
40692
- }, external_exports.string().optional()).catch(void 0);
40693
- var codexProviderEnvShape = {
40694
- OPENAI_BASE_URL: optionalBaseUrl3
40695
- };
40696
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
40697
-
40698
40227
  // ../../packages/plugin-sdk/src/provider-codex.ts
40699
40228
  function codexProviderFromModelId(modelId) {
40700
40229
  const id = modelId.trim();
@@ -40745,6 +40274,16 @@ function conditionsMatch(conditions, ctx) {
40745
40274
  if (conditions.provider !== void 0) return false;
40746
40275
  return true;
40747
40276
  }
40277
+ function readRemainingMs(largeInput) {
40278
+ const read = largeInput.remainingMs;
40279
+ if (read === void 0) return void 0;
40280
+ try {
40281
+ const remaining = read();
40282
+ return typeof remaining !== "number" || Number.isNaN(remaining) ? 0 : remaining;
40283
+ } catch {
40284
+ return 0;
40285
+ }
40286
+ }
40748
40287
  var bundlesPacked = false;
40749
40288
  function createPluginRuntime(gateway, settings, opts) {
40750
40289
  if (!bundlesPacked) {
@@ -40754,6 +40293,7 @@ function createPluginRuntime(gateway, settings, opts) {
40754
40293
  const policyMode = settings.policy;
40755
40294
  let redactFallback = settings.redactFallback;
40756
40295
  const dataDir2 = opts?.dataDir;
40296
+ const largeInput = opts?.largeInput;
40757
40297
  let rules = [];
40758
40298
  let evidenceOf = evidenceLookup(rules);
40759
40299
  let scanner;
@@ -40966,7 +40506,24 @@ function createPluginRuntime(gateway, settings, opts) {
40966
40506
  await ensureInitialized();
40967
40507
  if (!scanner) throw new Error("the runtime initialized without a scanner");
40968
40508
  const shielded = shieldPointers(text);
40969
- const matched = await scanner.scan(shielded.text, context);
40509
+ let matched;
40510
+ if (largeInput !== void 0 && shielded.text.length >= largeInput.thresholdChars) {
40511
+ const outcome = await scanner.scanBounded(shielded.text, context, {
40512
+ budgetMs: largeInput.budgetMs,
40513
+ startBudgetMs: largeInput.startBudgetMs,
40514
+ remainingMs: readRemainingMs(largeInput)
40515
+ });
40516
+ if (outcome.status !== "ok") {
40517
+ return {
40518
+ decision: { action: "block", text: null, findings: [], scanIncomplete: outcome.status },
40519
+ excepted: /* @__PURE__ */ new Set(),
40520
+ exceptionIds: []
40521
+ };
40522
+ }
40523
+ matched = outcome.findings;
40524
+ } else {
40525
+ matched = await scanner.scan(shielded.text, context);
40526
+ }
40970
40527
  const findings = dropShieldedFindings(matched, shielded.spans);
40971
40528
  const fpCache = /* @__PURE__ */ new Map();
40972
40529
  const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
@@ -40991,12 +40548,11 @@ function createPluginRuntime(gateway, settings, opts) {
40991
40548
  async function processText(text, context, opts2 = {}) {
40992
40549
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
40993
40550
  }
40994
- async function capture(input2, opts2 = {}) {
40551
+ async function evaluateCapture(input2, opts2) {
40995
40552
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
40996
- const filePath = input2.metadata?.filePath;
40997
40553
  const { decision, excepted, exceptionIds } = await evaluate(
40998
40554
  input2.text,
40999
- { filePath, eventKind: input2.kind },
40555
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
41000
40556
  {
41001
40557
  sourceTool: input2.sourceTool,
41002
40558
  metadata: input2.metadata,
@@ -41004,20 +40560,28 @@ function createPluginRuntime(gateway, settings, opts) {
41004
40560
  },
41005
40561
  opts2.rewritable
41006
40562
  );
41007
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
40563
+ return { decision, excepted, exceptionIds, timingStartedAt };
40564
+ }
40565
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
40566
+ const filePath = input2.metadata?.filePath;
40567
+ if (opts2.persist === "with-findings" && decision.findings.length === 0 && decision.scanIncomplete === void 0) {
40568
+ return;
40569
+ }
41008
40570
  try {
41009
40571
  const contentHash = contentHashOf(input2.text);
41010
40572
  const maskedFindings = decision.findings.filter(
41011
40573
  (match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
41012
40574
  );
41013
- const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
40575
+ const storedContent = decision.scanIncomplete !== void 0 ? "" : maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
41014
40576
  const inspectionMs = elapsedMs(timingStartedAt);
41015
40577
  const redactDegradedTo = decision.redactDegradedTo;
41016
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
40578
+ const scanIncomplete = decision.scanIncomplete;
40579
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 || scanIncomplete !== void 0 ? {
41017
40580
  ...input2.metadata,
41018
40581
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
41019
40582
  ...inspectionMs !== void 0 ? { inspectionMs } : {},
41020
- ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
40583
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {},
40584
+ ...scanIncomplete !== void 0 ? { scanIncomplete } : {}
41021
40585
  } : input2.metadata;
41022
40586
  const event = buildIngestEvent({
41023
40587
  kind: input2.kind,
@@ -41047,6 +40611,8 @@ function createPluginRuntime(gateway, settings, opts) {
41047
40611
  // exceptions/blocked_detections when a key is available;
41048
40612
  // falls back to the masked match so at-rest findings still get
41049
40613
  // a stable (if weaker) identity on a workspace with no dataDir.
40614
+ // Both ignore the same invisible padding, so a clean and a
40615
+ // padded occurrence of one secret key alike on either path.
41050
40616
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
41051
40617
  }) : void 0;
41052
40618
  return {
@@ -41074,7 +40640,37 @@ function createPluginRuntime(gateway, settings, opts) {
41074
40640
  }
41075
40641
  } catch {
41076
40642
  }
41077
- return decision;
40643
+ }
40644
+ async function enforcedIn(text, context) {
40645
+ try {
40646
+ await ensureInitialized();
40647
+ if (!scanner) return [];
40648
+ const shielded = shieldPointers(text);
40649
+ const matched = await scanner.scan(shielded.text, context);
40650
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
40651
+ const action = resolveAction(finding.ruleId, finding.category);
40652
+ return action === "block" || action === "redact";
40653
+ });
40654
+ } catch {
40655
+ return [];
40656
+ }
40657
+ }
40658
+ async function capture(input2, opts2 = {}) {
40659
+ const evaluated = await evaluateCapture(input2, opts2);
40660
+ await persistCapture(input2, opts2, evaluated);
40661
+ return evaluated.decision;
40662
+ }
40663
+ async function captureDeferred(input2, opts2 = {}) {
40664
+ const evaluated = await evaluateCapture(input2, opts2);
40665
+ let recorded = false;
40666
+ return {
40667
+ result: evaluated.decision,
40668
+ record: async () => {
40669
+ if (recorded) return;
40670
+ recorded = true;
40671
+ await persistCapture(input2, opts2, evaluated);
40672
+ }
40673
+ };
41078
40674
  }
41079
40675
  async function rulesetFingerprint() {
41080
40676
  try {
@@ -41095,12 +40691,20 @@ function createPluginRuntime(gateway, settings, opts) {
41095
40691
  }
41096
40692
  await gateway.close();
41097
40693
  }
41098
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
40694
+ return {
40695
+ processText,
40696
+ capture,
40697
+ captureDeferred,
40698
+ enforcedIn,
40699
+ rulesetFingerprint,
40700
+ scanIsolationDegraded,
40701
+ close
40702
+ };
41099
40703
  }
41100
40704
 
41101
40705
  // ../../packages/plugin-sdk/src/scope-key.ts
41102
- import { existsSync as existsSync12 } from "fs";
41103
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join25, normalize } from "path";
40706
+ import { existsSync as existsSync11 } from "fs";
40707
+ import { dirname as dirname5, isAbsolute as isAbsolute2, join as join19, normalize } from "path";
41104
40708
  function scopeKeyMemo() {
41105
40709
  const memo2 = /* @__PURE__ */ new Map();
41106
40710
  return (cwd) => {
@@ -41117,8 +40721,8 @@ function sessionRootScopeKey(cwd) {
41117
40721
  function toolCallScopeKey(tc, scopeKeyOf2) {
41118
40722
  if (tc.keyless === true) return void 0;
41119
40723
  if (tc.filePaths === void 0 && tc.searchRoot === void 0) return scopeKeyOf2(tc.cwd);
41120
- const resolved = (path) => isAbsolute2(path) ? normalize(path) : join25(tc.cwd ?? "", path);
41121
- const walkStart = (path) => isAbsolute2(path) && existsSync12(join25(path, ".git")) ? path : dirname6(path);
40724
+ const resolved = (path) => isAbsolute2(path) ? normalize(path) : join19(tc.cwd ?? "", path);
40725
+ const walkStart = (path) => isAbsolute2(path) && existsSync11(join19(path, ".git")) ? path : dirname5(path);
41122
40726
  const locations = [
41123
40727
  ...(tc.filePaths ?? []).map((path) => walkStart(resolved(path))),
41124
40728
  ...tc.searchRoot === void 0 ? [] : [resolved(tc.searchRoot)]
@@ -41132,16 +40736,9 @@ function toolCallScopeKey(tc, scopeKeyOf2) {
41132
40736
  return agreed;
41133
40737
  }
41134
40738
 
41135
- // ../../packages/plugin-sdk/src/suppressions.ts
41136
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
41137
-
41138
- // ../../packages/plugin-sdk/src/throttle.ts
41139
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
41140
- import { join as join26 } from "path";
41141
-
41142
40739
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
41143
- import { writeFileSync as writeFileSync8 } from "fs";
41144
- import { join as join27 } from "path";
40740
+ import { writeFileSync as writeFileSync5 } from "fs";
40741
+ import { join as join20 } from "path";
41145
40742
 
41146
40743
  // ../../packages/setup-wizard/src/triage/merge.ts
41147
40744
  var RANK = Object.fromEntries(
@@ -41149,9 +40746,9 @@ var RANK = Object.fromEntries(
41149
40746
  );
41150
40747
 
41151
40748
  // ../../packages/setup-wizard/src/triage/plan-file.ts
41152
- import { mkdtempSync, readFileSync as readFileSync17, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
40749
+ import { mkdtempSync, readFileSync as readFileSync12, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "fs";
41153
40750
  import { tmpdir } from "os";
41154
- import { basename as basename6, dirname as dirname7, join as join28 } from "path";
40751
+ import { basename as basename3, dirname as dirname6, join as join21 } from "path";
41155
40752
  var SuppressionEntrySchema = external_exports.object({
41156
40753
  ruleId: external_exports.string(),
41157
40754
  category: DetectionCategory,
@@ -41571,11 +41168,11 @@ function withTimeout(promise2, ms) {
41571
41168
  }
41572
41169
 
41573
41170
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
41574
- import { readFileSync as readFileSync18 } from "fs";
41575
- import { join as join29 } from "path";
41171
+ import { readFileSync as readFileSync13 } from "fs";
41172
+ import { join as join22 } from "path";
41576
41173
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
41577
41174
  function forwardDropsPath(dataDir2) {
41578
- return join29(dataDir2, FORWARD_DROPS_FILENAME);
41175
+ return join22(dataDir2, FORWARD_DROPS_FILENAME);
41579
41176
  }
41580
41177
  function recordForwardDrops(dataDir2, count, nowMs) {
41581
41178
  if (count <= 0) return;
@@ -41593,7 +41190,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
41593
41190
  }
41594
41191
  function readForwardDrops(dataDir2) {
41595
41192
  try {
41596
- const parsed2 = JSON.parse(readFileSync18(forwardDropsPath(dataDir2), "utf8"));
41193
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
41597
41194
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
41598
41195
  const record2 = parsed2;
41599
41196
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -41612,7 +41209,7 @@ function readForwardDrops(dataDir2) {
41612
41209
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
41613
41210
  import { randomUUID as randomUUID16 } from "crypto";
41614
41211
  import { readFile, rename, writeFile } from "fs/promises";
41615
- import { join as join30 } from "path";
41212
+ import { join as join23 } from "path";
41616
41213
  function isInvalidRequest(err) {
41617
41214
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
41618
41215
  }
@@ -41631,7 +41228,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
41631
41228
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
41632
41229
  function createForwardPolicy(deps) {
41633
41230
  const now = deps.now ?? (() => Date.now());
41634
- const file2 = join30(deps.dir, STATE_FILENAME);
41231
+ const file2 = join23(deps.dir, STATE_FILENAME);
41635
41232
  let state = null;
41636
41233
  let loading = null;
41637
41234
  async function readState() {
@@ -41797,6 +41394,9 @@ var AttachedDataGateway = class {
41797
41394
  *
41798
41395
  * Machine mode answers before any key is read, so a machine attachment pays
41799
41396
  * nothing for scoping and forwards exactly what it always has.
41397
+ *
41398
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
41399
+ * forwarding key for key.
41800
41400
  */
41801
41401
  verdictFor(keyOf) {
41802
41402
  try {
@@ -41813,24 +41413,27 @@ var AttachedDataGateway = class {
41813
41413
  * the key its row holds in the local store, recorded per root (see
41814
41414
  * `rootVerdict`), not the key on the root event just handed in: roots are
41815
41415
  * first-write-wins in the store, so when two producers record a root for one
41816
- * session (the session-start hook, then a reconcile pass) the second leaves
41817
- * the stored row as it was, and the history drain decides that row, not this
41818
- * event. Whether this root EVENT is itself sent takes both keys: the stored
41819
- * one AND its own. The event's attributes (cwd, project, repo) describe where
41820
- * it was recorded from, so a root event keyed to a personal directory is never
41821
- * sent under an enrolled stored root, though the enrolled leaves still forward
41822
- * under it: the instance that wrote the stored root is expected to have
41823
- * forwarded it. If it did not (the root was written while standalone or under
41824
- * another attachment, or its forward failed), the plane refuses those leaves
41825
- * and the history drain ships the root first. Any other row with a root
41826
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
41827
- * is in scope AND this instance recorded an in-scope verdict for that root.
41828
- * The audit-event route has real foreign keys on both columns and stubs no
41829
- * missing root, so a leaf sent after its root was kept local is refused
41830
- * there, and a refused forward counts toward the breaker that guards every
41831
- * other one. A root this instance never recorded is therefore `'local'`: the
41832
- * only answer that cannot orphan a row. A row with no root reference at all
41833
- * has nothing to orphan, and is decided by its own key.
41416
+ * session (the session-start hook, then a reconcile pass) the second leaves the
41417
+ * stored row as it was. That stored row, not this event, is what a history
41418
+ * drain pass would decide, if the root started before the attach; the drain
41419
+ * never offers one that started after it (`started_at < backlogBefore`).
41420
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
41421
+ * its own. The event's attributes (cwd, project, repo) describe where it was
41422
+ * recorded from, so a root event keyed to a personal directory is never sent
41423
+ * under an enrolled stored root, though the enrolled leaves still forward under
41424
+ * it: the instance that wrote the stored root is expected to have forwarded it.
41425
+ * If it did not (the root was written while standalone or under another
41426
+ * attachment, or its forward failed), the plane refuses those leaves. A root
41427
+ * that started before the attach is shipped, ahead of its leaves, by the
41428
+ * history drain; one that started after it is never offered by the drain. Any
41429
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
41430
+ * only when its own key is in scope AND this instance recorded an in-scope
41431
+ * verdict for that root. The audit-event route has real foreign keys on both
41432
+ * columns and stubs no missing root, so a leaf sent after its root was kept
41433
+ * local is refused there, and a refused forward counts toward the breaker that
41434
+ * guards every other one. A root this instance never recorded is therefore
41435
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
41436
+ * reference at all has nothing to orphan, and is decided by its own key.
41834
41437
  *
41835
41438
  * What this costs is stated rather than discovered. A session whose stored
41836
41439
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -41901,6 +41504,87 @@ var AttachedDataGateway = class {
41901
41504
  return [];
41902
41505
  }
41903
41506
  }
41507
+ /**
41508
+ * The verdict for the repositories nested in a scanned project, answered
41509
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
41510
+ *
41511
+ * A walk descends into a nested clone or submodule and folds its files into
41512
+ * the project it is walking, so one register can carry several
41513
+ * repositories' call sites under one project key. Each of them must be in
41514
+ * scope for it to forward. One key out of scope, or a nested repository with
41515
+ * no remote (an `undefined` key), keeps the whole register local.
41516
+ *
41517
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
41518
+ * what is nested in it, and every scan passes the list, empty when nothing
41519
+ * is nested. A register nobody vouched for is not one a scoped attachment
41520
+ * may send.
41521
+ *
41522
+ * Machine mode answers before reading the context, so a machine attachment
41523
+ * forwards exactly what it always has.
41524
+ */
41525
+ nestedVerdict(context) {
41526
+ try {
41527
+ if (this.deps.attachment.mode === "machine") return "forward";
41528
+ const keys = context?.nestedScopeKeys;
41529
+ if (keys === void 0) return "local";
41530
+ for (const key of keys) {
41531
+ if (this.verdictFor(() => key) === "local") return "local";
41532
+ }
41533
+ return "forward";
41534
+ } catch {
41535
+ return "local";
41536
+ }
41537
+ }
41538
+ /**
41539
+ * The register a scoped attachment sends, once the project and the repositories
41540
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
41541
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
41542
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
41543
+ *
41544
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
41545
+ * and the ledger holds every file the scanner ever read under the root, nested
41546
+ * clones' included. So a clone that was removed, or one an ignore file now
41547
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
41548
+ * paths come back as deleted. The scan names the repository of each deleted
41549
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
41550
+ * and each is held to the same verdict as any other key. A path whose key is
41551
+ * absent, or out of scope, is not sent.
41552
+ *
41553
+ * The list is asked for here, and only here: it is an async read of the scan
41554
+ * ledger that the scan makes on being called, so a machine attachment, which
41555
+ * returns before this, and a register already kept local never cause it.
41556
+ *
41557
+ * Anything the scan did not vouch for sends no deleted path, and the register
41558
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
41559
+ * list whose length is not the register's. Deleting is the only thing a dropped
41560
+ * path could have done on the server, so the cost of a refusal is a stored row
41561
+ * that stays, never a path that leaves.
41562
+ *
41563
+ * Machine mode returns `input` itself, the same object and unread, so a machine
41564
+ * attachment's request is exactly what it was. A register that lists no deleted
41565
+ * path, or that is not a ledger register, has nothing to cut and is returned
41566
+ * as it came, with the list unread.
41567
+ */
41568
+ async registerForWire(input2, context) {
41569
+ try {
41570
+ if (this.deps.attachment.mode === "machine") return input2;
41571
+ const { reconcile } = input2;
41572
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
41573
+ const deleted = reconcile.deletedFiles;
41574
+ let kept = [];
41575
+ try {
41576
+ const keys = await context?.deletedFileKeys?.();
41577
+ if (keys?.length === deleted.length) {
41578
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
41579
+ }
41580
+ } catch {
41581
+ kept = [];
41582
+ }
41583
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
41584
+ } catch {
41585
+ return void 0;
41586
+ }
41587
+ }
41904
41588
  /**
41905
41589
  * The event `recordCapture` sends for a capture the verdict let through, or
41906
41590
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -42226,12 +41910,24 @@ var AttachedDataGateway = class {
42226
41910
  * payload onto the wire-boundary-safe shape (no snippet, hashed
42227
41911
  * projectKey), and its result is discarded: `forward.run` never throws or
42228
41912
  * rejects, so there is nothing here to act on.
41913
+ *
41914
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
41915
+ * not say: the key of every repository nested below the scan root, whose
41916
+ * files the walk folded into this register. On a scoped attachment the
41917
+ * register is forwarded only when the project's own key AND every one of
41918
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
41919
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
41920
+ * `registerForWire`). Machine mode never reads either, and the local write
41921
+ * never receives the context and gets the register whole.
42229
41922
  */
42230
- async recordProjectEgress(input2) {
41923
+ async recordProjectEgress(input2, context) {
42231
41924
  const summary = await this.deps.local.recordProjectEgress(input2);
42232
41925
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
41926
+ if (this.nestedVerdict(context) === "local") return summary;
41927
+ const register = await this.registerForWire(input2, context);
41928
+ if (register === void 0) return summary;
42233
41929
  await this.deps.forward.run(
42234
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
41930
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
42235
41931
  );
42236
41932
  return summary;
42237
41933
  }
@@ -42285,6 +41981,11 @@ var AttachedDataGateway = class {
42285
41981
  async scanLedgerPaths() {
42286
41982
  return this.deps.local.scanLedgerPaths();
42287
41983
  }
41984
+ // Delegated, like the path list. An inner gateway that cannot say answers an
41985
+ // empty map, which gives every deleted path no key.
41986
+ async scanLedgerPathKeys() {
41987
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
41988
+ }
42288
41989
  async recordScanned(entries) {
42289
41990
  return this.deps.local.recordScanned(entries);
42290
41991
  }
@@ -42351,6 +42052,12 @@ var AttachedDataGateway = class {
42351
42052
  // and the spread above would otherwise drop the field silently — which is
42352
42053
  // exactly what it did, leaving the whole control inert on every device
42353
42054
  // while every test around it stayed green.
42055
+ //
42056
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
42057
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
42058
+ // reads this bundle once to build detection, so the detections it carries
42059
+ // apply to every event on the machine. Where a prohibition applies is
42060
+ // answered per event by `governanceAppliesTo` below.
42354
42061
  prohibitedModels: cached2.prohibitedModels,
42355
42062
  // NAMED for the same reason as the line above, and it is the same defect
42356
42063
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -42410,6 +42117,30 @@ var AttachedDataGateway = class {
42410
42117
  };
42411
42118
  }
42412
42119
  // ---------------------------------------------------------------------
42120
+ // GovernanceScope — where the organization's model policy applies
42121
+ // ---------------------------------------------------------------------
42122
+ /**
42123
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
42124
+ * the question a model-guard site asks once it has decided to refuse.
42125
+ *
42126
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
42127
+ * with the same key would be forwarded. A machine-wide attachment governs
42128
+ * every event, keyless included, exactly as before. A scoped one governs an
42129
+ * event only when its key names an enrolled repository. An event in a
42130
+ * personal repository, in no repository, with an empty key, or met by a fault
42131
+ * is not governed.
42132
+ *
42133
+ * The event's OWN key, never its session root's. The root rule in
42134
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
42135
+ * this decides whether a refusal applies, which is a question about where the
42136
+ * event happened.
42137
+ *
42138
+ * Answered from memory: no store read, no bundle read, nothing sent.
42139
+ */
42140
+ governanceAppliesTo(scopeKey) {
42141
+ return this.verdictFor(() => scopeKey) === "forward";
42142
+ }
42143
+ // ---------------------------------------------------------------------
42413
42144
  // LocalStoreMaintenance — by delegation (D3).
42414
42145
  //
42415
42146
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -42518,7 +42249,7 @@ function toWireInspection(insp) {
42518
42249
  }
42519
42250
 
42520
42251
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42521
- import { createHash as createHash6 } from "crypto";
42252
+ import { createHash as createHash7 } from "crypto";
42522
42253
  import { hostname as hostname5 } from "os";
42523
42254
 
42524
42255
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
@@ -42526,6 +42257,7 @@ var CORRELATION_ID = EventMetadata.shape.correlationId;
42526
42257
  var TRACE_ID = EventMetadata.shape.traceId;
42527
42258
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
42528
42259
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
42260
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
42529
42261
 
42530
42262
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42531
42263
  var CAPTURE_BATCH_BYTES = 1024 * 1024;
@@ -42537,17 +42269,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
42537
42269
 
42538
42270
  // ../../packages/plugin-runtime/src/attached/install-record.ts
42539
42271
  import { readFile as readFile2, stat } from "fs/promises";
42540
- import { basename as basename7, dirname as dirname8, join as join31, resolve as resolve2 } from "path";
42272
+ import { basename as basename4, dirname as dirname7, join as join24, resolve as resolve2 } from "path";
42541
42273
  async function readInstalledVersion(installRoot) {
42542
42274
  try {
42543
42275
  const versionDir = resolve2(installRoot);
42544
- const pluginDir = dirname8(versionDir);
42545
- const marketplaceDir = dirname8(pluginDir);
42546
- const cacheDir = dirname8(marketplaceDir);
42547
- if (basename7(cacheDir) !== "cache") return null;
42548
- const key = `${basename7(pluginDir)}@${basename7(marketplaceDir)}`;
42276
+ const pluginDir = dirname7(versionDir);
42277
+ const marketplaceDir = dirname7(pluginDir);
42278
+ const cacheDir = dirname7(marketplaceDir);
42279
+ if (basename4(cacheDir) !== "cache") return null;
42280
+ const key = `${basename4(pluginDir)}@${basename4(marketplaceDir)}`;
42549
42281
  const record2 = JSON.parse(
42550
- await readFile2(join31(dirname8(cacheDir), "installed_plugins.json"), "utf8")
42282
+ await readFile2(join24(dirname7(cacheDir), "installed_plugins.json"), "utf8")
42551
42283
  );
42552
42284
  const plugins = record2?.plugins;
42553
42285
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -42579,7 +42311,7 @@ async function exists(path) {
42579
42311
  }
42580
42312
 
42581
42313
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
42582
- import { readFileSync as readFileSync19 } from "fs";
42314
+ import { readFileSync as readFileSync14 } from "fs";
42583
42315
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
42584
42316
  var manifestBuildCache = /* @__PURE__ */ new Map();
42585
42317
  function readManifestBuild(manifestUrl, packageName) {
@@ -42587,7 +42319,7 @@ function readManifestBuild(manifestUrl, packageName) {
42587
42319
  if (!manifestBuildCache.has(key)) {
42588
42320
  let build;
42589
42321
  try {
42590
- const manifest = JSON.parse(readFileSync19(manifestUrl, "utf8"));
42322
+ const manifest = JSON.parse(readFileSync14(manifestUrl, "utf8"));
42591
42323
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
42592
42324
  } catch {
42593
42325
  build = void 0;
@@ -42624,7 +42356,7 @@ async function readInstalledVersionBounded(installRoot) {
42624
42356
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42625
42357
  import { randomUUID as randomUUID17 } from "crypto";
42626
42358
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42627
- import { join as join32 } from "path";
42359
+ import { join as join25 } from "path";
42628
42360
 
42629
42361
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
42630
42362
  import { rename as rename2 } from "fs/promises";
@@ -42653,7 +42385,7 @@ async function publishByRename(tmp, file2, move = rename2) {
42653
42385
 
42654
42386
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42655
42387
  function createPolicyStore(dir = dataDir()) {
42656
- const file2 = join32(dir, "policy-cache.json");
42388
+ const file2 = join25(dir, "policy-cache.json");
42657
42389
  async function read() {
42658
42390
  try {
42659
42391
  const raw = await readFile3(file2, "utf8");
@@ -42723,8 +42455,8 @@ function createPolicyStore(dir = dataDir()) {
42723
42455
  }
42724
42456
 
42725
42457
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
42726
- import { readFileSync as readFileSync20 } from "fs";
42727
- import { join as join33 } from "path";
42458
+ import { readFileSync as readFileSync15 } from "fs";
42459
+ import { join as join26 } from "path";
42728
42460
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
42729
42461
  var OUTCOME_KEYS = {
42730
42462
  ok: true,
@@ -42738,7 +42470,7 @@ var OUTCOME_KEYS = {
42738
42470
  };
42739
42471
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
42740
42472
  function postureReportStatePath(dataDir2) {
42741
- return join33(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42473
+ return join26(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42742
42474
  }
42743
42475
  function writePostureReportState(dataDir2, state) {
42744
42476
  try {
@@ -42779,10 +42511,19 @@ function createPostureReporter(deps) {
42779
42511
  hostname: deps.hostname(),
42780
42512
  capturedAt: nowMs,
42781
42513
  ...measurement,
42782
- // Omit the key rather than spread an explicit `undefined` —
42783
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
42784
- // factory.ts keys on presence.
42785
- ...plugin === void 0 ? {} : { plugin }
42514
+ // Omit the key rather than spread an explicit `undefined`. The type
42515
+ // admits `undefined` here (the schema's optional member), and
42516
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
42517
+ // in-memory object free of an explicit `undefined` member, which the
42518
+ // tests pin by key presence.
42519
+ ...plugin === void 0 ? {} : { plugin },
42520
+ // LAST, and only for a scoped attachment. A machine attachment omits
42521
+ // the key the same way, so its body is byte for byte the one it sent
42522
+ // before the member existed. Anything but exactly `machine` reports the
42523
+ // constant `scoped`, never the raw value: that is resolveScope's own
42524
+ // fail direction, and a value outside the wire's vocabulary would fail
42525
+ // the whole snapshot at the receiver, the wipe signal with it.
42526
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
42786
42527
  };
42787
42528
  } catch {
42788
42529
  return null;
@@ -42805,8 +42546,8 @@ function createPostureReporter(deps) {
42805
42546
  }
42806
42547
 
42807
42548
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
42808
- import { statSync as statSync9 } from "fs";
42809
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
42549
+ import { statSync as statSync7 } from "fs";
42550
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
42810
42551
 
42811
42552
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
42812
42553
  function emptyActionCounts() {
@@ -42836,7 +42577,7 @@ function emptyReadout(readError = false) {
42836
42577
  }
42837
42578
  function readStorePosture(dbPath2) {
42838
42579
  try {
42839
- statSync9(dbPath2);
42580
+ statSync7(dbPath2);
42840
42581
  } catch (err) {
42841
42582
  const code = err.code;
42842
42583
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -42864,7 +42605,7 @@ function readStorePosture(dbPath2) {
42864
42605
  readError: false
42865
42606
  });
42866
42607
  try {
42867
- db = new DatabaseSync4(dbPath2, { readOnly: true });
42608
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
42868
42609
  db.exec("PRAGMA busy_timeout = 2000");
42869
42610
  version2 = db.prepare("PRAGMA user_version").get().user_version;
42870
42611
  try {
@@ -42918,11 +42659,11 @@ function readStorePosture(dbPath2) {
42918
42659
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42919
42660
  import { randomUUID as randomUUID18 } from "crypto";
42920
42661
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42921
- import { join as join34 } from "path";
42662
+ import { join as join27 } from "path";
42922
42663
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42923
42664
  function createPostureStore(dir = settingsDir(), legacyDir) {
42924
- const file2 = join34(dir, "posture-state.json");
42925
- const legacyFile = legacyDir === void 0 ? null : join34(legacyDir, "posture-state.json");
42665
+ const file2 = join27(dir, "posture-state.json");
42666
+ const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
42926
42667
  async function persist(state) {
42927
42668
  await ensureDataDir(dir);
42928
42669
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -42990,8 +42731,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42990
42731
  }
42991
42732
 
42992
42733
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42993
- import { readFileSync as readFileSync21 } from "fs";
42994
- import { join as join35 } from "path";
42734
+ import { readFileSync as readFileSync16 } from "fs";
42735
+ import { join as join28 } from "path";
42995
42736
 
42996
42737
  // ../../packages/plugin-runtime/src/attached/status.ts
42997
42738
  var REFUSAL_LINES = {
@@ -43034,7 +42775,7 @@ var StandaloneDataGateway = class {
43034
42775
  // One notice per gateway — see warnRulesetDiscarded.
43035
42776
  warnedRulesetDiscarded = false;
43036
42777
  constructor(dataDir2, detections = [], meta4) {
43037
- this.db = openLocalDatabase(dataDir2);
42778
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
43038
42779
  this.dataDir = dataDir2;
43039
42780
  this.db.installedPacks.recordInventory(detections, meta4);
43040
42781
  }
@@ -43383,6 +43124,9 @@ var StandaloneDataGateway = class {
43383
43124
  scanLedgerPaths() {
43384
43125
  return Promise.resolve(this.db.scanLedger.allPaths());
43385
43126
  }
43127
+ scanLedgerPathKeys() {
43128
+ return Promise.resolve(this.db.scanLedger.pathKeys());
43129
+ }
43386
43130
  recordScanned(entries) {
43387
43131
  this.db.scanLedger.upsertEntries(entries);
43388
43132
  return Promise.resolve();
@@ -43470,11 +43214,15 @@ function resolveGatewayForConfig(config2, meta4) {
43470
43214
  readStore: () => readStorePosture(config2.dbPath),
43471
43215
  hostname: () => hostname6(),
43472
43216
  now: () => Date.now(),
43217
+ // The mode THIS gateway enforces, from the attachment resolved above,
43218
+ // so the report cannot name a mode the forward paths are not using.
43219
+ attachmentMode: attachment.mode,
43473
43220
  // The reporting build's identity, when the caller knows it (the plugin
43474
43221
  // adapters do; an embedder or a test may not). Composed with the SAME
43475
43222
  // policy store the sync child writes, so the block names the bundle
43476
- // actually in force. Key omitted rather than set undefined — the
43477
- // reporter keys on presence.
43223
+ // actually in force. The dependency key is omitted when no build is
43224
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
43225
+ // then adds no block.
43478
43226
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
43479
43227
  })
43480
43228
  });
@@ -43495,11 +43243,11 @@ import { randomUUID as randomUUID19 } from "crypto";
43495
43243
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
43496
43244
 
43497
43245
  // src/history/transcripts.ts
43498
- import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync22, readSync as readSync2, statSync as statSync10 } from "fs";
43499
- import { homedir as homedir3 } from "os";
43500
- import { join as join36 } from "path";
43246
+ import { closeSync as closeSync2, openSync as openSync2, readdirSync as readdirSync2, readFileSync as readFileSync17, readSync, statSync as statSync8 } from "fs";
43247
+ import { homedir as homedir2 } from "os";
43248
+ import { join as join29 } from "path";
43501
43249
  function transcriptsDir(home) {
43502
- return join36(home ?? homedir3(), ".codex", "sessions");
43250
+ return join29(home ?? homedir2(), ".codex", "sessions");
43503
43251
  }
43504
43252
  function isRecord(value) {
43505
43253
  return typeof value === "object" && value !== null;
@@ -43619,11 +43367,12 @@ function parseTranscriptUsage(jsonl, sinceMs = 0, knownSessionId) {
43619
43367
  const last = info.last_token_usage;
43620
43368
  if (!isRecord(last)) continue;
43621
43369
  const usage = {};
43622
- if (typeof last.input_tokens === "number") usage.input_tokens = last.input_tokens;
43623
- if (typeof last.output_tokens === "number") usage.output_tokens = last.output_tokens;
43624
- if (typeof last.cached_input_tokens === "number") {
43625
- usage.cache_read_input_tokens = last.cached_input_tokens;
43370
+ const cached2 = typeof last.cached_input_tokens === "number" ? Math.max(0, last.cached_input_tokens) : 0;
43371
+ if (typeof last.input_tokens === "number") {
43372
+ usage.input_tokens = Math.max(0, last.input_tokens - cached2);
43626
43373
  }
43374
+ if (typeof last.output_tokens === "number") usage.output_tokens = last.output_tokens;
43375
+ if (typeof last.cached_input_tokens === "number") usage.cache_read_input_tokens = cached2;
43627
43376
  if (typeof last.reasoning_output_tokens === "number") {
43628
43377
  usage.reasoning_output_tokens = last.reasoning_output_tokens;
43629
43378
  }
@@ -43765,12 +43514,12 @@ function* walkJsonlFiles(dir, depth = 0) {
43765
43514
  if (depth > 6) return;
43766
43515
  let entries;
43767
43516
  try {
43768
- entries = readdirSync5(dir, { withFileTypes: true });
43517
+ entries = readdirSync2(dir, { withFileTypes: true });
43769
43518
  } catch {
43770
43519
  return;
43771
43520
  }
43772
43521
  for (const entry of entries) {
43773
- const full = join36(dir, entry.name);
43522
+ const full = join29(dir, entry.name);
43774
43523
  if (entry.isDirectory()) {
43775
43524
  yield* walkJsonlFiles(full, depth + 1);
43776
43525
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -43781,8 +43530,8 @@ function* walkJsonlFiles(dir, depth = 0) {
43781
43530
  function* iterateFileContents(dir) {
43782
43531
  for (const filePath of walkJsonlFiles(dir)) {
43783
43532
  try {
43784
- statSync10(filePath);
43785
- yield { content: readFileSync22(filePath, "utf8"), filePath };
43533
+ statSync8(filePath);
43534
+ yield { content: readFileSync17(filePath, "utf8"), filePath };
43786
43535
  } catch {
43787
43536
  }
43788
43537
  }
@@ -43900,17 +43649,17 @@ function pluginBuild() {
43900
43649
  }
43901
43650
 
43902
43651
  // src/history/tail.ts
43903
- import { createHash as createHash7 } from "crypto";
43652
+ import { createHash as createHash8 } from "crypto";
43904
43653
  import {
43905
- closeSync as closeSync4,
43906
- fstatSync as fstatSync2,
43907
- mkdirSync as mkdirSync5,
43908
- openSync as openSync4,
43909
- readFileSync as readFileSync23,
43910
- readSync as readSync3,
43911
- writeFileSync as writeFileSync10
43654
+ closeSync as closeSync3,
43655
+ fstatSync,
43656
+ mkdirSync as mkdirSync2,
43657
+ openSync as openSync3,
43658
+ readFileSync as readFileSync18,
43659
+ readSync as readSync2,
43660
+ writeFileSync as writeFileSync7
43912
43661
  } from "fs";
43913
- import { join as join37 } from "path";
43662
+ import { join as join30 } from "path";
43914
43663
 
43915
43664
  // src/history/usage.ts
43916
43665
  var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";