@akasecurity/ai-tc-codex 0.9.16 → 0.9.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,892 +1,12 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- try {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- } catch (e) {
11
- throw mod = 0, e;
12
- }
13
- };
14
2
  var __export = (target, all) => {
15
3
  for (var name in all)
16
4
  __defProp(target, name, { get: all[name], enumerable: true });
17
5
  };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
-
35
- // ../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js
36
- var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js"(exports, module) {
38
- "use strict";
39
- function makeArray(subject) {
40
- return Array.isArray(subject) ? subject : [subject];
41
- }
42
- var UNDEFINED = void 0;
43
- var EMPTY = "";
44
- var SPACE = " ";
45
- var ESCAPE = "\\";
46
- var REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
47
- var REGEX_TEST_BLANK_LINE = /^\uFEFF? *$/;
48
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
49
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
50
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
51
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
52
- var DOUBLE_SLASH = "//";
53
- var SLASH_CODE = 47;
54
- var DOT_CODE = 46;
55
- var SLASH3 = "/";
56
- var TMP_KEY_IGNORE = "node-ignore";
57
- if (typeof Symbol !== "undefined") {
58
- TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
59
- }
60
- var KEY_IGNORE = TMP_KEY_IGNORE;
61
- var define = (object2, key, value) => {
62
- Object.defineProperty(object2, key, { value });
63
- return value;
64
- };
65
- var RETURN_FALSE = () => false;
66
- var cleanRangeBackSlash = (slashes) => {
67
- const { length } = slashes;
68
- return slashes.slice(0, length - length % 2);
69
- };
70
- var POSIX_CLASSES = {
71
- alnum: "0-9A-Za-z",
72
- alpha: "A-Za-z",
73
- blank: " \\t",
74
- cntrl: "\\x00-\\x1f\\x7f",
75
- digit: "0-9",
76
- graph: "!-.0-~",
77
- lower: "a-z",
78
- print: " -.0-~",
79
- punct: "!-.:-@\\[-`{-~",
80
- // git's `sane-ctype.h` classifies \v and \f as control, not space,
81
- // unlike C's `isspace`
82
- space: " \\t\\n\\r",
83
- upper: "A-Z",
84
- xdigit: "0-9A-Fa-f"
85
- };
86
- var CLASS_MEMBERS_TO_ESCAPE = "\\]^-[";
87
- var escapeMember = (char) => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0 ? char : ESCAPE + char;
88
- var NON_SLASH = "(?!\\/)";
89
- var classSource = (negated, body) => {
90
- if (negated) {
91
- return `[^\\/${body}]`;
92
- }
93
- const source = `[${body}]`;
94
- return new RegExp(source).test("/") ? NON_SLASH + source : source;
95
- };
96
- var scanBracket = (pattern, start) => {
97
- const { length } = pattern;
98
- let index = start + 1;
99
- let negated = EMPTY;
100
- const lead = pattern[index];
101
- if (lead === "!" || lead === "^") {
102
- negated = "^";
103
- index++;
104
- }
105
- let body = EMPTY;
106
- let prev = EMPTY;
107
- for (; ; ) {
108
- const char = pattern[index];
109
- if (char === UNDEFINED) {
110
- return null;
111
- }
112
- if (char === ESCAPE) {
113
- const escaped = pattern[index + 1];
114
- if (escaped === UNDEFINED) {
115
- return null;
116
- }
117
- body += escapeMember(escaped);
118
- prev = escaped;
119
- index++;
120
- } else if (char === "-" && prev && index + 1 < length && pattern[index + 1] !== "]") {
121
- index++;
122
- let to = pattern[index];
123
- if (to === ESCAPE) {
124
- to = pattern[index += 1];
125
- }
126
- if (prev <= to) {
127
- body += `-${escapeMember(to)}`;
128
- }
129
- prev = EMPTY;
130
- } else if (char === "[" && pattern[index + 1] === ":") {
131
- const nameStart = index + 2;
132
- let end = nameStart;
133
- while (end < length && pattern[end] !== "]") {
134
- end++;
135
- }
136
- if (end === length) {
137
- return null;
138
- }
139
- if (end > nameStart && pattern[end - 1] === ":") {
140
- const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)];
141
- if (expanded === UNDEFINED) {
142
- return null;
143
- }
144
- body += expanded;
145
- prev = EMPTY;
146
- index = end;
147
- } else {
148
- body += escapeMember("[");
149
- prev = "[";
150
- index = nameStart - 2;
151
- }
152
- } else {
153
- body += escapeMember(char);
154
- prev = char;
155
- }
156
- index++;
157
- if (pattern[index] === "]") {
158
- return {
159
- end: index,
160
- source: classSource(negated, body)
161
- };
162
- }
163
- }
164
- };
165
- var NEVER_MATCH = "[]";
166
- var PLACEHOLDER = "\0";
167
- var REGEX_RESTORE_PLACEHOLDER = new RegExp(
168
- `${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,
169
- "g"
170
- );
171
- var TRAILING_WILDCARD = "\uE000";
172
- var TRAILING_DOUBLESTAR = "\uE001";
173
- var extractBrackets = (pattern) => {
174
- const sources = [];
175
- const hold = (source) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
176
- const { length } = pattern;
177
- let out = EMPTY;
178
- let index = 0;
179
- while (index < length) {
180
- const char = pattern[index];
181
- if (char === ESCAPE) {
182
- const escaped = pattern[index + 1];
183
- if (escaped === "*" || escaped === "[" || escaped === SPACE || escaped === ESCAPE) {
184
- out += pattern.slice(index, index + 2);
185
- } else {
186
- out += hold(
187
- REGEX_LITERAL_SPECIAL.test(escaped) ? ESCAPE + escaped : escaped
188
- );
189
- }
190
- index += 2;
191
- } else if (char === PLACEHOLDER) {
192
- out += hold(`[${PLACEHOLDER}]`);
193
- index++;
194
- } else if (char === "[") {
195
- const scanned = scanBracket(pattern, index);
196
- if (scanned === null) {
197
- out += hold(NEVER_MATCH);
198
- index = length;
199
- } else {
200
- out += hold(scanned.source);
201
- index = scanned.end + 1;
202
- }
203
- } else {
204
- out += char;
205
- index++;
206
- }
207
- }
208
- return {
209
- source: out,
210
- sources
211
- };
212
- };
213
- var DIRECT = null;
214
- var REGEX_INNER_SLASH = /\/(?!$)/;
215
- var REPLACERS = [
216
- [
217
- // Remove BOM
218
- // TODO:
219
- // Other similar zero-width characters?
220
- /^\uFEFF/,
221
- () => EMPTY,
222
- "\uFEFF"
223
- ],
224
- [
225
- // A trailing line terminator, left on when a whole file's contents are
226
- // added as one pattern rather than split into lines. git never sees one
227
- // -- it reads a `.gitignore` line by line -- so it is not part of the
228
- // pattern and is dropped here, apart from the trailing-space trimming,
229
- // which follows git in touching spaces and nothing else.
230
- /[\r\n]+$/,
231
- () => EMPTY
232
- ],
233
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
234
- [
235
- // Only spaces, never tabs or other whitespace: git trims a trailing run
236
- // of `' '` and nothing else (dir.c, `trim_trailing_spaces`, a single
237
- // `case ' '`), so a pattern ending in a tab keeps it as a literal.
238
- // (a\ ) -> (a )
239
- // (a ) -> (a)
240
- // (a ) -> (a)
241
- // (a \ ) -> (a )
242
- /((?:\\\\)*?)(\\? +)$/,
243
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
244
- ],
245
- // Replace (\ ) with ' '
246
- // Only a space: an escaped tab or other whitespace is already a literal by
247
- // the time it reaches here, and a bare tab must be left as one, not turned
248
- // into a space.
249
- // (\ ) -> ' '
250
- // (\\ ) -> '\\ '
251
- // (\\\ ) -> '\\ '
252
- [
253
- /(\\+?) /g,
254
- (_, m1) => {
255
- const { length } = m1;
256
- return m1.slice(0, length - length % 2) + SPACE;
257
- }
258
- ],
259
- // Escape metacharacters
260
- // which is written down by users but means special for regular expressions.
261
- // > There are 12 characters with special meanings:
262
- // > - the backslash \,
263
- // > - the caret ^,
264
- // > - the dollar sign $,
265
- // > - the period or dot .,
266
- // > - the vertical bar or pipe symbol |,
267
- // > - the question mark ?,
268
- // > - the asterisk or star *,
269
- // > - the plus sign +,
270
- // > - the opening parenthesis (,
271
- // > - the closing parenthesis ),
272
- // > - and the opening square bracket [,
273
- // > - the opening curly brace {,
274
- // > These special characters are often called "metacharacters".
275
- [
276
- /[\\$.|*+(){^]/g,
277
- (match) => `\\${match}`
278
- ],
279
- [
280
- // > a question mark (?) matches a single character
281
- /(?!\\)\?/g,
282
- () => "[^/]",
283
- "?"
284
- ],
285
- // leading slash
286
- [
287
- // > A leading slash matches the beginning of the pathname.
288
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
289
- // A leading slash matches the beginning of the pathname
290
- /^\//,
291
- () => "^",
292
- SLASH3
293
- ],
294
- // replace special metacharacter slash after the leading slash
295
- [
296
- /\//g,
297
- () => "\\/",
298
- SLASH3
299
- ],
300
- [
301
- // > A leading "**" followed by a slash means match in all directories.
302
- // > For example, "**/foo" matches file or directory "foo" anywhere,
303
- // > the same as pattern "foo".
304
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
305
- // > under directory "foo".
306
- // Notice that the '*'s have been replaced as '\\*'
307
- /^\^*(?:\\\*\\\*\\\/)+/,
308
- // '**/foo' <-> 'foo'
309
- () => "^(?:.*\\/)?",
310
- "*"
311
- ],
312
- // starting
313
- [
314
- // there will be no leading '/'
315
- // (which has been replaced by section "leading slash")
316
- // If starts with '**', adding a '^' to the regular expression also works
317
- DIRECT,
318
- (source, pattern) => {
319
- if (!source || source[0] === "^") {
320
- return source;
321
- }
322
- const anchor2 = !REGEX_INNER_SLASH.test(pattern) ? "(?:^|\\/)" : "^";
323
- return anchor2 + source;
324
- }
325
- ],
326
- // two globstars
327
- [
328
- // Use lookahead assertions so that we could match more than one `'/**'`
329
- /\\\/\\\*\\\*(?=\\\/|$)/g,
330
- // Zero, one or several directories
331
- // should not use '*', or it will be replaced by the next replacer
332
- // Check if it is not the last `'/**'`
333
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
334
- "*"
335
- ],
336
- // normal intermediate wildcards
337
- [
338
- // Never replace escaped '*'
339
- // ignore rule '\*' will match the path '*'
340
- // 'abc.*/' -> go
341
- // 'abc.*' -> skip this rule,
342
- // coz trailing single wildcard will be handed by [trailing wildcard]
343
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
344
- // '*.js' matches '.js'
345
- // '*.js' doesn't match 'abc'
346
- (_, p1, p2) => {
347
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
348
- return p1 + unescaped;
349
- },
350
- "*"
351
- ],
352
- // trailing wildcard, held apart from a literal star
353
- [
354
- // The step above leaves a trailing `*` alone, so a single `\*` is all that
355
- // can be left at the end here. Whether it is a wildcard or a literal
356
- // turns on the backslashes the user put in front of it: the escaper has
357
- // since doubled every one, so what stands here is those `2N` doubled
358
- // backslashes and then the star's own escape. An even number of the
359
- // original `N` leaves the star unescaped -- a wildcard -- and an odd
360
- // number escapes it -- a literal. This runs while the two are still
361
- // distinct, before the unescape steps below collapse the literal onto
362
- // the very `\*` a wildcard leaves behind.
363
- /(^|[^\\])((?:\\\\)*)\\\*$/,
364
- (match, p1, p2) => (
365
- // `p2` holds the doubled user backslashes; half of them is `N`.
366
- p2.length / 2 % 2 === 0 ? p1 + p2 + TRAILING_WILDCARD : match
367
- ),
368
- "*"
369
- ],
370
- [
371
- // unescape, revert step 3 except for back slash
372
- // For example, if a user escape a '\\*',
373
- // after step 3, the result will be '\\\\\\*'
374
- /\\\\\\(?=[$.|*+(){^])/g,
375
- () => ESCAPE,
376
- ESCAPE + ESCAPE
377
- ],
378
- [
379
- // '\\\\' -> '\\'
380
- /\\\\/g,
381
- () => ESCAPE,
382
- ESCAPE + ESCAPE
383
- ],
384
- [
385
- // Every real bracket expression -- POSIX classes included -- has already
386
- // been held aside by `extractBrackets`, so the only `[` left in the
387
- // pattern is an escaped, literal one.
388
- // `\` is escaped by step 3
389
- /\\\[([^\]/]*?)(\\*)($|\])/g,
390
- // '\\[bar]' -> '\\\\[bar\\]'
391
- (match, range, endEscape, close) => `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,
392
- "["
393
- ],
394
- // ending
395
- [
396
- // 'js' will not match 'js.'
397
- // 'ab' will not match 'abc'
398
- DIRECT,
399
- // WTF!
400
- // https://git-scm.com/docs/gitignore
401
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
402
- // which re-fixes #24, #38
403
- // > If there is a separator at the end of the pattern then the pattern
404
- // > will only match directories, otherwise the pattern can match both
405
- // > files and directories.
406
- // 'js*' will not match 'a.js'
407
- // 'js/' will not match 'a.js'
408
- // 'js' will match 'a.js' and 'a.js/'
409
- (source) => {
410
- const last = source[source.length - 1];
411
- if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
412
- return source;
413
- }
414
- return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
415
- }
416
- ]
417
- ];
418
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\uE000$/;
419
- var MODE_IGNORE = "regex";
420
- var MODE_CHECK_IGNORE = "checkRegex";
421
- var UNDERSCORE = "_";
422
- var replaceTrailingWildcard = (_, p1) => {
423
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
- return `${prefix}(?=$|\\/$)`;
425
- };
426
- var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
427
- var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
428
- var WILDCARD = "[^\\/]*";
429
- var separatorAfter = (run, at) => {
430
- let separator = EMPTY;
431
- for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
432
- separator += run[index].single;
433
- }
434
- return separator;
435
- };
436
- var pinWildcards = (source) => {
437
- if (source.indexOf(WILDCARD) < 0) {
438
- return source;
439
- }
440
- const tokens = [];
441
- const { length } = source;
442
- let index = 0;
443
- while (index < length) {
444
- const char = source[index];
445
- if (source.startsWith(WILDCARD, index)) {
446
- tokens.push({ wildcard: true });
447
- index += WILDCARD.length;
448
- } else if (char === "[") {
449
- let end = index + 1;
450
- if (source[end] === "^") {
451
- end++;
452
- }
453
- if (source[end] === "]") {
454
- end++;
455
- }
456
- while (end < length && source[end] !== "]") {
457
- end += source[end] === ESCAPE ? 2 : 1;
458
- }
459
- end++;
460
- tokens.push({ single: source.slice(index, end) });
461
- index = end;
462
- } else if (char === ESCAPE) {
463
- tokens.push({ single: source.slice(index, index + 2) });
464
- index += 2;
465
- } else if (char === "(") {
466
- let depth = 0;
467
- let end = index;
468
- do {
469
- if (source[end] === ESCAPE) {
470
- end++;
471
- } else if (source[end] === "(") {
472
- depth++;
473
- } else if (source[end] === ")") {
474
- depth--;
475
- }
476
- end++;
477
- } while (end < length && depth > 0);
478
- if ("*+?".indexOf(source[end]) >= 0) {
479
- end++;
480
- }
481
- tokens.push({ boundary: source.slice(index, end) });
482
- index = end;
483
- } else if (char === "^" || char === "$") {
484
- tokens.push({ boundary: char });
485
- index++;
486
- } else {
487
- tokens.push({ single: char });
488
- index++;
489
- }
490
- }
491
- let out = EMPTY;
492
- let run = [];
493
- const flush = () => {
494
- let lastWildcard;
495
- run.forEach((token, at) => {
496
- if (token.wildcard) {
497
- lastWildcard = at;
498
- }
499
- });
500
- run.forEach((token, at) => {
501
- if (!token.wildcard) {
502
- out += token.single;
503
- return;
504
- }
505
- out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
506
- });
507
- run = [];
508
- };
509
- tokens.forEach((token) => {
510
- if (token.boundary === void 0) {
511
- run.push(token);
512
- return;
513
- }
514
- flush();
515
- out += token.boundary;
516
- });
517
- flush();
518
- return out;
519
- };
520
- var makeRegexPrefix = (pattern) => {
521
- const { source, sources } = extractBrackets(pattern);
522
- const replaced = REPLACERS.reduce(
523
- // A pass whose matcher finds nothing hands back the very string it was
524
- // given, so asking first costs a search and saves a rewrite. Ten of the
525
- // fifteen passes never fire for a typical .gitignore line, and between
526
- // them they were 45% of this chain.
527
- (prev, [matcher, replacer, required2]) => {
528
- if (matcher === DIRECT) {
529
- return replacer(prev, pattern);
530
- }
531
- if (required2 !== UNDEFINED && prev.indexOf(required2) < 0) {
532
- return prev;
533
- }
534
- return matcher.test(prev) ? prev.replace(matcher, replacer.bind(pattern)) : prev;
535
- },
536
- source
537
- );
538
- return sources.length ? replaced.replace(
539
- REGEX_RESTORE_PLACEHOLDER,
540
- (match, index) => sources[index]
541
- ) : replaced;
542
- };
543
- var checkSourceOf = (body, prefix) => {
544
- if (body[body.length - 1] === SLASH3) {
545
- prefix = makeRegexPrefix(body.slice(0, -1));
546
- }
547
- const head = prefix.slice(0, -1);
548
- const last = prefix[prefix.length - 1];
549
- return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
- };
551
- var matchesBasename = (body) => {
552
- const index = body.indexOf(SLASH3);
553
- return index < 0 || index === body.length - 1;
554
- };
555
- var basenameOf = (path) => {
556
- const end = path.length - 1;
557
- const index = path.lastIndexOf(
558
- SLASH3,
559
- path[end] === SLASH3 ? end - 1 : end
560
- );
561
- return index < 0 ? path : path.slice(index + 1);
562
- };
563
- var parentOf = (path) => {
564
- if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
565
- const slices = path.split(SLASH3).filter(Boolean);
566
- slices.pop();
567
- return slices.length ? slices.join(SLASH3) + SLASH3 : EMPTY;
568
- }
569
- const end = path.length - 1;
570
- const cut = path.lastIndexOf(
571
- SLASH3,
572
- path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
573
- );
574
- return cut < 0 ? EMPTY : path.slice(0, cut + 1);
575
- };
576
- var isString = (subject) => typeof subject === "string";
577
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
578
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
579
- var IgnoreRule = class {
580
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
581
- this.pattern = pattern;
582
- this.mark = mark;
583
- this.negative = negative;
584
- define(this, "body", body);
585
- define(this, "ignoreCase", ignoreCase);
586
- define(this, "regexPrefix", prefix);
587
- }
588
- // Worked out on first use and kept behind an own property, the way `regex`
589
- // caches itself in `_regex`. Deciding it in the constructor instead would
590
- // add a fourth `defineProperty` to every rule ever built, which cost 4% of
591
- // every compile -- including the compiles of rules that are never matched
592
- // against anything.
593
- get _basenameOnly() {
594
- return define(this, "_basenameOnly", matchesBasename(this.body));
595
- }
596
- get regex() {
597
- const key = UNDERSCORE + MODE_IGNORE;
598
- if (this[key]) {
599
- return this[key];
600
- }
601
- return this._make(MODE_IGNORE, key);
602
- }
603
- get checkRegex() {
604
- const key = UNDERSCORE + MODE_CHECK_IGNORE;
605
- if (this[key]) {
606
- return this[key];
607
- }
608
- return this._make(MODE_CHECK_IGNORE, key);
609
- }
610
- _make(mode, key) {
611
- const str2 = pinWildcards(
612
- mode === MODE_IGNORE ? this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar) : checkSourceOf(this.body, this.regexPrefix)
613
- );
614
- const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
615
- return define(this, key, regex);
616
- }
617
- };
618
- var createRule = ({
619
- pattern,
620
- mark
621
- }, ignoreCase) => {
622
- let negative = false;
623
- let body = pattern;
624
- if (body.indexOf("!") === 0) {
625
- negative = true;
626
- body = body.substr(1);
627
- }
628
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
629
- const regexPrefix = makeRegexPrefix(body);
630
- return new IgnoreRule(
631
- pattern,
632
- mark,
633
- body,
634
- ignoreCase,
635
- negative,
636
- regexPrefix
637
- );
638
- };
639
- var RuleManager = class {
640
- constructor(ignoreCase) {
641
- this._ignoreCase = ignoreCase;
642
- this._rules = [];
643
- this._basenameCount = 0;
644
- }
645
- _add(pattern) {
646
- if (pattern && pattern[KEY_IGNORE]) {
647
- this._rules = this._rules.concat(pattern._rules._rules);
648
- this._basenameCount += pattern._rules._basenameCount;
649
- this._added = true;
650
- return;
651
- }
652
- if (isString(pattern)) {
653
- pattern = {
654
- pattern
655
- };
656
- }
657
- if (checkPattern(pattern.pattern)) {
658
- const rule = createRule(pattern, this._ignoreCase);
659
- this._added = true;
660
- this._rules.push(rule);
661
- if (matchesBasename(rule.body)) {
662
- this._basenameCount++;
663
- }
664
- }
665
- }
666
- // @param {Array<string> | string | Ignore} pattern
667
- add(pattern) {
668
- this._added = false;
669
- makeArray(
670
- isString(pattern) ? splitPattern(pattern) : pattern
671
- ).forEach(this._add, this);
672
- if (this._added) {
673
- this._literalRules = UNDEFINED;
674
- }
675
- return this._added;
676
- }
677
- // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule
678
- // ending in a wildcard can match it (see `checkSourceOf`), so the rest
679
- // are left out once, rather than tested or compiled for every path.
680
- testLiteral(path) {
681
- const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
- ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
683
- ));
684
- let ignored = false;
685
- let unignored = false;
686
- let matchedRule;
687
- for (let index = rules.length - 1; index >= 0; index--) {
688
- const rule = rules[index];
689
- if (rule.checkRegex.test(path)) {
690
- ignored = !rule.negative;
691
- unignored = rule.negative;
692
- matchedRule = rule.negative ? UNDEFINED : rule;
693
- break;
694
- }
695
- }
696
- const ret = {
697
- ignored,
698
- unignored
699
- };
700
- if (matchedRule) {
701
- ret.rule = matchedRule;
702
- }
703
- return ret;
704
- }
705
- // Test one single path without recursively checking parent directories
706
- //
707
- // - checkUnignored `boolean` whether should check if the path is unignored,
708
- // setting `checkUnignored` to `false` could reduce additional
709
- // path matching.
710
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
711
- // @returns {TestResult} true if a file is ignored
712
- test(path, checkUnignored, mode) {
713
- let ignored = false;
714
- let unignored = false;
715
- let matchedRule;
716
- const rules = this._rules;
717
- const { length } = rules;
718
- const shortcut = this._basenameCount * 2 >= length;
719
- const basename7 = shortcut ? basenameOf(path) : path;
720
- for (let index = 0; index < length; index++) {
721
- const rule = rules[index];
722
- const { negative } = rule;
723
- const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
724
- if (!skip && rule[mode].test(
725
- shortcut && rule._basenameOnly ? basename7 : path
726
- )) {
727
- ignored = !negative;
728
- unignored = negative;
729
- matchedRule = negative ? UNDEFINED : rule;
730
- }
731
- }
732
- const ret = {
733
- ignored,
734
- unignored
735
- };
736
- if (matchedRule) {
737
- ret.rule = matchedRule;
738
- }
739
- return ret;
740
- }
741
- };
742
- var throwError = (message, Ctor) => {
743
- throw new Ctor(message);
744
- };
745
- var checkPath = (path, originalPath, doThrow) => {
746
- if (!isString(path)) {
747
- return doThrow(
748
- `path must be a string, but got \`${originalPath}\``,
749
- TypeError
750
- );
751
- }
752
- if (!path) {
753
- return doThrow(`path must not be empty`, TypeError);
754
- }
755
- if (checkPath.isNotRelative(path)) {
756
- const r = "`path.relative()`d";
757
- return doThrow(
758
- `path should be a ${r} string, but got "${originalPath}"`,
759
- RangeError
760
- );
761
- }
762
- return true;
763
- };
764
- var isNotRelative = (path) => {
765
- const first = path.charCodeAt(0);
766
- if (first === SLASH_CODE) {
767
- return true;
768
- }
769
- if (first !== DOT_CODE) {
770
- return false;
771
- }
772
- if (path.length === 1) {
773
- return true;
774
- }
775
- const second = path.charCodeAt(1);
776
- if (second === SLASH_CODE) {
777
- return true;
778
- }
779
- if (second !== DOT_CODE) {
780
- return false;
781
- }
782
- return path.length === 2 || path.charCodeAt(2) === SLASH_CODE;
783
- };
784
- checkPath.isNotRelative = isNotRelative;
785
- checkPath.convert = (p) => p;
786
- var Ignore = class {
787
- constructor({
788
- ignorecase = true,
789
- ignoreCase = ignorecase,
790
- allowRelativePaths = false
791
- } = {}) {
792
- define(this, KEY_IGNORE, true);
793
- this._rules = new RuleManager(ignoreCase);
794
- this._strictPathCheck = !allowRelativePaths;
795
- this._initCache();
796
- }
797
- _initCache() {
798
- this._ignoreCache = /* @__PURE__ */ Object.create(null);
799
- this._testCache = /* @__PURE__ */ Object.create(null);
800
- }
801
- add(pattern) {
802
- if (this._rules.add(pattern)) {
803
- this._initCache();
804
- }
805
- return this;
806
- }
807
- // legacy
808
- addPattern(pattern) {
809
- return this.add(pattern);
810
- }
811
- // @returns {TestResult}
812
- _test(originalPath, cache, checkUnignored) {
813
- const path = originalPath && checkPath.convert(originalPath);
814
- checkPath(
815
- path,
816
- originalPath,
817
- this._strictPathCheck ? throwError : RETURN_FALSE
818
- );
819
- return this._t(path, cache, checkUnignored);
820
- }
821
- checkIgnore(path) {
822
- if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {
823
- return this.test(path);
824
- }
825
- const dir = this._t(path, this._testCache, true);
826
- if (dir.ignored) {
827
- return dir;
828
- }
829
- const literal2 = this._rules.testLiteral(path);
830
- return literal2.ignored || literal2.unignored ? literal2 : dir;
831
- }
832
- _t(path, cache, checkUnignored) {
833
- if (path in cache) {
834
- return cache[path];
835
- }
836
- const parentPath = parentOf(path);
837
- const parent = parentPath ? this._t(parentPath, cache, checkUnignored) : UNDEFINED;
838
- return cache[path] = parent && parent.ignored ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE);
839
- }
840
- ignores(path) {
841
- return this._test(path, this._ignoreCache, false).ignored;
842
- }
843
- createFilter() {
844
- return (path) => !this.ignores(path);
845
- }
846
- filter(paths) {
847
- return makeArray(paths).filter(this.createFilter());
848
- }
849
- // @returns {TestResult}
850
- test(path) {
851
- return this._test(path, this._testCache, true);
852
- }
853
- };
854
- var factory = (options) => new Ignore(options);
855
- var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
856
- var setupWindows = () => {
857
- const makePosix = (str2) => /^\\\\\?\\/.test(str2) || /["<>|\u0000-\u001F]+/u.test(str2) ? str2 : str2.replace(/\\/g, "/");
858
- checkPath.convert = makePosix;
859
- const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
860
- checkPath.isNotRelative = (path) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
861
- };
862
- if (
863
- // Detect `process` so that it can run in browsers.
864
- typeof process !== "undefined" && process.platform === "win32"
865
- ) {
866
- setupWindows();
867
- }
868
- module.exports = factory;
869
- factory.default = factory;
870
- module.exports.isPathValid = isPathValid;
871
- define(module.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
872
- }
873
- });
874
6
 
