@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,888 +1,8 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- try {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- } catch (e) {
11
- throw mod = 0, e;
12
- }
13
- };
14
2
  var __export = (target, all) => {
15
3
  for (var name in all)
16
4
  __defProp(target, name, { get: all[name], enumerable: true });
17
5
  };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
-
35
- // ../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js
36
- var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js"(exports, module) {
38
- "use strict";
39
- function makeArray(subject) {
40
- return Array.isArray(subject) ? subject : [subject];
41
- }
42
- var UNDEFINED = void 0;
43
- var EMPTY = "";
44
- var SPACE = " ";
45
- var ESCAPE = "\\";
46
- var REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
47
- var REGEX_TEST_BLANK_LINE = /^\uFEFF? *$/;
48
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
49
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
50
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
51
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
52
- var DOUBLE_SLASH = "//";
53
- var SLASH_CODE = 47;
54
- var DOT_CODE = 46;
55
- var SLASH3 = "/";
56
- var TMP_KEY_IGNORE = "node-ignore";
57
- if (typeof Symbol !== "undefined") {
58
- TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
59
- }
60
- var KEY_IGNORE = TMP_KEY_IGNORE;
61
- var define = (object2, key, value) => {
62
- Object.defineProperty(object2, key, { value });
63
- return value;
64
- };
65
- var RETURN_FALSE = () => false;
66
- var cleanRangeBackSlash = (slashes) => {
67
- const { length } = slashes;
68
- return slashes.slice(0, length - length % 2);
69
- };
70
- var POSIX_CLASSES = {
71
- alnum: "0-9A-Za-z",
72
- alpha: "A-Za-z",
73
- blank: " \\t",
74
- cntrl: "\\x00-\\x1f\\x7f",
75
- digit: "0-9",
76
- graph: "!-.0-~",
77
- lower: "a-z",
78
- print: " -.0-~",
79
- punct: "!-.:-@\\[-`{-~",
80
- // git's `sane-ctype.h` classifies \v and \f as control, not space,
81
- // unlike C's `isspace`
82
- space: " \\t\\n\\r",
83
- upper: "A-Z",
84
- xdigit: "0-9A-Fa-f"
85
- };
86
- var CLASS_MEMBERS_TO_ESCAPE = "\\]^-[";
87
- var escapeMember = (char) => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0 ? char : ESCAPE + char;
88
- var NON_SLASH = "(?!\\/)";
89
- var classSource = (negated, body) => {
90
- if (negated) {
91
- return `[^\\/${body}]`;
92
- }
93
- const source = `[${body}]`;
94
- return new RegExp(source).test("/") ? NON_SLASH + source : source;
95
- };
96
- var scanBracket = (pattern, start) => {
97
- const { length } = pattern;
98
- let index = start + 1;
99
- let negated = EMPTY;
100
- const lead = pattern[index];
101
- if (lead === "!" || lead === "^") {
102
- negated = "^";
103
- index++;
104
- }
105
- let body = EMPTY;
106
- let prev = EMPTY;
107
- for (; ; ) {
108
- const char = pattern[index];
109
- if (char === UNDEFINED) {
110
- return null;
111
- }
112
- if (char === ESCAPE) {
113
- const escaped = pattern[index + 1];
114
- if (escaped === UNDEFINED) {
115
- return null;
116
- }
117
- body += escapeMember(escaped);
118
- prev = escaped;
119
- index++;
120
- } else if (char === "-" && prev && index + 1 < length && pattern[index + 1] !== "]") {
121
- index++;
122
- let to = pattern[index];
123
- if (to === ESCAPE) {
124
- to = pattern[index += 1];
125
- }
126
- if (prev <= to) {
127
- body += `-${escapeMember(to)}`;
128
- }
129
- prev = EMPTY;
130
- } else if (char === "[" && pattern[index + 1] === ":") {
131
- const nameStart = index + 2;
132
- let end = nameStart;
133
- while (end < length && pattern[end] !== "]") {
134
- end++;
135
- }
136
- if (end === length) {
137
- return null;
138
- }
139
- if (end > nameStart && pattern[end - 1] === ":") {
140
- const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)];
141
- if (expanded === UNDEFINED) {
142
- return null;
143
- }
144
- body += expanded;
145
- prev = EMPTY;
146
- index = end;
147
- } else {
148
- body += escapeMember("[");
149
- prev = "[";
150
- index = nameStart - 2;
151
- }
152
- } else {
153
- body += escapeMember(char);
154
- prev = char;
155
- }
156
- index++;
157
- if (pattern[index] === "]") {
158
- return {
159
- end: index,
160
- source: classSource(negated, body)
161
- };
162
- }
163
- }
164
- };
165
- var NEVER_MATCH = "[]";
166
- var PLACEHOLDER = "\0";
167
- var REGEX_RESTORE_PLACEHOLDER = new RegExp(
168
- `${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,
169
- "g"
170
- );
171
- var TRAILING_WILDCARD = "\uE000";
172
- var TRAILING_DOUBLESTAR = "\uE001";
173
- var extractBrackets = (pattern) => {
174
- const sources = [];
175
- const hold = (source) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
176
- const { length } = pattern;
177
- let out = EMPTY;
178
- let index = 0;
179
- while (index < length) {
180
- const char = pattern[index];
181
- if (char === ESCAPE) {
182
- const escaped = pattern[index + 1];
183
- if (escaped === "*" || escaped === "[" || escaped === SPACE || escaped === ESCAPE) {
184
- out += pattern.slice(index, index + 2);
185
- } else {
186
- out += hold(
187
- REGEX_LITERAL_SPECIAL.test(escaped) ? ESCAPE + escaped : escaped
188
- );
189
- }
190
- index += 2;
191
- } else if (char === PLACEHOLDER) {
192
- out += hold(`[${PLACEHOLDER}]`);
193
- index++;
194
- } else if (char === "[") {
195
- const scanned = scanBracket(pattern, index);
196
- if (scanned === null) {
197
- out += hold(NEVER_MATCH);
198
- index = length;
199
- } else {
200
- out += hold(scanned.source);
201
- index = scanned.end + 1;
202
- }
203
- } else {
204
- out += char;
205
- index++;
206
- }
207
- }
208
- return {
209
- source: out,
210
- sources
211
- };
212
- };
213
- var DIRECT = null;
214
- var REGEX_INNER_SLASH = /\/(?!$)/;
215
- var REPLACERS = [
216
- [
217
- // Remove BOM
218
- // TODO:
219
- // Other similar zero-width characters?
220
- /^\uFEFF/,
221
- () => EMPTY,
222
- "\uFEFF"
223
- ],
224
- [
225
- // A trailing line terminator, left on when a whole file's contents are
226
- // added as one pattern rather than split into lines. git never sees one
227
- // -- it reads a `.gitignore` line by line -- so it is not part of the
228
- // pattern and is dropped here, apart from the trailing-space trimming,
229
- // which follows git in touching spaces and nothing else.
230
- /[\r\n]+$/,
231
- () => EMPTY
232
- ],
233
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
234
- [
235
- // Only spaces, never tabs or other whitespace: git trims a trailing run
236
- // of `' '` and nothing else (dir.c, `trim_trailing_spaces`, a single
237
- // `case ' '`), so a pattern ending in a tab keeps it as a literal.
238
- // (a\ ) -> (a )
239
- // (a ) -> (a)
240
- // (a ) -> (a)
241
- // (a \ ) -> (a )
242
- /((?:\\\\)*?)(\\? +)$/,
243
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
244
- ],
245
- // Replace (\ ) with ' '
246
- // Only a space: an escaped tab or other whitespace is already a literal by
247
- // the time it reaches here, and a bare tab must be left as one, not turned
248
- // into a space.
249
- // (\ ) -> ' '
250
- // (\\ ) -> '\\ '
251
- // (\\\ ) -> '\\ '
252
- [
253
- /(\\+?) /g,
254
- (_, m1) => {
255
- const { length } = m1;
256
- return m1.slice(0, length - length % 2) + SPACE;
257
- }
258
- ],
259
- // Escape metacharacters
260
- // which is written down by users but means special for regular expressions.
261
- // > There are 12 characters with special meanings:
262
- // > - the backslash \,
263
- // > - the caret ^,
264
- // > - the dollar sign $,
265
- // > - the period or dot .,
266
- // > - the vertical bar or pipe symbol |,
267
- // > - the question mark ?,
268
- // > - the asterisk or star *,
269
- // > - the plus sign +,
270
- // > - the opening parenthesis (,
271
- // > - the closing parenthesis ),
272
- // > - and the opening square bracket [,
273
- // > - the opening curly brace {,
274
- // > These special characters are often called "metacharacters".
275
- [
276
- /[\\$.|*+(){^]/g,
277
- (match) => `\\${match}`
278
- ],
279
- [
280
- // > a question mark (?) matches a single character
281
- /(?!\\)\?/g,
282
- () => "[^/]",
283
- "?"
284
- ],
285
- // leading slash
286
- [
287
- // > A leading slash matches the beginning of the pathname.
288
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
289
- // A leading slash matches the beginning of the pathname
290
- /^\//,
291
- () => "^",
292
- SLASH3
293
- ],
294
- // replace special metacharacter slash after the leading slash
295
- [
296
- /\//g,
297
- () => "\\/",
298
- SLASH3
299
- ],
300
- [
301
- // > A leading "**" followed by a slash means match in all directories.
302
- // > For example, "**/foo" matches file or directory "foo" anywhere,
303
- // > the same as pattern "foo".
304
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
305
- // > under directory "foo".
306
- // Notice that the '*'s have been replaced as '\\*'
307
- /^\^*(?:\\\*\\\*\\\/)+/,
308
- // '**/foo' <-> 'foo'
309
- () => "^(?:.*\\/)?",
310
- "*"
311
- ],
312
- // starting
313
- [
314
- // there will be no leading '/'
315
- // (which has been replaced by section "leading slash")
316
- // If starts with '**', adding a '^' to the regular expression also works
317
- DIRECT,
318
- (source, pattern) => {
319
- if (!source || source[0] === "^") {
320
- return source;
321
- }
322
- const anchor2 = !REGEX_INNER_SLASH.test(pattern) ? "(?:^|\\/)" : "^";
323
- return anchor2 + source;
324
- }
325
- ],
326
- // two globstars
327
- [
328
- // Use lookahead assertions so that we could match more than one `'/**'`
329
- /\\\/\\\*\\\*(?=\\\/|$)/g,
330
- // Zero, one or several directories
331
- // should not use '*', or it will be replaced by the next replacer
332
- // Check if it is not the last `'/**'`
333
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
334
- "*"
335
- ],
336
- // normal intermediate wildcards
337
- [
338
- // Never replace escaped '*'
339
- // ignore rule '\*' will match the path '*'
340
- // 'abc.*/' -> go
341
- // 'abc.*' -> skip this rule,
342
- // coz trailing single wildcard will be handed by [trailing wildcard]
343
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
344
- // '*.js' matches '.js'
345
- // '*.js' doesn't match 'abc'
346
- (_, p1, p2) => {
347
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
348
- return p1 + unescaped;
349
- },
350
- "*"
351
- ],
352
- // trailing wildcard, held apart from a literal star
353
- [
354
- // The step above leaves a trailing `*` alone, so a single `\*` is all that
355
- // can be left at the end here. Whether it is a wildcard or a literal
356
- // turns on the backslashes the user put in front of it: the escaper has
357
- // since doubled every one, so what stands here is those `2N` doubled
358
- // backslashes and then the star's own escape. An even number of the
359
- // original `N` leaves the star unescaped -- a wildcard -- and an odd
360
- // number escapes it -- a literal. This runs while the two are still
361
- // distinct, before the unescape steps below collapse the literal onto
362
- // the very `\*` a wildcard leaves behind.
363
- /(^|[^\\])((?:\\\\)*)\\\*$/,
364
- (match, p1, p2) => (
365
- // `p2` holds the doubled user backslashes; half of them is `N`.
366
- p2.length / 2 % 2 === 0 ? p1 + p2 + TRAILING_WILDCARD : match
367
- ),
368
- "*"
369
- ],
370
- [
371
- // unescape, revert step 3 except for back slash
372
- // For example, if a user escape a '\\*',
373
- // after step 3, the result will be '\\\\\\*'
374
- /\\\\\\(?=[$.|*+(){^])/g,
375
- () => ESCAPE,
376
- ESCAPE + ESCAPE
377
- ],
378
- [
379
- // '\\\\' -> '\\'
380
- /\\\\/g,
381
- () => ESCAPE,
382
- ESCAPE + ESCAPE
383
- ],
384
- [
385
- // Every real bracket expression -- POSIX classes included -- has already
386
- // been held aside by `extractBrackets`, so the only `[` left in the
387
- // pattern is an escaped, literal one.
388
- // `\` is escaped by step 3
389
- /\\\[([^\]/]*?)(\\*)($|\])/g,
390
- // '\\[bar]' -> '\\\\[bar\\]'
391
- (match, range, endEscape, close) => `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,
392
- "["
393
- ],
394
- // ending
395
- [
396
- // 'js' will not match 'js.'
397
- // 'ab' will not match 'abc'
398
- DIRECT,
399
- // WTF!
400
- // https://git-scm.com/docs/gitignore
401
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
402
- // which re-fixes #24, #38
403
- // > If there is a separator at the end of the pattern then the pattern
404
- // > will only match directories, otherwise the pattern can match both
405
- // > files and directories.
406
- // 'js*' will not match 'a.js'
407
- // 'js/' will not match 'a.js'
408
- // 'js' will match 'a.js' and 'a.js/'
409
- (source) => {
410
- const last = source[source.length - 1];
411
- if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
412
- return source;
413
- }
414
- return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
415
- }
416
- ]
417
- ];
418
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\uE000$/;
419
- var MODE_IGNORE = "regex";
420
- var MODE_CHECK_IGNORE = "checkRegex";
421
- var UNDERSCORE = "_";
422
- var replaceTrailingWildcard = (_, p1) => {
423
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
- return `${prefix}(?=$|\\/$)`;
425
- };
426
- var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
427
- var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
428
- var WILDCARD = "[^\\/]*";
429
- var separatorAfter = (run, at) => {
430
- let separator = EMPTY;
431
- for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
432
- separator += run[index].single;
433
- }
434
- return separator;
435
- };
436
- var pinWildcards = (source) => {
437
- if (source.indexOf(WILDCARD) < 0) {
438
- return source;
439
- }
440
- const tokens = [];
441
- const { length } = source;
442
- let index = 0;
443
- while (index < length) {
444
- const char = source[index];
445
- if (source.startsWith(WILDCARD, index)) {
446
- tokens.push({ wildcard: true });
447
- index += WILDCARD.length;
448
- } else if (char === "[") {
449
- let end = index + 1;
450
- if (source[end] === "^") {
451
- end++;
452
- }
453
- if (source[end] === "]") {
454
- end++;
455
- }
456
- while (end < length && source[end] !== "]") {
457
- end += source[end] === ESCAPE ? 2 : 1;
458
- }
459
- end++;
460
- tokens.push({ single: source.slice(index, end) });
461
- index = end;
462
- } else if (char === ESCAPE) {
463
- tokens.push({ single: source.slice(index, index + 2) });
464
- index += 2;
465
- } else if (char === "(") {
466
- let depth = 0;
467
- let end = index;
468
- do {
469
- if (source[end] === ESCAPE) {
470
- end++;
471
- } else if (source[end] === "(") {
472
- depth++;
473
- } else if (source[end] === ")") {
474
- depth--;
475
- }
476
- end++;
477
- } while (end < length && depth > 0);
478
- if ("*+?".indexOf(source[end]) >= 0) {
479
- end++;
480
- }
481
- tokens.push({ boundary: source.slice(index, end) });
482
- index = end;
483
- } else if (char === "^" || char === "$") {
484
- tokens.push({ boundary: char });
485
- index++;
486
- } else {
487
- tokens.push({ single: char });
488
- index++;
489
- }
490
- }
491
- let out = EMPTY;
492
- let run = [];
493
- const flush = () => {
494
- let lastWildcard;
495
- run.forEach((token, at) => {
496
- if (token.wildcard) {
497
- lastWildcard = at;
498
- }
499
- });
500
- run.forEach((token, at) => {
501
- if (!token.wildcard) {
502
- out += token.single;
503
- return;
504
- }
505
- out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
506
- });
507
- run = [];
508
- };
509
- tokens.forEach((token) => {
510
- if (token.boundary === void 0) {
511
- run.push(token);
512
- return;
513
- }
514
- flush();
515
- out += token.boundary;
516
- });
517
- flush();
518
- return out;
519
- };
520
- var makeRegexPrefix = (pattern) => {
521
- const { source, sources } = extractBrackets(pattern);
522
- const replaced = REPLACERS.reduce(
523
- // A pass whose matcher finds nothing hands back the very string it was
524
- // given, so asking first costs a search and saves a rewrite. Ten of the
525
- // fifteen passes never fire for a typical .gitignore line, and between
526
- // them they were 45% of this chain.
527
- (prev, [matcher, replacer, required2]) => {
528
- if (matcher === DIRECT) {
529
- return replacer(prev, pattern);
530
- }
531
- if (required2 !== UNDEFINED && prev.indexOf(required2) < 0) {
532
- return prev;
533
- }
534
- return matcher.test(prev) ? prev.replace(matcher, replacer.bind(pattern)) : prev;
535
- },
536
- source
537
- );
538
- return sources.length ? replaced.replace(
539
- REGEX_RESTORE_PLACEHOLDER,
540
- (match, index) => sources[index]
541
- ) : replaced;
542
- };
543
- var checkSourceOf = (body, prefix) => {
544
- if (body[body.length - 1] === SLASH3) {
545
- prefix = makeRegexPrefix(body.slice(0, -1));
546
- }
547
- const head = prefix.slice(0, -1);
548
- const last = prefix[prefix.length - 1];
549
- return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
- };
551
- var matchesBasename = (body) => {
552
- const index = body.indexOf(SLASH3);
553
- return index < 0 || index === body.length - 1;
554
- };
555
- var basenameOf = (path) => {
556
- const end = path.length - 1;
557
- const index = path.lastIndexOf(
558
- SLASH3,
559
- path[end] === SLASH3 ? end - 1 : end
560
- );
561
- return index < 0 ? path : path.slice(index + 1);
562
- };
563
- var parentOf = (path) => {
564
- if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
565
- const slices = path.split(SLASH3).filter(Boolean);
566
- slices.pop();
567
- return slices.length ? slices.join(SLASH3) + SLASH3 : EMPTY;
568
- }
569
- const end = path.length - 1;
570
- const cut = path.lastIndexOf(
571
- SLASH3,
572
- path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
573
- );
574
- return cut < 0 ? EMPTY : path.slice(0, cut + 1);
575
- };
576
- var isString = (subject) => typeof subject === "string";
577
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
578
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
579
- var IgnoreRule = class {
580
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
581
- this.pattern = pattern;
582
- this.mark = mark;
583
- this.negative = negative;
584
- define(this, "body", body);
585
- define(this, "ignoreCase", ignoreCase);
586
- define(this, "regexPrefix", prefix);
587
- }
588
- // Worked out on first use and kept behind an own property, the way `regex`
589
- // caches itself in `_regex`. Deciding it in the constructor instead would
590
- // add a fourth `defineProperty` to every rule ever built, which cost 4% of
591
- // every compile -- including the compiles of rules that are never matched
592
- // against anything.
593
- get _basenameOnly() {
594
- return define(this, "_basenameOnly", matchesBasename(this.body));
595
- }
596
- get regex() {
597
- const key = UNDERSCORE + MODE_IGNORE;
598
- if (this[key]) {
599
- return this[key];
600
- }
601
- return this._make(MODE_IGNORE, key);
602
- }
603
- get checkRegex() {
604
- const key = UNDERSCORE + MODE_CHECK_IGNORE;
605
- if (this[key]) {
606
- return this[key];
607
- }
608
- return this._make(MODE_CHECK_IGNORE, key);
609
- }
610
- _make(mode, key) {
611
- const str2 = pinWildcards(
612
- mode === MODE_IGNORE ? this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar) : checkSourceOf(this.body, this.regexPrefix)
613
- );
614
- const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
615
- return define(this, key, regex);
616
- }
617
- };
618
- var createRule = ({
619
- pattern,
620
- mark
621
- }, ignoreCase) => {
622
- let negative = false;
623
- let body = pattern;
624
- if (body.indexOf("!") === 0) {
625
- negative = true;
626
- body = body.substr(1);
627
- }
628
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
629
- const regexPrefix = makeRegexPrefix(body);
630
- return new IgnoreRule(
631
- pattern,
632
- mark,
633
- body,
634
- ignoreCase,
635
- negative,
636
- regexPrefix
637
- );
638
- };
639
- var RuleManager = class {
640
- constructor(ignoreCase) {
641
- this._ignoreCase = ignoreCase;
642
- this._rules = [];
643
- this._basenameCount = 0;
644
- }
645
- _add(pattern) {
646
- if (pattern && pattern[KEY_IGNORE]) {
647
- this._rules = this._rules.concat(pattern._rules._rules);
648
- this._basenameCount += pattern._rules._basenameCount;
649
- this._added = true;
650
- return;
651
- }
652
- if (isString(pattern)) {
653
- pattern = {
654
- pattern
655
- };
656
- }
657
- if (checkPattern(pattern.pattern)) {
658
- const rule = createRule(pattern, this._ignoreCase);
659
- this._added = true;
660
- this._rules.push(rule);
661
- if (matchesBasename(rule.body)) {
662
- this._basenameCount++;
663
- }
664
- }
665
- }
666
- // @param {Array<string> | string | Ignore} pattern
667
- add(pattern) {
668
- this._added = false;
669
- makeArray(
670
- isString(pattern) ? splitPattern(pattern) : pattern
671
- ).forEach(this._add, this);
672
- if (this._added) {
673
- this._literalRules = UNDEFINED;
674
- }
675
- return this._added;
676
- }
677
- // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule
678
- // ending in a wildcard can match it (see `checkSourceOf`), so the rest
679
- // are left out once, rather than tested or compiled for every path.
680
- testLiteral(path) {
681
- const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
- ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
683
- ));
684
- let ignored = false;
685
- let unignored = false;
686
- let matchedRule;
687
- for (let index = rules.length - 1; index >= 0; index--) {
688
- const rule = rules[index];
689
- if (rule.checkRegex.test(path)) {
690
- ignored = !rule.negative;
691
- unignored = rule.negative;
692
- matchedRule = rule.negative ? UNDEFINED : rule;
693
- break;
694
- }
695
- }
696
- const ret = {
697
- ignored,
698
- unignored
699
- };
700
- if (matchedRule) {
701
- ret.rule = matchedRule;
702
- }
703
- return ret;
704
- }
705
- // Test one single path without recursively checking parent directories
706
- //
707
- // - checkUnignored `boolean` whether should check if the path is unignored,
708
- // setting `checkUnignored` to `false` could reduce additional
709
- // path matching.
710
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
711
- // @returns {TestResult} true if a file is ignored
712
- test(path, checkUnignored, mode) {
713
- let ignored = false;
714
- let unignored = false;
715
- let matchedRule;
716
- const rules = this._rules;
717
- const { length } = rules;
718
- const shortcut = this._basenameCount * 2 >= length;
719
- const basename8 = shortcut ? basenameOf(path) : path;
720
- for (let index = 0; index < length; index++) {
721
- const rule = rules[index];
722
- const { negative } = rule;
723
- const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
724
- if (!skip && rule[mode].test(
725
- shortcut && rule._basenameOnly ? basename8 : path
726
- )) {
727
- ignored = !negative;
728
- unignored = negative;
729
- matchedRule = negative ? UNDEFINED : rule;
730
- }
731
- }
732
- const ret = {
733
- ignored,
734
- unignored
735
- };
736
- if (matchedRule) {
737
- ret.rule = matchedRule;
738
- }
739
- return ret;
740
- }
741
- };
742
- var throwError = (message, Ctor) => {
743
- throw new Ctor(message);
744
- };
745
- var checkPath = (path, originalPath, doThrow) => {
746
- if (!isString(path)) {
747
- return doThrow(
748
- `path must be a string, but got \`${originalPath}\``,
749
- TypeError
750
- );
751
- }
752
- if (!path) {
753
- return doThrow(`path must not be empty`, TypeError);
754
- }
755
- if (checkPath.isNotRelative(path)) {
756
- const r = "`path.relative()`d";
757
- return doThrow(
758
- `path should be a ${r} string, but got "${originalPath}"`,
759
- RangeError
760
- );
761
- }
762
- return true;
763
- };
764
- var isNotRelative = (path) => {
765
- const first = path.charCodeAt(0);
766
- if (first === SLASH_CODE) {
767
- return true;
768
- }
769
- if (first !== DOT_CODE) {
770
- return false;
771
- }
772
- if (path.length === 1) {
773
- return true;
774
- }
775
- const second = path.charCodeAt(1);
776
- if (second === SLASH_CODE) {
777
- return true;
778
- }
779
- if (second !== DOT_CODE) {
780
- return false;
781
- }
782
- return path.length === 2 || path.charCodeAt(2) === SLASH_CODE;
783
- };
784
- checkPath.isNotRelative = isNotRelative;
785
- checkPath.convert = (p) => p;
786
- var Ignore = class {
787
- constructor({
788
- ignorecase = true,
789
- ignoreCase = ignorecase,
790
- allowRelativePaths = false
791
- } = {}) {
792
- define(this, KEY_IGNORE, true);
793
- this._rules = new RuleManager(ignoreCase);
794
- this._strictPathCheck = !allowRelativePaths;
795
- this._initCache();
796
- }
797
- _initCache() {
798
- this._ignoreCache = /* @__PURE__ */ Object.create(null);
799
- this._testCache = /* @__PURE__ */ Object.create(null);
800
- }
801
- add(pattern) {
802
- if (this._rules.add(pattern)) {
803
- this._initCache();
804
- }
805
- return this;
806
- }
807
- // legacy
808
- addPattern(pattern) {
809
- return this.add(pattern);
810
- }
811
- // @returns {TestResult}
812
- _test(originalPath, cache, checkUnignored) {
813
- const path = originalPath && checkPath.convert(originalPath);
814
- checkPath(
815
- path,
816
- originalPath,
817
- this._strictPathCheck ? throwError : RETURN_FALSE
818
- );
819
- return this._t(path, cache, checkUnignored);
820
- }
821
- checkIgnore(path) {
822
- if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {
823
- return this.test(path);
824
- }
825
- const dir = this._t(path, this._testCache, true);
826
- if (dir.ignored) {
827
- return dir;
828
- }
829
- const literal2 = this._rules.testLiteral(path);
830
- return literal2.ignored || literal2.unignored ? literal2 : dir;
831
- }
832
- _t(path, cache, checkUnignored) {
833
- if (path in cache) {
834
- return cache[path];
835
- }
836
- const parentPath = parentOf(path);
837
- const parent = parentPath ? this._t(parentPath, cache, checkUnignored) : UNDEFINED;
838
- return cache[path] = parent && parent.ignored ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE);
839
- }
840
- ignores(path) {
841
- return this._test(path, this._ignoreCache, false).ignored;
842
- }
843
- createFilter() {
844
- return (path) => !this.ignores(path);
845
- }
846
- filter(paths) {
847
- return makeArray(paths).filter(this.createFilter());
848
- }
849
- // @returns {TestResult}
850
- test(path) {
851
- return this._test(path, this._testCache, true);
852
- }
853
- };
854
- var factory = (options) => new Ignore(options);
855
- var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
856
- var setupWindows = () => {
857
- const makePosix = (str2) => /^\\\\\?\\/.test(str2) || /["<>|\u0000-\u001F]+/u.test(str2) ? str2 : str2.replace(/\\/g, "/");
858
- checkPath.convert = makePosix;
859
- const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
860
- checkPath.isNotRelative = (path) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
861
- };
862
- if (
863
- // Detect `process` so that it can run in browsers.
864
- typeof process !== "undefined" && process.platform === "win32"
865
- ) {
866
- setupWindows();
867
- }
868
- module.exports = factory;
869
- factory.default = factory;
870
- module.exports.isPathValid = isPathValid;
871
- define(module.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
872
- }
873
- });
874
-
875
- // ../../packages/persistence/src/attached-derived.ts
876
- import { rmSync } from "fs";
877
- import { join } from "path";
878
- var POLICY_CACHE_FILENAME = "policy-cache.json";
879
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
880
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
881
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
882
-
883
- // ../../packages/persistence/src/control-plane-credential.ts
884
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
885
- import { join as join2 } from "path";
886
6
 
