@akasecurity/ai-tc-codex 0.9.16 → 0.9.17-beta.1

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
  }
@@ -22703,8 +21867,9 @@ var SessionTokenReport = external_exports.object({
22703
21867
  totalTokens: external_exports.number().int().nonnegative(),
22704
21868
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22705
21869
  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
21870
+ // True whenever any call priced to null (an unknown provider/model, or a call
21871
+ // over a long-context threshold whose rate is unpublished), so the total
21872
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22708
21873
  // precise figure rather than silently dropping the unpriced calls.
22709
21874
  costIsPartial: external_exports.boolean()
22710
21875
  });
@@ -23581,7 +22746,15 @@ var StorePostureSnapshot = external_exports.object({
23581
22746
  policyCounts: StorePosturePolicyCounts,
23582
22747
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23583
22748
  // getting its 200 without a payload change.
23584
- plugin: StorePosturePlugin.optional()
22749
+ plugin: StorePosturePlugin.optional(),
22750
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22751
+ // machine attachment omits it, so its body is byte for byte the one it
22752
+ // sent before this member existed. Absent therefore means machine-wide OR
22753
+ // a reporter older than this member, never "scoped". Both values parse, so
22754
+ // a sender that one day spells `machine` breaks no receiver; any other
22755
+ // value fails the whole snapshot, which is why the reporter sends a
22756
+ // constant and never the raw mode.
22757
+ attachmentMode: AttachmentMode.optional()
23585
22758
  }).meta({ id: "StorePostureSnapshot" });
23586
22759
  var CAPTURE_VERSION_PREFIX = "capture/";
23587
22760
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -24028,7 +23201,7 @@ var Rule = external_exports.strictObject({
24028
23201
  postValidators: external_exports.array(PostValidatorRef).optional(),
24029
23202
  requiresNearby: RequiresNearby.optional(),
24030
23203
  examples: external_exports.array(external_exports.string()).optional(),
24031
- // Whether the matched text is itself sensitive. Absent means 'value'.
23204
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24032
23205
  evidence: RuleEvidence.optional()
24033
23206
  }).meta({ id: "Rule" });
24034
23207
  var Author = external_exports.object({
@@ -24120,7 +23293,13 @@ var DetectionRule = external_exports.object({
24120
23293
  // Representative matching strings the rule author shipped with the rule. The
24121
23294
  // cheapest honest answer to "show me what this rule catches" — every bundled
24122
23295
  // rule has them, and they are already in the stored snapshot.
24123
- examples: external_exports.array(external_exports.string()).optional()
23296
+ examples: external_exports.array(external_exports.string()).optional(),
23297
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23298
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23299
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23300
+ // in a value category (secret/pii/financial/phi) is always 'value',
23301
+ // whatever it declares.
23302
+ evidence: RuleEvidence.optional()
24124
23303
  }).meta({ id: "DetectionRule" });
24125
23304
  var DetectionUpdate = external_exports.object({
24126
23305
  available: external_exports.boolean(),
@@ -24188,8 +23367,10 @@ var ImportDetectionRequest = external_exports.object({
24188
23367
  }).meta({ id: "ImportDetectionRequest" });
24189
23368
 
24190
23369
  // ../../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 {};
23370
+ function optional2(key, raw, parse4) {
23371
+ if (raw === void 0) return {};
23372
+ const parsed2 = parse4(raw);
23373
+ if (!parsed2.success || parsed2.data === void 0) return {};
24193
23374
  return { [key]: parsed2.data };
24194
23375
  }
24195
23376
  function isStringArray(value) {
@@ -24224,10 +23405,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24224
23405
  category: r.category,
24225
23406
  severity: r.severity,
24226
23407
  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.
23408
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23409
+ // decides whether this rule fires. Carried so a consumer re-running the
23410
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23411
+ // than a matcher stripped of its guards — half the bundled catalog
23412
+ // carries at least one of these. `examples` and `evidence` describe the
23413
+ // rule and never gate a match.
24231
23414
  //
24232
23415
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24233
23416
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24237,18 +23420,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24237
23420
  // test should stay exactly what it was, namely a renderable matcher. A
24238
23421
  // field that fails validation is omitted, which reads as "not set" and is
24239
23422
  // the same thing the consumer saw before this change.
24240
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23423
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24241
23424
  ...optional2(
24242
23425
  "postValidators",
24243
- PostValidatorRef.array().safeParse(r.postValidators),
24244
- r.postValidators
23426
+ r.postValidators,
23427
+ (v) => PostValidatorRef.array().safeParse(v)
24245
23428
  ),
24246
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23429
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24247
23430
  ...optional2(
24248
23431
  "examples",
24249
- { success: isStringArray(r.examples), data: r.examples },
24250
- r.examples
24251
- )
23432
+ r.examples,
23433
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23434
+ ),
23435
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24252
23436
  }
24253
23437
  ];
24254
23438
  });
@@ -24941,11 +24125,14 @@ var PolicyBundle = external_exports.object({
24941
24125
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24942
24126
  // Model ids (the raw `model` string a harness reports, e.g.
24943
24127
  // `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.
24128
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24129
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24130
+ // wherever the organization governs the event: everywhere on a
24131
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24132
+ // one (the plugin runtime's `governanceApplies`).
24133
+ // Optional so an older backend — and an older on-disk cache — still
24134
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24135
+ // predates this field and the safe direction to default.
24949
24136
  //
24950
24137
  // Ids, not display names: the governance decision is keyed on the exact
24951
24138
  // string the harness reports (`model_status_override.versionId` in the
@@ -25404,6 +24591,8 @@ var AttachmentScopeEntry = external_exports.object({
25404
24591
  });
25405
24592
  var AttachmentScope = external_exports.object({
25406
24593
  endpoint: external_exports.string().min(1),
24594
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24595
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25407
24596
  entries: external_exports.array(AttachmentScopeEntry)
25408
24597
  });
25409
24598
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25416,7 +24605,13 @@ function parseAttachmentScope(raw) {
25416
24605
  const entry = AttachmentScopeEntry.safeParse(candidate);
25417
24606
  if (entry.success) entries.push(entry.data);
25418
24607
  }
25419
- return { endpoint: envelope.data.endpoint, entries };
24608
+ const { endpoint, tenantName, userEmail } = envelope.data;
24609
+ return {
24610
+ endpoint,
24611
+ ...tenantName === void 0 ? {} : { tenantName },
24612
+ ...userEmail === void 0 ? {} : { userEmail },
24613
+ entries
24614
+ };
25420
24615
  } catch {
25421
24616
  return void 0;
25422
24617
  }
@@ -25781,6 +24976,27 @@ var ManagedSettings = external_exports.object({
25781
24976
  };
25782
24977
  }).meta({ id: "ManagedSettings" });
25783
24978
 
24979
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24980
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24981
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24982
+ var ModPolicySnapshot = external_exports.object({
24983
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24984
+ generatedAt: external_exports.iso.datetime(),
24985
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24986
+ // user's enabled installed packs (user-modified and custom packs included).
24987
+ // Absent means the store holds no authoritative snapshot, and the reader
24988
+ // scans with the packs it ships — the hook's own fallback.
24989
+ rules: external_exports.array(Rule).optional(),
24990
+ // Rule-targeted actions (first enabled policy per rule wins).
24991
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
24992
+ // The resolved action per detection category.
24993
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
24994
+ // Rules with an active exception grant. Honouring a grant means matching a
24995
+ // keyed fingerprint of the value and consuming a use, which only the hook can
24996
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
24997
+ exceptionRuleIds: external_exports.array(external_exports.string())
24998
+ }).meta({ id: "ModPolicySnapshot" });
24999
+
25784
25000
  // ../../packages/schema/src/zod/project-files.ts
25785
25001
  var ProjectFileInput = external_exports.object({
25786
25002
  path: external_exports.string().min(1),
@@ -26101,7 +25317,16 @@ var AttachInput = external_exports.object({
26101
25317
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26102
25318
  // renders a longer one usefully.
26103
25319
  label: printable(200).optional(),
26104
- accessKey: external_exports.string()
25320
+ accessKey: external_exports.string(),
25321
+ // How much of this machine the attachment is for: everything, or only the
25322
+ // repositories its user enrolls. Optional, so an input without it still
25323
+ // parses; what an absent mode means is for whatever reads it to decide, not
25324
+ // this shape. This member validates the VALUE rather than leaving that to the
25325
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25326
+ // rejection names the field, so a value that is not a mode is refused as a bad
25327
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25328
+ // it as the mode to attach in.
25329
+ mode: AttachmentMode.optional()
26105
25330
  });
26106
25331
 
26107
25332
  // ../../packages/schema/src/zod/triage.ts
@@ -26387,6 +25612,18 @@ function fromCaptureStatusAttributes(bag) {
26387
25612
  return parsedStatus.success ? parsedStatus.data : null;
26388
25613
  }
26389
25614
 
25615
+ // ../../packages/persistence/src/attached-derived.ts
25616
+ import { rmSync } from "fs";
25617
+ import { join } from "path";
25618
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25619
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25620
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
25621
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
25622
+
25623
+ // ../../packages/persistence/src/control-plane-credential.ts
25624
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25625
+ import { join as join2 } from "path";
25626
+
26390
25627
  // ../../packages/persistence/src/paths.ts
26391
25628
  import {
26392
25629
  chmodSync,
@@ -26533,6 +25770,14 @@ function repairOrRefuseMode(file2) {
26533
25770
  }
26534
25771
  return "ok";
26535
25772
  }
25773
+ function asReadableCredential(value) {
25774
+ const result = AttachedCredentialAny.safeParse(value);
25775
+ if (!result.success) return null;
25776
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25777
+ return null;
25778
+ }
25779
+ return result.data;
25780
+ }
26536
25781
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26537
25782
  const file2 = controlPlaneCredentialPath(settingsDir2);
26538
25783
  let raw;
@@ -26551,20 +25796,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26551
25796
  } catch {
26552
25797
  return { usable: false, reason: "malformed" };
26553
25798
  }
26554
- const result = AttachedCredential.safeParse(parsed2);
26555
- if (!result.success) return { usable: false, reason: "malformed" };
26556
- if (!isSafeEndpoint(result.data.endpoint)) {
25799
+ const credential = asReadableCredential(parsed2);
25800
+ if (credential === null) return { usable: false, reason: "malformed" };
25801
+ if (!isSafeEndpoint(credential.endpoint)) {
26557
25802
  return { usable: false, reason: "unsafe-endpoint" };
26558
25803
  }
26559
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25804
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26560
25805
  return {
26561
25806
  usable: false,
26562
25807
  reason: "endpoint-mismatch",
26563
- credentialEndpoint: result.data.endpoint,
25808
+ credentialEndpoint: credential.endpoint,
26564
25809
  settingsEndpoint: connection.endpoint
26565
25810
  };
26566
25811
  }
26567
- return { usable: true, credential: result.data };
25812
+ return { usable: true, credential };
26568
25813
  }