875
7
  // ../../packages/plugin-sdk/src/config.ts
876
8
  import { existsSync as existsSync8 } from "fs";
877
- import { join as join16 } from "path";
878
-
879
- // ../../packages/persistence/src/attached-derived.ts
880
- import { rmSync } from "fs";
881
- import { join } from "path";
882
- var POLICY_CACHE_FILENAME = "policy-cache.json";
883
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
884
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
885
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
886
-
887
- // ../../packages/persistence/src/control-plane-credential.ts
888
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
889
- import { join as join2 } from "path";
9
+ import { join as join17 } from "path";
890
10
 
891
11
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
892
12
  var DEFERRED_MIGRATION_TAGS = [
@@ -1058,6 +178,12 @@ var HOUR_MS = 60 * MINUTE_MS;
1058
178
  var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1059
179
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1060
180
 
181
+ // ../../packages/schema/src/invisible-padding.ts
182
+ var INVISIBLE_PADDING = /[\u00AD\u061C\u180E\u200B\u200E\u200F\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\uFFF9-\uFFFB\u{E0001}\u{E0020}-\u{E007F}]/gu;
183
+ function stripInvisiblePadding(text) {
184
+ return text.replace(INVISIBLE_PADDING, "");
185
+ }
186
+
1061
187
  // ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
1062
188
  var external_exports = {};
1063
189
  __export(external_exports, {
@@ -20793,13 +19919,16 @@ function serviceTierMultiplier(tier) {
20793
19919
  if (tier === void 0) return 1;
20794
19920
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20795
19921
  }
19922
+ function promptTokensOf(usage) {
19923
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19924
+ }
20796
19925
  function costOf(price, usage) {
20797
19926
  const metered = [
20798
19927
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20799
19928
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20800
19929
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20801
19930
  ];
20802
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19931
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20803
19932
  if (band !== null && (band.input === null || band.output === null)) return null;
20804
19933
  const inputRate = band?.input ?? price.input;
20805
19934
  const outputRate = band?.output ?? price.output;
@@ -21009,7 +20138,7 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21009
20138
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21010
20139
  var BEDROCK_REVISION_RE = /:\d+$/u;
21011
20140
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21012
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20141
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21013
20142
  function stripPlatformDecorations(model) {
21014
20143
  let id = model.trim();
21015
20144
  let platform2 = null;
@@ -21159,7 +20288,7 @@ anthropic.model("claude-haiku-4-5", {
21159
20288
  name: "Claude Haiku 4.5",
21160
20289
  ctx: 2e5,
21161
20290
  maxOut: 64e3,
21162
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20291
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21163
20292
  capability: null,
21164
20293
  price: anthropicPrice(1, 5, 0.1),
21165
20294
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21290,6 +20419,11 @@ openai.model("gpt-4o", {
21290
20419
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21291
20420
  on: [...OPENAI_RESELLERS]
21292
20421
  });
20422
+ openai.model("gpt-4o-2024-05-13", {
20423
+ name: "GPT-4o (2024-05-13)",
20424
+ price: tokenPrice(5, 15),
20425
+ on: [...OPENAI_RESELLERS]
20426
+ });
21293
20427
  openai.model("gpt-4o-mini", {
21294
20428
  name: "GPT-4o mini",
21295
20429
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21309,6 +20443,24 @@ openai.model("o3", {
21309
20443
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21310
20444
  on: [...OPENAI_RESELLERS]
21311
20445
  });
20446
+ openai.model("text-embedding-3-small", {
20447
+ name: "text-embedding-3-small",
20448
+ capability: "embedding",
20449
+ price: tokenPrice(0.02, 0),
20450
+ on: [...OPENAI_RESELLERS]
20451
+ });
20452
+ openai.model("text-embedding-3-large", {
20453
+ name: "text-embedding-3-large",
20454
+ capability: "embedding",
20455
+ price: tokenPrice(0.13, 0),
20456
+ on: [...OPENAI_RESELLERS]
20457
+ });
20458
+ openai.model("text-embedding-ada-002", {
20459
+ name: "text-embedding-ada-002",
20460
+ capability: "embedding",
20461
+ price: tokenPrice(0.1, 0),
20462
+ on: [...OPENAI_RESELLERS]
20463
+ });
21312
20464
  openai.model("gpt-oss-120b", {
21313
20465
  name: "GPT-OSS 120B",
21314
20466
  openWeights: true,
@@ -21595,10 +20747,21 @@ var MODEL_ENTRIES = Object.freeze([
21595
20747
  ...alibaba.models(),
21596
20748
  ...amazon.models()
21597
20749
  ]);
20750
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20751
+ [
20752
+ ...new Set(
20753
+ MODEL_ENTRIES.flatMap(
20754
+ (entry) => [...entry.platforms.values()].flatMap(
20755
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20756
+ )
20757
+ )
20758
+ )
20759
+ ].sort((a, b) => a - b)
20760
+ );
21598
20761
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21599
20762
 
21600
20763
  // ../../packages/schema/src/model/governance.ts
21601
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20764
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21602
20765
  var DataRetention = external_exports.enum([
21603
20766
  "zero_retention",
21604
20767
  "no_storage",
@@ -21729,7 +20892,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21729
20892
 
21730
20893
  // ../../packages/schema/src/token/token-report.ts
21731
20894
  var num = (value) => value ?? 0;
21732
- function costUsageOf(a) {
20895
+ function costUsageOf(a, promptTokens) {
21733
20896
  const usage = {
21734
20897
  inputTokens: num(a.input_tokens),
21735
20898
  outputTokens: num(a.output_tokens),
@@ -21739,11 +20902,12 @@ function costUsageOf(a) {
21739
20902
  webSearchRequests: num(a.web_search_requests)
21740
20903
  };
21741
20904
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20905
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21742
20906
  return usage;
21743
20907
  }
21744
20908
  function buildTokenReports(leaves, costModel) {
21745
20909
  const bySession = /* @__PURE__ */ new Map();
21746
- for (const { sessionId, attributes } of leaves) {
20910
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21747
20911
  const provider = attributes.provider ?? "unknown";
21748
20912
  const model = attributes.model ?? "unknown";
21749
20913
  const key = `${provider} ${model}`;
@@ -21762,7 +20926,8 @@ function buildTokenReports(leaves, costModel) {
21762
20926
  cacheCreation: 0,
21763
20927
  cacheRead: 0,
21764
20928
  costUsd: 0,
21765
- priced: false
20929
+ priced: false,
20930
+ partial: false
21766
20931
  };
21767
20932
  rollups.set(key, acc);
21768
20933
  }
@@ -21770,8 +20935,14 @@ function buildTokenReports(leaves, costModel) {
21770
20935
  acc.output += num(attributes.output_tokens);
21771
20936
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21772
20937
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21773
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21774
- if (leafCost !== null) {
20938
+ const leafCost = costModel.costFor({
20939
+ provider,
20940
+ model,
20941
+ usage: costUsageOf(attributes, promptTokens)
20942
+ });
20943
+ if (leafCost === null) {
20944
+ acc.partial = true;
20945
+ } else {
21775
20946
  acc.costUsd += leafCost;
21776
20947
  acc.priced = true;
21777
20948
  }
@@ -21787,9 +20958,8 @@ function buildTokenReports(leaves, costModel) {
21787
20958
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21788
20959
  totalTokens += rollupTotal;
21789
20960
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21790
- if (estimatedCostUsd === null) {
21791
- anyUnpriced = true;
21792
- } else {
20961
+ if (acc.partial) anyUnpriced = true;
20962
+ if (estimatedCostUsd !== null) {
21793
20963
  anyPriced = true;
21794
20964
  costUsd += estimatedCostUsd;
21795
20965
  }
@@ -21812,7 +20982,7 @@ function buildTokenReports(leaves, costModel) {
21812
20982
  totalTokens,
21813
20983
  // Σ of the PRICED rollups; null when none had a known price.
21814
20984
  estimatedCostUsd: anyPriced ? costUsd : null,
21815
- // Any unknown (provider, model) means the total understates real spend.
20985
+ // Any call priced to null means the total understates real spend.
21816
20986
  costIsPartial: anyUnpriced
21817
20987
  });
21818
20988
  }
@@ -22517,6 +21687,11 @@ var CaptureAttributes = external_exports.object({
22517
21687
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22518
21688
  // repeated rather than referenced because a store reader opens this file.
22519
21689
  redact_degraded_to: ActionTaken.optional(),
21690
+ // Why a capture has no content and no findings: its field was refused
21691
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
21692
+ // whose value this is). Absent on every capture that was scanned, so a
21693
+ // reader can tell a refused row from an empty clean one.
21694
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22520
21695
  // The scope key this capture was stamped with: the canonical repository
22521
21696
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22522
21697
  // against its working directory), else of its own working directory, or a
@@ -22694,8 +21869,9 @@ var SessionTokenReport = external_exports.object({
22694
21869
  totalTokens: external_exports.number().int().nonnegative(),
22695
21870
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22696
21871
  estimatedCostUsd: external_exports.number().nullable(),
22697
- // True whenever any rollup has a null cost (unknown provider/model), so the
22698
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21872
+ // True whenever any call priced to null (an unknown provider/model, or a call
21873
+ // over a long-context threshold whose rate is unpublished), so the total
21874
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22699
21875
  // precise figure rather than silently dropping the unpriced calls.
22700
21876
  costIsPartial: external_exports.boolean()
22701
21877
  });
@@ -23572,7 +22748,15 @@ var StorePostureSnapshot = external_exports.object({
23572
22748
  policyCounts: StorePosturePolicyCounts,
23573
22749
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23574
22750
  // getting its 200 without a payload change.
23575
- plugin: StorePosturePlugin.optional()
22751
+ plugin: StorePosturePlugin.optional(),
22752
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22753
+ // machine attachment omits it, so its body is byte for byte the one it
22754
+ // sent before this member existed. Absent therefore means machine-wide OR
22755
+ // a reporter older than this member, never "scoped". Both values parse, so
22756
+ // a sender that one day spells `machine` breaks no receiver; any other
22757
+ // value fails the whole snapshot, which is why the reporter sends a
22758
+ // constant and never the raw mode.
22759
+ attachmentMode: AttachmentMode.optional()
23576
22760
  }).meta({ id: "StorePostureSnapshot" });
23577
22761
  var CAPTURE_VERSION_PREFIX = "capture/";
23578
22762
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23849,7 +23033,19 @@ var EventMetadata = external_exports.object({
23849
23033
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23850
23034
  // Closing either means moving the reason onto the finding row, which
23851
23035
  // already carries its own action.
23852
- redactDegradedTo: ActionTaken.optional()
23036
+ redactDegradedTo: ActionTaken.optional(),
23037
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23038
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23039
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23040
+ // field instead of letting it through unscanned.
23041
+ //
23042
+ // - 'timeout': the bounded scan ran out of time.
23043
+ // - 'unavailable': no worker could run it.
23044
+ //
23045
+ // A refused row stores '' as its content and has no findings, which is
23046
+ // exactly what a clean, empty capture looks like — this marker is the only
23047
+ // thing that tells the two apart. Absent on every capture that was scanned.
23048
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23853
23049
  }).meta({ id: "EventMetadata" });
23854
23050
  var Event = external_exports.object({
23855
23051
  id: external_exports.guid(),
@@ -24019,7 +23215,7 @@ var Rule = external_exports.strictObject({
24019
23215
  postValidators: external_exports.array(PostValidatorRef).optional(),
24020
23216
  requiresNearby: RequiresNearby.optional(),
24021
23217
  examples: external_exports.array(external_exports.string()).optional(),
24022
- // Whether the matched text is itself sensitive. Absent means 'value'.
23218
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24023
23219
  evidence: RuleEvidence.optional()
24024
23220
  }).meta({ id: "Rule" });
24025
23221
  var Author = external_exports.object({
@@ -24111,7 +23307,13 @@ var DetectionRule = external_exports.object({
24111
23307
  // Representative matching strings the rule author shipped with the rule. The
24112
23308
  // cheapest honest answer to "show me what this rule catches" — every bundled
24113
23309
  // rule has them, and they are already in the stored snapshot.
24114
- examples: external_exports.array(external_exports.string()).optional()
23310
+ examples: external_exports.array(external_exports.string()).optional(),
23311
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23312
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23313
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23314
+ // in a value category (secret/pii/financial/phi) is always 'value',
23315
+ // whatever it declares.
23316
+ evidence: RuleEvidence.optional()
24115
23317
  }).meta({ id: "DetectionRule" });
24116
23318
  var DetectionUpdate = external_exports.object({
24117
23319
  available: external_exports.boolean(),
@@ -24179,8 +23381,10 @@ var ImportDetectionRequest = external_exports.object({
24179
23381
  }).meta({ id: "ImportDetectionRequest" });
24180
23382
 
24181
23383
  // ../../packages/schema/src/zod/detection-build.ts
24182
- function optional2(key, parsed2, raw) {
24183
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
23384
+ function optional2(key, raw, parse4) {
23385
+ if (raw === void 0) return {};
23386
+ const parsed2 = parse4(raw);
23387
+ if (!parsed2.success || parsed2.data === void 0) return {};
24184
23388
  return { [key]: parsed2.data };
24185
23389
  }
24186
23390
  function isStringArray(value) {
@@ -24215,10 +23419,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24215
23419
  category: r.category,
24216
23420
  severity: r.severity,
24217
23421
  matcher: parsed2.data,
24218
- // The rest of what decides whether this rule fires. Carried so a consumer
24219
- // re-running the rule (a preview, a tester) evaluates what the engine
24220
- // evaluates rather than a matcher stripped of its guards — half the
24221
- // bundled catalog carries at least one of these.
23422
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23423
+ // decides whether this rule fires. Carried so a consumer re-running the
23424
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23425
+ // than a matcher stripped of its guards — half the bundled catalog
23426
+ // carries at least one of these. `examples` and `evidence` describe the
23427
+ // rule and never gate a match.
24222
23428
  //
24223
23429
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24224
23430
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24228,18 +23434,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24228
23434
  // test should stay exactly what it was, namely a renderable matcher. A
24229
23435
  // field that fails validation is omitted, which reads as "not set" and is
24230
23436
  // the same thing the consumer saw before this change.
24231
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23437
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24232
23438
  ...optional2(
24233
23439
  "postValidators",
24234
- PostValidatorRef.array().safeParse(r.postValidators),
24235
- r.postValidators
23440
+ r.postValidators,
23441
+ (v) => PostValidatorRef.array().safeParse(v)
24236
23442
  ),
24237
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23443
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24238
23444
  ...optional2(
24239
23445
  "examples",
24240
- { success: isStringArray(r.examples), data: r.examples },
24241
- r.examples
24242
- )
23446
+ r.examples,
23447
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23448
+ ),
23449
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24243
23450
  }
24244
23451
  ];
24245
23452
  });
@@ -24932,11 +24139,14 @@ var PolicyBundle = external_exports.object({
24932
24139
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24933
24140
  // Model ids (the raw `model` string a harness reports, e.g.
24934
24141
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24935
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24936
- // one (UserPromptSubmit). Optional so an older backend — and an older
24937
- // on-disk cache — still parses; consumers read `?? []`, which is the
24938
- // unenforced behaviour that predates this field and the safe direction to
24939
- // default.
24142
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24143
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24144
+ // wherever the organization governs the event: everywhere on a
24145
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24146
+ // one (the plugin runtime's `governanceApplies`).
24147
+ // Optional so an older backend — and an older on-disk cache — still
24148
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24149
+ // predates this field and the safe direction to default.
24940
24150
  //
24941
24151
  // Ids, not display names: the governance decision is keyed on the exact
24942
24152
  // string the harness reports (`model_status_override.versionId` in the
@@ -25390,6 +24600,8 @@ var AttachmentScopeEntry = external_exports.object({
25390
24600
  });
25391
24601
  var AttachmentScope = external_exports.object({
25392
24602
  endpoint: external_exports.string().min(1),
24603
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24604
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25393
24605
  entries: external_exports.array(AttachmentScopeEntry)
25394
24606
  });
25395
24607
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25402,7 +24614,13 @@ function parseAttachmentScope(raw) {
25402
24614
  const entry = AttachmentScopeEntry.safeParse(candidate);
25403
24615
  if (entry.success) entries.push(entry.data);
25404
24616
  }
25405
- return { endpoint: envelope.data.endpoint, entries };
24617
+ const { endpoint, tenantName, userEmail } = envelope.data;
24618
+ return {
24619
+ endpoint,
24620
+ ...tenantName === void 0 ? {} : { tenantName },
24621
+ ...userEmail === void 0 ? {} : { userEmail },
24622
+ entries
24623
+ };
25406
24624
  } catch {
25407
24625
  return void 0;
25408
24626
  }
@@ -25639,6 +24857,7 @@ function toCaptureAttributes(event) {
25639
24857
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25640
24858
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25641
24859
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24860
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25642
24861
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25643
24862
  // has ever populated either), but every legacy metadata key still rides
25644
24863
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25767,6 +24986,27 @@ var ManagedSettings = external_exports.object({
25767
24986
  };
25768
24987
  }).meta({ id: "ManagedSettings" });
25769
24988
 
24989
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24990
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24991
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24992
+ var ModPolicySnapshot = external_exports.object({
24993
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24994
+ generatedAt: external_exports.iso.datetime(),
24995
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24996
+ // user's enabled installed packs (user-modified and custom packs included).
24997
+ // Absent means the store holds no authoritative snapshot, and the reader
24998
+ // scans with the packs it ships — the hook's own fallback.
24999
+ rules: external_exports.array(Rule).optional(),
25000
+ // Rule-targeted actions (first enabled policy per rule wins).
25001
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25002
+ // The resolved action per detection category.
25003
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25004
+ // Rules with an active exception grant. Honouring a grant means matching a
25005
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25006
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25007
+ exceptionRuleIds: external_exports.array(external_exports.string())
25008
+ }).meta({ id: "ModPolicySnapshot" });
25009
+
25770
25010
  // ../../packages/schema/src/zod/project-files.ts
25771
25011
  var ProjectFileInput = external_exports.object({
25772
25012
  path: external_exports.string().min(1),
@@ -26087,7 +25327,16 @@ var AttachInput = external_exports.object({
26087
25327
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26088
25328
  // renders a longer one usefully.
26089
25329
  label: printable(200).optional(),
26090
- accessKey: external_exports.string()
25330
+ accessKey: external_exports.string(),
25331
+ // How much of this machine the attachment is for: everything, or only the
25332
+ // repositories its user enrolls. Optional, so an input without it still
25333
+ // parses; what an absent mode means is for whatever reads it to decide, not
25334
+ // this shape. This member validates the VALUE rather than leaving that to the
25335
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25336
+ // rejection names the field, so a value that is not a mode is refused as a bad
25337
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25338
+ // it as the mode to attach in.
25339
+ mode: AttachmentMode.optional()
26091
25340
  });
26092
25341
 
26093
25342
  // ../../packages/schema/src/zod/triage.ts
@@ -26373,6 +25622,18 @@ function fromCaptureStatusAttributes(bag) {
26373
25622
  return parsedStatus.success ? parsedStatus.data : null;
26374
25623
  }
26375
25624
 
25625
+ // ../../packages/persistence/src/attached-derived.ts
25626
+ import { rmSync } from "fs";
25627
+ import { join } from "path";
25628
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25629
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25630
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
25631
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
25632
+
25633
+ // ../../packages/persistence/src/control-plane-credential.ts
25634
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25635
+ import { join as join2 } from "path";
25636
+
26376
25637
  // ../../packages/persistence/src/paths.ts
26377
25638
  import {
26378
25639
  chmodSync,
@@ -26499,6 +25760,14 @@ function repairOrRefuseMode(file2) {
26499
25760
  }
26500
25761
  return "ok";
26501
25762
  }
25763
+ function asReadableCredential(value) {
25764
+ const result = AttachedCredentialAny.safeParse(value);
25765
+ if (!result.success) return null;
25766
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25767
+ return null;
25768
+ }
25769
+ return result.data;
25770
+ }
26502
25771
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26503
25772
  const file2 = controlPlaneCredentialPath(settingsDir2);
26504
25773
  let raw;
@@ -26517,20 +25786,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26517
25786
  } catch {
26518
25787
  return { usable: false, reason: "malformed" };
26519
25788
  }
26520
- const result = AttachedCredential.safeParse(parsed2);
26521
- if (!result.success) return { usable: false, reason: "malformed" };
26522
- if (!isSafeEndpoint(result.data.endpoint)) {
25789
+ const credential = asReadableCredential(parsed2);
25790
+ if (credential === null) return { usable: false, reason: "malformed" };
25791
+ if (!isSafeEndpoint(credential.endpoint)) {
26523
25792
  return { usable: false, reason: "unsafe-endpoint" };
26524
25793
  }
26525
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25794
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26526
25795
  return {
26527
25796
  usable: false,
26528
25797
  reason: "endpoint-mismatch",
26529
- credentialEndpoint: result.data.endpoint,
25798
+ credentialEndpoint: credential.endpoint,
26530
25799
  settingsEndpoint: connection.endpoint
26531
25800
  };
26532
25801
  }
26533
- return { usable: true, credential: result.data };
25802
+ return { usable: true, credential };
26534
25803
  }
26535
25804
  function readControlPlaneCredential(settingsDir2, connection) {
26536
25805
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26539,7 +25808,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26539
25808
 
26540
25809
  // ../../packages/persistence/src/database.ts
26541
25810
  import { randomUUID as randomUUID11 } from "crypto";
26542
- import { dirname as dirname2, join as join7, sep } from "path";
25811
+ import { dirname as dirname2, join as join8, sep } from "path";
26543
25812
  import { DatabaseSync } from "node:sqlite";
26544
25813
 
26545
25814
  // ../../packages/persistence/src/ids.ts
@@ -26583,6 +25852,7 @@ function captureId(sessionId, contentHash, filePath = null) {
26583
25852
  canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
26584
25853
  );
26585
25854
  }
25855
+ var DOT = ".".charCodeAt(0);
26586
25856
 
26587
25857
  // ../../packages/persistence/src/internal/snapshot.ts
26588
25858
  import { randomUUID } from "crypto";
@@ -26910,6 +26180,25 @@ function scopeKeysParam(scopeKeys) {
26910
26180
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26911
26181
  FROM audit_events AS session_root
26912
26182
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26183
+ var COUNTED_IN_SCOPE = `
26184
+ AND ${inScope("scope_key")}
26185
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26186
+ var DRAIN_TOTALS = `SELECT
26187
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26188
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26189
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26190
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26191
+ THEN 1 ELSE 0 END) AS skipped,
26192
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26193
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26194
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26195
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26196
+ FROM audit_events
26197
+ WHERE event_type IN (${TYPE_LIST})`;
26198
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26199
+ FROM audit_events
26200
+ WHERE synced_at = ${String(SKIPPED)}
26201
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26913
26202
  var ROW_COLUMNS = `id,
26914
26203
  parent_id AS parentId,
26915
26204
  root_session_id AS rootSessionId,
@@ -26985,7 +26274,7 @@ var SqliteHistorySyncRepository = class {
26985
26274
  );
26986
26275
  this.scopedCaptureRowsStmt = db.prepare(
26987
26276
  `SELECT ${ROW_COLUMNS}
26988
- FROM audit_events
26277
+ FROM audit_events INDEXED BY idx_audit_scope_owed
26989
26278
  WHERE synced_at IS NULL
26990
26279
  AND sync_claimed_at IS NULL
26991
26280
  AND outbox_owed = 1
@@ -27038,40 +26327,28 @@ var SqliteHistorySyncRepository = class {
27038
26327
  );
27039
26328
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27040
26329
  FROM audit_events${COUNTED_SCOPE}`);
26330
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26331
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27041
26332
  this.partitionByKindStmt = db.prepare(
27042
26333
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27043
26334
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27044
26335
  GROUP BY event_type`
27045
26336
  );
27046
- this.countsStmt = db.prepare(
27047
- `SELECT
27048
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27049
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27050
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27051
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27052
- THEN 1 ELSE 0 END) AS skipped,
27053
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27054
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27055
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27056
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27057
- FROM audit_events
27058
- WHERE event_type IN (${TYPE_LIST})`
26337
+ this.scopedPartitionByKindStmt = db.prepare(
26338
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26339
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26340
+ GROUP BY event_type`
27059
26341
  );
27060
- this.captureSkipCountStmt = db.prepare(
27061
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27062
- // way the structural totals are. The split exists because a refusal is
27063
- // terminal only against the deployment that gave it, and the structural
27064
- // re-arm frees it on a change of deployment. The capture lane has no such
27065
- // escape: re-arming a capture would offer one deployment's undelivered
27066
- // prompts, with their text, to a deployment that never saw them, which is
27067
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27068
- // reasons mean the same thing — this row will not be sent — and splitting
27069
- // them would put refused captures in a bucket nothing reads and nothing
27070
- // frees.
27071
- `SELECT COUNT(*) AS skipped
27072
- FROM audit_events
27073
- WHERE synced_at = ${String(SKIPPED)}
27074
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26342
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26343
+ this.scopedCountsStmt = db.prepare(
26344
+ `${DRAIN_TOTALS}
26345
+ AND ${inScope("scope_key")}
26346
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26347
+ );
26348
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26349
+ this.scopedCaptureSkipCountStmt = db.prepare(
26350
+ `${CAPTURE_SKIPS}
26351
+ AND ${inScope("scope_key")}`
27075
26352
  );
27076
26353
  this.fingerprintStmt = db.prepare(
27077
26354
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27185,6 +26462,10 @@ var SqliteHistorySyncRepository = class {
27185
26462
  scopedCaptureRowsStmt;
27186
26463
  scopedCaptureBacklogOwedStmt;
27187
26464
  markScopeCapturesOwedStmt;
26465
+ scopedPartitionStmt;
26466
+ scopedPartitionByKindStmt;
26467
+ scopedCountsStmt;
26468
+ scopedCaptureSkipCountStmt;
27188
26469
  /**
27189
26470
  * The masked detections recorded against one tool call.
27190
26471
  *
@@ -27406,7 +26687,29 @@ var SqliteHistorySyncRepository = class {
27406
26687
  * in" — and a machine that has never attached has no boundary to pass, so
27407
26688
  * requiring one would force a caller to invent one and report the whole store
27408
26689
  * as queued.
26690
+ *
26691
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26692
+ * the rows that pass the drain's reachability rule for that scope
26693
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26694
+ * drain never offers), so a personal repository's rows are in none of them.
26695
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26696
+ * nothing.
27409
26697
  */
26698
+ partition(scopeKeys) {
26699
+ const row = getRow(
26700
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26701
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26702
+ );
26703
+ return {
26704
+ queued: row?.queued ?? 0,
26705
+ inProgress: row?.inProgress ?? 0,
26706
+ synced: row?.synced ?? 0,
26707
+ failed: row?.failed ?? 0,
26708
+ refused: row?.refused ?? 0,
26709
+ detached: row?.detached ?? 0,
26710
+ total: row?.total ?? 0
26711
+ };
26712
+ }
27410
26713
  /**
27411
26714
  * The same partition, one row per kind that a lane carries.
27412
26715
  *
@@ -27416,11 +26719,14 @@ var SqliteHistorySyncRepository = class {
27416
26719
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27417
26720
  * rows", never as "zero sent"; the two look identical in a bar and mean
27418
26721
  * different things.
26722
+ *
26723
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26724
+ * still sum to the scoped aggregate. An empty list returns no rows.
27419
26725
  */
27420
- partitionByKind() {
26726
+ partitionByKind(scopeKeys) {
27421
26727
  return allRows(
27422
- this.partitionByKindStmt,
27423
- {}
26728
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26729
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27424
26730
  ).map((row) => ({
27425
26731
  kind: row.kind,
27426
26732
  queued: row.queued ?? 0,
@@ -27432,22 +26738,25 @@ var SqliteHistorySyncRepository = class {
27432
26738
  total: row.total ?? 0
27433
26739
  }));
27434
26740
  }
27435
- partition() {
27436
- const row = getRow(this.partitionStmt, {});
27437
- return {
27438
- queued: row?.queued ?? 0,
27439
- inProgress: row?.inProgress ?? 0,
27440
- synced: row?.synced ?? 0,
27441
- failed: row?.failed ?? 0,
27442
- refused: row?.refused ?? 0,
27443
- detached: row?.detached ?? 0,
27444
- total: row?.total ?? 0
27445
- };
27446
- }
27447
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27448
- counts(before) {
27449
- const row = getRow(this.countsStmt, { before });
27450
- const captures = getRow(this.captureSkipCountStmt);
26741
+ /**
26742
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26743
+ * and skipped are totals.
26744
+ *
26745
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26746
+ * `capturesSkipped` included: a structural row is counted only when its own
26747
+ * key and its session root's key are among them, a capture when its own key
26748
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26749
+ * under the same keys and boundary. Omitted, this runs the machine
26750
+ * statements, unchanged; an empty list counts nothing.
26751
+ */
26752
+ counts(before, scopeKeys) {
26753
+ const row = getRow(
26754
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26755
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26756
+ );
26757
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26758
+ scopeKeys: scopeKeysParam(scopeKeys)
26759
+ });
27451
26760
  return {
27452
26761
  pending: row?.pending ?? 0,
27453
26762
  sent: row?.sent ?? 0,
@@ -27699,6 +27008,7 @@ function applyMigrations(db, file2, options = {}) {
27699
27008
  }
27700
27009
  ensureSyncedAtColumn(db, "audit_events");
27701
27010
  ensureScopeKeyColumn(db);
27011
+ ensureScopeOwedIndex(db);
27702
27012
  ensureScanLedgerTable(db);
27703
27013
  ensureHistorySyncTable(db);
27704
27014
  ensureBlockedDetectionsTable(db);
@@ -28139,14 +27449,48 @@ function ensureScopeKeyColumn(db) {
28139
27449
  function hasScopeKeyColumn(db) {
28140
27450
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28141
27451
  }
27452
+ 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";
27453
+ function ensureScopeOwedIndex(db) {
27454
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27455
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27456
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27457
+ if (!complete) return;
27458
+ db.exec(SCOPE_OWED_INDEX_DDL);
27459
+ }
28142
27460
  function ensureScanLedgerTable(db) {
28143
27461
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28144
27462
  path TEXT PRIMARY KEY,
28145
27463
  mtime TEXT NOT NULL,
28146
27464
  content_hash TEXT NOT NULL,
28147
27465
  ruleset_hash TEXT NOT NULL,
28148
- scanned_at INTEGER NOT NULL
27466
+ scanned_at INTEGER NOT NULL,
27467
+ scope_key TEXT,
27468
+ scope_root TEXT
28149
27469
  )`);
27470
+ ensureScanLedgerScopeKeyColumn(db);
27471
+ ensureScanLedgerScopeRootColumn(db);
27472
+ }
27473
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27474
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27475
+ function ensureScanLedgerScopeKeyColumn(db) {
27476
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27477
+ }
27478
+ function ensureScanLedgerScopeRootColumn(db) {
27479
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27480
+ }
27481
+ function ensureScanLedgerColumn(db, column, ddl) {
27482
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27483
+ if (hasScanLedgerColumn(db, column)) return;
27484
+ withTransaction(
27485
+ db,
27486
+ () => {
27487
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27488
+ },
27489
+ "IMMEDIATE"
27490
+ );
27491
+ }
27492
+ function hasScanLedgerColumn(db, column) {
27493
+ return columnNames(db, "scan_ledger").includes(column);
28150
27494
  }
28151
27495
  function ensureHistorySyncTable(db) {
28152
27496
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28197,6 +27541,106 @@ function ensureRuleProbeCacheTable(db) {
28197
27541
  )`);
28198
27542
  }
28199
27543
 
27544
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27545
+ import { createHash as createHash2 } from "crypto";
27546
+ import { readFileSync as readFileSync2 } from "fs";
27547
+ import { join as join4 } from "path";
27548
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27549
+ function modPolicySnapshotPath(dataDir2) {
27550
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27551
+ }
27552
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27553
+ const byRule = /* @__PURE__ */ new Map();
27554
+ const byCategory = /* @__PURE__ */ new Map();
27555
+ for (const policy of input2.policies) {
27556
+ if (!policy.enabled) continue;
27557
+ if ("ruleId" in policy.target) {
27558
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27559
+ } else if (!byCategory.has(policy.target.category)) {
27560
+ byCategory.set(policy.target.category, policy.action);
27561
+ }
27562
+ }
27563
+ const categoryActions = {};
27564
+ for (const category of DetectionCategory.options) {
27565
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27566
+ }
27567
+ return {
27568
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27569
+ generatedAt: generatedAt.toISOString(),
27570
+ // `examples` is documentation the mod never reads, and a custom pack's are
27571
+ // whatever its author pasted in, so they stay behind.
27572
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27573
+ ruleActions: Object.fromEntries(byRule),
27574
+ categoryActions,
27575
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27576
+ };
27577
+ }
27578
+ function assignedRuleActionPolicies(installed) {
27579
+ const out = [];
27580
+ for (const [ruleId, action] of installed.ruleActions) {
27581
+ if (installed.assignedRules.has(ruleId))
27582
+ out.push({ target: { ruleId }, action, enabled: true });
27583
+ }
27584
+ return out;
27585
+ }
27586
+ function withoutExamples(rule) {
27587
+ const copy = { ...rule };
27588
+ delete copy.examples;
27589
+ return copy;
27590
+ }
27591
+ function sameContent(a, b) {
27592
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27593
+ }
27594
+ function readModPolicySnapshot(dataDir2) {
27595
+ try {
27596
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27597
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27598
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27599
+ return parsed2.success ? parsed2.data : null;
27600
+ } catch {
27601
+ return null;
27602
+ }
27603
+ }
27604
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27605
+ const text = JSON.stringify(snapshot);
27606
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27607
+ const existing = readModPolicySnapshot(dataDir2);
27608
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27609
+ ensureDataDirSync(dataDir2);
27610
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27611
+ return true;
27612
+ }
27613
+ function regexProbeKey(matcher) {
27614
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27615
+ }
27616
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27617
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27618
+ return rules.filter((rule) => {
27619
+ if (rule.matcher.type !== "regex") return true;
27620
+ const key = regexProbeKey(rule.matcher);
27621
+ const verdict = sources.probeVerdict(key);
27622
+ if (verdict === "quarantined") return false;
27623
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27624
+ });
27625
+ }
27626
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27627
+ const policies = sources.readPolicies();
27628
+ const snapshot = sources.installedRuleset();
27629
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27630
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27631
+ return {
27632
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27633
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27634
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27635
+ };
27636
+ }
27637
+ function refreshModPolicySnapshot(dataDir2, sources) {
27638
+ try {
27639
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27640
+ } catch {
27641
+ }
27642
+ }
27643
+
28200
27644
  // ../../packages/persistence/src/internal/json.ts
28201
27645
  function safeJson(s, fallback) {
28202
27646
  if (s == null) return fallback;
@@ -28371,6 +27815,11 @@ var TIMELINE_COLUMNS = `
28371
27815
  json_extract(attributes, '$.targetId') AS target_id,
28372
27816
  json_extract(attributes, '$.internal') AS internal,
28373
27817
  json_extract(attributes, '$.flagged') AS flagged`;
27818
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27819
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27820
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27821
+ " + "
27822
+ );
28374
27823
  var LLM_USAGE_SELECT = `
28375
27824
  SELECT root_session_id AS sessionId,
28376
27825
  provider,
@@ -28382,9 +27831,10 @@ var LLM_USAGE_SELECT = `
28382
27831
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28383
27832
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28384
27833
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28385
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27834
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27835
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28386
27836
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28387
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27837
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28388
27838
  function usageLeaves(rows) {
28389
27839
  return rows.map((row) => {
28390
27840
  const attributes = {
@@ -28399,7 +27849,7 @@ function usageLeaves(rows) {
28399
27849
  if (row.provider !== null) attributes.provider = row.provider;
28400
27850
  if (row.model !== null) attributes.model = row.model;
28401
27851
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28402
- return { sessionId: row.sessionId, attributes };
27852
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28403
27853
  });
28404
27854
  }
28405
27855
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29733,9 +29183,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29733
29183
  AND conditions IS NULL
29734
29184
  AND ${ACTIVE_PREDICATE}`;
29735
29185
  var SqliteExceptionsRepository = class {
29736
- constructor(db, now = () => Date.now()) {
29186
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29737
29187
  this.db = db;
29738
29188
  this.now = now;
29189
+ this.onChange = onChange;
29739
29190
  this.consumeStmt = db.prepare(
29740
29191
  `UPDATE exceptions
29741
29192
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29754,6 +29205,7 @@ var SqliteExceptionsRepository = class {
29754
29205
  }
29755
29206
  db;
29756
29207
  now;
29208
+ onChange;
29757
29209
  consumeStmt;
29758
29210
  insertBlockedStmt;
29759
29211
  sweepBlockedStmt;
@@ -29769,7 +29221,9 @@ var SqliteExceptionsRepository = class {
29769
29221
  */
29770
29222
  create(input2) {
29771
29223
  try {
29772
- return Promise.resolve(this.createSync(input2));
29224
+ const created = this.createSync(input2);
29225
+ this.onChange();
29226
+ return Promise.resolve(created);
29773
29227
  } catch (err) {
29774
29228
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29775
29229
  }
@@ -29900,6 +29354,7 @@ var SqliteExceptionsRepository = class {
29900
29354
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29901
29355
  WHERE id = :id AND revoked_at IS NULL`
29902
29356
  ).run({ id, revokedBy, reason: reason ?? null, now });
29357
+ if (Number(result.changes) === 1) this.onChange();
29903
29358
  return Promise.resolve(Number(result.changes) === 1);
29904
29359
  }
29905
29360
  /**
@@ -29912,6 +29367,15 @@ var SqliteExceptionsRepository = class {
29912
29367
  const result = this.consumeStmt.run({ id, now });
29913
29368
  return Promise.resolve(Number(result.changes) === 1);
29914
29369
  }
29370
+ /** The rule ids with at least one active grant, under any key version. */
29371
+ activeRuleIds(now = this.now()) {
29372
+ return allRows(
29373
+ this.db.prepare(
29374
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29375
+ ),
29376
+ { now }
29377
+ ).map((row) => row.ruleId);
29378
+ }
29915
29379
  /**
29916
29380
  * The evaluation subset of every active grant under one fingerprint key
29917
29381
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31035,28 +30499,28 @@ var SqliteInspectionFindingsRepository = class {
31035
30499
  };
31036
30500
 
31037
30501
  // ../../packages/persistence/src/repositories/installed-packs.ts
31038
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30502
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31039
30503
 
31040
30504
  // ../../packages/persistence/src/policy-floor.ts
31041
- import { readFileSync as readFileSync5 } from "fs";
31042
- import { join as join6 } from "path";
30505
+ import { readFileSync as readFileSync6 } from "fs";
30506
+ import { join as join7 } from "path";
31043
30507
 
31044
30508
  // ../../packages/persistence/src/local-layout.ts
31045
30509
  import { renameSync as renameSync3 } from "fs";
31046
30510
  import { mkdir } from "fs/promises";
31047
30511
  import { homedir } from "os";
31048
- import { join as join4 } from "path";
30512
+ import { join as join5 } from "path";
31049
30513
  function defaultDataDir() {
31050
- return join4(homedir(), ".aka");
30514
+ return join5(homedir(), ".aka");
31051
30515
  }
31052
30516
  function settingsDir(base = defaultDataDir()) {
31053
- return join4(base, "settings");
30517
+ return join5(base, "settings");
31054
30518
  }
31055
30519
  function dataDir(base = defaultDataDir()) {
31056
- return join4(base, "data");
30520
+ return join5(base, "data");
31057
30521
  }
31058
30522
  function dbPath(base = defaultDataDir()) {
31059
- return join4(dataDir(base), "aka.db");
30523
+ return join5(dataDir(base), "aka.db");
31060
30524
  }
31061
30525
  async function ensureDataDir(dir = defaultDataDir()) {
31062
30526
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31073,8 +30537,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31073
30537
  for (const { name, dest } of moves) {
31074
30538
  try {
31075
30539
  ensureDataDirSync(dest);
31076
- const moved = join4(dest, name);
31077
- renameSync3(join4(base, name), moved);
30540
+ const moved = join5(dest, name);
30541
+ renameSync3(join5(base, name), moved);
31078
30542
  tightenFile(moved);
31079
30543
  } catch {
31080
30544
  }
@@ -31082,8 +30546,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31082
30546
  }
31083
30547
 
31084
30548
  // ../../packages/persistence/src/settings.ts
31085
- import { readFileSync as readFileSync4 } from "fs";
31086
- import { join as join5 } from "path";
30549
+ import { readFileSync as readFileSync5 } from "fs";
30550
+ import { join as join6 } from "path";
31087
30551
 
31088
30552
  // ../../packages/persistence/src/file-lock.ts
31089
30553
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31091,7 +30555,7 @@ import {
31091
30555
  closeSync,
31092
30556
  existsSync as existsSync2,
31093
30557
  openSync,
31094
- readFileSync as readFileSync2,
30558
+ readFileSync as readFileSync3,
31095
30559
  rmSync as rmSync5,
31096
30560
  statSync as statSync3,
31097
30561
  writeFileSync as writeFileSync2
@@ -31100,7 +30564,7 @@ import { hostname as hostname3 } from "os";
31100
30564
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31101
30565
 
31102
30566
  // ../../packages/persistence/src/managed-settings.ts
31103
- import { readFileSync as readFileSync3 } from "fs";
30567
+ import { readFileSync as readFileSync4 } from "fs";
31104
30568
  import { posix, win32 } from "path";
31105
30569
  function managedSettingsPaths(platform2 = process.platform) {
31106
30570
  if (platform2 === "darwin") {
@@ -31119,7 +30583,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31119
30583
  for (const path of paths) {
31120
30584
  let text;
31121
30585
  try {
31122
- text = readFileSync3(path, "utf8");
30586
+ text = readFileSync4(path, "utf8");
31123
30587
  } catch {
31124
30588
  continue;
31125
30589
  }
@@ -31173,7 +30637,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31173
30637
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31174
30638
  }
31175
30639
  function readUserSettings(base) {
31176
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30640
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31177
30641
  if (!record2) return defaultWorkspaceSettings();
31178
30642
  try {
31179
30643
  return WorkspaceSettings.parse(record2);
@@ -31184,7 +30648,7 @@ function readUserSettings(base) {
31184
30648
  function readJson(file2) {
31185
30649
  let text;
31186
30650
  try {
31187
- text = readFileSync4(file2, "utf8");
30651
+ text = readFileSync5(file2, "utf8");
31188
30652
  } catch {
31189
30653
  return null;
31190
30654
  }
@@ -31224,7 +30688,7 @@ var PolicyFloorError = class extends Error {
31224
30688
  };
31225
30689
  function readCachedPolicyBundle(base = defaultDataDir()) {
31226
30690
  try {
31227
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30691
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31228
30692
  const parsed2 = JSON.parse(raw);
31229
30693
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31230
30694
  return PolicyBundle.parse(parsed2.bundle);
@@ -31348,7 +30812,7 @@ function inventorySignature(packs2) {
31348
30812
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31349
30813
  }
31350
30814
  function hashRules(rulesJson) {
31351
- return createHash2("sha256").update(rulesJson).digest("hex");
30815
+ return createHash3("sha256").update(rulesJson).digest("hex");
31352
30816
  }
31353
30817
  function parseVersion(v) {
31354
30818
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31390,9 +30854,10 @@ var SqliteInstalledPacksRepository = class {
31390
30854
  * from `openLocalDatabase`, which is the single construction site that owns a
31391
30855
  * real `~/.aka`.
31392
30856
  */
31393
- constructor(db, baseDir) {
30857
+ constructor(db, baseDir, onChange = () => void 0) {
31394
30858
  this.db = db;
31395
30859
  this.baseDir = baseDir;
30860
+ this.onChange = onChange;
31396
30861
  this.insertMissingStmt = db.prepare(
31397
30862
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31398
30863
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31421,6 +30886,7 @@ var SqliteInstalledPacksRepository = class {
31421
30886
  }
31422
30887
  db;
31423
30888
  baseDir;
30889
+ onChange;
31424
30890
  insertMissingStmt;
31425
30891
  upsertAvailableStmt;
31426
30892
  signatureStmt;
@@ -31493,6 +30959,7 @@ var SqliteInstalledPacksRepository = class {
31493
30959
  },
31494
30960
  "IMMEDIATE"
31495
30961
  );
30962
+ this.onChange();
31496
30963
  } catch {
31497
30964
  }
31498
30965
  }
@@ -31567,6 +31034,7 @@ var SqliteInstalledPacksRepository = class {
31567
31034
  },
31568
31035
  "IMMEDIATE"
31569
31036
  );
31037
+ if (changed) this.onChange();
31570
31038
  return changed;
31571
31039
  }
31572
31040
  /**
@@ -31808,6 +31276,7 @@ var SqliteInstalledPacksRepository = class {
31808
31276
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31809
31277
  WHERE namespace = :namespace AND pack_id = :packId`
31810
31278
  ).run({ policyId, now: Date.now(), namespace, packId });
31279
+ if (Number(res.changes) > 0) this.onChange();
31811
31280
  return Number(res.changes) > 0;
31812
31281
  }
31813
31282
  /**
@@ -31832,6 +31301,7 @@ var SqliteInstalledPacksRepository = class {
31832
31301
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31833
31302
  WHERE namespace = :namespace AND pack_id = :packId`
31834
31303
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31304
+ if (Number(res.changes) > 0) this.onChange();
31835
31305
  return Number(res.changes) > 0;
31836
31306
  }
31837
31307
  // Fingerprint of the recorded available mirror — compared against the
@@ -32729,13 +32199,19 @@ var SqliteInventoryAssetsRepository = class {
32729
32199
  import { randomUUID as randomUUID6 } from "crypto";
32730
32200
  var SEED_BATCH_WINDOW_MS = 6e4;
32731
32201
  var SqlitePoliciesRepository = class {
32732
- constructor(db) {
32202
+ constructor(db, onChange = () => void 0) {
32733
32203
  this.db = db;
32204
+ this.onChange = onChange;
32734
32205
  }
32735
32206
  db;
32207
+ onChange;
32736
32208
  readPolicies() {
32209
+ return Promise.resolve(this.listPolicies());
32210
+ }
32211
+ /** The synchronous read behind {@link readPolicies}. */
32212
+ listPolicies() {
32737
32213
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32738
- const policies = mapRowsTolerant(rows, (row) => {
32214
+ return mapRowsTolerant(rows, (row) => {
32739
32215
  const target = JSON.parse(row.target);
32740
32216
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32741
32217
  return Policy.parse({
@@ -32747,7 +32223,6 @@ var SqlitePoliciesRepository = class {
32747
32223
  customKeywords
32748
32224
  });
32749
32225
  });
32750
- return Promise.resolve(policies);
32751
32226
  }
32752
32227
  // Seed one policy per bundled category at Monitor so the detection-type config
32753
32228
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32758,7 +32233,7 @@ var SqlitePoliciesRepository = class {
32758
32233
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32759
32234
  if (count > 0) {
32760
32235
  this.markEarlierChoices();
32761
- this.monitorUntouchedSeeds();
32236
+ if (this.monitorUntouchedSeeds()) this.onChange();
32762
32237
  return;
32763
32238
  }
32764
32239
  const stmt = this.db.prepare(
@@ -32775,6 +32250,7 @@ var SqlitePoliciesRepository = class {
32775
32250
  });
32776
32251
  }
32777
32252
  });
32253
+ this.onChange();
32778
32254
  }
32779
32255
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32780
32256
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32840,7 +32316,7 @@ var SqlitePoliciesRepository = class {
32840
32316
  ).filter(
32841
32317
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32842
32318
  );
32843
- if (untouched.length === 0) return;
32319
+ if (untouched.length === 0) return false;
32844
32320
  const stmt = this.db.prepare(
32845
32321
  `UPDATE policies SET action = 'log'
32846
32322
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32851,6 +32327,7 @@ var SqlitePoliciesRepository = class {
32851
32327
  stmt.run({ category: row.category, seeded: row.action });
32852
32328
  }
32853
32329
  });
32330
+ return true;
32854
32331
  }
32855
32332
  // Insert-or-update the single global per-category policy row, keyed on the
32856
32333
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32867,6 +32344,7 @@ var SqlitePoliciesRepository = class {
32867
32344
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32868
32345
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32869
32346
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32347
+ this.onChange();
32870
32348
  }
32871
32349
  // Caps every global per-category policy currently set to block/redact down
32872
32350
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32877,6 +32355,7 @@ var SqlitePoliciesRepository = class {
32877
32355
  WHERE scope='global' AND action IN ('block','redact')
32878
32356
  AND json_extract(target,'$.category') IS NOT NULL`
32879
32357
  ).run({ now: Date.now() });
32358
+ if (Number(info.changes) > 0) this.onChange();
32880
32359
  return Number(info.changes);
32881
32360
  }
32882
32361
  // Whether the category's row was ever written after it was created — by the
@@ -33196,31 +32675,45 @@ var SqliteScanLedgerRepository = class {
33196
32675
  constructor(db) {
33197
32676
  this.db = db;
33198
32677
  this.upsertStmt = db.prepare(
33199
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33200
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32678
+ `INSERT INTO scan_ledger
32679
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32680
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33201
32681
  ON CONFLICT (path) DO UPDATE SET
33202
32682
  mtime = excluded.mtime,
33203
32683
  content_hash = excluded.content_hash,
33204
32684
  ruleset_hash = excluded.ruleset_hash,
32685
+ scope_key = excluded.scope_key,
32686
+ scope_root = excluded.scope_root,
33205
32687
  scanned_at = excluded.scanned_at`
33206
32688
  );
33207
32689
  this.readStmt = db.prepare(
33208
- `SELECT path, mtime, content_hash AS contentHash
32690
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32691
+ scope_root AS scopeRoot
33209
32692
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33210
32693
  );
33211
32694
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32695
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33212
32696
  }
33213
32697
  db;
33214
32698
  upsertStmt;
33215
32699
  readStmt;
33216
32700
  pathsStmt;
32701
+ pathKeysStmt;
33217
32702
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33218
32703
  // older ruleset are simply absent, which reads as "never scanned".
33219
32704
  entriesForRuleset(rulesetHash) {
33220
- const rows = allRows(this.readStmt, {
33221
- rulesetHash
33222
- });
33223
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32705
+ const rows = allRows(this.readStmt, { rulesetHash });
32706
+ return new Map(
32707
+ rows.map((r) => [
32708
+ r.path,
32709
+ {
32710
+ mtime: r.mtime,
32711
+ contentHash: r.contentHash,
32712
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32713
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32714
+ }
32715
+ ])
32716
+ );
33224
32717
  }
33225
32718
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33226
32719
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33229,6 +32722,14 @@ var SqliteScanLedgerRepository = class {
33229
32722
  allPaths() {
33230
32723
  return allRows(this.pathsStmt).map((r) => r.path);
33231
32724
  }
32725
+ // Every ledgered path with the repository it was in when it was last read,
32726
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32727
+ // which repository a vanished file belonged to. `undefined` for a row with no
32728
+ // key, which is every row written before the column existed.
32729
+ pathKeys() {
32730
+ const rows = allRows(this.pathKeysStmt);
32731
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32732
+ }
33232
32733
  upsertEntries(entries) {
33233
32734
  if (entries.length === 0) return;
33234
32735
  const scannedAt = Date.now();
@@ -33239,6 +32740,8 @@ var SqliteScanLedgerRepository = class {
33239
32740
  mtime: entry.mtime,
33240
32741
  contentHash: entry.contentHash,
33241
32742
  rulesetHash: entry.rulesetHash,
32743
+ scopeKey: entry.scopeKey ?? null,
32744
+ scopeRoot: entry.scopeRoot ?? null,
33242
32745
  scannedAt
33243
32746
  });
33244
32747
  }
@@ -34326,6 +33829,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34326
33829
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34327
33830
  };
34328
33831
  }
33832
+ function withoutTrailingSlashes(path) {
33833
+ let end = path.length;
33834
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33835
+ return path.slice(0, end);
33836
+ }
34329
33837
  function toEndpointSummary(row) {
34330
33838
  return {
34331
33839
  id: row.id,
@@ -34613,7 +34121,7 @@ var SqliteSharesRepository = class {
34613
34121
  */
34614
34122
  reconcileCallSites(projectKey, reconcile) {
34615
34123
  if (reconcile.mode === "walk") {
34616
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
34124
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34617
34125
  this.db.prepare(
34618
34126
  `DELETE FROM share_call_site
34619
34127
  WHERE project_key = :key
@@ -35181,7 +34689,7 @@ function backupLegacyStore(db, file2) {
35181
34689
  discardStore(file2, backup);
35182
34690
  return backup;
35183
34691
  }
35184
- function openAndInitialize(file2, base, skipTags) {
34692
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35185
34693
  let db = openWithPragmas(file2);
35186
34694
  try {
35187
34695
  if (isForeignSqliteLineage(db)) {
@@ -35193,8 +34701,15 @@ function openAndInitialize(file2, base, skipTags) {
35193
34701
  }
35194
34702
  applyMigrations(db, file2, { skipTags });
35195
34703
  tightenPerms(file2);
35196
- const policies = new SqlitePoliciesRepository(db);
35197
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34704
+ const modPolicy = {};
34705
+ const onPolicyStateChange = () => {
34706
+ if (modPolicy.current !== void 0)
34707
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34708
+ };
34709
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34710
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34711
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34712
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35198
34713
  const repositories = {
35199
34714
  events: new SqliteEventsRepository(db),
35200
34715
  findings: new SqliteFindingsRepository(db),
@@ -35203,9 +34718,9 @@ function openAndInitialize(file2, base, skipTags) {
35203
34718
  scanLedger: new SqliteScanLedgerRepository(db),
35204
34719
  historySync: new SqliteHistorySyncRepository(db),
35205
34720
  secretVault: new SqliteSecretVaultRepository(db),
35206
- exceptions: new SqliteExceptionsRepository(db),
34721
+ exceptions,
35207
34722
  resolutions: new SqliteResolutionsRepository(db),
35208
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34723
+ ruleProbeCache,
35209
34724
  bodyRetention: new SqliteBodyRetentionRepository(db),
35210
34725
  security: new SqliteSecurityRepository(db),
35211
34726
  detections: new SqliteDetectionsRepository(db),
@@ -35223,6 +34738,13 @@ function openAndInitialize(file2, base, skipTags) {
35223
34738
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35224
34739
  configInventory: new SqliteConfigInventoryRepository(db)
35225
34740
  };
34741
+ modPolicy.current = {
34742
+ installedRuleset: () => installedPacks.installedRuleset(),
34743
+ readPolicies: () => policies.listPolicies(),
34744
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34745
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34746
+ bundledRegexMatchers: () => shippedRegexMatchers2
34747
+ };
35226
34748
  policies.seedDefaults();
35227
34749
  return { db, ...repositories };
35228
34750
  } catch (err) {
@@ -35234,7 +34756,7 @@ function openAndInitialize(file2, base, skipTags) {
35234
34756
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35235
34757
  function openLocalDatabase(dir, options = {}) {
35236
34758
  ensureDataDirSync(dir);
35237
- const file2 = join7(dir, DB_FILENAME);
34759
+ const file2 = join8(dir, DB_FILENAME);
35238
34760
  reapStalePartials(file2);
35239
34761
  const {
35240
34762
  db,
@@ -35270,7 +34792,8 @@ function openLocalDatabase(dir, options = {}) {
35270
34792
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35271
34793
  // settings/ and data/, and the pack-policy floor needs both halves.
35272
34794
  dirname2(dir),
35273
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34795
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34796
+ options.shippedRegexMatchers ?? []
35274
34797
  );
35275
34798
  function captureRowId(event) {
35276
34799
  return captureId(
@@ -35535,7 +35058,7 @@ function openLocalDatabase(dir, options = {}) {
35535
35058
  }
35536
35059
 
35537
35060
  // ../../packages/persistence/src/egress-wire.ts
35538
- import { createHash as createHash3 } from "crypto";
35061
+ import { createHash as createHash4 } from "crypto";
35539
35062
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35540
35063
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35541
35064
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35567,7 +35090,7 @@ function canonicalGitUrl(url2) {
35567
35090
  }
35568
35091
  function hashProjectKey(projectKey) {
35569
35092
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35570
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35093
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35571
35094
  }
35572
35095
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35573
35096
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35632,17 +35155,16 @@ function toEgressIngestRequest(input2) {
35632
35155
  }
35633
35156
 
35634
35157
  // ../../packages/persistence/src/finding-key.ts
35635
- import { createHash as createHash4 } from "crypto";
35158
+ import { createHash as createHash5 } from "crypto";
35636
35159
 
35637
35160
  // ../../packages/persistence/src/fingerprint.ts
35638
35161
  import { createHmac, randomBytes } from "crypto";
35639
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35640
- import { join as join8 } from "path";
35641
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35162
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
35163
+ import { join as join9 } from "path";
35642
35164
  var EXCEPTION_KEY_FILENAME = "exception.key";
35643
35165
  var KEY_MATERIAL_BYTES = 32;
35644
35166
  function keyFilePath(dataDir2) {
35645
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
35167
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35646
35168
  }
35647
35169
  function parseKeyFile(raw) {
35648
35170
  const parsed2 = JSON.parse(raw);
@@ -35665,7 +35187,7 @@ function parseKeyFile(raw) {
35665
35187
  function readFingerprintKey(dataDir2) {
35666
35188
  let raw;
35667
35189
  try {
35668
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
35190
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35669
35191
  } catch (err) {
35670
35192
  if (err.code === "ENOENT") return null;
35671
35193
  throw err instanceof Error ? err : new Error(String(err));
@@ -35674,8 +35196,8 @@ function readFingerprintKey(dataDir2) {
35674
35196
  }
35675
35197
 
35676
35198
  // ../../packages/persistence/src/forward-health.ts
35677
- import { readFileSync as readFileSync7 } from "fs";
35678
- import { join as join9 } from "path";
35199
+ import { readFileSync as readFileSync8 } from "fs";
35200
+ import { join as join10 } from "path";
35679
35201
  var BREAKER_COOLDOWN_MS = 3e4;
35680
35202
  function parseForwardHealth(raw, nowMs) {
35681
35203
  try {
@@ -35699,20 +35221,21 @@ function isForwardPaused(health, nowMs) {
35699
35221
 
35700
35222
  // ../../packages/persistence/src/history-backfill.ts
35701
35223
  import { existsSync as existsSync4 } from "fs";
35702
- import { join as join10 } from "path";
35224
+ import { join as join11 } from "path";
35703
35225
 
35704
35226
  // ../../packages/persistence/src/history-preview.ts
35705
35227
  import { existsSync as existsSync5 } from "fs";
35706
- import { join as join11 } from "path";
35707
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
35228
+ import { join as join12 } from "path";
35229
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35708
35230
 
35709
35231
  // ../../packages/persistence/src/history-sync-state.ts
35710
- import { readFileSync as readFileSync8 } from "fs";
35711
- import { join as join12 } from "path";
35232
+ import { readFileSync as readFileSync9 } from "fs";
35233
+ import { join as join13 } from "path";
35234
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35712
35235
 
35713
35236
  // ../../packages/persistence/src/store-symlinks.ts
35714
35237
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35715
- import { dirname as dirname3, join as join13, resolve } from "path";
35238
+ import { dirname as dirname3, join as join14, resolve } from "path";
35716
35239
 
35717
35240
  // ../../packages/persistence/src/vault/crypto.ts
35718
35241
  import {
@@ -35726,19 +35249,19 @@ import {
35726
35249
  // ../../packages/persistence/src/vault/key-provider.ts
35727
35250
  import { execFileSync } from "child_process";
35728
35251
  import { randomBytes as randomBytes2 } from "crypto";
35729
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35730
- import { join as join14 } from "path";
35252
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35253
+ import { join as join15 } from "path";
35731
35254
 
35732
35255
  // ../../packages/persistence/src/vault/vault.ts
35733
35256
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35734
35257
 
35735
35258
  // ../../packages/persistence/src/warn-era-cap.ts
35736
35259
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35737
- import { join as join15 } from "path";
35260
+ import { join as join16 } from "path";
35738
35261
  var MARKER = "warn-era-capped";
35739
35262
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35740
35263
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35741
- const marker = join15(dataDir2, MARKER);
35264
+ const marker = join16(dataDir2, MARKER);
35742
35265
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35743
35266
  const capped = db.policies.capCategoryActions();
35744
35267
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35798,7 +35321,7 @@ function resolveProvider() {
35798
35321
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
35799
35322
  try {
35800
35323
  ensureLayoutDirSync(base);
35801
- const settingsFile = join16(settingsDir(base), "settings.json");
35324
+ const settingsFile = join17(settingsDir(base), "settings.json");
35802
35325
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
35803
35326
  } catch {
35804
35327
  }
@@ -35821,11 +35344,6 @@ function resolveProviderSafe(resolveProviderFn) {
35821
35344
  }
35822
35345
  }
35823
35346
 
35824
- // ../../packages/plugin-sdk/src/config-inventory.ts
35825
- import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
35826
- import { homedir as homedir2 } from "os";
35827
- import { basename as basename3, join as join18 } from "path";
35828
-
35829
35347
  // ../../packages/detections/src/egress/registry.ts
35830
35348
  var EXTRACTOR_VERSION = "3";
35831
35349
  var PROVIDER_REGISTRY = [
@@ -36936,17 +36454,18 @@ function ruleEvidence(rule) {
36936
36454
 
36937
36455
  // ../../packages/detections/src/mask.ts
36938
36456
  function maskMatch(raw) {
36939
- if (raw.length <= 5) return "***";
36940
- const atIndex = raw.indexOf("@");
36941
- if (atIndex > 0 && atIndex < raw.length - 1) {
36942
- const domain2 = raw.slice(atIndex + 1);
36457
+ const visible = stripInvisiblePadding(raw);
36458
+ if (visible.length <= 5) return "***";
36459
+ const atIndex = visible.indexOf("@");
36460
+ if (atIndex > 0 && atIndex < visible.length - 1) {
36461
+ const domain2 = visible.slice(atIndex + 1);
36943
36462
  if (domain2.includes(".")) {
36944
- const local = raw.slice(0, atIndex);
36463
+ const local = visible.slice(0, atIndex);
36945
36464
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
36946
36465
  return `${maskedLocal}@${domain2}`;
36947
36466
  }
36948
36467
  }
36949
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
36468
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
36950
36469
  }
36951
36470
 
36952
36471
  // ../../packages/detections/src/pointer-shield.ts
@@ -37101,6 +36620,38 @@ var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].m
37101
36620
  );
37102
36621
  var CPU_CORROBORATION_SHARE = 0.2;
37103
36622
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36623
+ function repeatTo(unit, length) {
36624
+ return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
36625
+ }
36626
+ function joinTo(length, open3, close, item) {
36627
+ const parts = [];
36628
+ let size = open3.length;
36629
+ for (let i = 0; size < length; i++) {
36630
+ const next = (i === 0 ? "" : ",") + item(i);
36631
+ parts.push(next);
36632
+ size += next.length;
36633
+ }
36634
+ return (open3 + parts.join("") + close).slice(0, length);
36635
+ }
36636
+ var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
36637
+ var GROWTH_CORPORA = [
36638
+ {
36639
+ name: "one-line JSON dictionary",
36640
+ build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
36641
+ },
36642
+ {
36643
+ name: "JSON array of quoted SQL keywords",
36644
+ build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
36645
+ },
36646
+ { name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
36647
+ { name: "double-quote run", build: (length) => repeatTo('"', length) },
36648
+ { name: "space run", build: (length) => repeatTo(" ", length) },
36649
+ { name: "newline run", build: (length) => repeatTo("\n", length) },
36650
+ ...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
36651
+ name: `unit run ${JSON.stringify(unit)}`,
36652
+ build: (length) => repeatTo(unit, length)
36653
+ }))
36654
+ ];
37104
36655
 
37105
36656
  // ../../packages/plugin-sdk/src/raw-egress.ts
37106
36657
  var RawEgressError = class extends Error {
@@ -37121,7 +36672,12 @@ var MIN_RAW_LEN = 4;
37121
36672
  var RAW_RUN_LEN = 8;
37122
36673
  function carriesRawRun(text, rawValues) {
37123
36674
  let windows = null;
37124
- for (const raw of new Set(rawValues)) {
36675
+ const values = /* @__PURE__ */ new Set();
36676
+ for (const raw of rawValues) {
36677
+ values.add(raw);
36678
+ values.add(stripInvisiblePadding(raw));
36679
+ }
36680
+ for (const raw of values) {
37125
36681
  if (raw.length < MIN_RAW_LEN) continue;
37126
36682
  if (raw.length < RAW_RUN_LEN) {
37127
36683
  if (text.includes(raw)) return true;
@@ -37145,11 +36701,16 @@ function carriesRawRun(text, rawValues) {
37145
36701
  return false;
37146
36702
  }
37147
36703
  function safeMaskedMatch(rawMatch) {
37148
- const masked = maskMatch(rawMatch);
37149
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37150
- return "***";
36704
+ const visible = stripInvisiblePadding(rawMatch);
36705
+ const masked = maskMatch(visible);
36706
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
36707
+ if (!reveals(masked)) return masked;
36708
+ const atIndex = masked.indexOf("@");
36709
+ if (atIndex > 0 && atIndex < masked.length - 1) {
36710
+ const emailFallback = `*${masked.slice(atIndex)}`;
36711
+ if (!reveals(emailFallback)) return emailFallback;
37151
36712
  }
37152
- return masked;
36713
+ return "***";
37153
36714
  }
37154
36715
  function assertRawFree(text, rawValues) {
37155
36716
  if (carriesRawRun(text, rawValues)) {
@@ -37386,7 +36947,7 @@ var auth_jwt_no_verify_default = {
37386
36947
  severity: "critical",
37387
36948
  matcher: {
37388
36949
  type: "regex",
37389
- pattern: "(verify\\s*=\\s*false|verify_signature.*false|algorithms\\s*=\\s*\\[\\])",
36950
+ pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
37390
36951
  flags: "gi"
37391
36952
  },
37392
36953
  requiresNearby: {
@@ -37474,7 +37035,7 @@ var cmd_inject_shell_default = {
37474
37035
  severity: "critical",
37475
37036
  matcher: {
37476
37037
  type: "regex",
37477
- pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
37038
+ pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
37478
37039
  flags: "gi"
37479
37040
  },
37480
37041
  requiresNearby: {
@@ -37603,7 +37164,7 @@ var deser_yaml_unsafe_default = {
37603
37164
  severity: "high",
37604
37165
  matcher: {
37605
37166
  type: "regex",
37606
- pattern: "\\byaml\\.load\\s*\\((?![^)]*SafeLoader|[^)]*safe_load)",
37167
+ pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
37607
37168
  flags: "gi"
37608
37169
  },
37609
37170
  examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
@@ -37820,7 +37381,7 @@ var sql_inject_concat_dot_default = {
37820
37381
  severity: "high",
37821
37382
  matcher: {
37822
37383
  type: "regex",
37823
- pattern: `["'][^\\n]*?(select|insert|update|delete|drop|where)[^\\n]*?["']\\s*\\.`,
37384
+ pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
37824
37385
  flags: "gi"
37825
37386
  },
37826
37387
  appliesTo: {
@@ -37838,7 +37399,7 @@ var sql_inject_concat_default = {
37838
37399
  severity: "high",
37839
37400
  matcher: {
37840
37401
  type: "regex",
37841
- pattern: `["']\\s*(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?["']\\s*\\+`,
37402
+ pattern: `(["'])\\s*(?=(select\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?=))\\2(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?["']\\s*\\+`,
37842
37403
  flags: "gi"
37843
37404
  },
37844
37405
  examples: ['"SELECT * FROM users WHERE id = " + userId']
@@ -37853,7 +37414,7 @@ var sql_inject_format_default = {
37853
37414
  severity: "high",
37854
37415
  matcher: {
37855
37416
  type: "regex",
37856
- pattern: "\\b(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?(?:[%][sd]|\\{[^}]+\\})",
37417
+ pattern: "\\b(?=(select\\b(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))\\1(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})|\\b(?=(where\\b(?:(?!\\bwhere\\b)[^\\n])*?=))\\2(?:(?!\\bwhere\\b)[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})",
37857
37418
  flags: "gi"
37858
37419
  },
37859
37420
  examples: [
@@ -37871,7 +37432,7 @@ var sql_inject_interp_default = {
37871
37432
  severity: "high",
37872
37433
  matcher: {
37873
37434
  type: "regex",
37874
- pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
37435
+ pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
37875
37436
  flags: "gi"
37876
37437
  },
37877
37438
  examples: [
@@ -38246,7 +37807,7 @@ var stack_trace_default = {
38246
37807
  severity: "low",
38247
37808
  matcher: {
38248
37809
  type: "regex",
38249
- pattern: "(?:^|\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
37810
+ pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38250
37811
  flags: "g"
38251
37812
  },
38252
37813
  examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
@@ -39404,7 +38965,7 @@ var BUNDLED_PACKS = [
39404
38965
  {
39405
38966
  packId: "code-flaws",
39406
38967
  name: "Code Security Flaws",
39407
- version: "0.1.0",
38968
+ version: "0.1.1",
39408
38969
  rawRules: [
39409
38970
  sql_inject_concat_default,
39410
38971
  sql_inject_concat_dot_default,
@@ -39454,7 +39015,7 @@ var BUNDLED_PACKS = [
39454
39015
  {
39455
39016
  packId: "core-code-context",
39456
39017
  name: "Code Context",
39457
- version: "0.2.1",
39018
+ version: "0.2.2",
39458
39019
  rawRules: [
39459
39020
  internal_ip_default,
39460
39021
  localhost_ref_default,
@@ -39591,6 +39152,11 @@ function bundledDetections() {
39591
39152
  }));
39592
39153
  return cachedDetections;
39593
39154
  }
39155
+ function shippedRegexMatchers() {
39156
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
39157
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
39158
+ );
39159
+ }
39594
39160
 
39595
39161
  // ../../packages/plugin-sdk/src/mask.ts
39596
39162
  var packsReady = false;
@@ -39643,8 +39209,8 @@ function scanText(text, ruleVersions, options = {}) {
39643
39209
  }
39644
39210
 
39645
39211
  // ../../packages/plugin-sdk/src/repo.ts
39646
- import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
39647
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
39212
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
39213
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
39648
39214
  function resolveRepoIdentity(cwd) {
39649
39215
  try {
39650
39216
  const location = locateRepo(cwd);
@@ -39663,8 +39229,9 @@ function resolveRepoIdentity(cwd) {
39663
39229
  var ATTRIBUTION_MEMO_LIMIT = 64;
39664
39230
  var attributionMemo = /* @__PURE__ */ new Map();
39665
39231
  var NO_ATTRIBUTION = Object.freeze({});
39666
- function resolveRepoAttribution(cwd) {
39232
+ function resolveRepoAttribution(cwd, options) {
39667
39233
  try {
39234
+ if (options?.cache === false) return attributeRepo(cwd);
39668
39235
  const remembered = attributionMemo.get(cwd);
39669
39236
  if (remembered !== void 0) return remembered;
39670
39237
  const attribution = attributeRepo(cwd);
@@ -39688,36 +39255,36 @@ function attributeRepo(cwd) {
39688
39255
  function findGitRoot(start) {
39689
39256
  let dir = start;
39690
39257
  for (; ; ) {
39691
- if (existsSync9(join17(dir, ".git"))) return dir;
39258
+ if (existsSync9(join18(dir, ".git"))) return dir;
39692
39259
  const parent = dirname4(dir);
39693
39260
  if (parent === dir) return void 0;
39694
39261
  dir = parent;
39695
39262
  }
39696
39263
  }
39697
39264
  function resolveGitContext(root) {
39698
- const dotGit = join17(root, ".git");
39265
+ const dotGit = join18(root, ".git");
39699
39266
  try {
39700
39267
  if (statSync6(dotGit).isDirectory()) {
39701
- return { configPath: join17(dotGit, "config"), headRoot: root };
39268
+ return { configPath: join18(dotGit, "config"), headRoot: root };
39702
39269
  }
39703
39270
  } catch {
39704
39271
  return void 0;
39705
39272
  }
39706
39273
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
39707
39274
  if (!target) return void 0;
39708
- const gitdir = isAbsolute(target) ? target : join17(root, target);
39709
- if (existsSync9(join17(gitdir, "config"))) {
39710
- return { configPath: join17(gitdir, "config"), headRoot: root };
39275
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
39276
+ if (existsSync9(join18(gitdir, "config"))) {
39277
+ return { configPath: join18(gitdir, "config"), headRoot: root };
39711
39278
  }
39712
- const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
39279
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
39713
39280
  if (!commonRaw) return void 0;
39714
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
39281
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
39715
39282
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
39716
- return { configPath: join17(commonGitDir, "config"), headRoot };
39283
+ return { configPath: join18(commonGitDir, "config"), headRoot };
39717
39284
  }
39718
39285
  function safeRead(path) {
39719
39286
  try {
39720
- return readFileSync10(path, "utf8");
39287
+ return readFileSync11(path, "utf8");
39721
39288
  } catch {
39722
39289
  return void 0;
39723
39290
  }
@@ -39763,68 +39330,6 @@ function slugFromUrl(url2) {
39763
39330
  return segment && segment.length > 0 ? segment : void 0;
39764
39331
  }
39765
39332
 
39766
- // ../../packages/plugin-sdk/src/events.ts
39767
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39768
-
39769
- // ../../packages/plugin-sdk/src/isolated-scan.ts
39770
- import { existsSync as existsSync10 } from "fs";
39771
- import { fileURLToPath } from "url";
39772
- import { Worker } from "worker_threads";
39773
-
39774
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
39775
- import { readFileSync as readFileSync12 } from "fs";
39776
- import { join as join19 } from "path";
39777
-
39778
- // ../../packages/plugin-sdk/src/host-floor.ts
39779
- import { readFileSync as readFileSync14 } from "fs";
39780
- import { join as join21 } from "path";
39781
-
39782
- // ../../packages/plugin-sdk/src/model-governance.ts
39783
- import {
39784
- closeSync as closeSync2,
39785
- fstatSync,
39786
- mkdirSync as mkdirSync2,
39787
- openSync as openSync2,
39788
- readFileSync as readFileSync13,
39789
- readSync,
39790
- writeFileSync as writeFileSync5
39791
- } from "fs";
39792
- import { join as join20 } from "path";
39793
- var TAIL_BYTES = 256 * 1024;
39794
-
39795
- // ../../packages/plugin-sdk/src/host-floor.ts
39796
- var HOST_FEATURE = {
39797
- ModelSwitch: "model-switch",
39798
- VaultPointerDisplay: "vault-pointer-display"
39799
- };
39800
- var HOST_FLOORS = {
39801
- [HOST_FEATURE.ModelSwitch]: {
39802
- label: "model-switch protection",
39803
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
39804
- since: "2.1.251"
39805
- },
39806
- [HOST_FEATURE.VaultPointerDisplay]: {
39807
- label: "vault pointer display",
39808
- hookEvents: ["MessageDisplay"],
39809
- since: "2.1.152"
39810
- }
39811
- };
39812
- var ANTIGRAVITY_HOST_FEATURE = {
39813
- EndOfTurnCapture: "end-of-turn-capture"
39814
- };
39815
- var ANTIGRAVITY_HOST_FLOORS = {
39816
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
39817
- label: "end-of-turn history capture",
39818
- hookEvents: ["Stop"],
39819
- since: "1.1.10"
39820
- }
39821
- };
39822
-
39823
- // ../../packages/plugin-sdk/src/ignore-layers.ts
39824
- var import_ignore = __toESM(require_ignore(), 1);
39825
- import { readFileSync as readFileSync15 } from "fs";
39826
- import { join as join22 } from "path";
39827
-
39828
39333
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
39829
39334
  import { arch, hostname as hostname4, platform, release } from "os";
39830
39335
  function resolveInventoryContext(input2) {
@@ -39854,55 +39359,17 @@ function resolveInventoryContext(input2) {
39854
39359
  return ctx;
39855
39360
  }
39856
39361
 
39857
- // ../../packages/plugin-sdk/src/nudge.ts
39858
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
39859
- import { join as join23 } from "path";
39860
-
39861
- // ../../packages/plugin-sdk/src/paths.ts
39862
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
39863
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
39864
-
39865
39362
  // ../../packages/plugin-sdk/src/policy-resolver.ts
39866
- import { randomUUID as randomUUID14 } from "crypto";
39363
+ import { randomUUID as randomUUID13 } from "crypto";
39867
39364
  function assignedRulePolicies(installed) {
39868
39365
  const out = [];
39869
39366
  for (const [ruleId, action] of installed.ruleActions) {
39870
39367
  if (installed.assignedRules && !installed.assignedRules.has(ruleId)) continue;
39871
- out.push({ id: randomUUID14(), scope: "global", target: { ruleId }, action, enabled: true });
39368
+ out.push({ id: randomUUID13(), scope: "global", target: { ruleId }, action, enabled: true });
39872
39369
  }
39873
39370
  return out;
39874
39371
  }
39875
39372
 
39876
- // ../../packages/plugin-sdk/src/project-files.ts
39877
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
39878
- import { basename as basename5, join as join24 } from "path";
39879
-
39880
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
39881
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
39882
- if (typeof v === "string" && v.trim() === "") return void 0;
39883
- return v;
39884
- }, external_exports.string().optional()).catch(void 0);
39885
- var optionalFlag = external_exports.preprocess((v) => {
39886
- if (typeof v !== "string") return false;
39887
- const normalized = v.trim().toLowerCase();
39888
- return normalized !== "" && normalized !== "0" && normalized !== "false";
39889
- }, external_exports.boolean()).catch(false);
39890
- var antigravityProviderEnvShape = {
39891
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
39892
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
39893
- };
39894
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
39895
-
39896
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
39897
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
39898
- if (typeof v === "string" && v.trim() === "") return void 0;
39899
- return v;
39900
- }, external_exports.string().optional()).catch(void 0);
39901
- var codexProviderEnvShape = {
39902
- OPENAI_BASE_URL: optionalBaseUrl3
39903
- };
39904
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
39905
-
39906
39373
  // ../../packages/plugin-sdk/src/provider-codex.ts
39907
39374
  function codexProviderFromModelId(modelId) {
39908
39375
  const id = modelId.trim();
@@ -39913,12 +39380,9 @@ function codexProviderFromModelId(modelId) {
39913
39380
  return "unknown";
39914
39381
  }
39915
39382
 
39916
- // ../../packages/plugin-sdk/src/runtime.ts
39917
- import { randomUUID as randomUUID15 } from "crypto";
39918
-
39919
39383
  // ../../packages/plugin-sdk/src/scope-key.ts
39920
- import { existsSync as existsSync12 } from "fs";
39921
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join25, normalize } from "path";
39384
+ import { existsSync as existsSync10 } from "fs";
39385
+ import { dirname as dirname5, isAbsolute as isAbsolute2, join as join19, normalize } from "path";
39922
39386
  function scopeKeyMemo() {
39923
39387
  const memo2 = /* @__PURE__ */ new Map();
39924
39388
  return (cwd) => {
@@ -39935,8 +39399,8 @@ function sessionRootScopeKey(cwd) {
39935
39399
  function toolCallScopeKey(tc, scopeKeyOf2) {
39936
39400
  if (tc.keyless === true) return void 0;
39937
39401
  if (tc.filePaths === void 0 && tc.searchRoot === void 0) return scopeKeyOf2(tc.cwd);
39938
- const resolved = (path) => isAbsolute2(path) ? normalize(path) : join25(tc.cwd ?? "", path);
39939
- const walkStart = (path) => isAbsolute2(path) && existsSync12(join25(path, ".git")) ? path : dirname6(path);
39402
+ const resolved = (path) => isAbsolute2(path) ? normalize(path) : join19(tc.cwd ?? "", path);
39403
+ const walkStart = (path) => isAbsolute2(path) && existsSync10(join19(path, ".git")) ? path : dirname5(path);
39940
39404
  const locations = [
39941
39405
  ...(tc.filePaths ?? []).map((path) => walkStart(resolved(path))),
39942
39406
  ...tc.searchRoot === void 0 ? [] : [resolved(tc.searchRoot)]
@@ -39950,13 +39414,6 @@ function toolCallScopeKey(tc, scopeKeyOf2) {
39950
39414
  return agreed;
39951
39415
  }
39952
39416
 
39953
- // ../../packages/plugin-sdk/src/suppressions.ts
39954
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
39955
-
39956
- // ../../packages/plugin-sdk/src/throttle.ts
39957
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
39958
- import { join as join26 } from "path";
39959
-
39960
39417
  // ../../packages/remote/src/http.ts
39961
39418
  import { request as httpRequest } from "http";
39962
39419
  import { request as httpsRequest } from "https";
@@ -40333,11 +39790,11 @@ function withTimeout(promise2, ms) {
40333
39790
  }
40334
39791
 
40335
39792
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
40336
- import { readFileSync as readFileSync17 } from "fs";
40337
- import { join as join27 } from "path";
39793
+ import { readFileSync as readFileSync12 } from "fs";
39794
+ import { join as join20 } from "path";
40338
39795
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
40339
39796
  function forwardDropsPath(dataDir2) {
40340
- return join27(dataDir2, FORWARD_DROPS_FILENAME);
39797
+ return join20(dataDir2, FORWARD_DROPS_FILENAME);
40341
39798
  }
40342
39799
  function recordForwardDrops(dataDir2, count, nowMs) {
40343
39800
  if (count <= 0) return;
@@ -40355,7 +39812,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
40355
39812
  }
40356
39813
  function readForwardDrops(dataDir2) {
40357
39814
  try {
40358
- const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
39815
+ const parsed2 = JSON.parse(readFileSync12(forwardDropsPath(dataDir2), "utf8"));
40359
39816
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
40360
39817
  const record2 = parsed2;
40361
39818
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -40372,9 +39829,9 @@ function readForwardDrops(dataDir2) {
40372
39829
  }
40373
39830
 
40374
39831
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
40375
- import { randomUUID as randomUUID16 } from "crypto";
39832
+ import { randomUUID as randomUUID14 } from "crypto";
40376
39833
  import { readFile, rename, writeFile } from "fs/promises";
40377
- import { join as join28 } from "path";
39834
+ import { join as join21 } from "path";
40378
39835
  function isInvalidRequest(err) {
40379
39836
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
40380
39837
  }
@@ -40393,7 +39850,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
40393
39850
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
40394
39851
  function createForwardPolicy(deps) {
40395
39852
  const now = deps.now ?? (() => Date.now());
40396
- const file2 = join28(deps.dir, STATE_FILENAME);
39853
+ const file2 = join21(deps.dir, STATE_FILENAME);
40397
39854
  let state = null;
40398
39855
  let loading = null;
40399
39856
  async function readState() {
@@ -40418,7 +39875,7 @@ function createForwardPolicy(deps) {
40418
39875
  state = next;
40419
39876
  try {
40420
39877
  await ensureDataDir(deps.dir);
40421
- const tmp = `${file2}.${randomUUID16()}.tmp`;
39878
+ const tmp = `${file2}.${randomUUID14()}.tmp`;
40422
39879
  await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
40423
39880
  await rename(tmp, file2);
40424
39881
  } catch {
@@ -40559,6 +40016,9 @@ var AttachedDataGateway = class {
40559
40016
  *
40560
40017
  * Machine mode answers before any key is read, so a machine attachment pays
40561
40018
  * nothing for scoping and forwards exactly what it always has.
40019
+ *
40020
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
40021
+ * forwarding key for key.
40562
40022
  */
40563
40023
  verdictFor(keyOf) {
40564
40024
  try {
@@ -40575,24 +40035,27 @@ var AttachedDataGateway = class {
40575
40035
  * the key its row holds in the local store, recorded per root (see
40576
40036
  * `rootVerdict`), not the key on the root event just handed in: roots are
40577
40037
  * first-write-wins in the store, so when two producers record a root for one
40578
- * session (the session-start hook, then a reconcile pass) the second leaves
40579
- * the stored row as it was, and the history drain decides that row, not this
40580
- * event. Whether this root EVENT is itself sent takes both keys: the stored
40581
- * one AND its own. The event's attributes (cwd, project, repo) describe where
40582
- * it was recorded from, so a root event keyed to a personal directory is never
40583
- * sent under an enrolled stored root, though the enrolled leaves still forward
40584
- * under it: the instance that wrote the stored root is expected to have
40585
- * forwarded it. If it did not (the root was written while standalone or under
40586
- * another attachment, or its forward failed), the plane refuses those leaves
40587
- * and the history drain ships the root first. Any other row with a root
40588
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
40589
- * is in scope AND this instance recorded an in-scope verdict for that root.
40590
- * The audit-event route has real foreign keys on both columns and stubs no
40591
- * missing root, so a leaf sent after its root was kept local is refused
40592
- * there, and a refused forward counts toward the breaker that guards every
40593
- * other one. A root this instance never recorded is therefore `'local'`: the
40594
- * only answer that cannot orphan a row. A row with no root reference at all
40595
- * has nothing to orphan, and is decided by its own key.
40038
+ * session (the session-start hook, then a reconcile pass) the second leaves the
40039
+ * stored row as it was. That stored row, not this event, is what a history
40040
+ * drain pass would decide, if the root started before the attach; the drain
40041
+ * never offers one that started after it (`started_at < backlogBefore`).
40042
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
40043
+ * its own. The event's attributes (cwd, project, repo) describe where it was
40044
+ * recorded from, so a root event keyed to a personal directory is never sent
40045
+ * under an enrolled stored root, though the enrolled leaves still forward under
40046
+ * it: the instance that wrote the stored root is expected to have forwarded it.
40047
+ * If it did not (the root was written while standalone or under another
40048
+ * attachment, or its forward failed), the plane refuses those leaves. A root
40049
+ * that started before the attach is shipped, ahead of its leaves, by the
40050
+ * history drain; one that started after it is never offered by the drain. Any
40051
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
40052
+ * only when its own key is in scope AND this instance recorded an in-scope
40053
+ * verdict for that root. The audit-event route has real foreign keys on both
40054
+ * columns and stubs no missing root, so a leaf sent after its root was kept
40055
+ * local is refused there, and a refused forward counts toward the breaker that
40056
+ * guards every other one. A root this instance never recorded is therefore
40057
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
40058
+ * reference at all has nothing to orphan, and is decided by its own key.
40596
40059
  *
40597
40060
  * What this costs is stated rather than discovered. A session whose stored
40598
40061
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -40663,6 +40126,87 @@ var AttachedDataGateway = class {
40663
40126
  return [];
40664
40127
  }
40665
40128
  }
40129
+ /**
40130
+ * The verdict for the repositories nested in a scanned project, answered
40131
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
40132
+ *
40133
+ * A walk descends into a nested clone or submodule and folds its files into
40134
+ * the project it is walking, so one register can carry several
40135
+ * repositories' call sites under one project key. Each of them must be in
40136
+ * scope for it to forward. One key out of scope, or a nested repository with
40137
+ * no remote (an `undefined` key), keeps the whole register local.
40138
+ *
40139
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
40140
+ * what is nested in it, and every scan passes the list, empty when nothing
40141
+ * is nested. A register nobody vouched for is not one a scoped attachment
40142
+ * may send.
40143
+ *
40144
+ * Machine mode answers before reading the context, so a machine attachment
40145
+ * forwards exactly what it always has.
40146
+ */
40147
+ nestedVerdict(context) {
40148
+ try {
40149
+ if (this.deps.attachment.mode === "machine") return "forward";
40150
+ const keys = context?.nestedScopeKeys;
40151
+ if (keys === void 0) return "local";
40152
+ for (const key of keys) {
40153
+ if (this.verdictFor(() => key) === "local") return "local";
40154
+ }
40155
+ return "forward";
40156
+ } catch {
40157
+ return "local";
40158
+ }
40159
+ }
40160
+ /**
40161
+ * The register a scoped attachment sends, once the project and the repositories
40162
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
40163
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
40164
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
40165
+ *
40166
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
40167
+ * and the ledger holds every file the scanner ever read under the root, nested
40168
+ * clones' included. So a clone that was removed, or one an ignore file now
40169
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
40170
+ * paths come back as deleted. The scan names the repository of each deleted
40171
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
40172
+ * and each is held to the same verdict as any other key. A path whose key is
40173
+ * absent, or out of scope, is not sent.
40174
+ *
40175
+ * The list is asked for here, and only here: it is an async read of the scan
40176
+ * ledger that the scan makes on being called, so a machine attachment, which
40177
+ * returns before this, and a register already kept local never cause it.
40178
+ *
40179
+ * Anything the scan did not vouch for sends no deleted path, and the register
40180
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
40181
+ * list whose length is not the register's. Deleting is the only thing a dropped
40182
+ * path could have done on the server, so the cost of a refusal is a stored row
40183
+ * that stays, never a path that leaves.
40184
+ *
40185
+ * Machine mode returns `input` itself, the same object and unread, so a machine
40186
+ * attachment's request is exactly what it was. A register that lists no deleted
40187
+ * path, or that is not a ledger register, has nothing to cut and is returned
40188
+ * as it came, with the list unread.
40189
+ */
40190
+ async registerForWire(input2, context) {
40191
+ try {
40192
+ if (this.deps.attachment.mode === "machine") return input2;
40193
+ const { reconcile } = input2;
40194
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
40195
+ const deleted = reconcile.deletedFiles;
40196
+ let kept = [];
40197
+ try {
40198
+ const keys = await context?.deletedFileKeys?.();
40199
+ if (keys?.length === deleted.length) {
40200
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
40201
+ }
40202
+ } catch {
40203
+ kept = [];
40204
+ }
40205
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
40206
+ } catch {
40207
+ return void 0;
40208
+ }
40209
+ }
40666
40210
  /**
40667
40211
  * The event `recordCapture` sends for a capture the verdict let through, or
40668
40212
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -40988,12 +40532,24 @@ var AttachedDataGateway = class {
40988
40532
  * payload onto the wire-boundary-safe shape (no snippet, hashed
40989
40533
  * projectKey), and its result is discarded: `forward.run` never throws or
40990
40534
  * rejects, so there is nothing here to act on.
40535
+ *
40536
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
40537
+ * not say: the key of every repository nested below the scan root, whose
40538
+ * files the walk folded into this register. On a scoped attachment the
40539
+ * register is forwarded only when the project's own key AND every one of
40540
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
40541
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
40542
+ * `registerForWire`). Machine mode never reads either, and the local write
40543
+ * never receives the context and gets the register whole.
40991
40544
  */
40992
- async recordProjectEgress(input2) {
40545
+ async recordProjectEgress(input2, context) {
40993
40546
  const summary = await this.deps.local.recordProjectEgress(input2);
40994
40547
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
40548
+ if (this.nestedVerdict(context) === "local") return summary;
40549
+ const register = await this.registerForWire(input2, context);
40550
+ if (register === void 0) return summary;
40995
40551
  await this.deps.forward.run(
40996
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
40552
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
40997
40553
  );
40998
40554
  return summary;
40999
40555
  }
@@ -41047,6 +40603,11 @@ var AttachedDataGateway = class {
41047
40603
  async scanLedgerPaths() {
41048
40604
  return this.deps.local.scanLedgerPaths();
41049
40605
  }
40606
+ // Delegated, like the path list. An inner gateway that cannot say answers an
40607
+ // empty map, which gives every deleted path no key.
40608
+ async scanLedgerPathKeys() {
40609
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
40610
+ }
41050
40611
  async recordScanned(entries) {
41051
40612
  return this.deps.local.recordScanned(entries);
41052
40613
  }
@@ -41113,6 +40674,12 @@ var AttachedDataGateway = class {
41113
40674
  // and the spread above would otherwise drop the field silently — which is
41114
40675
  // exactly what it did, leaving the whole control inert on every device
41115
40676
  // while every test around it stayed green.
40677
+ //
40678
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
40679
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
40680
+ // reads this bundle once to build detection, so the detections it carries
40681
+ // apply to every event on the machine. Where a prohibition applies is
40682
+ // answered per event by `governanceAppliesTo` below.
41116
40683
  prohibitedModels: cached2.prohibitedModels,
41117
40684
  // NAMED for the same reason as the line above, and it is the same defect
41118
40685
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -41172,6 +40739,30 @@ var AttachedDataGateway = class {
41172
40739
  };
41173
40740
  }
41174
40741
  // ---------------------------------------------------------------------
40742
+ // GovernanceScope — where the organization's model policy applies
40743
+ // ---------------------------------------------------------------------
40744
+ /**
40745
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
40746
+ * the question a model-guard site asks once it has decided to refuse.
40747
+ *
40748
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
40749
+ * with the same key would be forwarded. A machine-wide attachment governs
40750
+ * every event, keyless included, exactly as before. A scoped one governs an
40751
+ * event only when its key names an enrolled repository. An event in a
40752
+ * personal repository, in no repository, with an empty key, or met by a fault
40753
+ * is not governed.
40754
+ *
40755
+ * The event's OWN key, never its session root's. The root rule in
40756
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
40757
+ * this decides whether a refusal applies, which is a question about where the
40758
+ * event happened.
40759
+ *
40760
+ * Answered from memory: no store read, no bundle read, nothing sent.
40761
+ */
40762
+ governanceAppliesTo(scopeKey) {
40763
+ return this.verdictFor(() => scopeKey) === "forward";
40764
+ }
40765
+ // ---------------------------------------------------------------------
41175
40766
  // LocalStoreMaintenance — by delegation (D3).
41176
40767
  //
41177
40768
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -41288,28 +40879,29 @@ var CORRELATION_ID = EventMetadata.shape.correlationId;
41288
40879
  var TRACE_ID = EventMetadata.shape.traceId;
41289
40880
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
41290
40881
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40882
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
41291
40883
 
41292
40884
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
41293
40885
  var CAPTURE_BATCH_BYTES = 1024 * 1024;
41294
40886
 
41295
40887
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
41296
40888
  import { spawn } from "child_process";
41297
- import { fileURLToPath as fileURLToPath2 } from "url";
40889
+ import { fileURLToPath } from "url";
41298
40890
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
41299
40891
 
41300
40892
  // ../../packages/plugin-runtime/src/attached/install-record.ts
41301
40893
  import { readFile as readFile2, stat } from "fs/promises";
41302
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
40894
+ import { basename as basename3, dirname as dirname6, join as join22, resolve as resolve2 } from "path";
41303
40895
  async function readInstalledVersion(installRoot) {
41304
40896
  try {
41305
40897
  const versionDir = resolve2(installRoot);
41306
- const pluginDir = dirname7(versionDir);
41307
- const marketplaceDir = dirname7(pluginDir);
41308
- const cacheDir = dirname7(marketplaceDir);
41309
- if (basename6(cacheDir) !== "cache") return null;
41310
- const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
40898
+ const pluginDir = dirname6(versionDir);
40899
+ const marketplaceDir = dirname6(pluginDir);
40900
+ const cacheDir = dirname6(marketplaceDir);
40901
+ if (basename3(cacheDir) !== "cache") return null;
40902
+ const key = `${basename3(pluginDir)}@${basename3(marketplaceDir)}`;
41311
40903
  const record2 = JSON.parse(
41312
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
40904
+ await readFile2(join22(dirname6(cacheDir), "installed_plugins.json"), "utf8")
41313
40905
  );
41314
40906
  const plugins = record2?.plugins;
41315
40907
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -41341,7 +40933,7 @@ async function exists(path) {
41341
40933
  }
41342
40934
 
41343
40935
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
41344
- import { readFileSync as readFileSync18 } from "fs";
40936
+ import { readFileSync as readFileSync13 } from "fs";
41345
40937
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
41346
40938
  var manifestBuildCache = /* @__PURE__ */ new Map();
41347
40939
  function readManifestBuild(manifestUrl, packageName) {
@@ -41349,7 +40941,7 @@ function readManifestBuild(manifestUrl, packageName) {
41349
40941
  if (!manifestBuildCache.has(key)) {
41350
40942
  let build;
41351
40943
  try {
41352
- const manifest = JSON.parse(readFileSync18(manifestUrl, "utf8"));
40944
+ const manifest = JSON.parse(readFileSync13(manifestUrl, "utf8"));
41353
40945
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
41354
40946
  } catch {
41355
40947
  build = void 0;
@@ -41384,9 +40976,9 @@ async function readInstalledVersionBounded(installRoot) {
41384
40976
  }
41385
40977
 
41386
40978
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41387
- import { randomUUID as randomUUID17 } from "crypto";
40979
+ import { randomUUID as randomUUID15 } from "crypto";
41388
40980
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
41389
- import { join as join30 } from "path";
40981
+ import { join as join23 } from "path";
41390
40982
 
41391
40983
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
41392
40984
  import { rename as rename2 } from "fs/promises";
@@ -41415,7 +41007,7 @@ async function publishByRename(tmp, file2, move = rename2) {
41415
41007
 
41416
41008
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41417
41009
  function createPolicyStore(dir = dataDir()) {
41418
- const file2 = join30(dir, "policy-cache.json");
41010
+ const file2 = join23(dir, "policy-cache.json");
41419
41011
  async function read() {
41420
41012
  try {
41421
41013
  const raw = await readFile3(file2, "utf8");
@@ -41447,7 +41039,7 @@ function createPolicyStore(dir = dataDir()) {
41447
41039
  }
41448
41040
  }
41449
41041
  async function publishRecord(record2) {
41450
- const tmp = `${file2}.${randomUUID17()}.tmp`;
41042
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
41451
41043
  try {
41452
41044
  await writeFile2(tmp, JSON.stringify(record2), {
41453
41045
  encoding: "utf8",
@@ -41485,8 +41077,8 @@ function createPolicyStore(dir = dataDir()) {
41485
41077
  }
41486
41078
 
41487
41079
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
41488
- import { readFileSync as readFileSync19 } from "fs";
41489
- import { join as join31 } from "path";
41080
+ import { readFileSync as readFileSync14 } from "fs";
41081
+ import { join as join24 } from "path";
41490
41082
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
41491
41083
  var OUTCOME_KEYS = {
41492
41084
  ok: true,
@@ -41500,7 +41092,7 @@ var OUTCOME_KEYS = {
41500
41092
  };
41501
41093
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
41502
41094
  function postureReportStatePath(dataDir2) {
41503
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41095
+ return join24(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41504
41096
  }
41505
41097
  function writePostureReportState(dataDir2, state) {
41506
41098
  try {
@@ -41541,10 +41133,19 @@ function createPostureReporter(deps) {
41541
41133
  hostname: deps.hostname(),
41542
41134
  capturedAt: nowMs,
41543
41135
  ...measurement,
41544
- // Omit the key rather than spread an explicit `undefined` —
41545
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
41546
- // factory.ts keys on presence.
41547
- ...plugin === void 0 ? {} : { plugin }
41136
+ // Omit the key rather than spread an explicit `undefined`. The type
41137
+ // admits `undefined` here (the schema's optional member), and
41138
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
41139
+ // in-memory object free of an explicit `undefined` member, which the
41140
+ // tests pin by key presence.
41141
+ ...plugin === void 0 ? {} : { plugin },
41142
+ // LAST, and only for a scoped attachment. A machine attachment omits
41143
+ // the key the same way, so its body is byte for byte the one it sent
41144
+ // before the member existed. Anything but exactly `machine` reports the
41145
+ // constant `scoped`, never the raw value: that is resolveScope's own
41146
+ // fail direction, and a value outside the wire's vocabulary would fail
41147
+ // the whole snapshot at the receiver, the wipe signal with it.
41148
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
41548
41149
  };
41549
41150
  } catch {
41550
41151
  return null;
@@ -41567,8 +41168,8 @@ function createPostureReporter(deps) {
41567
41168
  }
41568
41169
 
41569
41170
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
41570
- import { statSync as statSync9 } from "fs";
41571
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
41171
+ import { statSync as statSync7 } from "fs";
41172
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
41572
41173
 
41573
41174
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
41574
41175
  function emptyActionCounts() {
@@ -41598,7 +41199,7 @@ function emptyReadout(readError = false) {
41598
41199
  }
41599
41200
  function readStorePosture(dbPath2) {
41600
41201
  try {
41601
- statSync9(dbPath2);
41202
+ statSync7(dbPath2);
41602
41203
  } catch (err) {
41603
41204
  const code = err.code;
41604
41205
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -41626,7 +41227,7 @@ function readStorePosture(dbPath2) {
41626
41227
  readError: false
41627
41228
  });
41628
41229
  try {
41629
- db = new DatabaseSync4(dbPath2, { readOnly: true });
41230
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
41630
41231
  db.exec("PRAGMA busy_timeout = 2000");
41631
41232
  version2 = db.prepare("PRAGMA user_version").get().user_version;
41632
41233
  try {
@@ -41678,16 +41279,16 @@ function readStorePosture(dbPath2) {
41678
41279
  }
41679
41280
 
41680
41281
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
41681
- import { randomUUID as randomUUID18 } from "crypto";
41282
+ import { randomUUID as randomUUID16 } from "crypto";
41682
41283
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
41683
- import { join as join32 } from "path";
41284
+ import { join as join25 } from "path";
41684
41285
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
41685
41286
  function createPostureStore(dir = settingsDir(), legacyDir) {
41686
- const file2 = join32(dir, "posture-state.json");
41687
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
41287
+ const file2 = join25(dir, "posture-state.json");
41288
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
41688
41289
  async function persist(state) {
41689
41290
  await ensureDataDir(dir);
41690
- const tmp = `${file2}.${randomUUID18()}.tmp`;
41291
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
41691
41292
  try {
41692
41293
  await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
41693
41294
  await publishByRename(tmp, file2);
@@ -41729,7 +41330,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
41729
41330
  }
41730
41331
  return legacy;
41731
41332
  }
41732
- const fresh = { deviceId: randomUUID18(), lastAttemptedAtMs: 0 };
41333
+ const fresh = { deviceId: randomUUID16(), lastAttemptedAtMs: 0 };
41733
41334
  try {
41734
41335
  await ensureDataDir(dir);
41735
41336
  if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
@@ -41752,8 +41353,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
41752
41353
  }
41753
41354
 
41754
41355
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
41755
- import { readFileSync as readFileSync20 } from "fs";
41756
- import { join as join33 } from "path";
41356
+ import { readFileSync as readFileSync15 } from "fs";
41357
+ import { join as join26 } from "path";
41757
41358
 
41758
41359
  // ../../packages/plugin-runtime/src/attached/status.ts
41759
41360
  var REFUSAL_LINES = {
@@ -41771,7 +41372,7 @@ var OUTCOME_LINES = {
41771
41372
 
41772
41373
  // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
41773
41374
  import { spawn as spawn2 } from "child_process";
41774
- import { fileURLToPath as fileURLToPath3 } from "url";
41375
+ import { fileURLToPath as fileURLToPath2 } from "url";
41775
41376
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
41776
41377
 
41777
41378
  // ../../packages/plugin-runtime/src/content-retention-pass.ts
@@ -41779,7 +41380,7 @@ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
41779
41380
 
41780
41381
  // ../../packages/plugin-runtime/src/content-retention-trigger.ts
41781
41382
  import { spawn as spawn3 } from "child_process";
41782
- import { fileURLToPath as fileURLToPath4 } from "url";
41383
+ import { fileURLToPath as fileURLToPath3 } from "url";
41783
41384
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
41784
41385
 
41785
41386
  // ../../packages/plugin-runtime/src/attached/factory.ts
@@ -41796,7 +41397,7 @@ var StandaloneDataGateway = class {
41796
41397
  // One notice per gateway — see warnRulesetDiscarded.
41797
41398
  warnedRulesetDiscarded = false;
41798
41399
  constructor(dataDir2, detections = [], meta4) {
41799
- this.db = openLocalDatabase(dataDir2);
41400
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
41800
41401
  this.dataDir = dataDir2;
41801
41402
  this.db.installedPacks.recordInventory(detections, meta4);
41802
41403
  }
@@ -42145,6 +41746,9 @@ var StandaloneDataGateway = class {
42145
41746
  scanLedgerPaths() {
42146
41747
  return Promise.resolve(this.db.scanLedger.allPaths());
42147
41748
  }
41749
+ scanLedgerPathKeys() {
41750
+ return Promise.resolve(this.db.scanLedger.pathKeys());
41751
+ }
42148
41752
  recordScanned(entries) {
42149
41753
  this.db.scanLedger.upsertEntries(entries);
42150
41754
  return Promise.resolve();
@@ -42232,11 +41836,15 @@ function resolveGatewayForConfig(config2, meta4) {
42232
41836
  readStore: () => readStorePosture(config2.dbPath),
42233
41837
  hostname: () => hostname6(),
42234
41838
  now: () => Date.now(),
41839
+ // The mode THIS gateway enforces, from the attachment resolved above,
41840
+ // so the report cannot name a mode the forward paths are not using.
41841
+ attachmentMode: attachment.mode,
42235
41842
  // The reporting build's identity, when the caller knows it (the plugin
42236
41843
  // adapters do; an embedder or a test may not). Composed with the SAME
42237
41844
  // policy store the sync child writes, so the block names the bundle
42238
- // actually in force. Key omitted rather than set undefined — the
42239
- // reporter keys on presence.
41845
+ // actually in force. The dependency key is omitted when no build is
41846
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
41847
+ // then adds no block.
42240
41848
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
42241
41849
  })
42242
41850
  });
@@ -42253,7 +41861,7 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
42253
41861
  }
42254
41862
 
42255
41863
  // ../../packages/plugin-runtime/src/handle-session-start.ts
42256
- import { randomUUID as randomUUID19 } from "crypto";
41864
+ import { randomUUID as randomUUID17 } from "crypto";
42257
41865
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
42258
41866
 
42259
41867
  // src/build-info.ts
@@ -42266,17 +41874,17 @@ function pluginBuild() {
42266
41874
  // src/history/tail.ts
42267
41875
  import { createHash as createHash7 } from "crypto";
42268
41876
  import {
42269
- closeSync as closeSync3,
42270
- fstatSync as fstatSync2,
42271
- mkdirSync as mkdirSync5,
42272
- openSync as openSync3,
42273
- readFileSync as readFileSync21,
42274
- readSync as readSync2,
42275
- writeFileSync as writeFileSync8
41877
+ closeSync as closeSync2,
41878
+ fstatSync,
41879
+ mkdirSync as mkdirSync2,
41880
+ openSync as openSync2,
41881
+ readFileSync as readFileSync16,
41882
+ readSync,
41883
+ writeFileSync as writeFileSync5
42276
41884
  } from "fs";
42277
- import { join as join34 } from "path";
41885
+ import { join as join27 } from "path";
42278
41886
  function offsetsDir(dataDir2) {
42279
- return join34(dataDir2, "usage-offsets");
41887
+ return join27(dataDir2, "usage-offsets");
42280
41888
  }
42281
41889
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
42282
41890
  function safeSessionId(sessionId) {
@@ -42286,11 +41894,11 @@ function safeSessionId(sessionId) {
42286
41894
  return createHash7("sha256").update(sessionId).digest("hex");
42287
41895
  }
42288
41896
  function offsetPath(dataDir2, sessionId) {
42289
- return join34(offsetsDir(dataDir2), safeSessionId(sessionId));
41897
+ return join27(offsetsDir(dataDir2), safeSessionId(sessionId));
42290
41898
  }
42291
41899
  function readOffset(dataDir2, sessionId) {
42292
41900
  try {
42293
- const raw = readFileSync21(offsetPath(dataDir2, sessionId), "utf8");
41901
+ const raw = readFileSync16(offsetPath(dataDir2, sessionId), "utf8");
42294
41902
  const parsed2 = JSON.parse(raw);
42295
41903
  if (typeof parsed2 === "object" && parsed2 !== null) {
42296
41904
  const rec = parsed2;
@@ -42304,9 +41912,9 @@ function readOffset(dataDir2, sessionId) {
42304
41912
  }
42305
41913
  function writeOffset(dataDir2, sessionId, value) {
42306
41914
  try {
42307
- mkdirSync5(offsetsDir(dataDir2), { recursive: true, mode: DATA_DIR_MODE });
41915
+ mkdirSync2(offsetsDir(dataDir2), { recursive: true, mode: DATA_DIR_MODE });
42308
41916
  const payload = value.lastPromptId !== void 0 ? { offset: value.offset, lastPromptId: value.lastPromptId } : { offset: value.offset };
42309
- writeFileSync8(offsetPath(dataDir2, sessionId), JSON.stringify(payload), {
41917
+ writeFileSync5(offsetPath(dataDir2, sessionId), JSON.stringify(payload), {
42310
41918
  mode: DATA_FILE_MODE
42311
41919
  });
42312
41920
  } catch {
@@ -42315,19 +41923,19 @@ function writeOffset(dataDir2, sessionId, value) {
42315
41923
  function readTail(transcriptPath, startOffset) {
42316
41924
  let fd;
42317
41925
  try {
42318
- fd = openSync3(transcriptPath, "r");
41926
+ fd = openSync2(transcriptPath, "r");
42319
41927
  } catch {
42320
41928
  return { chunk: "", nextOffset: startOffset };
42321
41929
  }
42322
41930
  try {
42323
- const size = fstatSync2(fd).size;
41931
+ const size = fstatSync(fd).size;
42324
41932
  const from = size < startOffset ? 0 : startOffset;
42325
41933
  if (from >= size) return { chunk: "", nextOffset: from };
42326
41934
  const length = size - from;
42327
41935
  const buf = Buffer.allocUnsafe(length);
42328
41936
  let filled = 0;
42329
41937
  while (filled < length) {
42330
- const bytesRead = readSync2(fd, buf, filled, length - filled, from + filled);
41938
+ const bytesRead = readSync(fd, buf, filled, length - filled, from + filled);
42331
41939
  if (bytesRead === 0) break;
42332
41940
  filled += bytesRead;
42333
41941
  }
@@ -42341,16 +41949,16 @@ function readTail(transcriptPath, startOffset) {
42341
41949
  return { chunk: "", nextOffset: startOffset };
42342
41950
  } finally {
42343
41951
  try {
42344
- closeSync3(fd);
41952
+ closeSync2(fd);
42345
41953
  } catch {
42346
41954
  }
42347
41955
  }
42348
41956
  }
42349
41957
 
42350
41958
  // src/history/transcripts.ts
42351
- import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync22, readSync as readSync3, statSync as statSync10 } from "fs";
42352
- import { homedir as homedir3 } from "os";
42353
- import { join as join35 } from "path";
41959
+ import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync2, readFileSync as readFileSync17, readSync as readSync2, statSync as statSync8 } from "fs";
41960
+ import { homedir as homedir2 } from "os";
41961
+ import { join as join28 } from "path";
42354
41962
  function isRecord(value) {
42355
41963
  return typeof value === "object" && value !== null;
42356
41964
  }
@@ -42412,11 +42020,12 @@ function parseTranscriptUsage(jsonl, sinceMs = 0, knownSessionId) {
42412
42020
  const last = info.last_token_usage;
42413
42021
  if (!isRecord(last)) continue;
42414
42022
  const usage = {};
42415
- if (typeof last.input_tokens === "number") usage.input_tokens = last.input_tokens;
42416
- if (typeof last.output_tokens === "number") usage.output_tokens = last.output_tokens;
42417
- if (typeof last.cached_input_tokens === "number") {
42418
- usage.cache_read_input_tokens = last.cached_input_tokens;
42023
+ const cached2 = typeof last.cached_input_tokens === "number" ? Math.max(0, last.cached_input_tokens) : 0;
42024
+ if (typeof last.input_tokens === "number") {
42025
+ usage.input_tokens = Math.max(0, last.input_tokens - cached2);
42419
42026
  }
42027
+ if (typeof last.output_tokens === "number") usage.output_tokens = last.output_tokens;
42028
+ if (typeof last.cached_input_tokens === "number") usage.cache_read_input_tokens = cached2;
42420
42029
  if (typeof last.reasoning_output_tokens === "number") {
42421
42030
  usage.reasoning_output_tokens = last.reasoning_output_tokens;
42422
42031
  }