@bbcsoftwarefactory/cli 0.1.0 → 1.1.2

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.
Files changed (126) hide show
  1. package/dist/audit-ledger.d.ts +2 -0
  2. package/dist/audit-ledger.js +71 -0
  3. package/dist/bbc-install.d.ts +2 -0
  4. package/dist/bbc-install.js +1250 -0
  5. package/dist/bbc.d.ts +2 -0
  6. package/dist/bbc.js +124 -0
  7. package/dist/bigo/complexity.d.ts +18 -0
  8. package/dist/bigo/complexity.js +139 -0
  9. package/dist/bigo/functions.d.ts +5 -0
  10. package/dist/bigo/functions.js +174 -0
  11. package/dist/bigo/keywords.d.ts +1 -0
  12. package/dist/bigo/keywords.js +43 -0
  13. package/dist/bigo/lexical.d.ts +14 -0
  14. package/dist/bigo/lexical.js +69 -0
  15. package/dist/bigo/source-files.d.ts +1 -0
  16. package/dist/bigo/source-files.js +80 -0
  17. package/dist/change-lane/classification.d.ts +41 -0
  18. package/dist/change-lane/classification.js +104 -0
  19. package/dist/change-lane/git.d.ts +8 -0
  20. package/dist/change-lane/git.js +105 -0
  21. package/dist/check-issue-claim.d.ts +2 -0
  22. package/dist/check-issue-claim.js +146 -0
  23. package/dist/check-worktree-guard.d.ts +2 -0
  24. package/dist/check-worktree-guard.js +114 -0
  25. package/dist/classify-change-lane.d.ts +2 -0
  26. package/dist/classify-change-lane.js +128 -0
  27. package/dist/diff-scope/git-diff.d.ts +25 -0
  28. package/dist/diff-scope/git-diff.js +146 -0
  29. package/dist/error-scan.d.ts +3 -0
  30. package/dist/error-scan.js +216 -0
  31. package/dist/export-public.d.ts +9 -0
  32. package/dist/export-public.js +274 -0
  33. package/dist/extract-diff-scope.d.ts +2 -0
  34. package/dist/extract-diff-scope.js +111 -0
  35. package/dist/fetch-issue-attachments.d.ts +22 -0
  36. package/dist/fetch-issue-attachments.js +325 -0
  37. package/dist/issue-claim/evaluation.d.ts +66 -0
  38. package/dist/issue-claim/evaluation.js +259 -0
  39. package/dist/issue-claim/loaders.d.ts +5 -0
  40. package/dist/issue-claim/loaders.js +116 -0
  41. package/dist/list-zed-commands.d.ts +7 -0
  42. package/dist/list-zed-commands.js +288 -0
  43. package/dist/measure-bigo.d.ts +2 -0
  44. package/dist/measure-bigo.js +84 -0
  45. package/dist/plan-issue-triage.d.ts +3 -0
  46. package/dist/plan-issue-triage.js +404 -0
  47. package/dist/question-gate/ledger.d.ts +5 -0
  48. package/dist/question-gate/ledger.js +115 -0
  49. package/dist/question-gate/rules.d.ts +40 -0
  50. package/dist/question-gate/rules.js +483 -0
  51. package/dist/recap/board.d.ts +5 -0
  52. package/dist/recap/board.js +384 -0
  53. package/dist/recap/git-and-github.d.ts +11 -0
  54. package/dist/recap/git-and-github.js +620 -0
  55. package/dist/recap/report-and-hud.d.ts +2 -0
  56. package/dist/recap/report-and-hud.js +294 -0
  57. package/dist/recap/time-and-refs.d.ts +27 -0
  58. package/dist/recap/time-and-refs.js +148 -0
  59. package/dist/recap.d.ts +2 -0
  60. package/dist/recap.js +217 -0
  61. package/dist/render-workflow.d.ts +2 -0
  62. package/dist/render-workflow.js +142 -0
  63. package/dist/resolve-containers.d.ts +2 -0
  64. package/dist/resolve-containers.js +96 -0
  65. package/dist/review-loop.d.ts +7 -0
  66. package/dist/review-loop.js +622 -0
  67. package/dist/save-counts.d.ts +2 -0
  68. package/dist/save-counts.js +191 -0
  69. package/dist/summarize-logs.d.ts +2 -0
  70. package/dist/summarize-logs.js +41 -0
  71. package/dist/sweep-github.d.ts +10 -0
  72. package/dist/sweep-github.js +453 -0
  73. package/dist/sweep-issues.d.ts +56 -0
  74. package/dist/sweep-issues.js +650 -0
  75. package/dist/sweep.d.ts +2 -0
  76. package/dist/sweep.js +301 -0
  77. package/dist/triage-question.d.ts +2 -0
  78. package/dist/triage-question.js +189 -0
  79. package/dist/validate-skills.d.ts +2 -0
  80. package/dist/validate-skills.js +48 -0
  81. package/dist/watch-live.d.ts +7 -0
  82. package/dist/watch-live.js +83 -0
  83. package/dist/watcher/config.d.ts +11 -0
  84. package/dist/watcher/config.js +265 -0
  85. package/dist/watcher/live-classifier.d.ts +52 -0
  86. package/dist/watcher/live-classifier.js +510 -0
  87. package/dist/watcher/safe-fs.d.ts +9 -0
  88. package/dist/watcher/safe-fs.js +159 -0
  89. package/dist/watcher/stream.d.ts +27 -0
  90. package/dist/watcher/stream.js +340 -0
  91. package/dist/watcher/summarizer.d.ts +19 -0
  92. package/dist/watcher/summarizer.js +121 -0
  93. package/dist/wave3/process.d.ts +14 -0
  94. package/dist/wave3/process.js +84 -0
  95. package/dist/wave4/process.d.ts +14 -0
  96. package/dist/wave4/process.js +128 -0
  97. package/dist/workflow/render.d.ts +13 -0
  98. package/dist/workflow/render.js +31 -0
  99. package/dist/workflow/schema.d.ts +25 -0
  100. package/dist/workflow/schema.js +99 -0
  101. package/dist/workflow-auditor/audit.d.ts +27 -0
  102. package/dist/workflow-auditor/audit.js +583 -0
  103. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  104. package/dist/workflow-auditor/ledger-io.js +99 -0
  105. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  106. package/dist/workflow-auditor/skills-validator.js +533 -0
  107. package/dist/worktree-guard/evaluation.d.ts +19 -0
  108. package/dist/worktree-guard/evaluation.js +84 -0
  109. package/dist/worktree-guard/git.d.ts +3 -0
  110. package/dist/worktree-guard/git.js +61 -0
  111. package/package.json +32 -33
  112. package/src/bbc.ts +0 -39
  113. package/src/bigo/complexity.ts +0 -138
  114. package/src/bigo/functions.ts +0 -183
  115. package/src/bigo/keywords.ts +0 -41
  116. package/src/bigo/lexical.ts +0 -68
  117. package/src/bigo/source-files.ts +0 -80
  118. package/src/change-lane/classification.ts +0 -128
  119. package/src/change-lane/git.ts +0 -110
  120. package/src/classify-change-lane.ts +0 -140
  121. package/src/diff-scope/git-diff.ts +0 -161
  122. package/src/extract-diff-scope.ts +0 -130
  123. package/src/measure-bigo.ts +0 -86
  124. package/src/render-workflow.ts +0 -144
  125. package/src/workflow/render.ts +0 -40
  126. package/src/workflow/schema.ts +0 -141