26569
25814
  function readControlPlaneCredential(settingsDir2, connection) {
26570
25815
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26573,7 +25818,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26573
25818
 
26574
25819
  // ../../packages/persistence/src/database.ts
26575
25820
  import { randomUUID as randomUUID11 } from "crypto";
26576
- import { dirname as dirname2, join as join7, sep } from "path";
25821
+ import { dirname as dirname2, join as join8, sep } from "path";
26577
25822
  import { DatabaseSync } from "node:sqlite";
26578
25823
 
26579
25824
  // ../../packages/persistence/src/ids.ts
@@ -26627,6 +25872,7 @@ function uuidFromDigest(digest) {
26627
25872
  function captureWireId(sessionId, contentHash, filePath = null) {
26628
25873
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26629
25874
  }
25875
+ var DOT = ".".charCodeAt(0);
26630
25876
 
26631
25877
  // ../../packages/persistence/src/internal/snapshot.ts
26632
25878
  import { randomUUID } from "crypto";
@@ -26954,6 +26200,25 @@ function scopeKeysParam(scopeKeys) {
26954
26200
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26955
26201
  FROM audit_events AS session_root
26956
26202
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26203
+ var COUNTED_IN_SCOPE = `
26204
+ AND ${inScope("scope_key")}
26205
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26206
+ var DRAIN_TOTALS = `SELECT
26207
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26208
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26209
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26210
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26211
+ THEN 1 ELSE 0 END) AS skipped,
26212
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26213
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26214
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26215
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26216
+ FROM audit_events
26217
+ WHERE event_type IN (${TYPE_LIST})`;
26218
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26219
+ FROM audit_events
26220
+ WHERE synced_at = ${String(SKIPPED)}
26221
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26957
26222
  var ROW_COLUMNS = `id,
26958
26223
  parent_id AS parentId,
26959
26224
  root_session_id AS rootSessionId,
@@ -27029,7 +26294,7 @@ var SqliteHistorySyncRepository = class {
27029
26294
  );
27030
26295
  this.scopedCaptureRowsStmt = db.prepare(
27031
26296
  `SELECT ${ROW_COLUMNS}
27032
- FROM audit_events
26297
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27033
26298
  WHERE synced_at IS NULL
27034
26299
  AND sync_claimed_at IS NULL
27035
26300
  AND outbox_owed = 1
@@ -27082,40 +26347,28 @@ var SqliteHistorySyncRepository = class {
27082
26347
  );
27083
26348
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27084
26349
  FROM audit_events${COUNTED_SCOPE}`);
26350
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26351
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27085
26352
  this.partitionByKindStmt = db.prepare(
27086
26353
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27087
26354
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27088
26355
  GROUP BY event_type`
27089
26356
  );
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})`
26357
+ this.scopedPartitionByKindStmt = db.prepare(
26358
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26359
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26360
+ GROUP BY event_type`
27103
26361
  );
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})`
26362
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26363
+ this.scopedCountsStmt = db.prepare(
26364
+ `${DRAIN_TOTALS}
26365
+ AND ${inScope("scope_key")}
26366
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26367
+ );
26368
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26369
+ this.scopedCaptureSkipCountStmt = db.prepare(
26370
+ `${CAPTURE_SKIPS}
26371
+ AND ${inScope("scope_key")}`
27119
26372
  );
27120
26373
  this.fingerprintStmt = db.prepare(
27121
26374
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27229,6 +26482,10 @@ var SqliteHistorySyncRepository = class {
27229
26482
  scopedCaptureRowsStmt;
27230
26483
  scopedCaptureBacklogOwedStmt;
27231
26484
  markScopeCapturesOwedStmt;
26485
+ scopedPartitionStmt;
26486
+ scopedPartitionByKindStmt;
26487
+ scopedCountsStmt;
26488
+ scopedCaptureSkipCountStmt;
27232
26489
  /**
27233
26490
  * The masked detections recorded against one tool call.
27234
26491
  *
@@ -27450,7 +26707,29 @@ var SqliteHistorySyncRepository = class {
27450
26707
  * in" — and a machine that has never attached has no boundary to pass, so
27451
26708
  * requiring one would force a caller to invent one and report the whole store
27452
26709
  * as queued.
26710
+ *
26711
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26712
+ * the rows that pass the drain's reachability rule for that scope
26713
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26714
+ * drain never offers), so a personal repository's rows are in none of them.
26715
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26716
+ * nothing.
27453
26717
  */
26718
+ partition(scopeKeys) {
26719
+ const row = getRow(
26720
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26721
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26722
+ );
26723
+ return {
26724
+ queued: row?.queued ?? 0,
26725
+ inProgress: row?.inProgress ?? 0,
26726
+ synced: row?.synced ?? 0,
26727
+ failed: row?.failed ?? 0,
26728
+ refused: row?.refused ?? 0,
26729
+ detached: row?.detached ?? 0,
26730
+ total: row?.total ?? 0
26731
+ };
26732
+ }
27454
26733
  /**
27455
26734
  * The same partition, one row per kind that a lane carries.
27456
26735
  *
@@ -27460,11 +26739,14 @@ var SqliteHistorySyncRepository = class {
27460
26739
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27461
26740
  * rows", never as "zero sent"; the two look identical in a bar and mean
27462
26741
  * different things.
26742
+ *
26743
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26744
+ * still sum to the scoped aggregate. An empty list returns no rows.
27463
26745
  */
27464
- partitionByKind() {
26746
+ partitionByKind(scopeKeys) {
27465
26747
  return allRows(
27466
- this.partitionByKindStmt,
27467
- {}
26748
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26749
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27468
26750
  ).map((row) => ({
27469
26751
  kind: row.kind,
27470
26752
  queued: row.queued ?? 0,
@@ -27476,22 +26758,25 @@ var SqliteHistorySyncRepository = class {
27476
26758
  total: row.total ?? 0
27477
26759
  }));
27478
26760
  }
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);
26761
+ /**
26762
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26763
+ * and skipped are totals.
26764
+ *
26765
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26766
+ * `capturesSkipped` included: a structural row is counted only when its own
26767
+ * key and its session root's key are among them, a capture when its own key
26768
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26769
+ * under the same keys and boundary. Omitted, this runs the machine
26770
+ * statements, unchanged; an empty list counts nothing.
26771
+ */
26772
+ counts(before, scopeKeys) {
26773
+ const row = getRow(
26774
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26775
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26776
+ );
26777
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26778
+ scopeKeys: scopeKeysParam(scopeKeys)
26779
+ });
27495
26780
  return {
27496
26781
  pending: row?.pending ?? 0,
27497
26782
  sent: row?.sent ?? 0,
@@ -27743,6 +27028,7 @@ function applyMigrations(db, file2, options = {}) {
27743
27028
  }
27744
27029
  ensureSyncedAtColumn(db, "audit_events");
27745
27030
  ensureScopeKeyColumn(db);
27031
+ ensureScopeOwedIndex(db);
27746
27032
  ensureScanLedgerTable(db);
27747
27033
  ensureHistorySyncTable(db);
27748
27034
  ensureBlockedDetectionsTable(db);
@@ -28183,14 +27469,48 @@ function ensureScopeKeyColumn(db) {
28183
27469
  function hasScopeKeyColumn(db) {
28184
27470
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28185
27471
  }
27472
+ 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";
27473
+ function ensureScopeOwedIndex(db) {
27474
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27475
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27476
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27477
+ if (!complete) return;
27478
+ db.exec(SCOPE_OWED_INDEX_DDL);
27479
+ }
28186
27480
  function ensureScanLedgerTable(db) {
28187
27481
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28188
27482
  path TEXT PRIMARY KEY,
28189
27483
  mtime TEXT NOT NULL,
28190
27484
  content_hash TEXT NOT NULL,
28191
27485
  ruleset_hash TEXT NOT NULL,
28192
- scanned_at INTEGER NOT NULL
27486
+ scanned_at INTEGER NOT NULL,
27487
+ scope_key TEXT,
27488
+ scope_root TEXT
28193
27489
  )`);
27490
+ ensureScanLedgerScopeKeyColumn(db);
27491
+ ensureScanLedgerScopeRootColumn(db);
27492
+ }
27493
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27494
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27495
+ function ensureScanLedgerScopeKeyColumn(db) {
27496
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27497
+ }
27498
+ function ensureScanLedgerScopeRootColumn(db) {
27499
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27500
+ }
27501
+ function ensureScanLedgerColumn(db, column, ddl) {
27502
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27503
+ if (hasScanLedgerColumn(db, column)) return;
27504
+ withTransaction(
27505
+ db,
27506
+ () => {
27507
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27508
+ },
27509
+ "IMMEDIATE"
27510
+ );
27511
+ }
27512
+ function hasScanLedgerColumn(db, column) {
27513
+ return columnNames(db, "scan_ledger").includes(column);
28194
27514
  }
28195
27515
  function ensureHistorySyncTable(db) {
28196
27516
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28241,6 +27561,106 @@ function ensureRuleProbeCacheTable(db) {
28241
27561
  )`);
28242
27562
  }
28243
27563
 
27564
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27565
+ import { createHash as createHash2 } from "crypto";
27566
+ import { readFileSync as readFileSync2 } from "fs";
27567
+ import { join as join4 } from "path";
27568
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27569
+ function modPolicySnapshotPath(dataDir2) {
27570
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27571
+ }
27572
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27573
+ const byRule = /* @__PURE__ */ new Map();
27574
+ const byCategory = /* @__PURE__ */ new Map();
27575
+ for (const policy of input2.policies) {
27576
+ if (!policy.enabled) continue;
27577
+ if ("ruleId" in policy.target) {
27578
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27579
+ } else if (!byCategory.has(policy.target.category)) {
27580
+ byCategory.set(policy.target.category, policy.action);
27581
+ }
27582
+ }
27583
+ const categoryActions = {};
27584
+ for (const category of DetectionCategory.options) {
27585
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27586
+ }
27587
+ return {
27588
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27589
+ generatedAt: generatedAt.toISOString(),
27590
+ // `examples` is documentation the mod never reads, and a custom pack's are
27591
+ // whatever its author pasted in, so they stay behind.
27592
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27593
+ ruleActions: Object.fromEntries(byRule),
27594
+ categoryActions,
27595
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27596
+ };
27597
+ }
27598
+ function assignedRuleActionPolicies(installed) {
27599
+ const out = [];
27600
+ for (const [ruleId, action] of installed.ruleActions) {
27601
+ if (installed.assignedRules.has(ruleId))
27602
+ out.push({ target: { ruleId }, action, enabled: true });
27603
+ }
27604
+ return out;
27605
+ }
27606
+ function withoutExamples(rule) {
27607
+ const copy = { ...rule };
27608
+ delete copy.examples;
27609
+ return copy;
27610
+ }
27611
+ function sameContent(a, b) {
27612
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27613
+ }
27614
+ function readModPolicySnapshot(dataDir2) {
27615
+ try {
27616
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27617
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27618
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27619
+ return parsed2.success ? parsed2.data : null;
27620
+ } catch {
27621
+ return null;
27622
+ }
27623
+ }
27624
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27625
+ const text = JSON.stringify(snapshot);
27626
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27627
+ const existing = readModPolicySnapshot(dataDir2);
27628
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27629
+ ensureDataDirSync(dataDir2);
27630
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27631
+ return true;
27632
+ }
27633
+ function regexProbeKey(matcher) {
27634
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27635
+ }
27636
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27637
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27638
+ return rules.filter((rule) => {
27639
+ if (rule.matcher.type !== "regex") return true;
27640
+ const key = regexProbeKey(rule.matcher);
27641
+ const verdict = sources.probeVerdict(key);
27642
+ if (verdict === "quarantined") return false;
27643
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27644
+ });
27645
+ }
27646
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27647
+ const policies = sources.readPolicies();
27648
+ const snapshot = sources.installedRuleset();
27649
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27650
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27651
+ return {
27652
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27653
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27654
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27655
+ };
27656
+ }
27657
+ function refreshModPolicySnapshot(dataDir2, sources) {
27658
+ try {
27659
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27660
+ } catch {
27661
+ }
27662
+ }
27663
+
28244
27664
  // ../../packages/persistence/src/internal/json.ts
28245
27665
  function safeJson(s, fallback) {
28246
27666
  if (s == null) return fallback;
@@ -28415,6 +27835,11 @@ var TIMELINE_COLUMNS = `
28415
27835
  json_extract(attributes, '$.targetId') AS target_id,
28416
27836
  json_extract(attributes, '$.internal') AS internal,
28417
27837
  json_extract(attributes, '$.flagged') AS flagged`;
27838
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27839
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27840
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27841
+ " + "
27842
+ );
28418
27843
  var LLM_USAGE_SELECT = `
28419
27844
  SELECT root_session_id AS sessionId,
28420
27845
  provider,
@@ -28426,9 +27851,10 @@ var LLM_USAGE_SELECT = `
28426
27851
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28427
27852
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28428
27853
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28429
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27854
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27855
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28430
27856
  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`;
27857
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28432
27858
  function usageLeaves(rows) {
28433
27859
  return rows.map((row) => {
28434
27860
  const attributes = {
@@ -28443,7 +27869,7 @@ function usageLeaves(rows) {
28443
27869
  if (row.provider !== null) attributes.provider = row.provider;
28444
27870
  if (row.model !== null) attributes.model = row.model;
28445
27871
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28446
- return { sessionId: row.sessionId, attributes };
27872
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28447
27873
  });
28448
27874
  }
28449
27875
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29777,9 +29203,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29777
29203
  AND conditions IS NULL
29778
29204
  AND ${ACTIVE_PREDICATE}`;
29779
29205
  var SqliteExceptionsRepository = class {
29780
- constructor(db, now = () => Date.now()) {
29206
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29781
29207
  this.db = db;
29782
29208
  this.now = now;
29209
+ this.onChange = onChange;
29783
29210
  this.consumeStmt = db.prepare(
29784
29211
  `UPDATE exceptions
29785
29212
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29798,6 +29225,7 @@ var SqliteExceptionsRepository = class {
29798
29225
  }
29799
29226
  db;
29800
29227
  now;
29228
+ onChange;
29801
29229
  consumeStmt;
29802
29230
  insertBlockedStmt;
29803
29231
  sweepBlockedStmt;
@@ -29813,7 +29241,9 @@ var SqliteExceptionsRepository = class {
29813
29241
  */
29814
29242
  create(input2) {
29815
29243
  try {
29816
- return Promise.resolve(this.createSync(input2));
29244
+ const created = this.createSync(input2);
29245
+ this.onChange();
29246
+ return Promise.resolve(created);
29817
29247
  } catch (err) {
29818
29248
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29819
29249
  }
@@ -29944,6 +29374,7 @@ var SqliteExceptionsRepository = class {
29944
29374
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29945
29375
  WHERE id = :id AND revoked_at IS NULL`
29946
29376
  ).run({ id, revokedBy, reason: reason ?? null, now });
29377
+ if (Number(result.changes) === 1) this.onChange();
29947
29378
  return Promise.resolve(Number(result.changes) === 1);
29948
29379
  }
29949
29380
  /**
@@ -29956,6 +29387,15 @@ var SqliteExceptionsRepository = class {
29956
29387
  const result = this.consumeStmt.run({ id, now });
29957
29388
  return Promise.resolve(Number(result.changes) === 1);
29958
29389
  }
29390
+ /** The rule ids with at least one active grant, under any key version. */
29391
+ activeRuleIds(now = this.now()) {
29392
+ return allRows(
29393
+ this.db.prepare(
29394
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29395
+ ),
29396
+ { now }
29397
+ ).map((row) => row.ruleId);
29398
+ }
29959
29399
  /**
29960
29400
  * The evaluation subset of every active grant under one fingerprint key
29961
29401
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31079,28 +30519,28 @@ var SqliteInspectionFindingsRepository = class {
31079
30519
  };
31080
30520
 
31081
30521
  // ../../packages/persistence/src/repositories/installed-packs.ts
31082
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30522
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31083
30523
 
31084
30524
  // ../../packages/persistence/src/policy-floor.ts
31085
- import { readFileSync as readFileSync5 } from "fs";
31086
- import { join as join6 } from "path";
30525
+ import { readFileSync as readFileSync6 } from "fs";
30526
+ import { join as join7 } from "path";
31087
30527
 
31088
30528
  // ../../packages/persistence/src/local-layout.ts
31089
30529
  import { renameSync as renameSync3 } from "fs";
31090
30530
  import { mkdir } from "fs/promises";
31091
30531
  import { homedir } from "os";
31092
- import { join as join4 } from "path";
30532
+ import { join as join5 } from "path";
31093
30533
  function defaultDataDir() {
31094
- return join4(homedir(), ".aka");
30534
+ return join5(homedir(), ".aka");
31095
30535
  }
31096
30536
  function settingsDir(base = defaultDataDir()) {
31097
- return join4(base, "settings");
30537
+ return join5(base, "settings");
31098
30538
  }
31099
30539
  function dataDir(base = defaultDataDir()) {
31100
- return join4(base, "data");
30540
+ return join5(base, "data");
31101
30541
  }
31102
30542
  function dbPath(base = defaultDataDir()) {
31103
- return join4(dataDir(base), "aka.db");
30543
+ return join5(dataDir(base), "aka.db");
31104
30544
  }
31105
30545
  async function ensureDataDir(dir = defaultDataDir()) {
31106
30546
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31117,8 +30557,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31117
30557
  for (const { name, dest } of moves) {
31118
30558
  try {
31119
30559
  ensureDataDirSync(dest);
31120
- const moved = join4(dest, name);
31121
- renameSync3(join4(base, name), moved);
30560
+ const moved = join5(dest, name);
30561
+ renameSync3(join5(base, name), moved);
31122
30562
  tightenFile(moved);
31123
30563
  } catch {
31124
30564
  }
@@ -31126,8 +30566,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31126
30566
  }
31127
30567
 
31128
30568
  // ../../packages/persistence/src/settings.ts
31129
- import { readFileSync as readFileSync4 } from "fs";
31130
- import { join as join5 } from "path";
30569
+ import { readFileSync as readFileSync5 } from "fs";
30570
+ import { join as join6 } from "path";
31131
30571
 
31132
30572
  // ../../packages/persistence/src/file-lock.ts
31133
30573
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31135,7 +30575,7 @@ import {
31135
30575
  closeSync,
31136
30576
  existsSync as existsSync2,
31137
30577
  openSync,
31138
- readFileSync as readFileSync2,
30578
+ readFileSync as readFileSync3,
31139
30579
  rmSync as rmSync5,
31140
30580
  statSync as statSync3,
31141
30581
  writeFileSync as writeFileSync2
@@ -31144,7 +30584,7 @@ import { hostname as hostname3 } from "os";
31144
30584
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31145
30585
 
31146
30586
  // ../../packages/persistence/src/managed-settings.ts
31147
- import { readFileSync as readFileSync3 } from "fs";
30587
+ import { readFileSync as readFileSync4 } from "fs";
31148
30588
  import { posix, win32 } from "path";
31149
30589
  function managedSettingsPaths(platform2 = process.platform) {
31150
30590
  if (platform2 === "darwin") {
@@ -31163,7 +30603,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31163
30603
  for (const path of paths) {
31164
30604
  let text;
31165
30605
  try {
31166
- text = readFileSync3(path, "utf8");
30606
+ text = readFileSync4(path, "utf8");
31167
30607
  } catch {
31168
30608
  continue;
31169
30609
  }
@@ -31217,7 +30657,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31217
30657
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31218
30658
  }
31219
30659
  function readUserSettings(base) {
31220
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30660
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31221
30661
  if (!record2) return defaultWorkspaceSettings();
31222
30662
  try {
31223
30663
  return WorkspaceSettings.parse(record2);
@@ -31228,7 +30668,7 @@ function readUserSettings(base) {
31228
30668
  function readJson(file2) {
31229
30669
  let text;
31230
30670
  try {
31231
- text = readFileSync4(file2, "utf8");
30671
+ text = readFileSync5(file2, "utf8");
31232
30672
  } catch {
31233
30673
  return null;
31234
30674
  }
@@ -31268,7 +30708,7 @@ var PolicyFloorError = class extends Error {
31268
30708
  };
31269
30709
  function readCachedPolicyBundle(base = defaultDataDir()) {
31270
30710
  try {
31271
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30711
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31272
30712
  const parsed2 = JSON.parse(raw);
31273
30713
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31274
30714
  return PolicyBundle.parse(parsed2.bundle);
@@ -31392,7 +30832,7 @@ function inventorySignature(packs2) {
31392
30832
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31393
30833
  }
31394
30834
  function hashRules(rulesJson) {
31395
- return createHash2("sha256").update(rulesJson).digest("hex");
30835
+ return createHash3("sha256").update(rulesJson).digest("hex");
31396
30836
  }
31397
30837
  function parseVersion(v) {
31398
30838
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31434,9 +30874,10 @@ var SqliteInstalledPacksRepository = class {
31434
30874
  * from `openLocalDatabase`, which is the single construction site that owns a
31435
30875
  * real `~/.aka`.
31436
30876
  */
31437
- constructor(db, baseDir) {
30877
+ constructor(db, baseDir, onChange = () => void 0) {
31438
30878
  this.db = db;
31439
30879
  this.baseDir = baseDir;
30880
+ this.onChange = onChange;
31440
30881
  this.insertMissingStmt = db.prepare(
31441
30882
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31442
30883
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31465,6 +30906,7 @@ var SqliteInstalledPacksRepository = class {
31465
30906
  }
31466
30907
  db;
31467
30908
  baseDir;
30909
+ onChange;
31468
30910
  insertMissingStmt;
31469
30911
  upsertAvailableStmt;
31470
30912
  signatureStmt;
@@ -31537,6 +30979,7 @@ var SqliteInstalledPacksRepository = class {
31537
30979
  },
31538
30980
  "IMMEDIATE"
31539
30981
  );
30982
+ this.onChange();
31540
30983
  } catch {
31541
30984
  }
31542
30985
  }
@@ -31611,6 +31054,7 @@ var SqliteInstalledPacksRepository = class {
31611
31054
  },
31612
31055
  "IMMEDIATE"
31613
31056
  );
31057
+ if (changed) this.onChange();
31614
31058
  return changed;
31615
31059
  }
31616
31060
  /**
@@ -31852,6 +31296,7 @@ var SqliteInstalledPacksRepository = class {
31852
31296
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31853
31297
  WHERE namespace = :namespace AND pack_id = :packId`
31854
31298
  ).run({ policyId, now: Date.now(), namespace, packId });
31299
+ if (Number(res.changes) > 0) this.onChange();
31855
31300
  return Number(res.changes) > 0;
31856
31301
  }
31857
31302
  /**
@@ -31876,6 +31321,7 @@ var SqliteInstalledPacksRepository = class {
31876
31321
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31877
31322
  WHERE namespace = :namespace AND pack_id = :packId`
31878
31323
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31324
+ if (Number(res.changes) > 0) this.onChange();
31879
31325
  return Number(res.changes) > 0;
31880
31326
  }
31881
31327
  // Fingerprint of the recorded available mirror — compared against the
@@ -32773,13 +32219,19 @@ var SqliteInventoryAssetsRepository = class {
32773
32219
  import { randomUUID as randomUUID6 } from "crypto";
32774
32220
  var SEED_BATCH_WINDOW_MS = 6e4;
32775
32221
  var SqlitePoliciesRepository = class {
32776
- constructor(db) {
32222
+ constructor(db, onChange = () => void 0) {
32777
32223
  this.db = db;
32224
+ this.onChange = onChange;
32778
32225
  }
32779
32226
  db;
32227
+ onChange;
32780
32228
  readPolicies() {
32229
+ return Promise.resolve(this.listPolicies());
32230
+ }
32231
+ /** The synchronous read behind {@link readPolicies}. */
32232
+ listPolicies() {
32781
32233
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32782
- const policies = mapRowsTolerant(rows, (row) => {
32234
+ return mapRowsTolerant(rows, (row) => {
32783
32235
  const target = JSON.parse(row.target);
32784
32236
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32785
32237
  return Policy.parse({
@@ -32791,7 +32243,6 @@ var SqlitePoliciesRepository = class {
32791
32243
  customKeywords
32792
32244
  });
32793
32245
  });
32794
- return Promise.resolve(policies);
32795
32246
  }
32796
32247
  // Seed one policy per bundled category at Monitor so the detection-type config
32797
32248
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32802,7 +32253,7 @@ var SqlitePoliciesRepository = class {
32802
32253
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32803
32254
  if (count > 0) {
32804
32255
  this.markEarlierChoices();
32805
- this.monitorUntouchedSeeds();
32256
+ if (this.monitorUntouchedSeeds()) this.onChange();
32806
32257
  return;
32807
32258
  }
32808
32259
  const stmt = this.db.prepare(
@@ -32819,6 +32270,7 @@ var SqlitePoliciesRepository = class {
32819
32270
  });
32820
32271
  }
32821
32272
  });
32273
+ this.onChange();
32822
32274
  }
32823
32275
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32824
32276
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32884,7 +32336,7 @@ var SqlitePoliciesRepository = class {
32884
32336
  ).filter(
32885
32337
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32886
32338
  );
32887
- if (untouched.length === 0) return;
32339
+ if (untouched.length === 0) return false;
32888
32340
  const stmt = this.db.prepare(
32889
32341
  `UPDATE policies SET action = 'log'
32890
32342
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32895,6 +32347,7 @@ var SqlitePoliciesRepository = class {
32895
32347
  stmt.run({ category: row.category, seeded: row.action });
32896
32348
  }
32897
32349
  });
32350
+ return true;
32898
32351
  }
32899
32352
  // Insert-or-update the single global per-category policy row, keyed on the
32900
32353
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32911,6 +32364,7 @@ var SqlitePoliciesRepository = class {
32911
32364
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32912
32365
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32913
32366
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32367
+ this.onChange();
32914
32368
  }
32915
32369
  // Caps every global per-category policy currently set to block/redact down
32916
32370
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32921,6 +32375,7 @@ var SqlitePoliciesRepository = class {
32921
32375
  WHERE scope='global' AND action IN ('block','redact')
32922
32376
  AND json_extract(target,'$.category') IS NOT NULL`
32923
32377
  ).run({ now: Date.now() });
32378
+ if (Number(info.changes) > 0) this.onChange();
32924
32379
  return Number(info.changes);
32925
32380
  }
32926
32381
  // Whether the category's row was ever written after it was created — by the
@@ -33240,31 +32695,45 @@ var SqliteScanLedgerRepository = class {
33240
32695
  constructor(db) {
33241
32696
  this.db = db;
33242
32697
  this.upsertStmt = db.prepare(
33243
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33244
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32698
+ `INSERT INTO scan_ledger
32699
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32700
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33245
32701
  ON CONFLICT (path) DO UPDATE SET
33246
32702
  mtime = excluded.mtime,
33247
32703
  content_hash = excluded.content_hash,
33248
32704
  ruleset_hash = excluded.ruleset_hash,
32705
+ scope_key = excluded.scope_key,
32706
+ scope_root = excluded.scope_root,
33249
32707
  scanned_at = excluded.scanned_at`
33250
32708
  );
33251
32709
  this.readStmt = db.prepare(
33252
- `SELECT path, mtime, content_hash AS contentHash
32710
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32711
+ scope_root AS scopeRoot
33253
32712
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33254
32713
  );
33255
32714
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32715
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33256
32716
  }
33257
32717
  db;
33258
32718
  upsertStmt;
33259
32719
  readStmt;
33260
32720
  pathsStmt;
32721
+ pathKeysStmt;
33261
32722
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33262
32723
  // older ruleset are simply absent, which reads as "never scanned".
33263
32724
  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 }]));
32725
+ const rows = allRows(this.readStmt, { rulesetHash });
32726
+ return new Map(
32727
+ rows.map((r) => [
32728
+ r.path,
32729
+ {
32730
+ mtime: r.mtime,
32731
+ contentHash: r.contentHash,
32732
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32733
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32734
+ }
32735
+ ])
32736
+ );
33268
32737
  }
33269
32738
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33270
32739
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33273,6 +32742,14 @@ var SqliteScanLedgerRepository = class {
33273
32742
  allPaths() {
33274
32743
  return allRows(this.pathsStmt).map((r) => r.path);
33275
32744
  }
32745
+ // Every ledgered path with the repository it was in when it was last read,
32746
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32747
+ // which repository a vanished file belonged to. `undefined` for a row with no
32748
+ // key, which is every row written before the column existed.
32749
+ pathKeys() {
32750
+ const rows = allRows(this.pathKeysStmt);
32751
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32752
+ }
33276
32753
  upsertEntries(entries) {
33277
32754
  if (entries.length === 0) return;
33278
32755
  const scannedAt = Date.now();
@@ -33283,6 +32760,8 @@ var SqliteScanLedgerRepository = class {
33283
32760
  mtime: entry.mtime,
33284
32761
  contentHash: entry.contentHash,
33285
32762
  rulesetHash: entry.rulesetHash,
32763
+ scopeKey: entry.scopeKey ?? null,
32764
+ scopeRoot: entry.scopeRoot ?? null,
33286
32765
  scannedAt
33287
32766
  });
33288
32767
  }
@@ -34370,6 +33849,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34370
33849
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34371
33850
  };
34372
33851
  }
33852
+ function withoutTrailingSlashes(path) {
33853
+ let end = path.length;
33854
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33855
+ return path.slice(0, end);
33856
+ }
34373
33857
  function toEndpointSummary(row) {
34374
33858
  return {
34375
33859
  id: row.id,
@@ -34657,7 +34141,7 @@ var SqliteSharesRepository = class {
34657
34141
  */
34658
34142
  reconcileCallSites(projectKey, reconcile) {
34659
34143
  if (reconcile.mode === "walk") {
34660
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
34144
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34661
34145
  this.db.prepare(
34662
34146
  `DELETE FROM share_call_site
34663
34147
  WHERE project_key = :key
@@ -35225,7 +34709,7 @@ function backupLegacyStore(db, file2) {
35225
34709
  discardStore(file2, backup);
35226
34710
  return backup;
35227
34711
  }
35228
- function openAndInitialize(file2, base, skipTags) {
34712
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35229
34713
  let db = openWithPragmas(file2);
35230
34714
  try {
35231
34715
  if (isForeignSqliteLineage(db)) {
@@ -35237,8 +34721,15 @@ function openAndInitialize(file2, base, skipTags) {
35237
34721
  }
35238
34722
  applyMigrations(db, file2, { skipTags });
35239
34723
  tightenPerms(file2);
35240
- const policies = new SqlitePoliciesRepository(db);
35241
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34724
+ const modPolicy = {};
34725
+ const onPolicyStateChange = () => {
34726
+ if (modPolicy.current !== void 0)
34727
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34728
+ };
34729
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34730
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34731
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34732
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35242
34733
  const repositories = {
35243
34734
  events: new SqliteEventsRepository(db),
35244
34735
  findings: new SqliteFindingsRepository(db),
@@ -35247,9 +34738,9 @@ function openAndInitialize(file2, base, skipTags) {
35247
34738
  scanLedger: new SqliteScanLedgerRepository(db),
35248
34739
  historySync: new SqliteHistorySyncRepository(db),
35249
34740
  secretVault: new SqliteSecretVaultRepository(db),
35250
- exceptions: new SqliteExceptionsRepository(db),
34741
+ exceptions,
35251
34742
  resolutions: new SqliteResolutionsRepository(db),
35252
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34743
+ ruleProbeCache,
35253
34744
  bodyRetention: new SqliteBodyRetentionRepository(db),
35254
34745
  security: new SqliteSecurityRepository(db),
35255
34746
  detections: new SqliteDetectionsRepository(db),
@@ -35267,6 +34758,13 @@ function openAndInitialize(file2, base, skipTags) {
35267
34758
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35268
34759
  configInventory: new SqliteConfigInventoryRepository(db)
35269
34760
  };
34761
+ modPolicy.current = {
34762
+ installedRuleset: () => installedPacks.installedRuleset(),
34763
+ readPolicies: () => policies.listPolicies(),
34764
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34765
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34766
+ bundledRegexMatchers: () => shippedRegexMatchers2
34767
+ };
35270
34768
  policies.seedDefaults();
35271
34769
  return { db, ...repositories };
35272
34770
  } catch (err) {
@@ -35278,7 +34776,7 @@ function openAndInitialize(file2, base, skipTags) {
35278
34776
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35279
34777
  function openLocalDatabase(dir, options = {}) {
35280
34778
  ensureDataDirSync(dir);
35281
- const file2 = join7(dir, DB_FILENAME);
34779
+ const file2 = join8(dir, DB_FILENAME);
35282
34780
  reapStalePartials(file2);
35283
34781
  const {
35284
34782
  db,
@@ -35314,7 +34812,8 @@ function openLocalDatabase(dir, options = {}) {
35314
34812
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35315
34813
  // settings/ and data/, and the pack-policy floor needs both halves.
35316
34814
  dirname2(dir),
35317
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34815
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34816
+ options.shippedRegexMatchers ?? []
35318
34817
  );
35319
34818
  function captureRowId(event) {
35320
34819
  return captureId(
@@ -35579,7 +35078,7 @@ function openLocalDatabase(dir, options = {}) {
35579
35078
  }
35580
35079
 
35581
35080
  // ../../packages/persistence/src/egress-wire.ts
35582
- import { createHash as createHash3 } from "crypto";
35081
+ import { createHash as createHash4 } from "crypto";
35583
35082
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35584
35083
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35585
35084
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35611,7 +35110,7 @@ function canonicalGitUrl(url2) {
35611
35110
  }
35612
35111
  function hashProjectKey(projectKey) {
35613
35112
  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");
35113
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35615
35114
  }
35616
35115
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35617
35116
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35676,24 +35175,23 @@ function toEgressIngestRequest(input2) {
35676
35175
  }
35677
35176
 
35678
35177
  // ../../packages/persistence/src/finding-key.ts
35679
- import { createHash as createHash4 } from "crypto";
35178
+ import { createHash as createHash5 } from "crypto";
35680
35179
  function normalizeFilePath(filePath) {
35681
35180
  return filePath.replaceAll("\\", "/");
35682
35181
  }
35683
35182
  function computeFindingKey(input2) {
35684
35183
  const normalizedPath = normalizeFilePath(input2.filePath);
35685
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35184
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35686
35185
  }
35687
35186
 
35688
35187
  // ../../packages/persistence/src/fingerprint.ts
35689
35188
  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";
35189
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
35190
+ import { join as join9 } from "path";
35693
35191
  var EXCEPTION_KEY_FILENAME = "exception.key";
35694
35192
  var KEY_MATERIAL_BYTES = 32;
35695
35193
  function keyFilePath(dataDir2) {
35696
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
35194
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35697
35195
  }
35698
35196
  function parseKeyFile(raw) {
35699
35197
  const parsed2 = JSON.parse(raw);
@@ -35720,6 +35218,12 @@ var KEY_VERSION_COLUMNS = {
35720
35218
  };
35721
35219
  var SQLITE_ERROR2 = 1;
35722
35220
  var FLOOR_BUSY_TIMEOUT_MS = 250;
35221
+ function openReadOnly(file2) {
35222
+ const host = process;
35223
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
35224
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
35225
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
35226
+ }
35723
35227
  var FloorUnreadableError = class extends Error {
35724
35228
  code = "floor-unreadable";
35725
35229
  constructor(cause) {
@@ -35731,11 +35235,11 @@ var FloorUnreadableError = class extends Error {
35731
35235
  }
35732
35236
  };
35733
35237
  function storedKeyVersionFloor(dataDir2) {
35734
- const file2 = join8(dataDir2, DB_FILENAME);
35238
+ const file2 = join9(dataDir2, DB_FILENAME);
35735
35239
  if (!existsSync3(file2)) return 0;
35736
35240
  let db;
35737
35241
  try {
35738
- db = new DatabaseSync2(file2, { readOnly: true });
35242
+ db = openReadOnly(file2);
35739
35243
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35740
35244
  let floor = 0;
35741
35245
  for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35786,7 +35290,7 @@ function occupantMessage(file2, kind) {
35786
35290
  function readFingerprintKey(dataDir2) {
35787
35291
  let raw;
35788
35292
  try {
35789
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
35293
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35790
35294
  } catch (err) {
35791
35295
  if (err.code === "ENOENT") return null;
35792
35296
  throw err instanceof Error ? err : new Error(String(err));
@@ -35812,8 +35316,8 @@ function exactFingerprintValue(key, raw) {
35812
35316
  }
35813
35317
 
35814
35318
  // ../../packages/persistence/src/forward-health.ts
35815
- import { readFileSync as readFileSync7 } from "fs";
35816
- import { join as join9 } from "path";
35319
+ import { readFileSync as readFileSync8 } from "fs";
35320
+ import { join as join10 } from "path";
35817
35321
  var BREAKER_COOLDOWN_MS = 3e4;
35818
35322
  function parseForwardHealth(raw, nowMs) {
35819
35323
  try {
@@ -35837,20 +35341,21 @@ function isForwardPaused(health, nowMs) {
35837
35341
 
35838
35342
  // ../../packages/persistence/src/history-backfill.ts
35839
35343
  import { existsSync as existsSync4 } from "fs";
35840
- import { join as join10 } from "path";
35344
+ import { join as join11 } from "path";
35841
35345
 
35842
35346
  // ../../packages/persistence/src/history-preview.ts
35843
35347
  import { existsSync as existsSync5 } from "fs";
35844
- import { join as join11 } from "path";
35845
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
35348
+ import { join as join12 } from "path";
35349
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35846
35350
 
35847
35351
  // ../../packages/persistence/src/history-sync-state.ts
35848
- import { readFileSync as readFileSync8 } from "fs";
35849
- import { join as join12 } from "path";
35352
+ import { readFileSync as readFileSync9 } from "fs";
35353
+ import { join as join13 } from "path";
35354
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35850
35355
 
35851
35356
  // ../../packages/persistence/src/store-symlinks.ts
35852
35357
  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";
35358
+ import { dirname as dirname3, join as join14, resolve } from "path";
35854
35359
 
35855
35360
  // ../../packages/persistence/src/vault/crypto.ts
35856
35361
  import {
@@ -35864,19 +35369,19 @@ import {
35864
35369
  // ../../packages/persistence/src/vault/key-provider.ts
35865
35370
  import { execFileSync } from "child_process";
35866
35371
  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";
35372
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35373
+ import { join as join15 } from "path";
35869
35374
 
35870
35375
  // ../../packages/persistence/src/vault/vault.ts
35871
35376
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35872
35377
 
35873
35378
  // ../../packages/persistence/src/warn-era-cap.ts
35874
35379
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35875
- import { join as join15 } from "path";
35380
+ import { join as join16 } from "path";
35876
35381
  var MARKER = "warn-era-capped";
35877
35382
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35878
35383
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35879
- const marker = join15(dataDir2, MARKER);
35384
+ const marker = join16(dataDir2, MARKER);
35880
35385
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35881
35386
  const capped = db.policies.capCategoryActions();
35882
35387
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35936,7 +35441,7 @@ function resolveProvider() {
35936
35441
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
35937
35442
  try {
35938
35443
  ensureLayoutDirSync(base);
35939
- const settingsFile = join16(settingsDir(base), "settings.json");
35444
+ const settingsFile = join17(settingsDir(base), "settings.json");
35940
35445
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
35941
35446
  } catch {
35942
35447
  }
@@ -35959,11 +35464,6 @@ function resolveProviderSafe(resolveProviderFn) {
35959
35464
  }
35960
35465
  }
35961
35466
 
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
35467
  // ../../packages/detections/src/egress/registry.ts
35968
35468
  var EXTRACTOR_VERSION = "3";
35969
35469
  var PROVIDER_REGISTRY = [
@@ -37074,17 +36574,18 @@ function ruleEvidence(rule) {
37074
36574
 
37075
36575
  // ../../packages/detections/src/mask.ts
37076
36576
  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);
36577
+ const visible = stripInvisiblePadding(raw);
36578
+ if (visible.length <= 5) return "***";
36579
+ const atIndex = visible.indexOf("@");
36580
+ if (atIndex > 0 && atIndex < visible.length - 1) {
36581
+ const domain2 = visible.slice(atIndex + 1);
37081
36582
  if (domain2.includes(".")) {
37082
- const local = raw.slice(0, atIndex);
36583
+ const local = visible.slice(0, atIndex);
37083
36584
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
37084
36585
  return `${maskedLocal}@${domain2}`;
37085
36586
  }
37086
36587
  }
37087
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
36588
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
37088
36589
  }
37089
36590
 
37090
36591
  // ../../packages/detections/src/pointer-shield.ts
@@ -37346,7 +36847,12 @@ var MIN_RAW_LEN = 4;
37346
36847
  var RAW_RUN_LEN = 8;
37347
36848
  function carriesRawRun(text, rawValues) {
37348
36849
  let windows = null;
37349
- for (const raw of new Set(rawValues)) {
36850
+ const values = /* @__PURE__ */ new Set();
36851
+ for (const raw of rawValues) {
36852
+ values.add(raw);
36853
+ values.add(stripInvisiblePadding(raw));
36854
+ }
36855
+ for (const raw of values) {
37350
36856
  if (raw.length < MIN_RAW_LEN) continue;
37351
36857
  if (raw.length < RAW_RUN_LEN) {
37352
36858
  if (text.includes(raw)) return true;
@@ -37393,11 +36899,16 @@ function maskContextSlice(slice, sliceStart, hits) {
37393
36899
  return masked;
37394
36900
  }
37395
36901
  function safeMaskedMatch(rawMatch) {
37396
- const masked = maskMatch(rawMatch);
37397
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37398
- return "***";
36902
+ const visible = stripInvisiblePadding(rawMatch);
36903
+ const masked = maskMatch(visible);
36904
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
36905
+ if (!reveals(masked)) return masked;
36906
+ const atIndex = masked.indexOf("@");
36907
+ if (atIndex > 0 && atIndex < masked.length - 1) {
36908
+ const emailFallback = `*${masked.slice(atIndex)}`;
36909
+ if (!reveals(emailFallback)) return emailFallback;
37399
36910
  }
37400
- return masked;
36911
+ return "***";
37401
36912
  }
37402
36913
  function assertRawFree(text, rawValues) {
37403
36914
  if (carriesRawRun(text, rawValues)) {
@@ -39839,6 +39350,11 @@ function bundledDetections() {
39839
39350
  }));
39840
39351
  return cachedDetections;
39841
39352
  }
39353
+ function shippedRegexMatchers() {
39354
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
39355
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
39356
+ );
39357
+ }
39842
39358
 
39843
39359
  // ../../packages/plugin-sdk/src/mask.ts
39844
39360
  var packsReady = false;
@@ -39894,8 +39410,8 @@ function scanText(text, ruleVersions, options = {}) {
39894
39410
  }
39895
39411
 
39896
39412
  // ../../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";
39413
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
39414
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
39899
39415
  function resolveRepoIdentity(cwd) {
39900
39416
  try {
39901
39417
  const location = locateRepo(cwd);
@@ -39914,8 +39430,9 @@ function resolveRepoIdentity(cwd) {
39914
39430
  var ATTRIBUTION_MEMO_LIMIT = 64;
39915
39431
  var attributionMemo = /* @__PURE__ */ new Map();
39916
39432
  var NO_ATTRIBUTION = Object.freeze({});
39917
- function resolveRepoAttribution(cwd) {
39433
+ function resolveRepoAttribution(cwd, options) {
39918
39434
  try {
39435
+ if (options?.cache === false) return attributeRepo(cwd);
39919
39436
  const remembered = attributionMemo.get(cwd);
39920
39437
  if (remembered !== void 0) return remembered;
39921
39438
  const attribution = attributeRepo(cwd);
@@ -39939,36 +39456,36 @@ function attributeRepo(cwd) {
39939
39456
  function findGitRoot(start) {
39940
39457
  let dir = start;
39941
39458
  for (; ; ) {
39942
- if (existsSync9(join17(dir, ".git"))) return dir;
39459
+ if (existsSync9(join18(dir, ".git"))) return dir;
39943
39460
  const parent = dirname4(dir);
39944
39461
  if (parent === dir) return void 0;
39945
39462
  dir = parent;
39946
39463
  }
39947
39464
  }
39948
39465
  function resolveGitContext(root) {
39949
- const dotGit = join17(root, ".git");
39466
+ const dotGit = join18(root, ".git");
39950
39467
  try {
39951
39468
  if (statSync6(dotGit).isDirectory()) {
39952
- return { configPath: join17(dotGit, "config"), headRoot: root };
39469
+ return { configPath: join18(dotGit, "config"), headRoot: root };
39953
39470
  }
39954
39471
  } catch {
39955
39472
  return void 0;
39956
39473
  }
39957
39474
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
39958
39475
  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 };
39476
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
39477
+ if (existsSync9(join18(gitdir, "config"))) {
39478
+ return { configPath: join18(gitdir, "config"), headRoot: root };
39962
39479
  }
39963
- const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
39480
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
39964
39481
  if (!commonRaw) return void 0;
39965
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
39482
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
39966
39483
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
39967
- return { configPath: join17(commonGitDir, "config"), headRoot };
39484
+ return { configPath: join18(commonGitDir, "config"), headRoot };
39968
39485
  }
39969
39486
  function safeRead(path) {
39970
39487
  try {
39971
- return readFileSync10(path, "utf8");
39488
+ return readFileSync11(path, "utf8");
39972
39489
  } catch {
39973
39490
  return void 0;
39974
39491
  }
@@ -40015,9 +39532,9 @@ function slugFromUrl(url2) {
40015
39532
  }
40016
39533
 
40017
39534
  // ../../packages/plugin-sdk/src/events.ts
40018
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39535
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
40019
39536
  function contentHashOf(text) {
40020
- return createHash5("sha256").update(text).digest("hex");
39537
+ return createHash6("sha256").update(text).digest("hex");
40021
39538
  }
40022
39539
  function buildIngestEvent(input2) {
40023
39540
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -40530,60 +40047,6 @@ function createGuardedScanner(partition, gateway, opts) {
40530
40047
  };
40531
40048
  }
40532
40049
 
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
40050
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
40588
40051
  import { arch, hostname as hostname4, platform, release } from "os";
40589
40052
  function resolveInventoryContext(input2) {
@@ -40613,14 +40076,6 @@ function resolveInventoryContext(input2) {
40613
40076
  return ctx;
40614
40077
  }
40615
40078
 
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
40079
  // ../../packages/plugin-sdk/src/policy-resolver.ts
40625
40080
  import { randomUUID as randomUUID14 } from "crypto";
40626
40081
  function createPolicyResolver(bundle) {
@@ -40665,36 +40120,6 @@ function assignedRulePolicies(installed) {
40665
40120
  return out;
40666
40121
  }
40667
40122
 
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
40123
  // ../../packages/plugin-sdk/src/provider-codex.ts
40699
40124
  function codexProviderFromModelId(modelId) {
40700
40125
  const id = modelId.trim();
@@ -40991,12 +40416,11 @@ function createPluginRuntime(gateway, settings, opts) {
40991
40416
  async function processText(text, context, opts2 = {}) {
40992
40417
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
40993
40418
  }
40994
- async function capture(input2, opts2 = {}) {
40419
+ async function evaluateCapture(input2, opts2) {
40995
40420
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
40996
- const filePath = input2.metadata?.filePath;
40997
40421
  const { decision, excepted, exceptionIds } = await evaluate(
40998
40422
  input2.text,
40999
- { filePath, eventKind: input2.kind },
40423
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
41000
40424
  {
41001
40425
  sourceTool: input2.sourceTool,
41002
40426
  metadata: input2.metadata,
@@ -41004,7 +40428,11 @@ function createPluginRuntime(gateway, settings, opts) {
41004
40428
  },
41005
40429
  opts2.rewritable
41006
40430
  );
41007
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
40431
+ return { decision, excepted, exceptionIds, timingStartedAt };
40432
+ }
40433
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
40434
+ const filePath = input2.metadata?.filePath;
40435
+ if (opts2.persist === "with-findings" && decision.findings.length === 0) return;
41008
40436
  try {
41009
40437
  const contentHash = contentHashOf(input2.text);
41010
40438
  const maskedFindings = decision.findings.filter(
@@ -41047,6 +40475,8 @@ function createPluginRuntime(gateway, settings, opts) {
41047
40475
  // exceptions/blocked_detections when a key is available;
41048
40476
  // falls back to the masked match so at-rest findings still get
41049
40477
  // a stable (if weaker) identity on a workspace with no dataDir.
40478
+ // Both ignore the same invisible padding, so a clean and a
40479
+ // padded occurrence of one secret key alike on either path.
41050
40480
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
41051
40481
  }) : void 0;
41052
40482
  return {
@@ -41074,7 +40504,37 @@ function createPluginRuntime(gateway, settings, opts) {
41074
40504
  }
41075
40505
  } catch {
41076
40506
  }
41077
- return decision;
40507
+ }
40508
+ async function enforcedIn(text, context) {
40509
+ try {
40510
+ await ensureInitialized();
40511
+ if (!scanner) return [];
40512
+ const shielded = shieldPointers(text);
40513
+ const matched = await scanner.scan(shielded.text, context);
40514
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
40515
+ const action = resolveAction(finding.ruleId, finding.category);
40516
+ return action === "block" || action === "redact";
40517
+ });
40518
+ } catch {
40519
+ return [];
40520
+ }
40521
+ }
40522
+ async function capture(input2, opts2 = {}) {
40523
+ const evaluated = await evaluateCapture(input2, opts2);
40524
+ await persistCapture(input2, opts2, evaluated);
40525
+ return evaluated.decision;
40526
+ }
40527
+ async function captureDeferred(input2, opts2 = {}) {
40528
+ const evaluated = await evaluateCapture(input2, opts2);
40529
+ let recorded = false;
40530
+ return {
40531
+ result: evaluated.decision,
40532
+ record: async () => {
40533
+ if (recorded) return;
40534
+ recorded = true;
40535
+ await persistCapture(input2, opts2, evaluated);
40536
+ }
40537
+ };
41078
40538
  }
41079
40539
  async function rulesetFingerprint() {
41080
40540
  try {
@@ -41095,12 +40555,20 @@ function createPluginRuntime(gateway, settings, opts) {
41095
40555
  }
41096
40556
  await gateway.close();
41097
40557
  }
41098
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
40558
+ return {
40559
+ processText,
40560
+ capture,
40561
+ captureDeferred,
40562
+ enforcedIn,
40563
+ rulesetFingerprint,
40564
+ scanIsolationDegraded,
40565
+ close
40566
+ };
41099
40567
  }
41100
40568
 
41101
40569
  // ../../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";
40570
+ import { existsSync as existsSync11 } from "fs";
40571
+ import { dirname as dirname5, isAbsolute as isAbsolute2, join as join19, normalize } from "path";
41104
40572
  function scopeKeyMemo() {
41105
40573
  const memo2 = /* @__PURE__ */ new Map();
41106
40574
  return (cwd) => {
@@ -41117,8 +40585,8 @@ function sessionRootScopeKey(cwd) {
41117
40585
  function toolCallScopeKey(tc, scopeKeyOf2) {
41118
40586
  if (tc.keyless === true) return void 0;
41119
40587
  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);
40588
+ const resolved = (path) => isAbsolute2(path) ? normalize(path) : join19(tc.cwd ?? "", path);
40589
+ const walkStart = (path) => isAbsolute2(path) && existsSync11(join19(path, ".git")) ? path : dirname5(path);
41122
40590
  const locations = [
41123
40591
  ...(tc.filePaths ?? []).map((path) => walkStart(resolved(path))),
41124
40592
  ...tc.searchRoot === void 0 ? [] : [resolved(tc.searchRoot)]
@@ -41132,16 +40600,9 @@ function toolCallScopeKey(tc, scopeKeyOf2) {
41132
40600
  return agreed;
41133
40601
  }
41134
40602
 
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
40603
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
41143
- import { writeFileSync as writeFileSync8 } from "fs";
41144
- import { join as join27 } from "path";
40604
+ import { writeFileSync as writeFileSync5 } from "fs";
40605
+ import { join as join20 } from "path";
41145
40606
 
41146
40607
  // ../../packages/setup-wizard/src/triage/merge.ts
41147
40608
  var RANK = Object.fromEntries(
@@ -41149,9 +40610,9 @@ var RANK = Object.fromEntries(
41149
40610
  );
41150
40611
 
41151
40612
  // ../../packages/setup-wizard/src/triage/plan-file.ts
41152
- import { mkdtempSync, readFileSync as readFileSync17, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
40613
+ import { mkdtempSync, readFileSync as readFileSync12, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "fs";
41153
40614
  import { tmpdir } from "os";
41154
- import { basename as basename6, dirname as dirname7, join as join28 } from "path";
40615
+ import { basename as basename3, dirname as dirname6, join as join21 } from "path";
41155
40616
  var SuppressionEntrySchema = external_exports.object({
41156
40617
  ruleId: external_exports.string(),
41157
40618
  category: DetectionCategory,
@@ -41571,11 +41032,11 @@ function withTimeout(promise2, ms) {
41571
41032
  }
41572
41033
 
41573
41034
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
41574
- import { readFileSync as readFileSync18 } from "fs";
41575
- import { join as join29 } from "path";
41035
+ import { readFileSync as readFileSync13 } from "fs";
41036
+ import { join as join22 } from "path";
41576
41037
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
41577
41038
  function forwardDropsPath(dataDir2) {
41578
- return join29(dataDir2, FORWARD_DROPS_FILENAME);
41039
+ return join22(dataDir2, FORWARD_DROPS_FILENAME);
41579
41040
  }
41580
41041
  function recordForwardDrops(dataDir2, count, nowMs) {
41581
41042
  if (count <= 0) return;
@@ -41593,7 +41054,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
41593
41054
  }
41594
41055
  function readForwardDrops(dataDir2) {
41595
41056
  try {
41596
- const parsed2 = JSON.parse(readFileSync18(forwardDropsPath(dataDir2), "utf8"));
41057
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
41597
41058
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
41598
41059
  const record2 = parsed2;
41599
41060
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -41612,7 +41073,7 @@ function readForwardDrops(dataDir2) {
41612
41073
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
41613
41074
  import { randomUUID as randomUUID16 } from "crypto";
41614
41075
  import { readFile, rename, writeFile } from "fs/promises";
41615
- import { join as join30 } from "path";
41076
+ import { join as join23 } from "path";
41616
41077
  function isInvalidRequest(err) {
41617
41078
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
41618
41079
  }
@@ -41631,7 +41092,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
41631
41092
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
41632
41093
  function createForwardPolicy(deps) {
41633
41094
  const now = deps.now ?? (() => Date.now());
41634
- const file2 = join30(deps.dir, STATE_FILENAME);
41095
+ const file2 = join23(deps.dir, STATE_FILENAME);
41635
41096
  let state = null;
41636
41097
  let loading = null;
41637
41098
  async function readState() {
@@ -41797,6 +41258,9 @@ var AttachedDataGateway = class {
41797
41258
  *
41798
41259
  * Machine mode answers before any key is read, so a machine attachment pays
41799
41260
  * nothing for scoping and forwards exactly what it always has.
41261
+ *
41262
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
41263
+ * forwarding key for key.
41800
41264
  */
41801
41265
  verdictFor(keyOf) {
41802
41266
  try {
@@ -41813,24 +41277,27 @@ var AttachedDataGateway = class {
41813
41277
  * the key its row holds in the local store, recorded per root (see
41814
41278
  * `rootVerdict`), not the key on the root event just handed in: roots are
41815
41279
  * 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.
41280
+ * session (the session-start hook, then a reconcile pass) the second leaves the
41281
+ * stored row as it was. That stored row, not this event, is what a history
41282
+ * drain pass would decide, if the root started before the attach; the drain
41283
+ * never offers one that started after it (`started_at < backlogBefore`).
41284
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
41285
+ * its own. The event's attributes (cwd, project, repo) describe where it was
41286
+ * recorded from, so a root event keyed to a personal directory is never sent
41287
+ * under an enrolled stored root, though the enrolled leaves still forward under
41288
+ * it: the instance that wrote the stored root is expected to have forwarded it.
41289
+ * If it did not (the root was written while standalone or under another
41290
+ * attachment, or its forward failed), the plane refuses those leaves. A root
41291
+ * that started before the attach is shipped, ahead of its leaves, by the
41292
+ * history drain; one that started after it is never offered by the drain. Any
41293
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
41294
+ * only when its own key is in scope AND this instance recorded an in-scope
41295
+ * verdict for that root. The audit-event route has real foreign keys on both
41296
+ * columns and stubs no missing root, so a leaf sent after its root was kept
41297
+ * local is refused there, and a refused forward counts toward the breaker that
41298
+ * guards every other one. A root this instance never recorded is therefore
41299
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
41300
+ * reference at all has nothing to orphan, and is decided by its own key.
41834
41301
  *
41835
41302
  * What this costs is stated rather than discovered. A session whose stored
41836
41303
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -41901,6 +41368,87 @@ var AttachedDataGateway = class {
41901
41368
  return [];
41902
41369
  }
41903
41370
  }
41371
+ /**
41372
+ * The verdict for the repositories nested in a scanned project, answered
41373
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
41374
+ *
41375
+ * A walk descends into a nested clone or submodule and folds its files into
41376
+ * the project it is walking, so one register can carry several
41377
+ * repositories' call sites under one project key. Each of them must be in
41378
+ * scope for it to forward. One key out of scope, or a nested repository with
41379
+ * no remote (an `undefined` key), keeps the whole register local.
41380
+ *
41381
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
41382
+ * what is nested in it, and every scan passes the list, empty when nothing
41383
+ * is nested. A register nobody vouched for is not one a scoped attachment
41384
+ * may send.
41385
+ *
41386
+ * Machine mode answers before reading the context, so a machine attachment
41387
+ * forwards exactly what it always has.
41388
+ */
41389
+ nestedVerdict(context) {
41390
+ try {
41391
+ if (this.deps.attachment.mode === "machine") return "forward";
41392
+ const keys = context?.nestedScopeKeys;
41393
+ if (keys === void 0) return "local";
41394
+ for (const key of keys) {
41395
+ if (this.verdictFor(() => key) === "local") return "local";
41396
+ }
41397
+ return "forward";
41398
+ } catch {
41399
+ return "local";
41400
+ }
41401
+ }
41402
+ /**
41403
+ * The register a scoped attachment sends, once the project and the repositories
41404
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
41405
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
41406
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
41407
+ *
41408
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
41409
+ * and the ledger holds every file the scanner ever read under the root, nested
41410
+ * clones' included. So a clone that was removed, or one an ignore file now
41411
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
41412
+ * paths come back as deleted. The scan names the repository of each deleted
41413
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
41414
+ * and each is held to the same verdict as any other key. A path whose key is
41415
+ * absent, or out of scope, is not sent.
41416
+ *
41417
+ * The list is asked for here, and only here: it is an async read of the scan
41418
+ * ledger that the scan makes on being called, so a machine attachment, which
41419
+ * returns before this, and a register already kept local never cause it.
41420
+ *
41421
+ * Anything the scan did not vouch for sends no deleted path, and the register
41422
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
41423
+ * list whose length is not the register's. Deleting is the only thing a dropped
41424
+ * path could have done on the server, so the cost of a refusal is a stored row
41425
+ * that stays, never a path that leaves.
41426
+ *
41427
+ * Machine mode returns `input` itself, the same object and unread, so a machine
41428
+ * attachment's request is exactly what it was. A register that lists no deleted
41429
+ * path, or that is not a ledger register, has nothing to cut and is returned
41430
+ * as it came, with the list unread.
41431
+ */
41432
+ async registerForWire(input2, context) {
41433
+ try {
41434
+ if (this.deps.attachment.mode === "machine") return input2;
41435
+ const { reconcile } = input2;
41436
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
41437
+ const deleted = reconcile.deletedFiles;
41438
+ let kept = [];
41439
+ try {
41440
+ const keys = await context?.deletedFileKeys?.();
41441
+ if (keys?.length === deleted.length) {
41442
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
41443
+ }
41444
+ } catch {
41445
+ kept = [];
41446
+ }
41447
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
41448
+ } catch {
41449
+ return void 0;
41450
+ }
41451
+ }
41904
41452
  /**
41905
41453
  * The event `recordCapture` sends for a capture the verdict let through, or
41906
41454
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -42226,12 +41774,24 @@ var AttachedDataGateway = class {
42226
41774
  * payload onto the wire-boundary-safe shape (no snippet, hashed
42227
41775
  * projectKey), and its result is discarded: `forward.run` never throws or
42228
41776
  * rejects, so there is nothing here to act on.
41777
+ *
41778
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
41779
+ * not say: the key of every repository nested below the scan root, whose
41780
+ * files the walk folded into this register. On a scoped attachment the
41781
+ * register is forwarded only when the project's own key AND every one of
41782
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
41783
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
41784
+ * `registerForWire`). Machine mode never reads either, and the local write
41785
+ * never receives the context and gets the register whole.
42229
41786
  */
42230
- async recordProjectEgress(input2) {
41787
+ async recordProjectEgress(input2, context) {
42231
41788
  const summary = await this.deps.local.recordProjectEgress(input2);
42232
41789
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
41790
+ if (this.nestedVerdict(context) === "local") return summary;
41791
+ const register = await this.registerForWire(input2, context);
41792
+ if (register === void 0) return summary;
42233
41793
  await this.deps.forward.run(
42234
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
41794
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
42235
41795
  );
42236
41796
  return summary;
42237
41797
  }
@@ -42285,6 +41845,11 @@ var AttachedDataGateway = class {
42285
41845
  async scanLedgerPaths() {
42286
41846
  return this.deps.local.scanLedgerPaths();
42287
41847
  }
41848
+ // Delegated, like the path list. An inner gateway that cannot say answers an
41849
+ // empty map, which gives every deleted path no key.
41850
+ async scanLedgerPathKeys() {
41851
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
41852
+ }
42288
41853
  async recordScanned(entries) {
42289
41854
  return this.deps.local.recordScanned(entries);
42290
41855
  }
@@ -42351,6 +41916,12 @@ var AttachedDataGateway = class {
42351
41916
  // and the spread above would otherwise drop the field silently — which is
42352
41917
  // exactly what it did, leaving the whole control inert on every device
42353
41918
  // while every test around it stayed green.
41919
+ //
41920
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
41921
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
41922
+ // reads this bundle once to build detection, so the detections it carries
41923
+ // apply to every event on the machine. Where a prohibition applies is
41924
+ // answered per event by `governanceAppliesTo` below.
42354
41925
  prohibitedModels: cached2.prohibitedModels,
42355
41926
  // NAMED for the same reason as the line above, and it is the same defect
42356
41927
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -42410,6 +41981,30 @@ var AttachedDataGateway = class {
42410
41981
  };
42411
41982
  }
42412
41983
  // ---------------------------------------------------------------------
41984
+ // GovernanceScope — where the organization's model policy applies
41985
+ // ---------------------------------------------------------------------
41986
+ /**
41987
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
41988
+ * the question a model-guard site asks once it has decided to refuse.
41989
+ *
41990
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
41991
+ * with the same key would be forwarded. A machine-wide attachment governs
41992
+ * every event, keyless included, exactly as before. A scoped one governs an
41993
+ * event only when its key names an enrolled repository. An event in a
41994
+ * personal repository, in no repository, with an empty key, or met by a fault
41995
+ * is not governed.
41996
+ *
41997
+ * The event's OWN key, never its session root's. The root rule in
41998
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
41999
+ * this decides whether a refusal applies, which is a question about where the
42000
+ * event happened.
42001
+ *
42002
+ * Answered from memory: no store read, no bundle read, nothing sent.
42003
+ */
42004
+ governanceAppliesTo(scopeKey) {
42005
+ return this.verdictFor(() => scopeKey) === "forward";
42006
+ }
42007
+ // ---------------------------------------------------------------------
42413
42008
  // LocalStoreMaintenance — by delegation (D3).
42414
42009
  //
42415
42010
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -42518,7 +42113,7 @@ function toWireInspection(insp) {
42518
42113
  }
42519
42114
 
42520
42115
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42521
- import { createHash as createHash6 } from "crypto";
42116
+ import { createHash as createHash7 } from "crypto";
42522
42117
  import { hostname as hostname5 } from "os";
42523
42118
 
42524
42119
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
@@ -42537,17 +42132,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
42537
42132
 
42538
42133
  // ../../packages/plugin-runtime/src/attached/install-record.ts
42539
42134
  import { readFile as readFile2, stat } from "fs/promises";
42540
- import { basename as basename7, dirname as dirname8, join as join31, resolve as resolve2 } from "path";
42135
+ import { basename as basename4, dirname as dirname7, join as join24, resolve as resolve2 } from "path";
42541
42136
  async function readInstalledVersion(installRoot) {
42542
42137
  try {
42543
42138
  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)}`;
42139
+ const pluginDir = dirname7(versionDir);
42140
+ const marketplaceDir = dirname7(pluginDir);
42141
+ const cacheDir = dirname7(marketplaceDir);
42142
+ if (basename4(cacheDir) !== "cache") return null;
42143
+ const key = `${basename4(pluginDir)}@${basename4(marketplaceDir)}`;
42549
42144
  const record2 = JSON.parse(
42550
- await readFile2(join31(dirname8(cacheDir), "installed_plugins.json"), "utf8")
42145
+ await readFile2(join24(dirname7(cacheDir), "installed_plugins.json"), "utf8")
42551
42146
  );
42552
42147
  const plugins = record2?.plugins;
42553
42148
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -42579,7 +42174,7 @@ async function exists(path) {
42579
42174
  }
42580
42175
 
42581
42176
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
42582
- import { readFileSync as readFileSync19 } from "fs";
42177
+ import { readFileSync as readFileSync14 } from "fs";
42583
42178
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
42584
42179
  var manifestBuildCache = /* @__PURE__ */ new Map();
42585
42180
  function readManifestBuild(manifestUrl, packageName) {
@@ -42587,7 +42182,7 @@ function readManifestBuild(manifestUrl, packageName) {
42587
42182
  if (!manifestBuildCache.has(key)) {
42588
42183
  let build;
42589
42184
  try {
42590
- const manifest = JSON.parse(readFileSync19(manifestUrl, "utf8"));
42185
+ const manifest = JSON.parse(readFileSync14(manifestUrl, "utf8"));
42591
42186
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
42592
42187
  } catch {
42593
42188
  build = void 0;
@@ -42624,7 +42219,7 @@ async function readInstalledVersionBounded(installRoot) {
42624
42219
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42625
42220
  import { randomUUID as randomUUID17 } from "crypto";
42626
42221
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42627
- import { join as join32 } from "path";
42222
+ import { join as join25 } from "path";
42628
42223
 
42629
42224
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
42630
42225
  import { rename as rename2 } from "fs/promises";
@@ -42653,7 +42248,7 @@ async function publishByRename(tmp, file2, move = rename2) {
42653
42248
 
42654
42249
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42655
42250
  function createPolicyStore(dir = dataDir()) {
42656
- const file2 = join32(dir, "policy-cache.json");
42251
+ const file2 = join25(dir, "policy-cache.json");
42657
42252
  async function read() {
42658
42253
  try {
42659
42254
  const raw = await readFile3(file2, "utf8");
@@ -42723,8 +42318,8 @@ function createPolicyStore(dir = dataDir()) {
42723
42318
  }
42724
42319
 
42725
42320
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
42726
- import { readFileSync as readFileSync20 } from "fs";
42727
- import { join as join33 } from "path";
42321
+ import { readFileSync as readFileSync15 } from "fs";
42322
+ import { join as join26 } from "path";
42728
42323
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
42729
42324
  var OUTCOME_KEYS = {
42730
42325
  ok: true,
@@ -42738,7 +42333,7 @@ var OUTCOME_KEYS = {
42738
42333
  };
42739
42334
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
42740
42335
  function postureReportStatePath(dataDir2) {
42741
- return join33(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42336
+ return join26(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42742
42337
  }
42743
42338
  function writePostureReportState(dataDir2, state) {
42744
42339
  try {
@@ -42779,10 +42374,19 @@ function createPostureReporter(deps) {
42779
42374
  hostname: deps.hostname(),
42780
42375
  capturedAt: nowMs,
42781
42376
  ...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 }
42377
+ // Omit the key rather than spread an explicit `undefined`. The type
42378
+ // admits `undefined` here (the schema's optional member), and
42379
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
42380
+ // in-memory object free of an explicit `undefined` member, which the
42381
+ // tests pin by key presence.
42382
+ ...plugin === void 0 ? {} : { plugin },
42383
+ // LAST, and only for a scoped attachment. A machine attachment omits
42384
+ // the key the same way, so its body is byte for byte the one it sent
42385
+ // before the member existed. Anything but exactly `machine` reports the
42386
+ // constant `scoped`, never the raw value: that is resolveScope's own
42387
+ // fail direction, and a value outside the wire's vocabulary would fail
42388
+ // the whole snapshot at the receiver, the wipe signal with it.
42389
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
42786
42390
  };
42787
42391
  } catch {
42788
42392
  return null;
@@ -42805,8 +42409,8 @@ function createPostureReporter(deps) {
42805
42409
  }
42806
42410
 
42807
42411
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
42808
- import { statSync as statSync9 } from "fs";
42809
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
42412
+ import { statSync as statSync7 } from "fs";
42413
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
42810
42414
 
42811
42415
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
42812
42416
  function emptyActionCounts() {
@@ -42836,7 +42440,7 @@ function emptyReadout(readError = false) {
42836
42440
  }
42837
42441
  function readStorePosture(dbPath2) {
42838
42442
  try {
42839
- statSync9(dbPath2);
42443
+ statSync7(dbPath2);
42840
42444
  } catch (err) {
42841
42445
  const code = err.code;
42842
42446
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -42864,7 +42468,7 @@ function readStorePosture(dbPath2) {
42864
42468
  readError: false
42865
42469
  });
42866
42470
  try {
42867
- db = new DatabaseSync4(dbPath2, { readOnly: true });
42471
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
42868
42472
  db.exec("PRAGMA busy_timeout = 2000");
42869
42473
  version2 = db.prepare("PRAGMA user_version").get().user_version;
42870
42474
  try {
@@ -42918,11 +42522,11 @@ function readStorePosture(dbPath2) {
42918
42522
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42919
42523
  import { randomUUID as randomUUID18 } from "crypto";
42920
42524
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42921
- import { join as join34 } from "path";
42525
+ import { join as join27 } from "path";
42922
42526
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42923
42527
  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");
42528
+ const file2 = join27(dir, "posture-state.json");
42529
+ const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
42926
42530
  async function persist(state) {
42927
42531
  await ensureDataDir(dir);
42928
42532
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -42990,8 +42594,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42990
42594
  }
42991
42595
 
42992
42596
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42993
- import { readFileSync as readFileSync21 } from "fs";
42994
- import { join as join35 } from "path";
42597
+ import { readFileSync as readFileSync16 } from "fs";
42598
+ import { join as join28 } from "path";
42995
42599
 
42996
42600
  // ../../packages/plugin-runtime/src/attached/status.ts
42997
42601
  var REFUSAL_LINES = {
@@ -43034,7 +42638,7 @@ var StandaloneDataGateway = class {
43034
42638
  // One notice per gateway — see warnRulesetDiscarded.
43035
42639
  warnedRulesetDiscarded = false;
43036
42640
  constructor(dataDir2, detections = [], meta4) {
43037
- this.db = openLocalDatabase(dataDir2);
42641
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
43038
42642
  this.dataDir = dataDir2;
43039
42643
  this.db.installedPacks.recordInventory(detections, meta4);
43040
42644
  }
@@ -43383,6 +42987,9 @@ var StandaloneDataGateway = class {
43383
42987
  scanLedgerPaths() {
43384
42988
  return Promise.resolve(this.db.scanLedger.allPaths());
43385
42989
  }
42990
+ scanLedgerPathKeys() {
42991
+ return Promise.resolve(this.db.scanLedger.pathKeys());
42992
+ }
43386
42993
  recordScanned(entries) {
43387
42994
  this.db.scanLedger.upsertEntries(entries);
43388
42995
  return Promise.resolve();
@@ -43470,11 +43077,15 @@ function resolveGatewayForConfig(config2, meta4) {
43470
43077
  readStore: () => readStorePosture(config2.dbPath),
43471
43078
  hostname: () => hostname6(),
43472
43079
  now: () => Date.now(),
43080
+ // The mode THIS gateway enforces, from the attachment resolved above,
43081
+ // so the report cannot name a mode the forward paths are not using.
43082
+ attachmentMode: attachment.mode,
43473
43083
  // The reporting build's identity, when the caller knows it (the plugin
43474
43084
  // adapters do; an embedder or a test may not). Composed with the SAME
43475
43085
  // 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.
43086
+ // actually in force. The dependency key is omitted when no build is
43087
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
43088
+ // then adds no block.
43478
43089
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
43479
43090
  })
43480
43091
  });
@@ -43495,11 +43106,11 @@ import { randomUUID as randomUUID19 } from "crypto";
43495
43106
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
43496
43107
 
43497
43108
  // 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";
43109
+ import { closeSync as closeSync2, openSync as openSync2, readdirSync as readdirSync2, readFileSync as readFileSync17, readSync, statSync as statSync8 } from "fs";
43110
+ import { homedir as homedir2 } from "os";
43111
+ import { join as join29 } from "path";
43501
43112
  function transcriptsDir(home) {
43502
- return join36(home ?? homedir3(), ".codex", "sessions");
43113
+ return join29(home ?? homedir2(), ".codex", "sessions");
43503
43114
  }
43504
43115
  function isRecord(value) {
43505
43116
  return typeof value === "object" && value !== null;
@@ -43619,11 +43230,12 @@ function parseTranscriptUsage(jsonl, sinceMs = 0, knownSessionId) {
43619
43230
  const last = info.last_token_usage;
43620
43231
  if (!isRecord(last)) continue;
43621
43232
  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;
43233
+ const cached2 = typeof last.cached_input_tokens === "number" ? Math.max(0, last.cached_input_tokens) : 0;
43234
+ if (typeof last.input_tokens === "number") {
43235
+ usage.input_tokens = Math.max(0, last.input_tokens - cached2);
43626
43236
  }
43237
+ if (typeof last.output_tokens === "number") usage.output_tokens = last.output_tokens;
43238
+ if (typeof last.cached_input_tokens === "number") usage.cache_read_input_tokens = cached2;
43627
43239
  if (typeof last.reasoning_output_tokens === "number") {
43628
43240
  usage.reasoning_output_tokens = last.reasoning_output_tokens;
43629
43241
  }
@@ -43765,12 +43377,12 @@ function* walkJsonlFiles(dir, depth = 0) {
43765
43377
  if (depth > 6) return;
43766
43378
  let entries;
43767
43379
  try {
43768
- entries = readdirSync5(dir, { withFileTypes: true });
43380
+ entries = readdirSync2(dir, { withFileTypes: true });
43769
43381
  } catch {
43770
43382
  return;
43771
43383
  }
43772
43384
  for (const entry of entries) {
43773
- const full = join36(dir, entry.name);
43385
+ const full = join29(dir, entry.name);
43774
43386
  if (entry.isDirectory()) {
43775
43387
  yield* walkJsonlFiles(full, depth + 1);
43776
43388
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -43781,8 +43393,8 @@ function* walkJsonlFiles(dir, depth = 0) {
43781
43393
  function* iterateFileContents(dir) {
43782
43394
  for (const filePath of walkJsonlFiles(dir)) {
43783
43395
  try {
43784
- statSync10(filePath);
43785
- yield { content: readFileSync22(filePath, "utf8"), filePath };
43396
+ statSync8(filePath);
43397
+ yield { content: readFileSync17(filePath, "utf8"), filePath };
43786
43398
  } catch {
43787
43399
  }
43788
43400
  }
@@ -43900,17 +43512,17 @@ function pluginBuild() {
43900
43512
  }
43901
43513
 
43902
43514
  // src/history/tail.ts
43903
- import { createHash as createHash7 } from "crypto";
43515
+ import { createHash as createHash8 } from "crypto";
43904
43516
  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
43517
+ closeSync as closeSync3,
43518
+ fstatSync,
43519
+ mkdirSync as mkdirSync2,
43520
+ openSync as openSync3,
43521
+ readFileSync as readFileSync18,
43522
+ readSync as readSync2,
43523
+ writeFileSync as writeFileSync7
43912
43524
  } from "fs";
43913
- import { join as join37 } from "path";
43525
+ import { join as join30 } from "path";
43914
43526
 
43915
43527
  // src/history/usage.ts
43916
43528
  var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";