887
7
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
888
8
  var DEFERRED_MIGRATION_TAGS = [
@@ -3867,9 +2987,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3867
2987
  function stripTabAndNewline(value) {
3868
2988
  return value.replace(asciiTabOrNewline, "");
3869
2989
  }
3870
- function urlHostnameOk(url2, hostname7) {
3871
- hostname7.lastIndex = 0;
3872
- return hostname7.test(url2.hostname);
2990
+ function urlHostnameOk(url2, hostname6) {
2991
+ hostname6.lastIndex = 0;
2992
+ return hostname6.test(url2.hostname);
3873
2993
  }
3874
2994
  function urlProtocolOk(url2, protocol) {
3875
2995
  protocol.lastIndex = 0;
@@ -20789,13 +19909,16 @@ function serviceTierMultiplier(tier) {
20789
19909
  if (tier === void 0) return 1;
20790
19910
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20791
19911
  }
19912
+ function promptTokensOf(usage) {
19913
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19914
+ }
20792
19915
  function costOf(price, usage) {
20793
19916
  const metered = [
20794
19917
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20795
19918
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20796
19919
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20797
19920
  ];
20798
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19921
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20799
19922
  if (band !== null && (band.input === null || band.output === null)) return null;
20800
19923
  const inputRate = band?.input ?? price.input;
20801
19924
  const outputRate = band?.output ?? price.output;
@@ -20868,8 +19991,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20868
19991
  ["ollama", "local"],
20869
19992
  ["local", "local"]
20870
19993
  ]);
20871
- function hostingFor(platform2) {
20872
- return PLATFORM_HOSTING.get(platform2) ?? "api";
19994
+ function hostingFor(platform) {
19995
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20873
19996
  }
20874
19997
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20875
19998
  ["anthropic", "anthropic"],
@@ -20883,8 +20006,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20883
20006
  function firstPartyPlatformFor(vendor2) {
20884
20007
  return FIRST_PARTY.get(vendor2) ?? null;
20885
20008
  }
20886
- function isFirstParty(vendor2, platform2) {
20887
- return FIRST_PARTY.get(vendor2) === platform2;
20009
+ function isFirstParty(vendor2, platform) {
20010
+ return FIRST_PARTY.get(vendor2) === platform;
20888
20011
  }
20889
20012
  var PLATFORM_NAMESPACES = Object.freeze([
20890
20013
  "anthropic",
@@ -20945,14 +20068,14 @@ var ModelVendorBuilder = class {
20945
20068
  );
20946
20069
  }
20947
20070
  for (const ref of spec.on ?? []) {
20948
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20949
- const firstParty = isFirstParty(this.vendor, platform2);
20950
- const hosting = hostingFor(platform2);
20071
+ const { platform, price, retention, region } = normalizeRef(ref);
20072
+ const firstParty = isFirstParty(this.vendor, platform);
20073
+ const hosting = hostingFor(platform);
20951
20074
  const isSelfHosted = hosting === "local";
20952
20075
  platforms.set(
20953
- platform2,
20076
+ platform,
20954
20077
  Object.freeze({
20955
- platform: platform2,
20078
+ platform,
20956
20079
  hosting,
20957
20080
  firstParty,
20958
20081
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21005,35 +20128,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21005
20128
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21006
20129
  var BEDROCK_REVISION_RE = /:\d+$/u;
21007
20130
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21008
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20131
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21009
20132
  function stripPlatformDecorations(model) {
21010
20133
  let id = model.trim();
21011
- let platform2 = null;
20134
+ let platform = null;
21012
20135
  if (GEO_PREFIX_RE.test(id)) {
21013
20136
  id = id.replace(GEO_PREFIX_RE, "");
21014
- platform2 = "bedrock";
20137
+ platform = "bedrock";
21015
20138
  }
21016
20139
  if (NAMESPACE_DOT_RE.test(id)) {
21017
20140
  id = id.replace(NAMESPACE_DOT_RE, "");
21018
- platform2 ??= "bedrock";
20141
+ platform ??= "bedrock";
21019
20142
  }
21020
20143
  if (BEDROCK_VERSION_RE.test(id)) {
21021
20144
  id = id.replace(BEDROCK_VERSION_RE, "");
21022
- platform2 ??= "bedrock";
20145
+ platform ??= "bedrock";
21023
20146
  } else if (BEDROCK_REVISION_RE.test(id)) {
21024
20147
  id = id.replace(BEDROCK_REVISION_RE, "");
21025
- platform2 ??= "bedrock";
20148
+ platform ??= "bedrock";
21026
20149
  }
21027
20150
  if (VERTEX_VERSION_RE.test(id)) {
21028
20151
  id = id.replace(VERTEX_VERSION_RE, "");
21029
- platform2 ??= "vertex";
20152
+ platform ??= "vertex";
21030
20153
  }
21031
20154
  if (NAMESPACE_SLASH_RE.test(id)) {
21032
20155
  id = id.replace(NAMESPACE_SLASH_RE, "");
21033
20156
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21034
20157
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21035
20158
  }
21036
- return { id, platform: platform2 };
20159
+ return { id, platform };
21037
20160
  }
21038
20161
  function buildModelIndex(entries) {
21039
20162
  const byId = /* @__PURE__ */ new Map();
@@ -21050,19 +20173,19 @@ function resolveModel(raw, index) {
21050
20173
  if (exact !== void 0) {
21051
20174
  return { entry: exact, canonicalId: raw, platform: null, raw };
21052
20175
  }
21053
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
20176
+ const { id, platform } = stripPlatformDecorations(raw);
21054
20177
  const stripped = index.byId.get(id);
21055
20178
  if (stripped !== void 0) {
21056
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
20179
+ return { entry: stripped, canonicalId: id, platform, raw };
21057
20180
  }
21058
20181
  if (DATED_SUFFIX_RE.test(id)) {
21059
20182
  const undated = id.replace(DATED_SUFFIX_RE, "");
21060
20183
  const byDate = index.byId.get(undated);
21061
20184
  if (byDate !== void 0) {
21062
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
20185
+ return { entry: byDate, canonicalId: undated, platform, raw };
21063
20186
  }
21064
20187
  }
21065
- return { entry: null, canonicalId: raw, platform: platform2, raw };
20188
+ return { entry: null, canonicalId: raw, platform, raw };
21066
20189
  }
21067
20190
 
21068
20191
  // ../../packages/schema/src/model/catalog.ts
@@ -21155,7 +20278,7 @@ anthropic.model("claude-haiku-4-5", {
21155
20278
  name: "Claude Haiku 4.5",
21156
20279
  ctx: 2e5,
21157
20280
  maxOut: 64e3,
21158
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20281
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21159
20282
  capability: null,
21160
20283
  price: anthropicPrice(1, 5, 0.1),
21161
20284
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21286,6 +20409,11 @@ openai.model("gpt-4o", {
21286
20409
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21287
20410
  on: [...OPENAI_RESELLERS]
21288
20411
  });
20412
+ openai.model("gpt-4o-2024-05-13", {
20413
+ name: "GPT-4o (2024-05-13)",
20414
+ price: tokenPrice(5, 15),
20415
+ on: [...OPENAI_RESELLERS]
20416
+ });
21289
20417
  openai.model("gpt-4o-mini", {
21290
20418
  name: "GPT-4o mini",
21291
20419
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21305,6 +20433,24 @@ openai.model("o3", {
21305
20433
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21306
20434
  on: [...OPENAI_RESELLERS]
21307
20435
  });
20436
+ openai.model("text-embedding-3-small", {
20437
+ name: "text-embedding-3-small",
20438
+ capability: "embedding",
20439
+ price: tokenPrice(0.02, 0),
20440
+ on: [...OPENAI_RESELLERS]
20441
+ });
20442
+ openai.model("text-embedding-3-large", {
20443
+ name: "text-embedding-3-large",
20444
+ capability: "embedding",
20445
+ price: tokenPrice(0.13, 0),
20446
+ on: [...OPENAI_RESELLERS]
20447
+ });
20448
+ openai.model("text-embedding-ada-002", {
20449
+ name: "text-embedding-ada-002",
20450
+ capability: "embedding",
20451
+ price: tokenPrice(0.1, 0),
20452
+ on: [...OPENAI_RESELLERS]
20453
+ });
21308
20454
  openai.model("gpt-oss-120b", {
21309
20455
  name: "GPT-OSS 120B",
21310
20456
  openWeights: true,
@@ -21591,10 +20737,21 @@ var MODEL_ENTRIES = Object.freeze([
21591
20737
  ...alibaba.models(),
21592
20738
  ...amazon.models()
21593
20739
  ]);
20740
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20741
+ [
20742
+ ...new Set(
20743
+ MODEL_ENTRIES.flatMap(
20744
+ (entry) => [...entry.platforms.values()].flatMap(
20745
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20746
+ )
20747
+ )
20748
+ )
20749
+ ].sort((a, b) => a - b)
20750
+ );
21594
20751
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21595
20752
 
21596
20753
  // ../../packages/schema/src/model/governance.ts
21597
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20754
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21598
20755
  var DataRetention = external_exports.enum([
21599
20756
  "zero_retention",
21600
20757
  "no_storage",
@@ -21777,16 +20934,16 @@ function platformForProvider(provider) {
21777
20934
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21778
20935
  }
21779
20936
  function isLocalProvider(provider) {
21780
- const platform2 = platformForProvider(provider);
21781
- return platform2 !== null && hostingFor(platform2) === "local";
20937
+ const platform = platformForProvider(provider);
20938
+ return platform !== null && hostingFor(platform) === "local";
21782
20939
  }
21783
20940
  function priceFor(provider, model) {
21784
20941
  if (isLocalProvider(provider)) return ZERO_PRICE;
21785
20942
  const resolved = resolveModel(model, MODEL_INDEX);
21786
20943
  if (resolved.entry === null) return null;
21787
- const platform2 = resolved.platform ?? platformForProvider(provider);
21788
- if (platform2 === null) return null;
21789
- return resolved.entry.platforms.get(platform2)?.price ?? null;
20944
+ const platform = resolved.platform ?? platformForProvider(provider);
20945
+ if (platform === null) return null;
20946
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21790
20947
  }
21791
20948
  var defaultCostModel = {
21792
20949
  normalizeModelId(provider, model) {
@@ -21812,7 +20969,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21812
20969
 
21813
20970
  // ../../packages/schema/src/token/token-report.ts
21814
20971
  var num = (value) => value ?? 0;
21815
- function costUsageOf(a) {
20972
+ function costUsageOf(a, promptTokens) {
21816
20973
  const usage = {
21817
20974
  inputTokens: num(a.input_tokens),
21818
20975
  outputTokens: num(a.output_tokens),
@@ -21822,11 +20979,12 @@ function costUsageOf(a) {
21822
20979
  webSearchRequests: num(a.web_search_requests)
21823
20980
  };
21824
20981
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20982
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21825
20983
  return usage;
21826
20984
  }
21827
20985
  function buildTokenReports(leaves, costModel) {
21828
20986
  const bySession = /* @__PURE__ */ new Map();
21829
- for (const { sessionId, attributes } of leaves) {
20987
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21830
20988
  const provider = attributes.provider ?? "unknown";
21831
20989
  const model = attributes.model ?? "unknown";
21832
20990
  const key = `${provider} ${model}`;
@@ -21845,7 +21003,8 @@ function buildTokenReports(leaves, costModel) {
21845
21003
  cacheCreation: 0,
21846
21004
  cacheRead: 0,
21847
21005
  costUsd: 0,
21848
- priced: false
21006
+ priced: false,
21007
+ partial: false
21849
21008
  };
21850
21009
  rollups.set(key, acc);
21851
21010
  }
@@ -21853,8 +21012,14 @@ function buildTokenReports(leaves, costModel) {
21853
21012
  acc.output += num(attributes.output_tokens);
21854
21013
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21855
21014
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21856
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21857
- if (leafCost !== null) {
21015
+ const leafCost = costModel.costFor({
21016
+ provider,
21017
+ model,
21018
+ usage: costUsageOf(attributes, promptTokens)
21019
+ });
21020
+ if (leafCost === null) {
21021
+ acc.partial = true;
21022
+ } else {
21858
21023
  acc.costUsd += leafCost;
21859
21024
  acc.priced = true;
21860
21025
  }
@@ -21870,9 +21035,8 @@ function buildTokenReports(leaves, costModel) {
21870
21035
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21871
21036
  totalTokens += rollupTotal;
21872
21037
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21873
- if (estimatedCostUsd === null) {
21874
- anyUnpriced = true;
21875
- } else {
21038
+ if (acc.partial) anyUnpriced = true;
21039
+ if (estimatedCostUsd !== null) {
21876
21040
  anyPriced = true;
21877
21041
  costUsd += estimatedCostUsd;
21878
21042
  }
@@ -21895,7 +21059,7 @@ function buildTokenReports(leaves, costModel) {
21895
21059
  totalTokens,
21896
21060
  // Σ of the PRICED rollups; null when none had a known price.
21897
21061
  estimatedCostUsd: anyPriced ? costUsd : null,
21898
- // Any unknown (provider, model) means the total understates real spend.
21062
+ // Any call priced to null means the total understates real spend.
21899
21063
  costIsPartial: anyUnpriced
21900
21064
  });
21901
21065
  }
@@ -22597,6 +21761,11 @@ var CaptureAttributes = external_exports.object({
22597
21761
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22598
21762
  // repeated rather than referenced because a store reader opens this file.
22599
21763
  redact_degraded_to: ActionTaken.optional(),
21764
+ // Why a capture has no content and no findings: its field was refused
21765
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
21766
+ // whose value this is). Absent on every capture that was scanned, so a
21767
+ // reader can tell a refused row from an empty clean one.
21768
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22600
21769
  // The scope key this capture was stamped with: the canonical repository
22601
21770
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22602
21771
  // against its working directory), else of its own working directory, or a
@@ -22774,8 +21943,9 @@ var SessionTokenReport = external_exports.object({
22774
21943
  totalTokens: external_exports.number().int().nonnegative(),
22775
21944
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22776
21945
  estimatedCostUsd: external_exports.number().nullable(),
22777
- // True whenever any rollup has a null cost (unknown provider/model), so the
22778
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21946
+ // True whenever any call priced to null (an unknown provider/model, or a call
21947
+ // over a long-context threshold whose rate is unpublished), so the total
21948
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22779
21949
  // precise figure rather than silently dropping the unpriced calls.
22780
21950
  costIsPartial: external_exports.boolean()
22781
21951
  });
@@ -23652,7 +22822,15 @@ var StorePostureSnapshot = external_exports.object({
23652
22822
  policyCounts: StorePosturePolicyCounts,
23653
22823
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23654
22824
  // getting its 200 without a payload change.
23655
- plugin: StorePosturePlugin.optional()
22825
+ plugin: StorePosturePlugin.optional(),
22826
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22827
+ // machine attachment omits it, so its body is byte for byte the one it
22828
+ // sent before this member existed. Absent therefore means machine-wide OR
22829
+ // a reporter older than this member, never "scoped". Both values parse, so
22830
+ // a sender that one day spells `machine` breaks no receiver; any other
22831
+ // value fails the whole snapshot, which is why the reporter sends a
22832
+ // constant and never the raw mode.
22833
+ attachmentMode: AttachmentMode.optional()
23656
22834
  }).meta({ id: "StorePostureSnapshot" });
23657
22835
  var CAPTURE_VERSION_PREFIX = "capture/";
23658
22836
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23929,7 +23107,19 @@ var EventMetadata = external_exports.object({
23929
23107
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23930
23108
  // Closing either means moving the reason onto the finding row, which
23931
23109
  // already carries its own action.
23932
- redactDegradedTo: ActionTaken.optional()
23110
+ redactDegradedTo: ActionTaken.optional(),
23111
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23112
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23113
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23114
+ // field instead of letting it through unscanned.
23115
+ //
23116
+ // - 'timeout': the bounded scan ran out of time.
23117
+ // - 'unavailable': no worker could run it.
23118
+ //
23119
+ // A refused row stores '' as its content and has no findings, which is
23120
+ // exactly what a clean, empty capture looks like — this marker is the only
23121
+ // thing that tells the two apart. Absent on every capture that was scanned.
23122
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23933
23123
  }).meta({ id: "EventMetadata" });
23934
23124
  var Event = external_exports.object({
23935
23125
  id: external_exports.guid(),
@@ -24099,7 +23289,7 @@ var Rule = external_exports.strictObject({
24099
23289
  postValidators: external_exports.array(PostValidatorRef).optional(),
24100
23290
  requiresNearby: RequiresNearby.optional(),
24101
23291
  examples: external_exports.array(external_exports.string()).optional(),
24102
- // Whether the matched text is itself sensitive. Absent means 'value'.
23292
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24103
23293
  evidence: RuleEvidence.optional()
24104
23294
  }).meta({ id: "Rule" });
24105
23295
  var Author = external_exports.object({
@@ -24191,7 +23381,13 @@ var DetectionRule = external_exports.object({
24191
23381
  // Representative matching strings the rule author shipped with the rule. The
24192
23382
  // cheapest honest answer to "show me what this rule catches" — every bundled
24193
23383
  // rule has them, and they are already in the stored snapshot.
24194
- examples: external_exports.array(external_exports.string()).optional()
23384
+ examples: external_exports.array(external_exports.string()).optional(),
23385
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23386
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23387
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23388
+ // in a value category (secret/pii/financial/phi) is always 'value',
23389
+ // whatever it declares.
23390
+ evidence: RuleEvidence.optional()
24195
23391
  }).meta({ id: "DetectionRule" });
24196
23392
  var DetectionUpdate = external_exports.object({
24197
23393
  available: external_exports.boolean(),
@@ -24259,8 +23455,10 @@ var ImportDetectionRequest = external_exports.object({
24259
23455
  }).meta({ id: "ImportDetectionRequest" });
24260
23456
 
24261
23457
  // ../../packages/schema/src/zod/detection-build.ts
24262
- function optional2(key, parsed2, raw) {
24263
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
23458
+ function optional2(key, raw, parse4) {
23459
+ if (raw === void 0) return {};
23460
+ const parsed2 = parse4(raw);
23461
+ if (!parsed2.success || parsed2.data === void 0) return {};
24264
23462
  return { [key]: parsed2.data };
24265
23463
  }
24266
23464
  function isStringArray(value) {
@@ -24295,10 +23493,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24295
23493
  category: r.category,
24296
23494
  severity: r.severity,
24297
23495
  matcher: parsed2.data,
24298
- // The rest of what decides whether this rule fires. Carried so a consumer
24299
- // re-running the rule (a preview, a tester) evaluates what the engine
24300
- // evaluates rather than a matcher stripped of its guards — half the
24301
- // bundled catalog carries at least one of these.
23496
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23497
+ // decides whether this rule fires. Carried so a consumer re-running the
23498
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23499
+ // than a matcher stripped of its guards — half the bundled catalog
23500
+ // carries at least one of these. `examples` and `evidence` describe the
23501
+ // rule and never gate a match.
24302
23502
  //
24303
23503
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24304
23504
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24308,18 +23508,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24308
23508
  // test should stay exactly what it was, namely a renderable matcher. A
24309
23509
  // field that fails validation is omitted, which reads as "not set" and is
24310
23510
  // the same thing the consumer saw before this change.
24311
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23511
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24312
23512
  ...optional2(
24313
23513
  "postValidators",
24314
- PostValidatorRef.array().safeParse(r.postValidators),
24315
- r.postValidators
23514
+ r.postValidators,
23515
+ (v) => PostValidatorRef.array().safeParse(v)
24316
23516
  ),
24317
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23517
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24318
23518
  ...optional2(
24319
23519
  "examples",
24320
- { success: isStringArray(r.examples), data: r.examples },
24321
- r.examples
24322
- )
23520
+ r.examples,
23521
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23522
+ ),
23523
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24323
23524
  }
24324
23525
  ];
24325
23526
  });
@@ -25012,11 +24213,14 @@ var PolicyBundle = external_exports.object({
25012
24213
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
25013
24214
  // Model ids (the raw `model` string a harness reports, e.g.
25014
24215
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
25015
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
25016
- // one (UserPromptSubmit). Optional so an older backend — and an older
25017
- // on-disk cache — still parses; consumers read `?? []`, which is the
25018
- // unenforced behaviour that predates this field and the safe direction to
25019
- // default.
24216
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24217
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24218
+ // wherever the organization governs the event: everywhere on a
24219
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24220
+ // one (the plugin runtime's `governanceApplies`).
24221
+ // Optional so an older backend — and an older on-disk cache — still
24222
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24223
+ // predates this field and the safe direction to default.
25020
24224
  //
25021
24225
  // Ids, not display names: the governance decision is keyed on the exact
25022
24226
  // string the harness reports (`model_status_override.versionId` in the
@@ -25467,6 +24671,8 @@ var AttachmentScopeEntry = external_exports.object({
25467
24671
  });
25468
24672
  var AttachmentScope = external_exports.object({
25469
24673
  endpoint: external_exports.string().min(1),
24674
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24675
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25470
24676
  entries: external_exports.array(AttachmentScopeEntry)
25471
24677
  });
25472
24678
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25479,7 +24685,13 @@ function parseAttachmentScope(raw) {
25479
24685
  const entry = AttachmentScopeEntry.safeParse(candidate);
25480
24686
  if (entry.success) entries.push(entry.data);
25481
24687
  }
25482
- return { endpoint: envelope.data.endpoint, entries };
24688
+ const { endpoint, tenantName, userEmail } = envelope.data;
24689
+ return {
24690
+ endpoint,
24691
+ ...tenantName === void 0 ? {} : { tenantName },
24692
+ ...userEmail === void 0 ? {} : { userEmail },
24693
+ entries
24694
+ };
25483
24695
  } catch {
25484
24696
  return void 0;
25485
24697
  }
@@ -25716,6 +24928,7 @@ function toCaptureAttributes(event) {
25716
24928
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25717
24929
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25718
24930
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24931
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25719
24932
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25720
24933
  // has ever populated either), but every legacy metadata key still rides
25721
24934
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25844,6 +25057,27 @@ var ManagedSettings = external_exports.object({
25844
25057
  };
25845
25058
  }).meta({ id: "ManagedSettings" });
25846
25059
 
25060
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
25061
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
25062
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
25063
+ var ModPolicySnapshot = external_exports.object({
25064
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
25065
+ generatedAt: external_exports.iso.datetime(),
25066
+ // The complete effective ruleset, as the hook's runtime scans with it: the
25067
+ // user's enabled installed packs (user-modified and custom packs included).
25068
+ // Absent means the store holds no authoritative snapshot, and the reader
25069
+ // scans with the packs it ships — the hook's own fallback.
25070
+ rules: external_exports.array(Rule).optional(),
25071
+ // Rule-targeted actions (first enabled policy per rule wins).
25072
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25073
+ // The resolved action per detection category.
25074
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25075
+ // Rules with an active exception grant. Honouring a grant means matching a
25076
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25077
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25078
+ exceptionRuleIds: external_exports.array(external_exports.string())
25079
+ }).meta({ id: "ModPolicySnapshot" });
25080
+
25847
25081
  // ../../packages/schema/src/zod/project-files.ts
25848
25082
  var ProjectFileInput = external_exports.object({
25849
25083
  path: external_exports.string().min(1),
@@ -26164,7 +25398,16 @@ var AttachInput = external_exports.object({
26164
25398
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26165
25399
  // renders a longer one usefully.
26166
25400
  label: printable(200).optional(),
26167
- accessKey: external_exports.string()
25401
+ accessKey: external_exports.string(),
25402
+ // How much of this machine the attachment is for: everything, or only the
25403
+ // repositories its user enrolls. Optional, so an input without it still
25404
+ // parses; what an absent mode means is for whatever reads it to decide, not
25405
+ // this shape. This member validates the VALUE rather than leaving that to the
25406
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25407
+ // rejection names the field, so a value that is not a mode is refused as a bad
25408
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25409
+ // it as the mode to attach in.
25410
+ mode: AttachmentMode.optional()
26168
25411
  });
26169
25412
 
26170
25413
  // ../../packages/schema/src/zod/triage.ts
@@ -26450,6 +25693,18 @@ function fromCaptureStatusAttributes(bag) {
26450
25693
  return parsedStatus.success ? parsedStatus.data : null;
26451
25694
  }
26452
25695
 
25696
+ // ../../packages/persistence/src/attached-derived.ts
25697
+ import { rmSync } from "fs";
25698
+ import { join } from "path";
25699
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25700
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25701
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
25702
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
25703
+
25704
+ // ../../packages/persistence/src/control-plane-credential.ts
25705
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25706
+ import { join as join2 } from "path";
25707
+
26453
25708
  // ../../packages/persistence/src/paths.ts
26454
25709
  import {
26455
25710
  chmodSync,
@@ -26576,6 +25831,14 @@ function repairOrRefuseMode(file2) {
26576
25831
  }
26577
25832
  return "ok";
26578
25833
  }
25834
+ function asReadableCredential(value) {
25835
+ const result = AttachedCredentialAny.safeParse(value);
25836
+ if (!result.success) return null;
25837
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25838
+ return null;
25839
+ }
25840
+ return result.data;
25841
+ }
26579
25842
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26580
25843
  const file2 = controlPlaneCredentialPath(settingsDir2);
26581
25844
  let raw;
@@ -26594,20 +25857,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26594
25857
  } catch {
26595
25858
  return { usable: false, reason: "malformed" };
26596
25859
  }
26597
- const result = AttachedCredential.safeParse(parsed2);
26598
- if (!result.success) return { usable: false, reason: "malformed" };
26599
- if (!isSafeEndpoint(result.data.endpoint)) {
25860
+ const credential = asReadableCredential(parsed2);
25861
+ if (credential === null) return { usable: false, reason: "malformed" };
25862
+ if (!isSafeEndpoint(credential.endpoint)) {
26600
25863
  return { usable: false, reason: "unsafe-endpoint" };
26601
25864
  }
26602
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25865
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26603
25866
  return {
26604
25867
  usable: false,
26605
25868
  reason: "endpoint-mismatch",
26606
- credentialEndpoint: result.data.endpoint,
25869
+ credentialEndpoint: credential.endpoint,
26607
25870
  settingsEndpoint: connection.endpoint
26608
25871
  };
26609
25872
  }
26610
- return { usable: true, credential: result.data };
25873
+ return { usable: true, credential };
26611
25874
  }
26612
25875
  function readControlPlaneCredential(settingsDir2, connection) {
26613
25876
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26616,7 +25879,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26616
25879
 
26617
25880
  // ../../packages/persistence/src/database.ts
26618
25881
  import { randomUUID as randomUUID11 } from "crypto";
26619
- import { dirname as dirname2, join as join7, sep } from "path";
25882
+ import { dirname as dirname2, join as join8, sep } from "path";
26620
25883
  import { DatabaseSync } from "node:sqlite";
26621
25884
 
26622
25885
  // ../../packages/persistence/src/ids.ts
@@ -26660,6 +25923,7 @@ function captureId(sessionId, contentHash, filePath = null) {
26660
25923
  canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
26661
25924
  );
26662
25925
  }
25926
+ var DOT = ".".charCodeAt(0);
26663
25927
 
26664
25928
  // ../../packages/persistence/src/internal/snapshot.ts
26665
25929
  import { randomUUID } from "crypto";
@@ -26987,6 +26251,25 @@ function scopeKeysParam(scopeKeys) {
26987
26251
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26988
26252
  FROM audit_events AS session_root
26989
26253
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26254
+ var COUNTED_IN_SCOPE = `
26255
+ AND ${inScope("scope_key")}
26256
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26257
+ var DRAIN_TOTALS = `SELECT
26258
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26259
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26260
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26261
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26262
+ THEN 1 ELSE 0 END) AS skipped,
26263
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26264
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26265
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26266
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26267
+ FROM audit_events
26268
+ WHERE event_type IN (${TYPE_LIST})`;
26269
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26270
+ FROM audit_events
26271
+ WHERE synced_at = ${String(SKIPPED)}
26272
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26990
26273
  var ROW_COLUMNS = `id,
26991
26274
  parent_id AS parentId,
26992
26275
  root_session_id AS rootSessionId,
@@ -27062,7 +26345,7 @@ var SqliteHistorySyncRepository = class {
27062
26345
  );
27063
26346
  this.scopedCaptureRowsStmt = db.prepare(
27064
26347
  `SELECT ${ROW_COLUMNS}
27065
- FROM audit_events
26348
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27066
26349
  WHERE synced_at IS NULL
27067
26350
  AND sync_claimed_at IS NULL
27068
26351
  AND outbox_owed = 1
@@ -27115,40 +26398,28 @@ var SqliteHistorySyncRepository = class {
27115
26398
  );
27116
26399
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27117
26400
  FROM audit_events${COUNTED_SCOPE}`);
26401
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26402
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27118
26403
  this.partitionByKindStmt = db.prepare(
27119
26404
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27120
26405
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27121
26406
  GROUP BY event_type`
27122
26407
  );
27123
- this.countsStmt = db.prepare(
27124
- `SELECT
27125
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27126
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27127
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27128
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27129
- THEN 1 ELSE 0 END) AS skipped,
27130
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27131
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27132
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27133
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27134
- FROM audit_events
27135
- WHERE event_type IN (${TYPE_LIST})`
26408
+ this.scopedPartitionByKindStmt = db.prepare(
26409
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26410
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26411
+ GROUP BY event_type`
27136
26412
  );
27137
- this.captureSkipCountStmt = db.prepare(
27138
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27139
- // way the structural totals are. The split exists because a refusal is
27140
- // terminal only against the deployment that gave it, and the structural
27141
- // re-arm frees it on a change of deployment. The capture lane has no such
27142
- // escape: re-arming a capture would offer one deployment's undelivered
27143
- // prompts, with their text, to a deployment that never saw them, which is
27144
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27145
- // reasons mean the same thing — this row will not be sent — and splitting
27146
- // them would put refused captures in a bucket nothing reads and nothing
27147
- // frees.
27148
- `SELECT COUNT(*) AS skipped
27149
- FROM audit_events
27150
- WHERE synced_at = ${String(SKIPPED)}
27151
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26413
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26414
+ this.scopedCountsStmt = db.prepare(
26415
+ `${DRAIN_TOTALS}
26416
+ AND ${inScope("scope_key")}
26417
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26418
+ );
26419
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26420
+ this.scopedCaptureSkipCountStmt = db.prepare(
26421
+ `${CAPTURE_SKIPS}
26422
+ AND ${inScope("scope_key")}`
27152
26423
  );
27153
26424
  this.fingerprintStmt = db.prepare(
27154
26425
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27262,6 +26533,10 @@ var SqliteHistorySyncRepository = class {
27262
26533
  scopedCaptureRowsStmt;
27263
26534
  scopedCaptureBacklogOwedStmt;
27264
26535
  markScopeCapturesOwedStmt;
26536
+ scopedPartitionStmt;
26537
+ scopedPartitionByKindStmt;
26538
+ scopedCountsStmt;
26539
+ scopedCaptureSkipCountStmt;
27265
26540
  /**
27266
26541
  * The masked detections recorded against one tool call.
27267
26542
  *
@@ -27483,7 +26758,29 @@ var SqliteHistorySyncRepository = class {
27483
26758
  * in" — and a machine that has never attached has no boundary to pass, so
27484
26759
  * requiring one would force a caller to invent one and report the whole store
27485
26760
  * as queued.
26761
+ *
26762
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26763
+ * the rows that pass the drain's reachability rule for that scope
26764
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26765
+ * drain never offers), so a personal repository's rows are in none of them.
26766
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26767
+ * nothing.
27486
26768
  */
26769
+ partition(scopeKeys) {
26770
+ const row = getRow(
26771
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26772
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26773
+ );
26774
+ return {
26775
+ queued: row?.queued ?? 0,
26776
+ inProgress: row?.inProgress ?? 0,
26777
+ synced: row?.synced ?? 0,
26778
+ failed: row?.failed ?? 0,
26779
+ refused: row?.refused ?? 0,
26780
+ detached: row?.detached ?? 0,
26781
+ total: row?.total ?? 0
26782
+ };
26783
+ }
27487
26784
  /**
27488
26785
  * The same partition, one row per kind that a lane carries.
27489
26786
  *
@@ -27493,11 +26790,14 @@ var SqliteHistorySyncRepository = class {
27493
26790
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27494
26791
  * rows", never as "zero sent"; the two look identical in a bar and mean
27495
26792
  * different things.
26793
+ *
26794
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26795
+ * still sum to the scoped aggregate. An empty list returns no rows.
27496
26796
  */
27497
- partitionByKind() {
26797
+ partitionByKind(scopeKeys) {
27498
26798
  return allRows(
27499
- this.partitionByKindStmt,
27500
- {}
26799
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26800
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27501
26801
  ).map((row) => ({
27502
26802
  kind: row.kind,
27503
26803
  queued: row.queued ?? 0,
@@ -27509,22 +26809,25 @@ var SqliteHistorySyncRepository = class {
27509
26809
  total: row.total ?? 0
27510
26810
  }));
27511
26811
  }
27512
- partition() {
27513
- const row = getRow(this.partitionStmt, {});
27514
- return {
27515
- queued: row?.queued ?? 0,
27516
- inProgress: row?.inProgress ?? 0,
27517
- synced: row?.synced ?? 0,
27518
- failed: row?.failed ?? 0,
27519
- refused: row?.refused ?? 0,
27520
- detached: row?.detached ?? 0,
27521
- total: row?.total ?? 0
27522
- };
27523
- }
27524
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27525
- counts(before) {
27526
- const row = getRow(this.countsStmt, { before });
27527
- const captures = getRow(this.captureSkipCountStmt);
26812
+ /**
26813
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26814
+ * and skipped are totals.
26815
+ *
26816
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26817
+ * `capturesSkipped` included: a structural row is counted only when its own
26818
+ * key and its session root's key are among them, a capture when its own key
26819
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26820
+ * under the same keys and boundary. Omitted, this runs the machine
26821
+ * statements, unchanged; an empty list counts nothing.
26822
+ */
26823
+ counts(before, scopeKeys) {
26824
+ const row = getRow(
26825
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26826
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26827
+ );
26828
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26829
+ scopeKeys: scopeKeysParam(scopeKeys)
26830
+ });
27528
26831
  return {
27529
26832
  pending: row?.pending ?? 0,
27530
26833
  sent: row?.sent ?? 0,
@@ -27776,6 +27079,7 @@ function applyMigrations(db, file2, options = {}) {
27776
27079
  }
27777
27080
  ensureSyncedAtColumn(db, "audit_events");
27778
27081
  ensureScopeKeyColumn(db);
27082
+ ensureScopeOwedIndex(db);
27779
27083
  ensureScanLedgerTable(db);
27780
27084
  ensureHistorySyncTable(db);
27781
27085
  ensureBlockedDetectionsTable(db);
@@ -28216,14 +27520,48 @@ function ensureScopeKeyColumn(db) {
28216
27520
  function hasScopeKeyColumn(db) {
28217
27521
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28218
27522
  }
27523
+ 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";
27524
+ function ensureScopeOwedIndex(db) {
27525
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27526
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27527
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27528
+ if (!complete) return;
27529
+ db.exec(SCOPE_OWED_INDEX_DDL);
27530
+ }
28219
27531
  function ensureScanLedgerTable(db) {
28220
27532
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28221
27533
  path TEXT PRIMARY KEY,
28222
27534
  mtime TEXT NOT NULL,
28223
27535
  content_hash TEXT NOT NULL,
28224
27536
  ruleset_hash TEXT NOT NULL,
28225
- scanned_at INTEGER NOT NULL
27537
+ scanned_at INTEGER NOT NULL,
27538
+ scope_key TEXT,
27539
+ scope_root TEXT
28226
27540
  )`);
27541
+ ensureScanLedgerScopeKeyColumn(db);
27542
+ ensureScanLedgerScopeRootColumn(db);
27543
+ }
27544
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27545
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27546
+ function ensureScanLedgerScopeKeyColumn(db) {
27547
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27548
+ }
27549
+ function ensureScanLedgerScopeRootColumn(db) {
27550
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27551
+ }
27552
+ function ensureScanLedgerColumn(db, column, ddl) {
27553
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27554
+ if (hasScanLedgerColumn(db, column)) return;
27555
+ withTransaction(
27556
+ db,
27557
+ () => {
27558
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27559
+ },
27560
+ "IMMEDIATE"
27561
+ );
27562
+ }
27563
+ function hasScanLedgerColumn(db, column) {
27564
+ return columnNames(db, "scan_ledger").includes(column);
28227
27565
  }
28228
27566
  function ensureHistorySyncTable(db) {
28229
27567
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28274,6 +27612,106 @@ function ensureRuleProbeCacheTable(db) {
28274
27612
  )`);
28275
27613
  }
28276
27614
 
27615
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27616
+ import { createHash as createHash2 } from "crypto";
27617
+ import { readFileSync as readFileSync2 } from "fs";
27618
+ import { join as join4 } from "path";
27619
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27620
+ function modPolicySnapshotPath(dataDir2) {
27621
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27622
+ }
27623
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27624
+ const byRule = /* @__PURE__ */ new Map();
27625
+ const byCategory = /* @__PURE__ */ new Map();
27626
+ for (const policy of input2.policies) {
27627
+ if (!policy.enabled) continue;
27628
+ if ("ruleId" in policy.target) {
27629
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27630
+ } else if (!byCategory.has(policy.target.category)) {
27631
+ byCategory.set(policy.target.category, policy.action);
27632
+ }
27633
+ }
27634
+ const categoryActions = {};
27635
+ for (const category of DetectionCategory.options) {
27636
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27637
+ }
27638
+ return {
27639
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27640
+ generatedAt: generatedAt.toISOString(),
27641
+ // `examples` is documentation the mod never reads, and a custom pack's are
27642
+ // whatever its author pasted in, so they stay behind.
27643
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27644
+ ruleActions: Object.fromEntries(byRule),
27645
+ categoryActions,
27646
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27647
+ };
27648
+ }
27649
+ function assignedRuleActionPolicies(installed) {
27650
+ const out = [];
27651
+ for (const [ruleId, action] of installed.ruleActions) {
27652
+ if (installed.assignedRules.has(ruleId))
27653
+ out.push({ target: { ruleId }, action, enabled: true });
27654
+ }
27655
+ return out;
27656
+ }
27657
+ function withoutExamples(rule) {
27658
+ const copy = { ...rule };
27659
+ delete copy.examples;
27660
+ return copy;
27661
+ }
27662
+ function sameContent(a, b) {
27663
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27664
+ }
27665
+ function readModPolicySnapshot(dataDir2) {
27666
+ try {
27667
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27668
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27669
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27670
+ return parsed2.success ? parsed2.data : null;
27671
+ } catch {
27672
+ return null;
27673
+ }
27674
+ }
27675
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27676
+ const text = JSON.stringify(snapshot);
27677
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27678
+ const existing = readModPolicySnapshot(dataDir2);
27679
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27680
+ ensureDataDirSync(dataDir2);
27681
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27682
+ return true;
27683
+ }
27684
+ function regexProbeKey(matcher) {
27685
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27686
+ }
27687
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27688
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27689
+ return rules.filter((rule) => {
27690
+ if (rule.matcher.type !== "regex") return true;
27691
+ const key = regexProbeKey(rule.matcher);
27692
+ const verdict = sources.probeVerdict(key);
27693
+ if (verdict === "quarantined") return false;
27694
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27695
+ });
27696
+ }
27697
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27698
+ const policies = sources.readPolicies();
27699
+ const snapshot = sources.installedRuleset();
27700
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27701
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27702
+ return {
27703
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27704
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27705
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27706
+ };
27707
+ }
27708
+ function refreshModPolicySnapshot(dataDir2, sources) {
27709
+ try {
27710
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27711
+ } catch {
27712
+ }
27713
+ }
27714
+
28277
27715
  // ../../packages/persistence/src/internal/json.ts
28278
27716
  function safeJson(s, fallback) {
28279
27717
  if (s == null) return fallback;
@@ -28448,6 +27886,11 @@ var TIMELINE_COLUMNS = `
28448
27886
  json_extract(attributes, '$.targetId') AS target_id,
28449
27887
  json_extract(attributes, '$.internal') AS internal,
28450
27888
  json_extract(attributes, '$.flagged') AS flagged`;
27889
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27890
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27891
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27892
+ " + "
27893
+ );
28451
27894
  var LLM_USAGE_SELECT = `
28452
27895
  SELECT root_session_id AS sessionId,
28453
27896
  provider,
@@ -28459,9 +27902,10 @@ var LLM_USAGE_SELECT = `
28459
27902
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28460
27903
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28461
27904
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28462
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27905
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27906
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28463
27907
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28464
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27908
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28465
27909
  function usageLeaves(rows) {
28466
27910
  return rows.map((row) => {
28467
27911
  const attributes = {
@@ -28476,7 +27920,7 @@ function usageLeaves(rows) {
28476
27920
  if (row.provider !== null) attributes.provider = row.provider;
28477
27921
  if (row.model !== null) attributes.model = row.model;
28478
27922
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28479
- return { sessionId: row.sessionId, attributes };
27923
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28480
27924
  });
28481
27925
  }
28482
27926
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29810,9 +29254,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29810
29254
  AND conditions IS NULL
29811
29255
  AND ${ACTIVE_PREDICATE}`;
29812
29256
  var SqliteExceptionsRepository = class {
29813
- constructor(db, now = () => Date.now()) {
29257
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29814
29258
  this.db = db;
29815
29259
  this.now = now;
29260
+ this.onChange = onChange;
29816
29261
  this.consumeStmt = db.prepare(
29817
29262
  `UPDATE exceptions
29818
29263
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29831,6 +29276,7 @@ var SqliteExceptionsRepository = class {
29831
29276
  }
29832
29277
  db;
29833
29278
  now;
29279
+ onChange;
29834
29280
  consumeStmt;
29835
29281
  insertBlockedStmt;
29836
29282
  sweepBlockedStmt;
@@ -29846,7 +29292,9 @@ var SqliteExceptionsRepository = class {
29846
29292
  */
29847
29293
  create(input2) {
29848
29294
  try {
29849
- return Promise.resolve(this.createSync(input2));
29295
+ const created = this.createSync(input2);
29296
+ this.onChange();
29297
+ return Promise.resolve(created);
29850
29298
  } catch (err) {
29851
29299
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29852
29300
  }
@@ -29977,6 +29425,7 @@ var SqliteExceptionsRepository = class {
29977
29425
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29978
29426
  WHERE id = :id AND revoked_at IS NULL`
29979
29427
  ).run({ id, revokedBy, reason: reason ?? null, now });
29428
+ if (Number(result.changes) === 1) this.onChange();
29980
29429
  return Promise.resolve(Number(result.changes) === 1);
29981
29430
  }
29982
29431
  /**
@@ -29989,6 +29438,15 @@ var SqliteExceptionsRepository = class {
29989
29438
  const result = this.consumeStmt.run({ id, now });
29990
29439
  return Promise.resolve(Number(result.changes) === 1);
29991
29440
  }
29441
+ /** The rule ids with at least one active grant, under any key version. */
29442
+ activeRuleIds(now = this.now()) {
29443
+ return allRows(
29444
+ this.db.prepare(
29445
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29446
+ ),
29447
+ { now }
29448
+ ).map((row) => row.ruleId);
29449
+ }
29992
29450
  /**
29993
29451
  * The evaluation subset of every active grant under one fingerprint key
29994
29452
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31112,28 +30570,28 @@ var SqliteInspectionFindingsRepository = class {
31112
30570
  };
31113
30571
 
31114
30572
  // ../../packages/persistence/src/repositories/installed-packs.ts
31115
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30573
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31116
30574
 
31117
30575
  // ../../packages/persistence/src/policy-floor.ts
31118
- import { readFileSync as readFileSync5 } from "fs";
31119
- import { join as join6 } from "path";
30576
+ import { readFileSync as readFileSync6 } from "fs";
30577
+ import { join as join7 } from "path";
31120
30578
 
31121
30579
  // ../../packages/persistence/src/local-layout.ts
31122
30580
  import { renameSync as renameSync3 } from "fs";
31123
30581
  import { mkdir } from "fs/promises";
31124
30582
  import { homedir } from "os";
31125
- import { join as join4 } from "path";
30583
+ import { join as join5 } from "path";
31126
30584
  function defaultDataDir() {
31127
- return join4(homedir(), ".aka");
30585
+ return join5(homedir(), ".aka");
31128
30586
  }
31129
30587
  function settingsDir(base = defaultDataDir()) {
31130
- return join4(base, "settings");
30588
+ return join5(base, "settings");
31131
30589
  }
31132
30590
  function dataDir(base = defaultDataDir()) {
31133
- return join4(base, "data");
30591
+ return join5(base, "data");
31134
30592
  }
31135
30593
  function dbPath(base = defaultDataDir()) {
31136
- return join4(dataDir(base), "aka.db");
30594
+ return join5(dataDir(base), "aka.db");
31137
30595
  }
31138
30596
  async function ensureDataDir(dir = defaultDataDir()) {
31139
30597
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31150,8 +30608,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31150
30608
  for (const { name, dest } of moves) {
31151
30609
  try {
31152
30610
  ensureDataDirSync(dest);
31153
- const moved = join4(dest, name);
31154
- renameSync3(join4(base, name), moved);
30611
+ const moved = join5(dest, name);
30612
+ renameSync3(join5(base, name), moved);
31155
30613
  tightenFile(moved);
31156
30614
  } catch {
31157
30615
  }
@@ -31159,8 +30617,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31159
30617
  }
31160
30618
 
31161
30619
  // ../../packages/persistence/src/settings.ts
31162
- import { readFileSync as readFileSync4 } from "fs";
31163
- import { join as join5 } from "path";
30620
+ import { readFileSync as readFileSync5 } from "fs";
30621
+ import { join as join6 } from "path";
31164
30622
 
31165
30623
  // ../../packages/persistence/src/file-lock.ts
31166
30624
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31168,7 +30626,7 @@ import {
31168
30626
  closeSync,
31169
30627
  existsSync as existsSync2,
31170
30628
  openSync,
31171
- readFileSync as readFileSync2,
30629
+ readFileSync as readFileSync3,
31172
30630
  rmSync as rmSync5,
31173
30631
  statSync as statSync3,
31174
30632
  writeFileSync as writeFileSync2
@@ -31177,16 +30635,16 @@ import { hostname as hostname3 } from "os";
31177
30635
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31178
30636
 
31179
30637
  // ../../packages/persistence/src/managed-settings.ts
31180
- import { readFileSync as readFileSync3 } from "fs";
30638
+ import { readFileSync as readFileSync4 } from "fs";
31181
30639
  import { posix, win32 } from "path";
31182
- function managedSettingsPaths(platform2 = process.platform) {
31183
- if (platform2 === "darwin") {
30640
+ function managedSettingsPaths(platform = process.platform) {
30641
+ if (platform === "darwin") {
31184
30642
  return [
31185
30643
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31186
30644
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31187
30645
  ];
31188
30646
  }
31189
- if (platform2 === "win32") {
30647
+ if (platform === "win32") {
31190
30648
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31191
30649
  }
31192
30650
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -31196,7 +30654,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31196
30654
  for (const path of paths) {
31197
30655
  let text;
31198
30656
  try {
31199
- text = readFileSync3(path, "utf8");
30657
+ text = readFileSync4(path, "utf8");
31200
30658
  } catch {
31201
30659
  continue;
31202
30660
  }
@@ -31250,7 +30708,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31250
30708
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31251
30709
  }
31252
30710
  function readUserSettings(base) {
31253
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30711
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31254
30712
  if (!record2) return defaultWorkspaceSettings();
31255
30713
  try {
31256
30714
  return WorkspaceSettings.parse(record2);
@@ -31261,7 +30719,7 @@ function readUserSettings(base) {
31261
30719
  function readJson(file2) {
31262
30720
  let text;
31263
30721
  try {
31264
- text = readFileSync4(file2, "utf8");
30722
+ text = readFileSync5(file2, "utf8");
31265
30723
  } catch {
31266
30724
  return null;
31267
30725
  }
@@ -31301,7 +30759,7 @@ var PolicyFloorError = class extends Error {
31301
30759
  };
31302
30760
  function readCachedPolicyBundle(base = defaultDataDir()) {
31303
30761
  try {
31304
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30762
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31305
30763
  const parsed2 = JSON.parse(raw);
31306
30764
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31307
30765
  return PolicyBundle.parse(parsed2.bundle);
@@ -31425,7 +30883,7 @@ function inventorySignature(packs) {
31425
30883
  return packs.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31426
30884
  }
31427
30885
  function hashRules(rulesJson) {
31428
- return createHash2("sha256").update(rulesJson).digest("hex");
30886
+ return createHash3("sha256").update(rulesJson).digest("hex");
31429
30887
  }
31430
30888
  function parseVersion(v) {
31431
30889
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31467,9 +30925,10 @@ var SqliteInstalledPacksRepository = class {
31467
30925
  * from `openLocalDatabase`, which is the single construction site that owns a
31468
30926
  * real `~/.aka`.
31469
30927
  */
31470
- constructor(db, baseDir) {
30928
+ constructor(db, baseDir, onChange = () => void 0) {
31471
30929
  this.db = db;
31472
30930
  this.baseDir = baseDir;
30931
+ this.onChange = onChange;
31473
30932
  this.insertMissingStmt = db.prepare(
31474
30933
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31475
30934
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31498,6 +30957,7 @@ var SqliteInstalledPacksRepository = class {
31498
30957
  }
31499
30958
  db;
31500
30959
  baseDir;
30960
+ onChange;
31501
30961
  insertMissingStmt;
31502
30962
  upsertAvailableStmt;
31503
30963
  signatureStmt;
@@ -31570,6 +31030,7 @@ var SqliteInstalledPacksRepository = class {
31570
31030
  },
31571
31031
  "IMMEDIATE"
31572
31032
  );
31033
+ this.onChange();
31573
31034
  } catch {
31574
31035
  }
31575
31036
  }
@@ -31644,6 +31105,7 @@ var SqliteInstalledPacksRepository = class {
31644
31105
  },
31645
31106
  "IMMEDIATE"
31646
31107
  );
31108
+ if (changed) this.onChange();
31647
31109
  return changed;
31648
31110
  }
31649
31111
  /**
@@ -31885,6 +31347,7 @@ var SqliteInstalledPacksRepository = class {
31885
31347
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31886
31348
  WHERE namespace = :namespace AND pack_id = :packId`
31887
31349
  ).run({ policyId, now: Date.now(), namespace, packId });
31350
+ if (Number(res.changes) > 0) this.onChange();
31888
31351
  return Number(res.changes) > 0;
31889
31352
  }
31890
31353
  /**
@@ -31909,6 +31372,7 @@ var SqliteInstalledPacksRepository = class {
31909
31372
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31910
31373
  WHERE namespace = :namespace AND pack_id = :packId`
31911
31374
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31375
+ if (Number(res.changes) > 0) this.onChange();
31912
31376
  return Number(res.changes) > 0;
31913
31377
  }
31914
31378
  // Fingerprint of the recorded available mirror — compared against the
@@ -32806,13 +32270,19 @@ var SqliteInventoryAssetsRepository = class {
32806
32270
  import { randomUUID as randomUUID6 } from "crypto";
32807
32271
  var SEED_BATCH_WINDOW_MS = 6e4;
32808
32272
  var SqlitePoliciesRepository = class {
32809
- constructor(db) {
32273
+ constructor(db, onChange = () => void 0) {
32810
32274
  this.db = db;
32275
+ this.onChange = onChange;
32811
32276
  }
32812
32277
  db;
32278
+ onChange;
32813
32279
  readPolicies() {
32280
+ return Promise.resolve(this.listPolicies());
32281
+ }
32282
+ /** The synchronous read behind {@link readPolicies}. */
32283
+ listPolicies() {
32814
32284
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32815
- const policies = mapRowsTolerant(rows, (row) => {
32285
+ return mapRowsTolerant(rows, (row) => {
32816
32286
  const target = JSON.parse(row.target);
32817
32287
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32818
32288
  return Policy.parse({
@@ -32824,7 +32294,6 @@ var SqlitePoliciesRepository = class {
32824
32294
  customKeywords
32825
32295
  });
32826
32296
  });
32827
- return Promise.resolve(policies);
32828
32297
  }
32829
32298
  // Seed one policy per bundled category at Monitor so the detection-type config
32830
32299
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32835,7 +32304,7 @@ var SqlitePoliciesRepository = class {
32835
32304
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32836
32305
  if (count > 0) {
32837
32306
  this.markEarlierChoices();
32838
- this.monitorUntouchedSeeds();
32307
+ if (this.monitorUntouchedSeeds()) this.onChange();
32839
32308
  return;
32840
32309
  }
32841
32310
  const stmt = this.db.prepare(
@@ -32852,6 +32321,7 @@ var SqlitePoliciesRepository = class {
32852
32321
  });
32853
32322
  }
32854
32323
  });
32324
+ this.onChange();
32855
32325
  }
32856
32326
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32857
32327
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32917,7 +32387,7 @@ var SqlitePoliciesRepository = class {
32917
32387
  ).filter(
32918
32388
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32919
32389
  );
32920
- if (untouched.length === 0) return;
32390
+ if (untouched.length === 0) return false;
32921
32391
  const stmt = this.db.prepare(
32922
32392
  `UPDATE policies SET action = 'log'
32923
32393
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32928,6 +32398,7 @@ var SqlitePoliciesRepository = class {
32928
32398
  stmt.run({ category: row.category, seeded: row.action });
32929
32399
  }
32930
32400
  });
32401
+ return true;
32931
32402
  }
32932
32403
  // Insert-or-update the single global per-category policy row, keyed on the
32933
32404
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32944,6 +32415,7 @@ var SqlitePoliciesRepository = class {
32944
32415
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32945
32416
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32946
32417
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32418
+ this.onChange();
32947
32419
  }
32948
32420
  // Caps every global per-category policy currently set to block/redact down
32949
32421
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32954,6 +32426,7 @@ var SqlitePoliciesRepository = class {
32954
32426
  WHERE scope='global' AND action IN ('block','redact')
32955
32427
  AND json_extract(target,'$.category') IS NOT NULL`
32956
32428
  ).run({ now: Date.now() });
32429
+ if (Number(info.changes) > 0) this.onChange();
32957
32430
  return Number(info.changes);
32958
32431
  }
32959
32432
  // Whether the category's row was ever written after it was created — by the
@@ -33273,31 +32746,45 @@ var SqliteScanLedgerRepository = class {
33273
32746
  constructor(db) {
33274
32747
  this.db = db;
33275
32748
  this.upsertStmt = db.prepare(
33276
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33277
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32749
+ `INSERT INTO scan_ledger
32750
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32751
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33278
32752
  ON CONFLICT (path) DO UPDATE SET
33279
32753
  mtime = excluded.mtime,
33280
32754
  content_hash = excluded.content_hash,
33281
32755
  ruleset_hash = excluded.ruleset_hash,
32756
+ scope_key = excluded.scope_key,
32757
+ scope_root = excluded.scope_root,
33282
32758
  scanned_at = excluded.scanned_at`
33283
32759
  );
33284
32760
  this.readStmt = db.prepare(
33285
- `SELECT path, mtime, content_hash AS contentHash
32761
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32762
+ scope_root AS scopeRoot
33286
32763
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33287
32764
  );
33288
32765
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32766
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33289
32767
  }
33290
32768
  db;
33291
32769
  upsertStmt;
33292
32770
  readStmt;
33293
32771
  pathsStmt;
32772
+ pathKeysStmt;
33294
32773
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33295
32774
  // older ruleset are simply absent, which reads as "never scanned".
33296
32775
  entriesForRuleset(rulesetHash) {
33297
- const rows = allRows(this.readStmt, {
33298
- rulesetHash
33299
- });
33300
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32776
+ const rows = allRows(this.readStmt, { rulesetHash });
32777
+ return new Map(
32778
+ rows.map((r) => [
32779
+ r.path,
32780
+ {
32781
+ mtime: r.mtime,
32782
+ contentHash: r.contentHash,
32783
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32784
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32785
+ }
32786
+ ])
32787
+ );
33301
32788
  }
33302
32789
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33303
32790
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33306,6 +32793,14 @@ var SqliteScanLedgerRepository = class {
33306
32793
  allPaths() {
33307
32794
  return allRows(this.pathsStmt).map((r) => r.path);
33308
32795
  }
32796
+ // Every ledgered path with the repository it was in when it was last read,
32797
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32798
+ // which repository a vanished file belonged to. `undefined` for a row with no
32799
+ // key, which is every row written before the column existed.
32800
+ pathKeys() {
32801
+ const rows = allRows(this.pathKeysStmt);
32802
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32803
+ }
33309
32804
  upsertEntries(entries) {
33310
32805
  if (entries.length === 0) return;
33311
32806
  const scannedAt = Date.now();
@@ -33316,6 +32811,8 @@ var SqliteScanLedgerRepository = class {
33316
32811
  mtime: entry.mtime,
33317
32812
  contentHash: entry.contentHash,
33318
32813
  rulesetHash: entry.rulesetHash,
32814
+ scopeKey: entry.scopeKey ?? null,
32815
+ scopeRoot: entry.scopeRoot ?? null,
33319
32816
  scannedAt
33320
32817
  });
33321
32818
  }
@@ -34403,6 +33900,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34403
33900
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34404
33901
  };
34405
33902
  }
33903
+ function withoutTrailingSlashes(path) {
33904
+ let end = path.length;
33905
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33906
+ return path.slice(0, end);
33907
+ }
34406
33908
  function toEndpointSummary(row) {
34407
33909
  return {
34408
33910
  id: row.id,
@@ -34690,7 +34192,7 @@ var SqliteSharesRepository = class {
34690
34192
  */
34691
34193
  reconcileCallSites(projectKey, reconcile) {
34692
34194
  if (reconcile.mode === "walk") {
34693
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
34195
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34694
34196
  this.db.prepare(
34695
34197
  `DELETE FROM share_call_site
34696
34198
  WHERE project_key = :key
@@ -35258,7 +34760,7 @@ function backupLegacyStore(db, file2) {
35258
34760
  discardStore(file2, backup);
35259
34761
  return backup;
35260
34762
  }
35261
- function openAndInitialize(file2, base, skipTags) {
34763
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35262
34764
  let db = openWithPragmas(file2);
35263
34765
  try {
35264
34766
  if (isForeignSqliteLineage(db)) {
@@ -35270,8 +34772,15 @@ function openAndInitialize(file2, base, skipTags) {
35270
34772
  }
35271
34773
  applyMigrations(db, file2, { skipTags });
35272
34774
  tightenPerms(file2);
35273
- const policies = new SqlitePoliciesRepository(db);
35274
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34775
+ const modPolicy = {};
34776
+ const onPolicyStateChange = () => {
34777
+ if (modPolicy.current !== void 0)
34778
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34779
+ };
34780
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34781
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34782
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34783
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35275
34784
  const repositories = {
35276
34785
  events: new SqliteEventsRepository(db),
35277
34786
  findings: new SqliteFindingsRepository(db),
@@ -35280,9 +34789,9 @@ function openAndInitialize(file2, base, skipTags) {
35280
34789
  scanLedger: new SqliteScanLedgerRepository(db),
35281
34790
  historySync: new SqliteHistorySyncRepository(db),
35282
34791
  secretVault: new SqliteSecretVaultRepository(db),
35283
- exceptions: new SqliteExceptionsRepository(db),
34792
+ exceptions,
35284
34793
  resolutions: new SqliteResolutionsRepository(db),
35285
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34794
+ ruleProbeCache,
35286
34795
  bodyRetention: new SqliteBodyRetentionRepository(db),
35287
34796
  security: new SqliteSecurityRepository(db),
35288
34797
  detections: new SqliteDetectionsRepository(db),
@@ -35300,6 +34809,13 @@ function openAndInitialize(file2, base, skipTags) {
35300
34809
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35301
34810
  configInventory: new SqliteConfigInventoryRepository(db)
35302
34811
  };
34812
+ modPolicy.current = {
34813
+ installedRuleset: () => installedPacks.installedRuleset(),
34814
+ readPolicies: () => policies.listPolicies(),
34815
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34816
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34817
+ bundledRegexMatchers: () => shippedRegexMatchers2
34818
+ };
35303
34819
  policies.seedDefaults();
35304
34820
  return { db, ...repositories };
35305
34821
  } catch (err) {
@@ -35311,7 +34827,7 @@ function openAndInitialize(file2, base, skipTags) {
35311
34827
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35312
34828
  function openLocalDatabase(dir, options = {}) {
35313
34829
  ensureDataDirSync(dir);
35314
- const file2 = join7(dir, DB_FILENAME);
34830
+ const file2 = join8(dir, DB_FILENAME);
35315
34831
  reapStalePartials(file2);
35316
34832
  const {
35317
34833
  db,
@@ -35347,7 +34863,8 @@ function openLocalDatabase(dir, options = {}) {
35347
34863
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35348
34864
  // settings/ and data/, and the pack-policy floor needs both halves.
35349
34865
  dirname2(dir),
35350
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34866
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34867
+ options.shippedRegexMatchers ?? []
35351
34868
  );
35352
34869
  function captureRowId(event) {
35353
34870
  return captureId(
@@ -35612,7 +35129,7 @@ function openLocalDatabase(dir, options = {}) {
35612
35129
  }
35613
35130
 
35614
35131
  // ../../packages/persistence/src/egress-wire.ts
35615
- import { createHash as createHash3 } from "crypto";
35132
+ import { createHash as createHash4 } from "crypto";
35616
35133
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35617
35134
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35618
35135
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35644,7 +35161,7 @@ function canonicalGitUrl(url2) {
35644
35161
  }
35645
35162
  function hashProjectKey(projectKey) {
35646
35163
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35647
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35164
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35648
35165
  }
35649
35166
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35650
35167
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35709,17 +35226,16 @@ function toEgressIngestRequest(input2) {
35709
35226
  }
35710
35227
 
35711
35228
  // ../../packages/persistence/src/finding-key.ts
35712
- import { createHash as createHash4 } from "crypto";
35229
+ import { createHash as createHash5 } from "crypto";
35713
35230
 
35714
35231
  // ../../packages/persistence/src/fingerprint.ts
35715
35232
  import { createHmac, randomBytes } from "crypto";
35716
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35717
- import { join as join8 } from "path";
35718
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35233
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
35234
+ import { join as join9 } from "path";
35719
35235
  var EXCEPTION_KEY_FILENAME = "exception.key";
35720
35236
  var KEY_MATERIAL_BYTES = 32;
35721
35237
  function keyFilePath(dataDir2) {
35722
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
35238
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35723
35239
  }
35724
35240
  function parseKeyFile(raw) {
35725
35241
  const parsed2 = JSON.parse(raw);
@@ -35742,7 +35258,7 @@ function parseKeyFile(raw) {
35742
35258
  function readFingerprintKey(dataDir2) {
35743
35259
  let raw;
35744
35260
  try {
35745
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
35261
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35746
35262
  } catch (err) {
35747
35263
  if (err.code === "ENOENT") return null;
35748
35264
  throw err instanceof Error ? err : new Error(String(err));
@@ -35751,8 +35267,8 @@ function readFingerprintKey(dataDir2) {
35751
35267
  }
35752
35268
 
35753
35269
  // ../../packages/persistence/src/forward-health.ts
35754
- import { readFileSync as readFileSync7 } from "fs";
35755
- import { join as join9 } from "path";
35270
+ import { readFileSync as readFileSync8 } from "fs";
35271
+ import { join as join10 } from "path";
35756
35272
  var BREAKER_COOLDOWN_MS = 3e4;
35757
35273
  function parseForwardHealth(raw, nowMs) {
35758
35274
  try {
@@ -35776,20 +35292,21 @@ function isForwardPaused(health, nowMs) {
35776
35292
 
35777
35293
  // ../../packages/persistence/src/history-backfill.ts
35778
35294
  import { existsSync as existsSync4 } from "fs";
35779
- import { join as join10 } from "path";
35295
+ import { join as join11 } from "path";
35780
35296
 
35781
35297
  // ../../packages/persistence/src/history-preview.ts
35782
35298
  import { existsSync as existsSync5 } from "fs";
35783
- import { join as join11 } from "path";
35784
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
35299
+ import { join as join12 } from "path";
35300
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35785
35301
 
35786
35302
  // ../../packages/persistence/src/history-sync-state.ts
35787
- import { readFileSync as readFileSync8 } from "fs";
35788
- import { join as join12 } from "path";
35303
+ import { readFileSync as readFileSync9 } from "fs";
35304
+ import { join as join13 } from "path";
35305
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35789
35306
 
35790
35307
  // ../../packages/persistence/src/store-symlinks.ts
35791
35308
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35792
- import { dirname as dirname3, join as join13, resolve } from "path";
35309
+ import { dirname as dirname3, join as join14, resolve } from "path";
35793
35310
 
35794
35311
  // ../../packages/persistence/src/vault/crypto.ts
35795
35312
  import {
@@ -35803,19 +35320,19 @@ import {
35803
35320
  // ../../packages/persistence/src/vault/key-provider.ts
35804
35321
  import { execFileSync } from "child_process";
35805
35322
  import { randomBytes as randomBytes2 } from "crypto";
35806
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35807
- import { join as join14 } from "path";
35323
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35324
+ import { join as join15 } from "path";
35808
35325
 
35809
35326
  // ../../packages/persistence/src/vault/vault.ts
35810
35327
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35811
35328
 
35812
35329
  // ../../packages/persistence/src/warn-era-cap.ts
35813
35330
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35814
- import { join as join15 } from "path";
35331
+ import { join as join16 } from "path";
35815
35332
  var MARKER = "warn-era-capped";
35816
35333
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35817
35334
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35818
- const marker = join15(dataDir2, MARKER);
35335
+ const marker = join16(dataDir2, MARKER);
35819
35336
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35820
35337
  const capped = db.policies.capCategoryActions();
35821
35338
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35823,425 +35340,6 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35823
35340
  return { capped };
35824
35341
  }
35825
35342
 
35826
- // ../../packages/remote/src/http.ts
35827
- import { request as httpRequest } from "http";
35828
- import { request as httpsRequest } from "https";
35829
- var DEFAULT_TIMEOUT_MS = 1e4;
35830
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35831
- var RemoteRequestError = class extends Error {
35832
- constructor(status) {
35833
- super(`control-plane request failed with status ${String(status)}`);
35834
- this.status = status;
35835
- this.name = "RemoteRequestError";
35836
- }
35837
- status;
35838
- };
35839
- var RemoteRouteAbsent = class extends Error {
35840
- constructor(route) {
35841
- super(`control plane does not serve ${route}`);
35842
- this.route = route;
35843
- this.name = "RemoteRouteAbsent";
35844
- }
35845
- route;
35846
- };
35847
- var RemoteRequestInvalid = class extends Error {
35848
- constructor(route, cause) {
35849
- super(`refusing to send a malformed body to ${route}`);
35850
- this.cause = cause;
35851
- this.name = "RemoteRequestInvalid";
35852
- }
35853
- cause;
35854
- };
35855
- var RemoteEndpointRefused = class extends Error {
35856
- constructor(endpoint) {
35857
- super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
35858
- this.name = "RemoteEndpointRefused";
35859
- }
35860
- };
35861
- var RemoteResponseInvalid = class extends Error {
35862
- constructor(route, detail) {
35863
- super(`control plane answered ${route} with ${detail}`);
35864
- this.name = "RemoteResponseInvalid";
35865
- }
35866
- };
35867
- var RemoteTransportError = class extends Error {
35868
- /**
35869
- * The status the peer sent, when headers arrived and only the BODY was
35870
- * refused.
35871
- *
35872
- * Undefined for the ordinary case this class was written for — no answer at
35873
- * all. It exists because two paths reject after a status has already been
35874
- * delivered: an oversized body and an aborted response. Discarding it there
35875
- * reported a deployment answering 401 with a verbose body as a network
35876
- * outage, which sends the reader to look at their network instead of their
35877
- * credential.
35878
- */
35879
- constructor(reason, status) {
35880
- super(`control-plane request did not complete: ${reason}`);
35881
- this.status = status;
35882
- this.name = "RemoteTransportError";
35883
- }
35884
- status;
35885
- };
35886
- async function send(options) {
35887
- const url2 = new URL(options.url);
35888
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35889
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
35890
- const requestOptions = {
35891
- method: options.method,
35892
- headers: {
35893
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
35894
- // last they win, and two of the values below are ones no caller may
35895
- // replace: `x-api-key` is the credential, and `content-length` is the
35896
- // byte count that stops a multi-byte body being truncated by the
35897
- // receiver. `SendOptions.headers` is a free-form record on an exported
35898
- // function, so "no caller does that today" is not the guarantee to rely
35899
- // on. The one header any caller actually passes — `if-none-match` on the
35900
- // conditional GET — is untouched by this order.
35901
- ...options.headers,
35902
- // The credential. One header, matching what the deployment authenticates
35903
- // on; a second copy in an `Authorization` header would be one more place
35904
- // it can be logged by an intermediary for no gain.
35905
- //
35906
- // Spread conditionally rather than assigned as `undefined`: Node's header
35907
- // handling and `content-length` bookkeeping treat a present-but-undefined
35908
- // key differently from an absent one, and "the header is not there" is
35909
- // the property the attach flow needs.
35910
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
35911
- accept: "application/json",
35912
- ...options.body === void 0 ? {} : {
35913
- "content-type": "application/json",
35914
- // Byte length, not string length: a multi-byte body sent with a
35915
- // character count is truncated by the receiver.
35916
- "content-length": String(Buffer.byteLength(options.body))
35917
- }
35918
- }
35919
- };
35920
- return new Promise((resolve3, reject) => {
35921
- let settled = false;
35922
- const fail = (reason, status) => {
35923
- if (settled) return;
35924
- settled = true;
35925
- reject(new RemoteTransportError(reason, status));
35926
- };
35927
- const req = send_(url2, requestOptions, (res) => {
35928
- const chunks = [];
35929
- let size = 0;
35930
- res.on("data", (chunk) => {
35931
- size += chunk.length;
35932
- if (size > MAX_RESPONSE_BYTES) {
35933
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
35934
- res.destroy();
35935
- req.destroy();
35936
- return;
35937
- }
35938
- chunks.push(chunk);
35939
- });
35940
- res.on("aborted", () => {
35941
- fail("the response was aborted", res.statusCode);
35942
- });
35943
- res.on("end", () => {
35944
- if (settled) return;
35945
- settled = true;
35946
- resolve3({
35947
- status: res.statusCode ?? 0,
35948
- headers: res.headers,
35949
- body: Buffer.concat(chunks).toString("utf8")
35950
- });
35951
- });
35952
- });
35953
- const deadline = setTimeout(() => {
35954
- fail(`no response within ${String(timeoutMs)}ms`);
35955
- req.destroy();
35956
- }, timeoutMs);
35957
- deadline.unref();
35958
- req.on("upgrade", (_res, socket) => {
35959
- fail("the deployment answered with a protocol upgrade");
35960
- socket.destroy();
35961
- });
35962
- req.on("close", () => {
35963
- fail("the connection closed before a response was read");
35964
- clearTimeout(deadline);
35965
- });
35966
- req.on("error", (err) => {
35967
- fail(err.message);
35968
- });
35969
- if (options.body !== void 0) req.write(options.body);
35970
- req.end();
35971
- });
35972
- }
35973
-
35974
- // ../../packages/remote/src/client.ts
35975
- var ROUTES = {
35976
- events: "/v1/events",
35977
- auditEvents: "/v1/audit-events",
35978
- auditEventsBatch: "/v1/audit-events/batch",
35979
- inventory: "/v1/inventory",
35980
- storePosture: "/v1/store-posture",
35981
- policyBundle: "/v1/policy-bundle",
35982
- whoami: "/v1/plugin/whoami",
35983
- shares: "/v1/shares",
35984
- commands: "/v1/plugin/commands"
35985
- };
35986
- function ackRoute(id) {
35987
- return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
35988
- }
35989
- function headerValue(response, name) {
35990
- const raw = response.headers[name];
35991
- if (raw === void 0) return void 0;
35992
- return Array.isArray(raw) ? raw[0] : raw;
35993
- }
35994
- function okBody(response) {
35995
- if (response.status < 200 || response.status >= 300) {
35996
- throw new RemoteRequestError(response.status);
35997
- }
35998
- return response.body;
35999
- }
36000
- function parsed(schema, body, route) {
36001
- let json2;
36002
- try {
36003
- json2 = JSON.parse(body);
36004
- } catch {
36005
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
36006
- }
36007
- const result = schema.safeParse(json2);
36008
- if (!result.success) {
36009
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
36010
- }
36011
- return result.data;
36012
- }
36013
- function resolveBaseUrl(endpoint) {
36014
- if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
36015
- let end = endpoint.length;
36016
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
36017
- return endpoint.slice(0, end);
36018
- }
36019
- var SLASH2 = "/".charCodeAt(0);
36020
- function createRemoteClient(options) {
36021
- const base = resolveBaseUrl(options.endpoint);
36022
- const url2 = (route) => `${base}${route}`;
36023
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
36024
- const sendOne = async (event) => {
36025
- const validated = RecordAuditEventRequest.safeParse(event);
36026
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
36027
- const response = await send({
36028
- ...common,
36029
- method: "POST",
36030
- url: url2(ROUTES.auditEvents),
36031
- body: JSON.stringify(validated.data)
36032
- });
36033
- okBody(response);
36034
- };
36035
- return {
36036
- async ingestEvents(batch) {
36037
- const response = await send({
36038
- ...common,
36039
- method: "POST",
36040
- url: url2(ROUTES.events),
36041
- body: JSON.stringify(batch)
36042
- });
36043
- return parsed(IngestAck, okBody(response), ROUTES.events);
36044
- },
36045
- async ingestInventory(context) {
36046
- const response = await send({
36047
- ...common,
36048
- method: "POST",
36049
- url: url2(ROUTES.inventory),
36050
- body: JSON.stringify(context)
36051
- });
36052
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
36053
- },
36054
- async recordAuditEvent(event) {
36055
- await sendOne(event);
36056
- },
36057
- async recordAuditEvents(events, opts) {
36058
- const validated = RecordAuditEventBatch.safeParse({ events });
36059
- if (!validated.success) {
36060
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
36061
- }
36062
- const response = await send({
36063
- ...common,
36064
- method: "POST",
36065
- url: url2(ROUTES.auditEventsBatch),
36066
- body: JSON.stringify(validated.data)
36067
- });
36068
- if (response.status === 404) {
36069
- if (opts?.fallbackToSingleEvents !== true) {
36070
- throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
36071
- }
36072
- for (const event of validated.data.events) await sendOne(event);
36073
- return { accepted: validated.data.events.length };
36074
- }
36075
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
36076
- },
36077
- async reportStorePosture(snapshot) {
36078
- const response = await send({
36079
- ...common,
36080
- method: "POST",
36081
- url: url2(ROUTES.storePosture),
36082
- body: JSON.stringify(snapshot)
36083
- });
36084
- okBody(response);
36085
- },
36086
- async getPolicyBundle(etag) {
36087
- const response = await send({
36088
- ...common,
36089
- method: "GET",
36090
- url: url2(ROUTES.policyBundle),
36091
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
36092
- });
36093
- if (response.status === 304) {
36094
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
36095
- }
36096
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
36097
- return { changed: true, bundle, etag: headerValue(response, "etag") };
36098
- },
36099
- async whoami() {
36100
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
36101
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
36102
- },
36103
- async recordProjectEgress(request) {
36104
- const validated = EgressIngestRequest.safeParse(request);
36105
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
36106
- const response = await send({
36107
- ...common,
36108
- method: "POST",
36109
- url: url2(ROUTES.shares),
36110
- body: JSON.stringify(validated.data)
36111
- });
36112
- if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
36113
- okBody(response);
36114
- },
36115
- async pollCommand() {
36116
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
36117
- if (response.status === 404) return null;
36118
- return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
36119
- },
36120
- async ackCommand(id, body) {
36121
- const validated = DeviceCommandAckBody.safeParse(body);
36122
- const route = ackRoute(id);
36123
- if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
36124
- const response = await send({
36125
- ...common,
36126
- method: "POST",
36127
- url: url2(route),
36128
- body: JSON.stringify(validated.data)
36129
- });
36130
- okBody(response);
36131
- }
36132
- };
36133
- }
36134
-
36135
- // ../../packages/remote/src/failure-kind.ts
36136
- function statusOf(err) {
36137
- if (typeof err !== "object" || err === null || !("status" in err)) return null;
36138
- const { status } = err;
36139
- if (typeof status !== "number" || !Number.isInteger(status)) return null;
36140
- return status >= 100 && status <= 599 ? status : null;
36141
- }
36142
- function nameOf(err) {
36143
- if (typeof err !== "object" || err === null || !("name" in err)) return null;
36144
- return typeof err.name === "string" ? err.name : null;
36145
- }
36146
- function classifyRemoteFailure(err) {
36147
- switch (nameOf(err)) {
36148
- case "RemoteRouteAbsent":
36149
- return "route-absent";
36150
- case "RemoteRequestInvalid":
36151
- case "RemoteEndpointRefused":
36152
- return "invalid-request";
36153
- case "RemoteResponseInvalid":
36154
- return "rejected";
36155
- default:
36156
- break;
36157
- }
36158
- const status = statusOf(err);
36159
- if (status === null) return "unreachable";
36160
- switch (status) {
36161
- case 401:
36162
- return "unauthorized";
36163
- case 403:
36164
- return "forbidden";
36165
- case 429:
36166
- return "unreachable";
36167
- case 404:
36168
- return "unreachable";
36169
- default:
36170
- return status >= 400 && status <= 499 ? "rejected" : "unreachable";
36171
- }
36172
- }
36173
-
36174
- // ../../packages/plugin-runtime/src/attached/failure.ts
36175
- function classifyFailure(err) {
36176
- switch (classifyRemoteFailure(err)) {
36177
- case "unauthorized":
36178
- return "unauthorized";
36179
- case "forbidden":
36180
- return "forbidden";
36181
- default:
36182
- return "unreachable";
36183
- }
36184
- }
36185
-
36186
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36187
- var REQUEST_TIMEOUT_MS = 2e3;
36188
- function withTimeout(promise2, ms) {
36189
- let timer;
36190
- const timeout = new Promise((_, reject) => {
36191
- timer = setTimeout(() => {
36192
- reject(new Error("attached gateway request timed out"));
36193
- }, ms);
36194
- });
36195
- promise2.catch(() => void 0);
36196
- return Promise.race([promise2, timeout]).finally(() => {
36197
- clearTimeout(timer);
36198
- });
36199
- }
36200
-
36201
- // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36202
- import { readFileSync as readFileSync10 } from "fs";
36203
- import { join as join16 } from "path";
36204
- var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36205
- function forwardDropsPath(dataDir2) {
36206
- return join16(dataDir2, FORWARD_DROPS_FILENAME);
36207
- }
36208
- function recordForwardDrops(dataDir2, count, nowMs) {
36209
- if (count <= 0) return;
36210
- try {
36211
- ensureDataDirSync(dataDir2);
36212
- const previous = readForwardDrops(dataDir2);
36213
- const next = {
36214
- droppedForwards: (previous?.droppedForwards ?? 0) + count,
36215
- lastDropAtMs: nowMs
36216
- };
36217
- writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
36218
- `);
36219
- } catch {
36220
- }
36221
- }
36222
- function readForwardDrops(dataDir2) {
36223
- try {
36224
- const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
36225
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36226
- const record2 = parsed2;
36227
- if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
36228
- return null;
36229
- }
36230
- if (record2.droppedForwards <= 0) return null;
36231
- if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
36232
- return null;
36233
- }
36234
- return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
36235
- } catch {
36236
- return null;
36237
- }
36238
- }
36239
-
36240
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36241
- import { randomUUID as randomUUID16 } from "crypto";
36242
- import { readFile, rename, writeFile } from "fs/promises";
36243
- import { join as join28 } from "path";
36244
-
36245
35343
  // ../../packages/plugin-sdk/src/config.ts
36246
35344
  import { existsSync as existsSync8 } from "fs";
36247
35345
  import { join as join17 } from "path";
@@ -36321,11 +35419,6 @@ function resolveProviderSafe(resolveProviderFn) {
36321
35419
  }
36322
35420
  }
36323
35421
 
36324
- // ../../packages/plugin-sdk/src/config-inventory.ts
36325
- import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
36326
- import { homedir as homedir2 } from "os";
36327
- import { basename as basename3, join as join19 } from "path";
36328
-
36329
35422
  // ../../packages/detections/src/egress/registry.ts
36330
35423
  var EXTRACTOR_VERSION = "3";
36331
35424
  var PROVIDER_REGISTRY = [
@@ -37000,12 +36093,12 @@ var RegexMatcher2 = class {
37000
36093
  rule.matcher,
37001
36094
  () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
37002
36095
  );
37003
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
36096
+ const scanText = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
37004
36097
  const spans = [];
37005
36098
  let m;
37006
- const maxIterations = scanText2.length + 1;
36099
+ const maxIterations = scanText.length + 1;
37007
36100
  let iterations = 0;
37008
- while ((m = re.exec(scanText2)) !== null) {
36101
+ while ((m = re.exec(scanText)) !== null) {
37009
36102
  if (++iterations > maxIterations) break;
37010
36103
  const group = captureGroup != null ? m[captureGroup] : m[0];
37011
36104
  if (m[0].length === 0) re.lastIndex++;
@@ -37158,6 +36251,38 @@ var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].m
37158
36251
  );
37159
36252
  var CPU_CORROBORATION_SHARE = 0.2;
37160
36253
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36254
+ function repeatTo(unit, length) {
36255
+ return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
36256
+ }
36257
+ function joinTo(length, open3, close, item) {
36258
+ const parts = [];
36259
+ let size = open3.length;
36260
+ for (let i = 0; size < length; i++) {
36261
+ const next = (i === 0 ? "" : ",") + item(i);
36262
+ parts.push(next);
36263
+ size += next.length;
36264
+ }
36265
+ return (open3 + parts.join("") + close).slice(0, length);
36266
+ }
36267
+ var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
36268
+ var GROWTH_CORPORA = [
36269
+ {
36270
+ name: "one-line JSON dictionary",
36271
+ build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
36272
+ },
36273
+ {
36274
+ name: "JSON array of quoted SQL keywords",
36275
+ build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
36276
+ },
36277
+ { name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
36278
+ { name: "double-quote run", build: (length) => repeatTo('"', length) },
36279
+ { name: "space run", build: (length) => repeatTo(" ", length) },
36280
+ { name: "newline run", build: (length) => repeatTo("\n", length) },
36281
+ ...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
36282
+ name: `unit run ${JSON.stringify(unit)}`,
36283
+ build: (length) => repeatTo(unit, length)
36284
+ }))
36285
+ ];
37161
36286
 
37162
36287
  // ../../rules/code-flaws/auth-jwt-no-verify.json
37163
36288
  var auth_jwt_no_verify_default = {
@@ -37168,7 +36293,7 @@ var auth_jwt_no_verify_default = {
37168
36293
  severity: "critical",
37169
36294
  matcher: {
37170
36295
  type: "regex",
37171
- pattern: "(verify\\s*=\\s*false|verify_signature.*false|algorithms\\s*=\\s*\\[\\])",
36296
+ pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
37172
36297
  flags: "gi"
37173
36298
  },
37174
36299
  requiresNearby: {
@@ -37256,7 +36381,7 @@ var cmd_inject_shell_default = {
37256
36381
  severity: "critical",
37257
36382
  matcher: {
37258
36383
  type: "regex",
37259
- pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
36384
+ pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
37260
36385
  flags: "gi"
37261
36386
  },
37262
36387
  requiresNearby: {
@@ -37385,7 +36510,7 @@ var deser_yaml_unsafe_default = {
37385
36510
  severity: "high",
37386
36511
  matcher: {
37387
36512
  type: "regex",
37388
- pattern: "\\byaml\\.load\\s*\\((?![^)]*SafeLoader|[^)]*safe_load)",
36513
+ pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
37389
36514
  flags: "gi"
37390
36515
  },
37391
36516
  examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
@@ -37602,7 +36727,7 @@ var sql_inject_concat_dot_default = {
37602
36727
  severity: "high",
37603
36728
  matcher: {
37604
36729
  type: "regex",
37605
- pattern: `["'][^\\n]*?(select|insert|update|delete|drop|where)[^\\n]*?["']\\s*\\.`,
36730
+ pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
37606
36731
  flags: "gi"
37607
36732
  },
37608
36733
  appliesTo: {
@@ -37620,7 +36745,7 @@ var sql_inject_concat_default = {
37620
36745
  severity: "high",
37621
36746
  matcher: {
37622
36747
  type: "regex",
37623
- 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*\\+`,
36748
+ 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*\\+`,
37624
36749
  flags: "gi"
37625
36750
  },
37626
36751
  examples: ['"SELECT * FROM users WHERE id = " + userId']
@@ -37635,7 +36760,7 @@ var sql_inject_format_default = {
37635
36760
  severity: "high",
37636
36761
  matcher: {
37637
36762
  type: "regex",
37638
- 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]|\\{[^}]+\\})",
36763
+ 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]+\\})",
37639
36764
  flags: "gi"
37640
36765
  },
37641
36766
  examples: [
@@ -37653,7 +36778,7 @@ var sql_inject_interp_default = {
37653
36778
  severity: "high",
37654
36779
  matcher: {
37655
36780
  type: "regex",
37656
- pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
36781
+ pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
37657
36782
  flags: "gi"
37658
36783
  },
37659
36784
  examples: [
@@ -38028,7 +37153,7 @@ var stack_trace_default = {
38028
37153
  severity: "low",
38029
37154
  matcher: {
38030
37155
  type: "regex",
38031
- pattern: "(?:^|\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
37156
+ pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38032
37157
  flags: "g"
38033
37158
  },
38034
37159
  examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
@@ -39186,7 +38311,7 @@ var BUNDLED_PACKS = [
39186
38311
  {
39187
38312
  packId: "code-flaws",
39188
38313
  name: "Code Security Flaws",
39189
- version: "0.1.0",
38314
+ version: "0.1.1",
39190
38315
  rawRules: [
39191
38316
  sql_inject_concat_default,
39192
38317
  sql_inject_concat_dot_default,
@@ -39236,7 +38361,7 @@ var BUNDLED_PACKS = [
39236
38361
  {
39237
38362
  packId: "core-code-context",
39238
38363
  name: "Code Context",
39239
- version: "0.2.1",
38364
+ version: "0.2.2",
39240
38365
  rawRules: [
39241
38366
  internal_ip_default,
39242
38367
  localhost_ref_default,
@@ -39366,141 +38491,441 @@ function bundledDetections() {
39366
38491
  }));
39367
38492
  return cachedDetections;
39368
38493
  }
39369
-
39370
- // ../../packages/plugin-sdk/src/repo.ts
39371
- import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
39372
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
39373
- var NO_ATTRIBUTION = Object.freeze({});
39374
-
39375
- // ../../packages/plugin-sdk/src/events.ts
39376
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39377
-
39378
- // ../../packages/plugin-sdk/src/isolated-scan.ts
39379
- import { existsSync as existsSync10 } from "fs";
39380
- import { fileURLToPath } from "url";
39381
- import { Worker } from "worker_threads";
39382
-
39383
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
39384
- import { readFileSync as readFileSync13 } from "fs";
39385
- import { join as join20 } from "path";
39386
-
39387
- // ../../packages/plugin-sdk/src/host-floor.ts
39388
- import { readFileSync as readFileSync15 } from "fs";
39389
- import { join as join22 } from "path";
39390
-
39391
- // ../../packages/plugin-sdk/src/model-governance.ts
39392
- import {
39393
- closeSync as closeSync2,
39394
- fstatSync,
39395
- mkdirSync as mkdirSync2,
39396
- openSync as openSync2,
39397
- readFileSync as readFileSync14,
39398
- readSync,
39399
- writeFileSync as writeFileSync5
39400
- } from "fs";
39401
- import { join as join21 } from "path";
39402
- var TAIL_BYTES = 256 * 1024;
39403
-
39404
- // ../../packages/plugin-sdk/src/host-floor.ts
39405
- var HOST_FEATURE = {
39406
- ModelSwitch: "model-switch",
39407
- VaultPointerDisplay: "vault-pointer-display"
39408
- };
39409
- var HOST_FLOORS = {
39410
- [HOST_FEATURE.ModelSwitch]: {
39411
- label: "model-switch protection",
39412
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
39413
- since: "2.1.251"
39414
- },
39415
- [HOST_FEATURE.VaultPointerDisplay]: {
39416
- label: "vault pointer display",
39417
- hookEvents: ["MessageDisplay"],
39418
- since: "2.1.152"
39419
- }
39420
- };
39421
- var ANTIGRAVITY_HOST_FEATURE = {
39422
- EndOfTurnCapture: "end-of-turn-capture"
39423
- };
39424
- var ANTIGRAVITY_HOST_FLOORS = {
39425
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
39426
- label: "end-of-turn history capture",
39427
- hookEvents: ["Stop"],
39428
- since: "1.1.10"
39429
- }
39430
- };
39431
-
39432
- // ../../packages/plugin-sdk/src/ignore-layers.ts
39433
- var import_ignore = __toESM(require_ignore(), 1);
39434
- import { readFileSync as readFileSync16 } from "fs";
39435
- import { join as join23 } from "path";
39436
-
39437
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
39438
- import { arch, hostname as hostname4, platform, release } from "os";
39439
-
39440
- // ../../packages/plugin-sdk/src/nudge.ts
39441
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "fs";
39442
- import { join as join24 } from "path";
39443
-
39444
- // ../../packages/plugin-sdk/src/paths.ts
39445
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
39446
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
38494
+ function shippedRegexMatchers() {
38495
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
38496
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
38497
+ );
38498
+ }
39447
38499
 
39448
38500
  // ../../packages/plugin-sdk/src/policy-resolver.ts
39449
- import { randomUUID as randomUUID14 } from "crypto";
38501
+ import { randomUUID as randomUUID13 } from "crypto";
39450
38502
  function assignedRulePolicies(installed) {
39451
38503
  const out = [];
39452
38504
  for (const [ruleId, action] of installed.ruleActions) {
39453
38505
  if (installed.assignedRules && !installed.assignedRules.has(ruleId)) continue;
39454
- out.push({ id: randomUUID14(), scope: "global", target: { ruleId }, action, enabled: true });
38506
+ out.push({ id: randomUUID13(), scope: "global", target: { ruleId }, action, enabled: true });
39455
38507
  }
39456
38508
  return out;
39457
38509
  }
39458
38510
 
39459
- // ../../packages/plugin-sdk/src/project-files.ts
39460
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
39461
- import { basename as basename5, join as join25 } from "path";
38511
+ // ../../packages/remote/src/http.ts
38512
+ import { request as httpRequest } from "http";
38513
+ import { request as httpsRequest } from "https";
38514
+ var DEFAULT_TIMEOUT_MS = 1e4;
38515
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
38516
+ var RemoteRequestError = class extends Error {
38517
+ constructor(status) {
38518
+ super(`control-plane request failed with status ${String(status)}`);
38519
+ this.status = status;
38520
+ this.name = "RemoteRequestError";
38521
+ }
38522
+ status;
38523
+ };
38524
+ var RemoteRouteAbsent = class extends Error {
38525
+ constructor(route) {
38526
+ super(`control plane does not serve ${route}`);
38527
+ this.route = route;
38528
+ this.name = "RemoteRouteAbsent";
38529
+ }
38530
+ route;
38531
+ };
38532
+ var RemoteRequestInvalid = class extends Error {
38533
+ constructor(route, cause) {
38534
+ super(`refusing to send a malformed body to ${route}`);
38535
+ this.cause = cause;
38536
+ this.name = "RemoteRequestInvalid";
38537
+ }
38538
+ cause;
38539
+ };
38540
+ var RemoteEndpointRefused = class extends Error {
38541
+ constructor(endpoint) {
38542
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
38543
+ this.name = "RemoteEndpointRefused";
38544
+ }
38545
+ };
38546
+ var RemoteResponseInvalid = class extends Error {
38547
+ constructor(route, detail) {
38548
+ super(`control plane answered ${route} with ${detail}`);
38549
+ this.name = "RemoteResponseInvalid";
38550
+ }
38551
+ };
38552
+ var RemoteTransportError = class extends Error {
38553
+ /**
38554
+ * The status the peer sent, when headers arrived and only the BODY was
38555
+ * refused.
38556
+ *
38557
+ * Undefined for the ordinary case this class was written for — no answer at
38558
+ * all. It exists because two paths reject after a status has already been
38559
+ * delivered: an oversized body and an aborted response. Discarding it there
38560
+ * reported a deployment answering 401 with a verbose body as a network
38561
+ * outage, which sends the reader to look at their network instead of their
38562
+ * credential.
38563
+ */
38564
+ constructor(reason, status) {
38565
+ super(`control-plane request did not complete: ${reason}`);
38566
+ this.status = status;
38567
+ this.name = "RemoteTransportError";
38568
+ }
38569
+ status;
38570
+ };
38571
+ async function send(options) {
38572
+ const url2 = new URL(options.url);
38573
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
38574
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
38575
+ const requestOptions = {
38576
+ method: options.method,
38577
+ headers: {
38578
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
38579
+ // last they win, and two of the values below are ones no caller may
38580
+ // replace: `x-api-key` is the credential, and `content-length` is the
38581
+ // byte count that stops a multi-byte body being truncated by the
38582
+ // receiver. `SendOptions.headers` is a free-form record on an exported
38583
+ // function, so "no caller does that today" is not the guarantee to rely
38584
+ // on. The one header any caller actually passes — `if-none-match` on the
38585
+ // conditional GET — is untouched by this order.
38586
+ ...options.headers,
38587
+ // The credential. One header, matching what the deployment authenticates
38588
+ // on; a second copy in an `Authorization` header would be one more place
38589
+ // it can be logged by an intermediary for no gain.
38590
+ //
38591
+ // Spread conditionally rather than assigned as `undefined`: Node's header
38592
+ // handling and `content-length` bookkeeping treat a present-but-undefined
38593
+ // key differently from an absent one, and "the header is not there" is
38594
+ // the property the attach flow needs.
38595
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
38596
+ accept: "application/json",
38597
+ ...options.body === void 0 ? {} : {
38598
+ "content-type": "application/json",
38599
+ // Byte length, not string length: a multi-byte body sent with a
38600
+ // character count is truncated by the receiver.
38601
+ "content-length": String(Buffer.byteLength(options.body))
38602
+ }
38603
+ }
38604
+ };
38605
+ return new Promise((resolve3, reject) => {
38606
+ let settled = false;
38607
+ const fail = (reason, status) => {
38608
+ if (settled) return;
38609
+ settled = true;
38610
+ reject(new RemoteTransportError(reason, status));
38611
+ };
38612
+ const req = send_(url2, requestOptions, (res) => {
38613
+ const chunks = [];
38614
+ let size = 0;
38615
+ res.on("data", (chunk) => {
38616
+ size += chunk.length;
38617
+ if (size > MAX_RESPONSE_BYTES) {
38618
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
38619
+ res.destroy();
38620
+ req.destroy();
38621
+ return;
38622
+ }
38623
+ chunks.push(chunk);
38624
+ });
38625
+ res.on("aborted", () => {
38626
+ fail("the response was aborted", res.statusCode);
38627
+ });
38628
+ res.on("end", () => {
38629
+ if (settled) return;
38630
+ settled = true;
38631
+ resolve3({
38632
+ status: res.statusCode ?? 0,
38633
+ headers: res.headers,
38634
+ body: Buffer.concat(chunks).toString("utf8")
38635
+ });
38636
+ });
38637
+ });
38638
+ const deadline = setTimeout(() => {
38639
+ fail(`no response within ${String(timeoutMs)}ms`);
38640
+ req.destroy();
38641
+ }, timeoutMs);
38642
+ deadline.unref();
38643
+ req.on("upgrade", (_res, socket) => {
38644
+ fail("the deployment answered with a protocol upgrade");
38645
+ socket.destroy();
38646
+ });
38647
+ req.on("close", () => {
38648
+ fail("the connection closed before a response was read");
38649
+ clearTimeout(deadline);
38650
+ });
38651
+ req.on("error", (err) => {
38652
+ fail(err.message);
38653
+ });
38654
+ if (options.body !== void 0) req.write(options.body);
38655
+ req.end();
38656
+ });
38657
+ }
39462
38658
 
39463
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
39464
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
39465
- if (typeof v === "string" && v.trim() === "") return void 0;
39466
- return v;
39467
- }, external_exports.string().optional()).catch(void 0);
39468
- var optionalFlag = external_exports.preprocess((v) => {
39469
- if (typeof v !== "string") return false;
39470
- const normalized = v.trim().toLowerCase();
39471
- return normalized !== "" && normalized !== "0" && normalized !== "false";
39472
- }, external_exports.boolean()).catch(false);
39473
- var antigravityProviderEnvShape = {
39474
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
39475
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
39476
- };
39477
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
39478
-
39479
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
39480
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
39481
- if (typeof v === "string" && v.trim() === "") return void 0;
39482
- return v;
39483
- }, external_exports.string().optional()).catch(void 0);
39484
- var codexProviderEnvShape = {
39485
- OPENAI_BASE_URL: optionalBaseUrl3
38659
+ // ../../packages/remote/src/client.ts
38660
+ var ROUTES = {
38661
+ events: "/v1/events",
38662
+ auditEvents: "/v1/audit-events",
38663
+ auditEventsBatch: "/v1/audit-events/batch",
38664
+ inventory: "/v1/inventory",
38665
+ storePosture: "/v1/store-posture",
38666
+ policyBundle: "/v1/policy-bundle",
38667
+ whoami: "/v1/plugin/whoami",
38668
+ shares: "/v1/shares",
38669
+ commands: "/v1/plugin/commands"
39486
38670
  };
39487
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
38671
+ function ackRoute(id) {
38672
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
38673
+ }
38674
+ function headerValue(response, name) {
38675
+ const raw = response.headers[name];
38676
+ if (raw === void 0) return void 0;
38677
+ return Array.isArray(raw) ? raw[0] : raw;
38678
+ }
38679
+ function okBody(response) {
38680
+ if (response.status < 200 || response.status >= 300) {
38681
+ throw new RemoteRequestError(response.status);
38682
+ }
38683
+ return response.body;
38684
+ }
38685
+ function parsed(schema, body, route) {
38686
+ let json2;
38687
+ try {
38688
+ json2 = JSON.parse(body);
38689
+ } catch {
38690
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
38691
+ }
38692
+ const result = schema.safeParse(json2);
38693
+ if (!result.success) {
38694
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
38695
+ }
38696
+ return result.data;
38697
+ }
38698
+ function resolveBaseUrl(endpoint) {
38699
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
38700
+ let end = endpoint.length;
38701
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
38702
+ return endpoint.slice(0, end);
38703
+ }
38704
+ var SLASH2 = "/".charCodeAt(0);
38705
+ function createRemoteClient(options) {
38706
+ const base = resolveBaseUrl(options.endpoint);
38707
+ const url2 = (route) => `${base}${route}`;
38708
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
38709
+ const sendOne = async (event) => {
38710
+ const validated = RecordAuditEventRequest.safeParse(event);
38711
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
38712
+ const response = await send({
38713
+ ...common,
38714
+ method: "POST",
38715
+ url: url2(ROUTES.auditEvents),
38716
+ body: JSON.stringify(validated.data)
38717
+ });
38718
+ okBody(response);
38719
+ };
38720
+ return {
38721
+ async ingestEvents(batch) {
38722
+ const response = await send({
38723
+ ...common,
38724
+ method: "POST",
38725
+ url: url2(ROUTES.events),
38726
+ body: JSON.stringify(batch)
38727
+ });
38728
+ return parsed(IngestAck, okBody(response), ROUTES.events);
38729
+ },
38730
+ async ingestInventory(context) {
38731
+ const response = await send({
38732
+ ...common,
38733
+ method: "POST",
38734
+ url: url2(ROUTES.inventory),
38735
+ body: JSON.stringify(context)
38736
+ });
38737
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
38738
+ },
38739
+ async recordAuditEvent(event) {
38740
+ await sendOne(event);
38741
+ },
38742
+ async recordAuditEvents(events, opts) {
38743
+ const validated = RecordAuditEventBatch.safeParse({ events });
38744
+ if (!validated.success) {
38745
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
38746
+ }
38747
+ const response = await send({
38748
+ ...common,
38749
+ method: "POST",
38750
+ url: url2(ROUTES.auditEventsBatch),
38751
+ body: JSON.stringify(validated.data)
38752
+ });
38753
+ if (response.status === 404) {
38754
+ if (opts?.fallbackToSingleEvents !== true) {
38755
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
38756
+ }
38757
+ for (const event of validated.data.events) await sendOne(event);
38758
+ return { accepted: validated.data.events.length };
38759
+ }
38760
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
38761
+ },
38762
+ async reportStorePosture(snapshot) {
38763
+ const response = await send({
38764
+ ...common,
38765
+ method: "POST",
38766
+ url: url2(ROUTES.storePosture),
38767
+ body: JSON.stringify(snapshot)
38768
+ });
38769
+ okBody(response);
38770
+ },
38771
+ async getPolicyBundle(etag) {
38772
+ const response = await send({
38773
+ ...common,
38774
+ method: "GET",
38775
+ url: url2(ROUTES.policyBundle),
38776
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
38777
+ });
38778
+ if (response.status === 304) {
38779
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
38780
+ }
38781
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
38782
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
38783
+ },
38784
+ async whoami() {
38785
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
38786
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
38787
+ },
38788
+ async recordProjectEgress(request) {
38789
+ const validated = EgressIngestRequest.safeParse(request);
38790
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
38791
+ const response = await send({
38792
+ ...common,
38793
+ method: "POST",
38794
+ url: url2(ROUTES.shares),
38795
+ body: JSON.stringify(validated.data)
38796
+ });
38797
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
38798
+ okBody(response);
38799
+ },
38800
+ async pollCommand() {
38801
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
38802
+ if (response.status === 404) return null;
38803
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
38804
+ },
38805
+ async ackCommand(id, body) {
38806
+ const validated = DeviceCommandAckBody.safeParse(body);
38807
+ const route = ackRoute(id);
38808
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
38809
+ const response = await send({
38810
+ ...common,
38811
+ method: "POST",
38812
+ url: url2(route),
38813
+ body: JSON.stringify(validated.data)
38814
+ });
38815
+ okBody(response);
38816
+ }
38817
+ };
38818
+ }
39488
38819
 
39489
- // ../../packages/plugin-sdk/src/runtime.ts
39490
- import { randomUUID as randomUUID15 } from "crypto";
38820
+ // ../../packages/remote/src/failure-kind.ts
38821
+ function statusOf(err) {
38822
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
38823
+ const { status } = err;
38824
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
38825
+ return status >= 100 && status <= 599 ? status : null;
38826
+ }
38827
+ function nameOf(err) {
38828
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
38829
+ return typeof err.name === "string" ? err.name : null;
38830
+ }
38831
+ function classifyRemoteFailure(err) {
38832
+ switch (nameOf(err)) {
38833
+ case "RemoteRouteAbsent":
38834
+ return "route-absent";
38835
+ case "RemoteRequestInvalid":
38836
+ case "RemoteEndpointRefused":
38837
+ return "invalid-request";
38838
+ case "RemoteResponseInvalid":
38839
+ return "rejected";
38840
+ default:
38841
+ break;
38842
+ }
38843
+ const status = statusOf(err);
38844
+ if (status === null) return "unreachable";
38845
+ switch (status) {
38846
+ case 401:
38847
+ return "unauthorized";
38848
+ case 403:
38849
+ return "forbidden";
38850
+ case 429:
38851
+ return "unreachable";
38852
+ case 404:
38853
+ return "unreachable";
38854
+ default:
38855
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
38856
+ }
38857
+ }
39491
38858
 
39492
- // ../../packages/plugin-sdk/src/scope-key.ts
39493
- import { existsSync as existsSync12 } from "fs";
39494
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
38859
+ // ../../packages/plugin-runtime/src/attached/failure.ts
38860
+ function classifyFailure(err) {
38861
+ switch (classifyRemoteFailure(err)) {
38862
+ case "unauthorized":
38863
+ return "unauthorized";
38864
+ case "forbidden":
38865
+ return "forbidden";
38866
+ default:
38867
+ return "unreachable";
38868
+ }
38869
+ }
39495
38870
 
39496
- // ../../packages/plugin-sdk/src/suppressions.ts
39497
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38871
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
38872
+ var REQUEST_TIMEOUT_MS = 2e3;
38873
+ function withTimeout(promise2, ms) {
38874
+ let timer;
38875
+ const timeout = new Promise((_, reject) => {
38876
+ timer = setTimeout(() => {
38877
+ reject(new Error("attached gateway request timed out"));
38878
+ }, ms);
38879
+ });
38880
+ promise2.catch(() => void 0);
38881
+ return Promise.race([promise2, timeout]).finally(() => {
38882
+ clearTimeout(timer);
38883
+ });
38884
+ }
39498
38885
 
39499
- // ../../packages/plugin-sdk/src/throttle.ts
39500
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
39501
- import { join as join27 } from "path";
38886
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
38887
+ import { readFileSync as readFileSync11 } from "fs";
38888
+ import { join as join18 } from "path";
38889
+ var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
38890
+ function forwardDropsPath(dataDir2) {
38891
+ return join18(dataDir2, FORWARD_DROPS_FILENAME);
38892
+ }
38893
+ function recordForwardDrops(dataDir2, count, nowMs) {
38894
+ if (count <= 0) return;
38895
+ try {
38896
+ ensureDataDirSync(dataDir2);
38897
+ const previous = readForwardDrops(dataDir2);
38898
+ const next = {
38899
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
38900
+ lastDropAtMs: nowMs
38901
+ };
38902
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
38903
+ `);
38904
+ } catch {
38905
+ }
38906
+ }
38907
+ function readForwardDrops(dataDir2) {
38908
+ try {
38909
+ const parsed2 = JSON.parse(readFileSync11(forwardDropsPath(dataDir2), "utf8"));
38910
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
38911
+ const record2 = parsed2;
38912
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
38913
+ return null;
38914
+ }
38915
+ if (record2.droppedForwards <= 0) return null;
38916
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
38917
+ return null;
38918
+ }
38919
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
38920
+ } catch {
38921
+ return null;
38922
+ }
38923
+ }
39502
38924
 
39503
38925
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
38926
+ import { randomUUID as randomUUID14 } from "crypto";
38927
+ import { readFile, rename, writeFile } from "fs/promises";
38928
+ import { join as join19 } from "path";
39504
38929
  function isInvalidRequest(err) {
39505
38930
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
39506
38931
  }
@@ -39519,7 +38944,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
39519
38944
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
39520
38945
  function createForwardPolicy(deps) {
39521
38946
  const now = deps.now ?? (() => Date.now());
39522
- const file2 = join28(deps.dir, STATE_FILENAME);
38947
+ const file2 = join19(deps.dir, STATE_FILENAME);
39523
38948
  let state = null;
39524
38949
  let loading = null;
39525
38950
  async function readState() {
@@ -39544,7 +38969,7 @@ function createForwardPolicy(deps) {
39544
38969
  state = next;
39545
38970
  try {
39546
38971
  await ensureDataDir(deps.dir);
39547
- const tmp = `${file2}.${randomUUID16()}.tmp`;
38972
+ const tmp = `${file2}.${randomUUID14()}.tmp`;
39548
38973
  await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
39549
38974
  await rename(tmp, file2);
39550
38975
  } catch {
@@ -39685,6 +39110,9 @@ var AttachedDataGateway = class {
39685
39110
  *
39686
39111
  * Machine mode answers before any key is read, so a machine attachment pays
39687
39112
  * nothing for scoping and forwards exactly what it always has.
39113
+ *
39114
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
39115
+ * forwarding key for key.
39688
39116
  */
39689
39117
  verdictFor(keyOf) {
39690
39118
  try {
@@ -39701,24 +39129,27 @@ var AttachedDataGateway = class {
39701
39129
  * the key its row holds in the local store, recorded per root (see
39702
39130
  * `rootVerdict`), not the key on the root event just handed in: roots are
39703
39131
  * first-write-wins in the store, so when two producers record a root for one
39704
- * session (the session-start hook, then a reconcile pass) the second leaves
39705
- * the stored row as it was, and the history drain decides that row, not this
39706
- * event. Whether this root EVENT is itself sent takes both keys: the stored
39707
- * one AND its own. The event's attributes (cwd, project, repo) describe where
39708
- * it was recorded from, so a root event keyed to a personal directory is never
39709
- * sent under an enrolled stored root, though the enrolled leaves still forward
39710
- * under it: the instance that wrote the stored root is expected to have
39711
- * forwarded it. If it did not (the root was written while standalone or under
39712
- * another attachment, or its forward failed), the plane refuses those leaves
39713
- * and the history drain ships the root first. Any other row with a root
39714
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
39715
- * is in scope AND this instance recorded an in-scope verdict for that root.
39716
- * The audit-event route has real foreign keys on both columns and stubs no
39717
- * missing root, so a leaf sent after its root was kept local is refused
39718
- * there, and a refused forward counts toward the breaker that guards every
39719
- * other one. A root this instance never recorded is therefore `'local'`: the
39720
- * only answer that cannot orphan a row. A row with no root reference at all
39721
- * has nothing to orphan, and is decided by its own key.
39132
+ * session (the session-start hook, then a reconcile pass) the second leaves the
39133
+ * stored row as it was. That stored row, not this event, is what a history
39134
+ * drain pass would decide, if the root started before the attach; the drain
39135
+ * never offers one that started after it (`started_at < backlogBefore`).
39136
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
39137
+ * its own. The event's attributes (cwd, project, repo) describe where it was
39138
+ * recorded from, so a root event keyed to a personal directory is never sent
39139
+ * under an enrolled stored root, though the enrolled leaves still forward under
39140
+ * it: the instance that wrote the stored root is expected to have forwarded it.
39141
+ * If it did not (the root was written while standalone or under another
39142
+ * attachment, or its forward failed), the plane refuses those leaves. A root
39143
+ * that started before the attach is shipped, ahead of its leaves, by the
39144
+ * history drain; one that started after it is never offered by the drain. Any
39145
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
39146
+ * only when its own key is in scope AND this instance recorded an in-scope
39147
+ * verdict for that root. The audit-event route has real foreign keys on both
39148
+ * columns and stubs no missing root, so a leaf sent after its root was kept
39149
+ * local is refused there, and a refused forward counts toward the breaker that
39150
+ * guards every other one. A root this instance never recorded is therefore
39151
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
39152
+ * reference at all has nothing to orphan, and is decided by its own key.
39722
39153
  *
39723
39154
  * What this costs is stated rather than discovered. A session whose stored
39724
39155
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -39789,6 +39220,87 @@ var AttachedDataGateway = class {
39789
39220
  return [];
39790
39221
  }
39791
39222
  }
39223
+ /**
39224
+ * The verdict for the repositories nested in a scanned project, answered
39225
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
39226
+ *
39227
+ * A walk descends into a nested clone or submodule and folds its files into
39228
+ * the project it is walking, so one register can carry several
39229
+ * repositories' call sites under one project key. Each of them must be in
39230
+ * scope for it to forward. One key out of scope, or a nested repository with
39231
+ * no remote (an `undefined` key), keeps the whole register local.
39232
+ *
39233
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
39234
+ * what is nested in it, and every scan passes the list, empty when nothing
39235
+ * is nested. A register nobody vouched for is not one a scoped attachment
39236
+ * may send.
39237
+ *
39238
+ * Machine mode answers before reading the context, so a machine attachment
39239
+ * forwards exactly what it always has.
39240
+ */
39241
+ nestedVerdict(context) {
39242
+ try {
39243
+ if (this.deps.attachment.mode === "machine") return "forward";
39244
+ const keys = context?.nestedScopeKeys;
39245
+ if (keys === void 0) return "local";
39246
+ for (const key of keys) {
39247
+ if (this.verdictFor(() => key) === "local") return "local";
39248
+ }
39249
+ return "forward";
39250
+ } catch {
39251
+ return "local";
39252
+ }
39253
+ }
39254
+ /**
39255
+ * The register a scoped attachment sends, once the project and the repositories
39256
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
39257
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
39258
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
39259
+ *
39260
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
39261
+ * and the ledger holds every file the scanner ever read under the root, nested
39262
+ * clones' included. So a clone that was removed, or one an ignore file now
39263
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
39264
+ * paths come back as deleted. The scan names the repository of each deleted
39265
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
39266
+ * and each is held to the same verdict as any other key. A path whose key is
39267
+ * absent, or out of scope, is not sent.
39268
+ *
39269
+ * The list is asked for here, and only here: it is an async read of the scan
39270
+ * ledger that the scan makes on being called, so a machine attachment, which
39271
+ * returns before this, and a register already kept local never cause it.
39272
+ *
39273
+ * Anything the scan did not vouch for sends no deleted path, and the register
39274
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
39275
+ * list whose length is not the register's. Deleting is the only thing a dropped
39276
+ * path could have done on the server, so the cost of a refusal is a stored row
39277
+ * that stays, never a path that leaves.
39278
+ *
39279
+ * Machine mode returns `input` itself, the same object and unread, so a machine
39280
+ * attachment's request is exactly what it was. A register that lists no deleted
39281
+ * path, or that is not a ledger register, has nothing to cut and is returned
39282
+ * as it came, with the list unread.
39283
+ */
39284
+ async registerForWire(input2, context) {
39285
+ try {
39286
+ if (this.deps.attachment.mode === "machine") return input2;
39287
+ const { reconcile } = input2;
39288
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
39289
+ const deleted = reconcile.deletedFiles;
39290
+ let kept = [];
39291
+ try {
39292
+ const keys = await context?.deletedFileKeys?.();
39293
+ if (keys?.length === deleted.length) {
39294
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
39295
+ }
39296
+ } catch {
39297
+ kept = [];
39298
+ }
39299
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
39300
+ } catch {
39301
+ return void 0;
39302
+ }
39303
+ }
39792
39304
  /**
39793
39305
  * The event `recordCapture` sends for a capture the verdict let through, or
39794
39306
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -40114,12 +39626,24 @@ var AttachedDataGateway = class {
40114
39626
  * payload onto the wire-boundary-safe shape (no snippet, hashed
40115
39627
  * projectKey), and its result is discarded: `forward.run` never throws or
40116
39628
  * rejects, so there is nothing here to act on.
39629
+ *
39630
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
39631
+ * not say: the key of every repository nested below the scan root, whose
39632
+ * files the walk folded into this register. On a scoped attachment the
39633
+ * register is forwarded only when the project's own key AND every one of
39634
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
39635
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
39636
+ * `registerForWire`). Machine mode never reads either, and the local write
39637
+ * never receives the context and gets the register whole.
40117
39638
  */
40118
- async recordProjectEgress(input2) {
39639
+ async recordProjectEgress(input2, context) {
40119
39640
  const summary = await this.deps.local.recordProjectEgress(input2);
40120
39641
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
39642
+ if (this.nestedVerdict(context) === "local") return summary;
39643
+ const register = await this.registerForWire(input2, context);
39644
+ if (register === void 0) return summary;
40121
39645
  await this.deps.forward.run(
40122
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
39646
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
40123
39647
  );
40124
39648
  return summary;
40125
39649
  }
@@ -40173,6 +39697,11 @@ var AttachedDataGateway = class {
40173
39697
  async scanLedgerPaths() {
40174
39698
  return this.deps.local.scanLedgerPaths();
40175
39699
  }
39700
+ // Delegated, like the path list. An inner gateway that cannot say answers an
39701
+ // empty map, which gives every deleted path no key.
39702
+ async scanLedgerPathKeys() {
39703
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
39704
+ }
40176
39705
  async recordScanned(entries) {
40177
39706
  return this.deps.local.recordScanned(entries);
40178
39707
  }
@@ -40239,6 +39768,12 @@ var AttachedDataGateway = class {
40239
39768
  // and the spread above would otherwise drop the field silently — which is
40240
39769
  // exactly what it did, leaving the whole control inert on every device
40241
39770
  // while every test around it stayed green.
39771
+ //
39772
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
39773
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
39774
+ // reads this bundle once to build detection, so the detections it carries
39775
+ // apply to every event on the machine. Where a prohibition applies is
39776
+ // answered per event by `governanceAppliesTo` below.
40242
39777
  prohibitedModels: cached2.prohibitedModels,
40243
39778
  // NAMED for the same reason as the line above, and it is the same defect
40244
39779
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -40298,6 +39833,30 @@ var AttachedDataGateway = class {
40298
39833
  };
40299
39834
  }
40300
39835
  // ---------------------------------------------------------------------
39836
+ // GovernanceScope — where the organization's model policy applies
39837
+ // ---------------------------------------------------------------------
39838
+ /**
39839
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
39840
+ * the question a model-guard site asks once it has decided to refuse.
39841
+ *
39842
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
39843
+ * with the same key would be forwarded. A machine-wide attachment governs
39844
+ * every event, keyless included, exactly as before. A scoped one governs an
39845
+ * event only when its key names an enrolled repository. An event in a
39846
+ * personal repository, in no repository, with an empty key, or met by a fault
39847
+ * is not governed.
39848
+ *
39849
+ * The event's OWN key, never its session root's. The root rule in
39850
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
39851
+ * this decides whether a refusal applies, which is a question about where the
39852
+ * event happened.
39853
+ *
39854
+ * Answered from memory: no store read, no bundle read, nothing sent.
39855
+ */
39856
+ governanceAppliesTo(scopeKey) {
39857
+ return this.verdictFor(() => scopeKey) === "forward";
39858
+ }
39859
+ // ---------------------------------------------------------------------
40301
39860
  // LocalStoreMaintenance — by delegation (D3).
40302
39861
  //
40303
39862
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -40407,35 +39966,36 @@ function toWireInspection(insp) {
40407
39966
 
40408
39967
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
40409
39968
  import { createHash as createHash6 } from "crypto";
40410
- import { hostname as hostname5 } from "os";
39969
+ import { hostname as hostname4 } from "os";
40411
39970
 
40412
39971
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
40413
39972
  var CORRELATION_ID = EventMetadata.shape.correlationId;
40414
39973
  var TRACE_ID = EventMetadata.shape.traceId;
40415
39974
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40416
39975
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
39976
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
40417
39977
 
40418
39978
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
40419
39979
  var CAPTURE_BATCH_BYTES = 1024 * 1024;
40420
39980
 
40421
39981
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
40422
39982
  import { spawn } from "child_process";
40423
- import { fileURLToPath as fileURLToPath2 } from "url";
39983
+ import { fileURLToPath } from "url";
40424
39984
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
40425
39985
 
40426
39986
  // ../../packages/plugin-runtime/src/attached/install-record.ts
40427
39987
  import { readFile as readFile2, stat } from "fs/promises";
40428
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
39988
+ import { basename as basename2, dirname as dirname4, join as join20, resolve as resolve2 } from "path";
40429
39989
  async function readInstalledVersion(installRoot) {
40430
39990
  try {
40431
39991
  const versionDir = resolve2(installRoot);
40432
- const pluginDir = dirname7(versionDir);
40433
- const marketplaceDir = dirname7(pluginDir);
40434
- const cacheDir = dirname7(marketplaceDir);
40435
- if (basename6(cacheDir) !== "cache") return null;
40436
- const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
39992
+ const pluginDir = dirname4(versionDir);
39993
+ const marketplaceDir = dirname4(pluginDir);
39994
+ const cacheDir = dirname4(marketplaceDir);
39995
+ if (basename2(cacheDir) !== "cache") return null;
39996
+ const key = `${basename2(pluginDir)}@${basename2(marketplaceDir)}`;
40437
39997
  const record2 = JSON.parse(
40438
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
39998
+ await readFile2(join20(dirname4(cacheDir), "installed_plugins.json"), "utf8")
40439
39999
  );
40440
40000
  const plugins = record2?.plugins;
40441
40001
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -40467,7 +40027,7 @@ async function exists(path) {
40467
40027
  }
40468
40028
 
40469
40029
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
40470
- import { readFileSync as readFileSync18 } from "fs";
40030
+ import { readFileSync as readFileSync12 } from "fs";
40471
40031
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
40472
40032
  function createPluginBlock(build, policyStore) {
40473
40033
  return async () => {
@@ -40495,9 +40055,9 @@ async function readInstalledVersionBounded(installRoot) {
40495
40055
  }
40496
40056
 
40497
40057
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40498
- import { randomUUID as randomUUID17 } from "crypto";
40058
+ import { randomUUID as randomUUID15 } from "crypto";
40499
40059
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
40500
- import { join as join30 } from "path";
40060
+ import { join as join21 } from "path";
40501
40061
 
40502
40062
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
40503
40063
  import { rename as rename2 } from "fs/promises";
@@ -40526,7 +40086,7 @@ async function publishByRename(tmp, file2, move = rename2) {
40526
40086
 
40527
40087
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40528
40088
  function createPolicyStore(dir = dataDir()) {
40529
- const file2 = join30(dir, "policy-cache.json");
40089
+ const file2 = join21(dir, "policy-cache.json");
40530
40090
  async function read() {
40531
40091
  try {
40532
40092
  const raw = await readFile3(file2, "utf8");
@@ -40558,7 +40118,7 @@ function createPolicyStore(dir = dataDir()) {
40558
40118
  }
40559
40119
  }
40560
40120
  async function publishRecord(record2) {
40561
- const tmp = `${file2}.${randomUUID17()}.tmp`;
40121
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
40562
40122
  try {
40563
40123
  await writeFile2(tmp, JSON.stringify(record2), {
40564
40124
  encoding: "utf8",
@@ -40596,8 +40156,8 @@ function createPolicyStore(dir = dataDir()) {
40596
40156
  }
40597
40157
 
40598
40158
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
40599
- import { readFileSync as readFileSync19 } from "fs";
40600
- import { join as join31 } from "path";
40159
+ import { readFileSync as readFileSync13 } from "fs";
40160
+ import { join as join22 } from "path";
40601
40161
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
40602
40162
  var OUTCOME_KEYS = {
40603
40163
  ok: true,
@@ -40611,7 +40171,7 @@ var OUTCOME_KEYS = {
40611
40171
  };
40612
40172
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
40613
40173
  function postureReportStatePath(dataDir2) {
40614
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
40174
+ return join22(dataDir2, POSTURE_REPORT_STATE_FILENAME);
40615
40175
  }
40616
40176
  function writePostureReportState(dataDir2, state) {
40617
40177
  try {
@@ -40652,10 +40212,19 @@ function createPostureReporter(deps) {
40652
40212
  hostname: deps.hostname(),
40653
40213
  capturedAt: nowMs,
40654
40214
  ...measurement,
40655
- // Omit the key rather than spread an explicit `undefined` —
40656
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
40657
- // factory.ts keys on presence.
40658
- ...plugin === void 0 ? {} : { plugin }
40215
+ // Omit the key rather than spread an explicit `undefined`. The type
40216
+ // admits `undefined` here (the schema's optional member), and
40217
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
40218
+ // in-memory object free of an explicit `undefined` member, which the
40219
+ // tests pin by key presence.
40220
+ ...plugin === void 0 ? {} : { plugin },
40221
+ // LAST, and only for a scoped attachment. A machine attachment omits
40222
+ // the key the same way, so its body is byte for byte the one it sent
40223
+ // before the member existed. Anything but exactly `machine` reports the
40224
+ // constant `scoped`, never the raw value: that is resolveScope's own
40225
+ // fail direction, and a value outside the wire's vocabulary would fail
40226
+ // the whole snapshot at the receiver, the wipe signal with it.
40227
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
40659
40228
  };
40660
40229
  } catch {
40661
40230
  return null;
@@ -40678,8 +40247,8 @@ function createPostureReporter(deps) {
40678
40247
  }
40679
40248
 
40680
40249
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
40681
- import { statSync as statSync9 } from "fs";
40682
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
40250
+ import { statSync as statSync6 } from "fs";
40251
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
40683
40252
 
40684
40253
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
40685
40254
  function emptyActionCounts() {
@@ -40709,7 +40278,7 @@ function emptyReadout(readError = false) {
40709
40278
  }
40710
40279
  function readStorePosture(dbPath2) {
40711
40280
  try {
40712
- statSync9(dbPath2);
40281
+ statSync6(dbPath2);
40713
40282
  } catch (err) {
40714
40283
  const code = err.code;
40715
40284
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -40737,7 +40306,7 @@ function readStorePosture(dbPath2) {
40737
40306
  readError: false
40738
40307
  });
40739
40308
  try {
40740
- db = new DatabaseSync4(dbPath2, { readOnly: true });
40309
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
40741
40310
  db.exec("PRAGMA busy_timeout = 2000");
40742
40311
  version2 = db.prepare("PRAGMA user_version").get().user_version;
40743
40312
  try {
@@ -40789,16 +40358,16 @@ function readStorePosture(dbPath2) {
40789
40358
  }
40790
40359
 
40791
40360
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
40792
- import { randomUUID as randomUUID18 } from "crypto";
40361
+ import { randomUUID as randomUUID16 } from "crypto";
40793
40362
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
40794
- import { join as join32 } from "path";
40363
+ import { join as join23 } from "path";
40795
40364
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40796
40365
  function createPostureStore(dir = settingsDir(), legacyDir) {
40797
- const file2 = join32(dir, "posture-state.json");
40798
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
40366
+ const file2 = join23(dir, "posture-state.json");
40367
+ const legacyFile = legacyDir === void 0 ? null : join23(legacyDir, "posture-state.json");
40799
40368
  async function persist(state) {
40800
40369
  await ensureDataDir(dir);
40801
- const tmp = `${file2}.${randomUUID18()}.tmp`;
40370
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
40802
40371
  try {
40803
40372
  await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
40804
40373
  await publishByRename(tmp, file2);
@@ -40840,7 +40409,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40840
40409
  }
40841
40410
  return legacy;
40842
40411
  }
40843
- const fresh = { deviceId: randomUUID18(), lastAttemptedAtMs: 0 };
40412
+ const fresh = { deviceId: randomUUID16(), lastAttemptedAtMs: 0 };
40844
40413
  try {
40845
40414
  await ensureDataDir(dir);
40846
40415
  if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
@@ -40863,8 +40432,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40863
40432
  }
40864
40433
 
40865
40434
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
40866
- import { readFileSync as readFileSync20 } from "fs";
40867
- import { join as join33 } from "path";
40435
+ import { readFileSync as readFileSync14 } from "fs";
40436
+ import { join as join24 } from "path";
40868
40437
 
40869
40438
  // ../../packages/plugin-runtime/src/attached/status.ts
40870
40439
  var REFUSAL_LINES = {
@@ -40882,7 +40451,7 @@ var OUTCOME_LINES = {
40882
40451
 
40883
40452
  // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
40884
40453
  import { spawn as spawn2 } from "child_process";
40885
- import { fileURLToPath as fileURLToPath3 } from "url";
40454
+ import { fileURLToPath as fileURLToPath2 } from "url";
40886
40455
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
40887
40456
 
40888
40457
  // ../../packages/plugin-runtime/src/content-retention-pass.ts
@@ -40890,11 +40459,11 @@ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40890
40459
 
40891
40460
  // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40892
40461
  import { spawn as spawn3 } from "child_process";
40893
- import { fileURLToPath as fileURLToPath4 } from "url";
40462
+ import { fileURLToPath as fileURLToPath3 } from "url";
40894
40463
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40895
40464
 
40896
40465
  // ../../packages/plugin-runtime/src/attached/factory.ts
40897
- import { hostname as hostname6 } from "os";
40466
+ import { hostname as hostname5 } from "os";
40898
40467
 
40899
40468
  // ../../packages/plugin-runtime/src/recorder.ts
40900
40469
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -40907,7 +40476,7 @@ var StandaloneDataGateway = class {
40907
40476
  // One notice per gateway — see warnRulesetDiscarded.
40908
40477
  warnedRulesetDiscarded = false;
40909
40478
  constructor(dataDir2, detections = [], meta4) {
40910
- this.db = openLocalDatabase(dataDir2);
40479
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
40911
40480
  this.dataDir = dataDir2;
40912
40481
  this.db.installedPacks.recordInventory(detections, meta4);
40913
40482
  }
@@ -41256,6 +40825,9 @@ var StandaloneDataGateway = class {
41256
40825
  scanLedgerPaths() {
41257
40826
  return Promise.resolve(this.db.scanLedger.allPaths());
41258
40827
  }
40828
+ scanLedgerPathKeys() {
40829
+ return Promise.resolve(this.db.scanLedger.pathKeys());
40830
+ }
41259
40831
  recordScanned(entries) {
41260
40832
  this.db.scanLedger.upsertEntries(entries);
41261
40833
  return Promise.resolve();
@@ -41341,13 +40913,17 @@ function resolveGatewayForConfig(config2, meta4) {
41341
40913
  },
41342
40914
  store: postureStore,
41343
40915
  readStore: () => readStorePosture(config2.dbPath),
41344
- hostname: () => hostname6(),
40916
+ hostname: () => hostname5(),
41345
40917
  now: () => Date.now(),
40918
+ // The mode THIS gateway enforces, from the attachment resolved above,
40919
+ // so the report cannot name a mode the forward paths are not using.
40920
+ attachmentMode: attachment.mode,
41346
40921
  // The reporting build's identity, when the caller knows it (the plugin
41347
40922
  // adapters do; an embedder or a test may not). Composed with the SAME
41348
40923
  // policy store the sync child writes, so the block names the bundle
41349
- // actually in force. Key omitted rather than set undefined — the
41350
- // reporter keys on presence.
40924
+ // actually in force. The dependency key is omitted when no build is
40925
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
40926
+ // then adds no block.
41351
40927
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
41352
40928
  })
41353
40929
  });
@@ -41364,7 +40940,7 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
41364
40940
  }
41365
40941
 
41366
40942
  // ../../packages/plugin-runtime/src/handle-session-start.ts
41367
- import { randomUUID as randomUUID19 } from "crypto";
40943
+ import { randomUUID as randomUUID17 } from "crypto";
41368
40944
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
41369
40945
 
41370
40946
  // src/setup-frame-json.ts
@@ -41435,8 +41011,8 @@ function table(headers, rows, opts = {}) {
41435
41011
  const widths = headers.map(
41436
41012
  (h, i) => Math.max(visibleLength(h), ...rows.map((r) => visibleLength(r[i] ?? "")))
41437
41013
  );
41438
- const sep4 = " ".repeat(gap);
41439
- const fmt = (cells) => cells.map((cell, i) => padEnd(cell, widths[i] ?? 0)).join(sep4);
41014
+ const sep2 = " ".repeat(gap);
41015
+ const fmt = (cells) => cells.map((cell, i) => padEnd(cell, widths[i] ?? 0)).join(sep2);
41440
41016
  const headerLine = fmt(headers.map((h) => h.toUpperCase()));
41441
41017
  if (opts.rowSep === true) {
41442
41018
  const fullWidth = widths.reduce((n, w) => n + w, 0) + gap * Math.max(0, widths.length - 1);
@@ -41448,7 +41024,7 @@ function table(headers, rows, opts = {}) {
41448
41024
  });
41449
41025
  return [headerLine, rule, ...body].join("\n");
41450
41026
  }
41451
- const ruleLine = widths.map((w) => "\u2500".repeat(w)).join(sep4);
41027
+ const ruleLine = widths.map((w) => "\u2500".repeat(w)).join(sep2);
41452
41028
  return [headerLine, ruleLine, ...rows.map(fmt)].join("\n");
41453
41029
  }
41454
41030
  function fenced(body) {
@@ -41461,8 +41037,8 @@ function show(body) {
41461
41037
  }
41462
41038
 
41463
41039
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
41464
- import { writeFileSync as writeFileSync8 } from "fs";
41465
- import { join as join34 } from "path";
41040
+ import { writeFileSync as writeFileSync5 } from "fs";
41041
+ import { join as join25 } from "path";
41466
41042
 
41467
41043
  // ../../packages/setup-wizard/src/triage/merge.ts
41468
41044
  var RANK = Object.fromEntries(
@@ -41470,9 +41046,9 @@ var RANK = Object.fromEntries(
41470
41046
  );
41471
41047
 
41472
41048
  // ../../packages/setup-wizard/src/triage/plan-file.ts
41473
- import { mkdtempSync, readFileSync as readFileSync21, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
41049
+ import { mkdtempSync, readFileSync as readFileSync15, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "fs";
41474
41050
  import { tmpdir } from "os";
41475
- import { basename as basename7, dirname as dirname8, join as join35 } from "path";
41051
+ import { basename as basename3, dirname as dirname5, join as join26 } from "path";
41476
41052
  var SuppressionEntrySchema = external_exports.object({
41477
41053
  ruleId: external_exports.string(),
41478
41054
  category: DetectionCategory,
@@ -41514,10 +41090,10 @@ var PersistedPlanSchema = external_exports.object({
41514
41090
  });
41515
41091
 
41516
41092
  // src/skills-registry.ts
41517
- import { readdirSync as readdirSync5, readFileSync as readFileSync22 } from "fs";
41518
- import { join as join36 } from "path";
41519
- import { fileURLToPath as fileURLToPath5 } from "url";
41520
- var SKILLS_DIR = fileURLToPath5(new URL("../skills", import.meta.url));
41093
+ import { readdirSync as readdirSync2, readFileSync as readFileSync16 } from "fs";
41094
+ import { join as join27 } from "path";
41095
+ import { fileURLToPath as fileURLToPath4 } from "url";
41096
+ var SKILLS_DIR = fileURLToPath4(new URL("../skills", import.meta.url));
41521
41097
  function frontmatterName(content) {
41522
41098
  const block = /^---\n([\s\S]*?)\n---/.exec(content);
41523
41099
  if (block === null) return void 0;
@@ -41525,10 +41101,10 @@ function frontmatterName(content) {
41525
41101
  return name?.[1];
41526
41102
  }
41527
41103
  function readRegisteredSkills() {
41528
- return readdirSync5(SKILLS_DIR, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
41104
+ return readdirSync2(SKILLS_DIR, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
41529
41105
  let content;
41530
41106
  try {
41531
- content = readFileSync22(join36(SKILLS_DIR, entry.name, "SKILL.md"), "utf8");
41107
+ content = readFileSync16(join27(SKILLS_DIR, entry.name, "SKILL.md"), "utf8");
41532
41108
  } catch {
41533
41109
  return [];
41534
41110
  }