@@ -0,0 +1,510 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Windowed live log classifier, Sleuth allowlisted redactor, and JSON/plain matchers.
4
+ * Rules: Zero external dependencies; reconstruct Sleuth excerpts only from fixed allowlisted strings.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [LiveClassifier, SleuthRedactor, WindowedCapture]
7
+ * GOAL: Classify 4x15s live log windows and emit sanitized Sleuth evidence within fixed budgets.
8
+ */
9
+ import { strictJsonParse } from "./config.js";
10
+ export const WINDOW_SECONDS = 15;
11
+ export const WINDOWS = 4;
12
+ export const BYTE_LIMIT = 32_768;
13
+ export const PATTERNS = [
14
+ ['TypeError', /\bTypeError\b/i],
15
+ ['UnhandledPromiseRejection', /\bUnhandledPromiseRejection(?:Warning)?\b/i],
16
+ ['ECONNREFUSED', /\bECONNREFUSED\b/i],
17
+ ['ETIMEDOUT', /\bETIMEDOUT\b/i],
18
+ ['ECONNRESET', /\bECONNRESET\b/i],
19
+ ['EPIPE', /\bEPIPE\b/i],
20
+ ['ENOTFOUND', /\bENOTFOUND\b|\bEAI_AGAIN\b|\bgetaddrinfo\b/i],
21
+ ['HTTP_5xx', /\bHTTP(?:\/\d+(?:\.\d+)?)?\s+5\d{2}\b/i],
22
+ ['OutOfMemory', /\b(?:JavaScript )?[Hh]eap [Oo]ut [Oo]f [Mm]emory\b|\bOutOfMemory(?:Error)?\b/i],
23
+ ];
24
+ const JSON_NAMES = new Map(PATTERNS.map(([name], index) => [name.toLowerCase(), index]));
25
+ JSON_NAMES.set('unhandledpromiserejectionwarning', 1);
26
+ export const LEVELS = {
27
+ error: 'error',
28
+ fatal: 'error',
29
+ panic: 'error',
30
+ warn: 'warn',
31
+ warning: 'warn',
32
+ info: 'info',
33
+ debug: 'debug',
34
+ trace: 'debug',
35
+ };
36
+ const LEVEL_NAMES = Object.keys(LEVELS).join('|');
37
+ export const PLAIN_LEVEL_START_RE = new RegExp(`^(?:${LEVEL_NAMES})(?=$|[\\s:\\]])|\\[(?:${LEVEL_NAMES})\\]`, 'i');
38
+ export const PLAIN_LEVEL_RE = new RegExp(`^(${LEVEL_NAMES})(?=$|[\\s:\\]])|\\[(${LEVEL_NAMES})\\]`, 'i');
39
+ const TIMESTAMP_RE = /^(?:\[\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?\]|\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?|\d{1,2}:\d{2}:\d{2}(?:[.,]\d+)?|\d{4}\/\d{2}\/\d{2}[ T]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?)\s+/;
40
+ const NUMERIC_LEVELS = [
41
+ [60, 'error'],
42
+ [50, 'error'],
43
+ [40, 'warn'],
44
+ [30, 'info'],
45
+ [20, 'debug'],
46
+ [10, 'debug'],
47
+ ];
48
+ const JSON_LEVEL_FIELDS = ['level', 'severity', 'severityText', 'severity_text', 'lvl', 'logLevel'];
49
+ const JSON_ERROR_FIELDS = ['error', 'err', 'exception'];
50
+ const PYTHON_FILE_RE = /^File "[^"\n]+", line \d+\b/;
51
+ const FRAME_RE = /^(?:at\s+\S|Traceback \(most recent call last\):|Caused by:|\.\.\. \d+ more\b)/;
52
+ const CONTROL_RE = /^(?:}\s*)?(?:try|catch)\s*(?:\(|\{|$)/;
53
+ export const EXCEPTIONS = {
54
+ TypeError: 'TypeError',
55
+ ValueError: 'ValueError',
56
+ TimeoutError: 'TimeoutError',
57
+ ConnectionError: 'ConnectionError',
58
+ ReferenceError: 'ReferenceError',
59
+ RangeError: 'RangeError',
60
+ UnhandledPromiseRejection: 'UnhandledPromiseRejection',
61
+ UnhandledPromiseRejectionWarning: 'UnhandledPromiseRejection',
62
+ };
63
+ export const CODES = {
64
+ ECONNREFUSED: 'ECONNREFUSED',
65
+ ETIMEDOUT: 'ETIMEDOUT',
66
+ ECONNRESET: 'ECONNRESET',
67
+ EPIPE: 'EPIPE',
68
+ };
69
+ const WORDS = new Set([
70
+ 'connection', 'refused', 'timeout', 'timed', 'out', 'reset', 'upstream', 'unavailable',
71
+ ...Object.keys(CODES),
72
+ ]);
73
+ const REDACTED = '[redacted]';
74
+ const ID_FIELDS = {
75
+ trace: ['traceId', 'trace_id'],
76
+ request: ['requestId', 'request_id'],
77
+ correlation: ['correlationId', 'correlation_id'],
78
+ };
79
+ const SLEUTH_FRAMES = [
80
+ ['python', /^File "[^"\r\n]+", line ([0-9]{1,6})(?:, in [^\r\n]+)?$/],
81
+ ['node', /^at [^\s()]+ \([^()\s]+:([0-9]{1,6}):[0-9]{1,6}\)$/],
82
+ ['java', /^at [A-Za-z0-9_.$]+\([A-Za-z0-9_.$]+\.java:([0-9]{1,6})\)$/],
83
+ ];
84
+ const PLAIN_DIAGNOSTIC_RE = /^(?:(Caused by:) )?([A-Za-z]+)(?:: *(.*))?$/;
85
+ const EVENT_LIMIT = 24;
86
+ const ID_LIMIT = 16;
87
+ const FRAME_LIMIT = 3;
88
+ const EXCERPT_LIMIT = 4;
89
+ const WORD_LIMIT = 12;
90
+ export function stripHeaders(input, limit = 3) {
91
+ let text = input;
92
+ for (let i = 0; i < limit; i++) {
93
+ const stripped = text.replace(TIMESTAMP_RE, '');
94
+ if (stripped === text)
95
+ break;
96
+ text = stripped;
97
+ }
98
+ return text;
99
+ }
100
+ export function jsonLevel(record) {
101
+ for (const field of JSON_LEVEL_FIELDS) {
102
+ let value = record[field];
103
+ if (typeof value === 'string') {
104
+ const name = LEVELS[value.toLowerCase()];
105
+ if (name !== undefined)
106
+ return name;
107
+ if (/^\d+$/.test(value))
108
+ value = Number.parseInt(value, 10);
109
+ }
110
+ if (typeof value === 'number' && Number.isInteger(value)) {
111
+ for (const [threshold, name] of NUMERIC_LEVELS) {
112
+ if (value >= threshold)
113
+ return name;
114
+ }
115
+ }
116
+ }
117
+ return null;
118
+ }
119
+ export function jsonHit(record) {
120
+ for (const field of JSON_ERROR_FIELDS) {
121
+ const value = record[field];
122
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
123
+ const nested = value;
124
+ for (const key of ['name', 'code', 'type']) {
125
+ const candidate = nested[key];
126
+ if (typeof candidate === 'string') {
127
+ const hit = JSON_NAMES.get(candidate.toLowerCase());
128
+ if (hit !== undefined)
129
+ return hit;
130
+ }
131
+ }
132
+ }
133
+ else if (typeof value === 'string') {
134
+ const hit = JSON_NAMES.get(value.toLowerCase());
135
+ if (hit !== undefined)
136
+ return hit;
137
+ }
138
+ }
139
+ return null;
140
+ }
141
+ function objectOrEmpty(value) {
142
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
143
+ ? value
144
+ : {};
145
+ }
146
+ function eligibleStackLines(stack) {
147
+ let afterFile = false;
148
+ const out = [];
149
+ for (const raw of stack.split('\n')) {
150
+ if (afterFile && raw.startsWith(' '))
151
+ continue;
152
+ const text = raw.trim();
153
+ afterFile = PYTHON_FILE_RE.test(text);
154
+ out.push(text);
155
+ }
156
+ return out;
157
+ }
158
+ function frameLocation(text) {
159
+ for (const [kind, pattern] of SLEUTH_FRAMES) {
160
+ const match = pattern.exec(text);
161
+ if (match !== null)
162
+ return { kind, line: Number.parseInt(match[1], 10) };
163
+ }
164
+ return null;
165
+ }
166
+ function redactedExcerpt(message) {
167
+ const tokens = typeof message === 'string' ? message.trim().split(/\s+/).filter((t) => t !== '') : [];
168
+ const fragment = [];
169
+ for (const token of tokens.slice(0, WORD_LIMIT)) {
170
+ const word = WORDS.has(token) ? token : REDACTED;
171
+ if (word !== REDACTED || fragment.length === 0 || fragment.at(-1) !== REDACTED) {
172
+ fragment.push(word);
173
+ }
174
+ }
175
+ const truncated = tokens.length > WORD_LIMIT;
176
+ if (!fragment.some((w) => w !== REDACTED))
177
+ return { excerpt: null, truncated: false };
178
+ if (truncated && fragment.at(-1) !== REDACTED)
179
+ fragment.push(REDACTED);
180
+ return { excerpt: fragment.join(' '), truncated };
181
+ }
182
+ export class Sleuth {
183
+ window = 1;
184
+ rows = [];
185
+ labels = new Map();
186
+ excerpts = 0;
187
+ limits = {
188
+ records: 0,
189
+ unselected_records: 0,
190
+ invalid_records: 0,
191
+ event_drops: 0,
192
+ id_drops: 0,
193
+ frame_drops: 0,
194
+ excerpt_drops: 0,
195
+ excerpt_truncations: 0,
196
+ dropped_bytes: 0,
197
+ };
198
+ label(kind, value) {
199
+ const key = `${kind}\0${value}`;
200
+ const existing = this.labels.get(key);
201
+ if (existing !== undefined)
202
+ return existing;
203
+ if (this.labels.size === ID_LIMIT) {
204
+ this.limits.id_drops += 1;
205
+ return null;
206
+ }
207
+ const created = `id${this.labels.size + 1}`;
208
+ this.labels.set(key, created);
209
+ return created;
210
+ }
211
+ select(raw, sourceLine) {
212
+ this.limits.records += 1;
213
+ if (sourceLine) {
214
+ this.limits.unselected_records += 1;
215
+ return;
216
+ }
217
+ let body = '';
218
+ let plain = '';
219
+ let isObject = false;
220
+ let record = {};
221
+ try {
222
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(raw).trim();
223
+ body = stripHeaders(decoded);
224
+ const levelPrefix = PLAIN_LEVEL_START_RE.exec(body);
225
+ plain = levelPrefix !== null ? body.slice(levelPrefix[0].length).trim() : body;
226
+ const brace = body.indexOf('{');
227
+ isObject = brace >= 0 && body.trimEnd().endsWith('}');
228
+ if (isObject) {
229
+ const parsed = strictJsonParse(body.slice(brace));
230
+ record = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
231
+ ? parsed
232
+ : {};
233
+ }
234
+ }
235
+ catch {
236
+ this.limits.invalid_records += 1;
237
+ return;
238
+ }
239
+ const candidates = [];
240
+ for (const [kind, keys] of Object.entries(ID_FIELDS)) {
241
+ const values = keys.filter((key) => Object.hasOwn(record, key)).map((key) => record[key]);
242
+ if (values.length === 0)
243
+ continue;
244
+ const valid = values.every((v) => typeof v === 'string' && v.length > 0 && v.length <= 128) &&
245
+ values.every((v) => v === values[0]);
246
+ if (valid)
247
+ candidates.push([kind, values[0]]);
248
+ else
249
+ this.limits.id_drops += 1;
250
+ }
251
+ const error = objectOrEmpty(record.error);
252
+ const cause = objectOrEmpty(error.cause);
253
+ const fields = {};
254
+ for (const [key, value, table] of [
255
+ ['exception', error.name, EXCEPTIONS],
256
+ ['cause', cause.name, EXCEPTIONS],
257
+ ['code', error.code, CODES],
258
+ ['cause_code', cause.code, CODES],
259
+ ]) {
260
+ if (typeof value === 'string' && Object.hasOwn(table, value)) {
261
+ fields[key] = table[value];
262
+ }
263
+ }
264
+ if (record.status === 503)
265
+ fields.status = 503;
266
+ const stack = error.stack;
267
+ let frameLines = typeof stack === 'string' ? eligibleStackLines(stack) : [];
268
+ let message = record.message;
269
+ if (!isObject) {
270
+ frameLines = [plain];
271
+ const match = PLAIN_DIAGNOSTIC_RE.exec(plain);
272
+ if (match !== null) {
273
+ const [, causePrefix, name, detail] = match;
274
+ if (name !== undefined && Object.hasOwn(EXCEPTIONS, name)) {
275
+ fields[causePrefix ? 'cause' : 'exception'] = EXCEPTIONS[name];
276
+ message = detail;
277
+ }
278
+ else if (name !== undefined && Object.hasOwn(CODES, name) && !causePrefix) {
279
+ fields.code = CODES[name];
280
+ message = detail;
281
+ }
282
+ }
283
+ }
284
+ const frames = frameLines.map(frameLocation).filter((f) => f !== null);
285
+ const { excerpt, truncated } = redactedExcerpt(message);
286
+ if (candidates.length === 0 && Object.keys(fields).length === 0 && frames.length === 0 && excerpt === null) {
287
+ this.limits.unselected_records += 1;
288
+ return;
289
+ }
290
+ if (this.rows.length === EVENT_LIMIT) {
291
+ this.limits.event_drops += 1;
292
+ return;
293
+ }
294
+ const row = { window: this.window, seq: this.limits.records };
295
+ let level = isObject ? jsonLevel(record) : null;
296
+ if (level === null) {
297
+ const match = PLAIN_LEVEL_RE.exec(body);
298
+ if (match !== null)
299
+ level = LEVELS[(match[1] ?? match[2] ?? '').toLowerCase()] ?? null;
300
+ }
301
+ if (frames.length > 0) {
302
+ fields.frames = frames.slice(0, FRAME_LIMIT);
303
+ this.limits.frame_drops += Math.max(0, frames.length - FRAME_LIMIT);
304
+ }
305
+ if (excerpt !== null) {
306
+ if (this.excerpts < EXCERPT_LIMIT) {
307
+ fields.excerpt = excerpt;
308
+ this.excerpts += 1;
309
+ this.limits.excerpt_truncations += truncated ? 1 : 0;
310
+ }
311
+ else {
312
+ this.limits.excerpt_drops += 1;
313
+ }
314
+ }
315
+ if (Object.keys(fields).length === 0 && level !== 'error' && level !== 'warn') {
316
+ this.limits.unselected_records += 1;
317
+ return;
318
+ }
319
+ const ids = {};
320
+ for (const [kind, value] of candidates) {
321
+ const label = this.label(kind, value);
322
+ if (label !== null)
323
+ ids[kind] = label;
324
+ }
325
+ if (Object.keys(ids).length > 0)
326
+ row.ids = ids;
327
+ if (level !== null)
328
+ row.level = level;
329
+ Object.assign(row, fields);
330
+ this.rows.push(row);
331
+ }
332
+ finish() {
333
+ return {
334
+ status: 'authorized_sleuth',
335
+ events: this.rows,
336
+ coverage: { ...this.limits, coverage: 'incomplete' },
337
+ };
338
+ }
339
+ }
340
+ export class WindowCollector {
341
+ sleuth;
342
+ continuing;
343
+ pythonFrame;
344
+ bytes = 0;
345
+ dropped = 0;
346
+ partialChunks = [];
347
+ partialLen = 0;
348
+ counts = { error: 0, warn: 0, info: 0, debug: 0, unclassified: 0, frames: 0 };
349
+ hits = new Array(PATTERNS.length).fill(0);
350
+ constructor(continuing = false, pythonFrame = false, sleuth = null) {
351
+ this.continuing = continuing;
352
+ this.pythonFrame = pythonFrame;
353
+ this.sleuth = sleuth;
354
+ }
355
+ classify(lineBytes) {
356
+ if (this.sleuth !== null) {
357
+ const raw = new TextDecoder('utf-8', { fatal: false }).decode(lineBytes);
358
+ const sourceLine = this.pythonFrame && raw.startsWith(' ');
359
+ this.sleuth.select(lineBytes, sourceLine);
360
+ }
361
+ const raw = new TextDecoder('utf-8', { fatal: false }).decode(lineBytes);
362
+ const sourceLine = this.pythonFrame && raw.startsWith(' ');
363
+ const text = raw.trim();
364
+ if (sourceLine) {
365
+ this.counts.frames += 1;
366
+ return;
367
+ }
368
+ this.pythonFrame = PYTHON_FILE_RE.test(text);
369
+ if (this.pythonFrame || FRAME_RE.test(text)) {
370
+ this.counts.frames += 1;
371
+ return;
372
+ }
373
+ if (CONTROL_RE.test(text)) {
374
+ this.counts.unclassified += 1;
375
+ return;
376
+ }
377
+ const body = stripHeaders(text);
378
+ let record = null;
379
+ const brace = body.indexOf('{');
380
+ if (brace >= 0 && body.trimEnd().endsWith('}')) {
381
+ try {
382
+ const parsed = JSON.parse(body.slice(brace));
383
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
384
+ record = parsed;
385
+ }
386
+ }
387
+ catch {
388
+ record = null;
389
+ }
390
+ }
391
+ let level = record !== null ? jsonLevel(record) : null;
392
+ let hit = record !== null ? jsonHit(record) : null;
393
+ if (level === null) {
394
+ const match = PLAIN_LEVEL_RE.exec(body);
395
+ if (match !== null)
396
+ level = LEVELS[(match[1] ?? match[2] ?? '').toLowerCase()] ?? null;
397
+ }
398
+ if (hit === null) {
399
+ const idx = PATTERNS.findIndex(([, regex]) => regex.test(body));
400
+ hit = idx === -1 ? null : idx;
401
+ }
402
+ const bucket = level ?? (hit !== null ? 'error' : 'unclassified');
403
+ this.counts[bucket] = (this.counts[bucket] ?? 0) + 1;
404
+ if (hit !== null)
405
+ this.hits[hit] = (this.hits[hit] ?? 0) + 1;
406
+ }
407
+ discardPartial() {
408
+ if (this.partialLen === 0)
409
+ return;
410
+ this.dropped += this.partialLen;
411
+ this.partialChunks = [];
412
+ this.partialLen = 0;
413
+ this.continuing = true;
414
+ this.pythonFrame = false;
415
+ }
416
+ feed(data) {
417
+ const take = Math.min(data.length, BYTE_LIMIT - this.bytes);
418
+ this.bytes += take;
419
+ let start = 0;
420
+ while (start < take) {
421
+ const lf = data.subarray(start, take).indexOf(0x0a);
422
+ const absLf = lf >= 0 ? start + lf : -1;
423
+ const end = absLf >= 0 ? absLf + 1 : take;
424
+ if (this.continuing) {
425
+ this.dropped += end - start;
426
+ }
427
+ else {
428
+ const slice = data.subarray(start, absLf >= 0 ? absLf : end);
429
+ if (slice.length > 0) {
430
+ this.partialChunks.push(slice);
431
+ this.partialLen += slice.length;
432
+ }
433
+ if (absLf >= 0) {
434
+ const lineBytes = this.partialChunks.length === 1
435
+ ? this.partialChunks[0]
436
+ : Buffer.concat(this.partialChunks);
437
+ this.classify(lineBytes);
438
+ this.partialChunks = [];
439
+ this.partialLen = 0;
440
+ }
441
+ }
442
+ if (absLf >= 0)
443
+ this.continuing = false;
444
+ start = end;
445
+ }
446
+ if (take < data.length) {
447
+ this.discardPartial();
448
+ this.dropped += data.length - take;
449
+ this.continuing = data.at(-1) !== 0x0a;
450
+ this.pythonFrame = false;
451
+ }
452
+ }
453
+ finish(idx) {
454
+ this.discardPartial();
455
+ if (this.sleuth !== null) {
456
+ this.sleuth.limits.dropped_bytes += this.dropped;
457
+ this.sleuth.window = idx + 1;
458
+ }
459
+ const counts = Object.entries(this.counts).map(([name, count]) => `${name}=${count}`).join(' ');
460
+ const ranked = PATTERNS.map(([name], i) => ({ name, count: this.hits[i] ?? 0 }))
461
+ .sort((a, b) => b.count - a.count);
462
+ const top = ranked.map((item) => `${item.name}:${item.count}`).join(',');
463
+ return `window=${idx} ${counts} dropped_bytes=${this.dropped} top=${top}`;
464
+ }
465
+ }
466
+ export function liveOutput(rows, evidence) {
467
+ const out = ['live status=deadline', ...rows];
468
+ if (evidence !== null) {
469
+ for (const row of [...evidence.events, evidence.coverage]) {
470
+ out.push(`sleuth ${JSON.stringify(row)}`);
471
+ }
472
+ }
473
+ return out;
474
+ }
475
+ export async function observeWithStream(stream, sleuthRequested, monotonicSec) {
476
+ const started = monotonicSec();
477
+ const sleuth = sleuthRequested ? new Sleuth() : null;
478
+ const rows = [];
479
+ let window = new WindowCollector(false, false, sleuth);
480
+ let pending = null;
481
+ let stopped = false;
482
+ try {
483
+ for (let idx = 1; idx <= WINDOWS; idx++) {
484
+ const deadline = started + idx * WINDOW_SECONDS;
485
+ while (monotonicSec() < deadline) {
486
+ if (pending !== null) {
487
+ window.feed(pending);
488
+ pending = null;
489
+ }
490
+ const data = await stream.readUntil(deadline);
491
+ if (data !== null && data.length === 0)
492
+ return null;
493
+ if (data === null)
494
+ break;
495
+ pending = data;
496
+ }
497
+ if (idx === WINDOWS && pending !== null) {
498
+ window.dropped += pending.length;
499
+ }
500
+ rows.push(window.finish(idx));
501
+ window = new WindowCollector(window.continuing, window.pythonFrame, sleuth);
502
+ }
503
+ }
504
+ finally {
505
+ stopped = await stream.stop();
506
+ }
507
+ if (!stopped)
508
+ return null;
509
+ return { rows, evidence: sleuth !== null ? sleuth.finish() : null };
510
+ }
@@ -0,0 +1,9 @@
1
+ export declare function resolveWorktreeRoot(): string;
2
+ export declare function checkBaseDir(root: string): void;
3
+ export declare function requireRootIgnoreRule(root: string): void;
4
+ export declare function requireIgnoredPaths(root: string, paths: readonly string[]): void;
5
+ export declare function saveCountsReport(root: string, session: string, report: Record<string, unknown>): void;
6
+ export declare function saveScanReport(alias: string, container: string, selector: {
7
+ kind: 'since' | 'tail';
8
+ value: number;
9
+ }, counts: Record<string, number>, hits: readonly number[], patternNames: readonly string[], events: Record<string, number>, rows: ReadonlyArray<Record<string, unknown>>, bytesRead: number, project: string | null, filteredOut: number): string | null;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * LAYER: Infrastructure
3
+ * Contains: Worktree root resolution, /tmp_logs/ .gitignore validation, and safe report writes.
4
+ * Rules: Refuse symlinks/reparse points, non-regular .gitignore, or unignored tmp_logs targets.
5
+ * BigO: O(n) score:3
6
+ * keywords: [SafeReportFs, GitIgnoreGuard, ReparsePointCheck]
7
+ * GOAL: Persist sanitized error-scan and save-counts reports only to ignored tmp_logs/.
8
+ */
9
+ import { spawnSync } from 'node:child_process';
10
+ import { constants, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync, closeSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ function cleanGitEnv() {
13
+ const env = {};
14
+ for (const [key, value] of Object.entries(process.env)) {
15
+ if (!key.toUpperCase().startsWith('GIT_'))
16
+ env[key] = value;
17
+ }
18
+ return env;
19
+ }
20
+ function runGit(args, cwd) {
21
+ return spawnSync('git', [...args], {
22
+ cwd,
23
+ env: cleanGitEnv(),
24
+ stdio: ['ignore', 'pipe', 'ignore'],
25
+ timeout: 5_000,
26
+ encoding: null,
27
+ });
28
+ }
29
+ function isSafeDir(path) {
30
+ try {
31
+ const info = lstatSync(path);
32
+ if (info.isSymbolicLink() || !info.isDirectory())
33
+ return false;
34
+ if (process.platform !== 'win32') {
35
+ const uid = process.getuid?.();
36
+ if (uid !== undefined && info.uid !== uid)
37
+ return false;
38
+ if ((info.mode & 0o022) !== 0)
39
+ return false;
40
+ }
41
+ return true;
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
47
+ function isSafeIgnoreFile(path) {
48
+ try {
49
+ const info = lstatSync(path);
50
+ return !info.isSymbolicLink() && info.isFile() && info.nlink === 1;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ export function resolveWorktreeRoot() {
57
+ const result = runGit(['rev-parse', '--show-toplevel']);
58
+ if (result.status !== 0 || result.stdout.at(-1) !== 0x0a) {
59
+ throw new Error('no worktree');
60
+ }
61
+ const raw = result.stdout.subarray(0, -1).toString('utf8');
62
+ return realpathSync(raw);
63
+ }
64
+ export function checkBaseDir(root) {
65
+ const tmpBase = join(root, 'tmp_logs');
66
+ try {
67
+ lstatSync(tmpBase);
68
+ }
69
+ catch {
70
+ return;
71
+ }
72
+ if (!isSafeDir(tmpBase))
73
+ throw new Error('unsafe destination');
74
+ }
75
+ export function requireRootIgnoreRule(root) {
76
+ const ignorePath = join(root, '.gitignore');
77
+ if (!isSafeIgnoreFile(ignorePath))
78
+ throw new Error('unsafe root ignore file');
79
+ const lines = readFileSync(ignorePath, 'utf8').split(/\r?\n/);
80
+ if (!lines.includes('/tmp_logs/'))
81
+ throw new Error('missing exact root ignore rule');
82
+ }
83
+ export function requireIgnoredPaths(root, paths) {
84
+ requireRootIgnoreRule(root);
85
+ for (const rel of paths) {
86
+ if (runGit(['check-ignore', '-q', '--', rel], root).status !== 0) {
87
+ throw new Error('destination not ignored');
88
+ }
89
+ }
90
+ }
91
+ function writeExclusiveFile(filePath, content) {
92
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);
93
+ const fd = openSync(filePath, flags, 0o600);
94
+ try {
95
+ writeSync(fd, content);
96
+ }
97
+ finally {
98
+ closeSync(fd);
99
+ }
100
+ }
101
+ export function saveCountsReport(root, session, report) {
102
+ const payload = Buffer.from(`${JSON.stringify(report, null, 2)}\n`, 'ascii');
103
+ checkBaseDir(root);
104
+ requireIgnoredPaths(root, ['tmp_logs/', `tmp_logs/${session}/`, `tmp_logs/${session}/report.json`]);
105
+ const base = join(root, 'tmp_logs');
106
+ mkdirSync(base, { recursive: true, mode: 0o700 });
107
+ if (!isSafeDir(base))
108
+ throw new Error('unsafe destination');
109
+ const target = join(base, session);
110
+ mkdirSync(target, { mode: 0o700 });
111
+ if (!isSafeDir(target))
112
+ throw new Error('unsafe destination');
113
+ writeExclusiveFile(join(target, 'report.json'), payload);
114
+ }
115
+ export function saveScanReport(alias, container, selector, counts, hits, patternNames, events, rows, bytesRead, project, filteredOut) {
116
+ if (rows.length === 0 && (counts.error ?? 0) === 0 && (counts.warn ?? 0) === 0)
117
+ return null;
118
+ let root;
119
+ try {
120
+ root = resolveWorktreeRoot();
121
+ checkBaseDir(root);
122
+ requireIgnoredPaths(root, ['tmp_logs/scan']);
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ const target = join(root, 'tmp_logs', 'scan');
128
+ try {
129
+ mkdirSync(target, { recursive: true, mode: 0o700 });
130
+ if (!isSafeDir(target))
131
+ return null;
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ const signatures = {};
137
+ for (let i = 0; i < hits.length; i++) {
138
+ const n = hits[i] ?? 0;
139
+ if (n > 0)
140
+ signatures[patternNames[i]] = n;
141
+ }
142
+ const payload = {
143
+ mode: 'error-scan',
144
+ source: { alias, container },
145
+ selector: { kind: selector.kind, value: selector.value },
146
+ bytes_read: bytesRead,
147
+ counts,
148
+ signatures,
149
+ events,
150
+ rows,
151
+ };
152
+ if (project !== null) {
153
+ payload.project = project;
154
+ payload.filtered_out = filteredOut;
155
+ }
156
+ const name = join(target, `${selector.kind}-${selector.value}-${process.pid}.json`);
157
+ writeExclusiveFile(name, Buffer.from(JSON.stringify(payload, null, 1), 'utf8'));
158
+ return name;
159
+ }