@contextrail/assess 0.0.0-stage → 1.0.0-alpha.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 (73) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +82 -2
  3. package/assets/brand/icon-dark.png +0 -0
  4. package/assets/brand/icon-light.png +0 -0
  5. package/dist/assess.d.ts +109 -0
  6. package/dist/assess.js +1563 -0
  7. package/dist/assessment.d.ts +571 -0
  8. package/dist/assessment.js +404 -0
  9. package/dist/budget.d.ts +24 -0
  10. package/dist/budget.js +52 -0
  11. package/dist/candidate.d.ts +156 -0
  12. package/dist/candidate.js +361 -0
  13. package/dist/change-summary.d.ts +33 -0
  14. package/dist/change-summary.js +26 -0
  15. package/dist/cli.d.ts +2 -0
  16. package/dist/cli.js +406 -0
  17. package/dist/contracts.d.ts +99 -0
  18. package/dist/contracts.js +62 -0
  19. package/dist/diagnostics.d.ts +44 -0
  20. package/dist/diagnostics.js +412 -0
  21. package/dist/evidence.d.ts +73 -0
  22. package/dist/evidence.js +297 -0
  23. package/dist/feedback.d.ts +21 -0
  24. package/dist/feedback.js +154 -0
  25. package/dist/git.d.ts +40 -0
  26. package/dist/git.js +207 -0
  27. package/dist/github.d.ts +90 -0
  28. package/dist/github.js +1342 -0
  29. package/dist/index.d.ts +14 -0
  30. package/dist/index.js +14 -0
  31. package/dist/mcp.d.ts +28 -0
  32. package/dist/mcp.js +173 -0
  33. package/dist/pack.d.ts +160 -0
  34. package/dist/pack.js +377 -0
  35. package/dist/phases.d.ts +65 -0
  36. package/dist/phases.js +63 -0
  37. package/dist/planning.d.ts +64 -0
  38. package/dist/planning.js +135 -0
  39. package/dist/pr-context.d.ts +316 -0
  40. package/dist/pr-context.js +198 -0
  41. package/dist/prepare.d.ts +71 -0
  42. package/dist/prepare.js +335 -0
  43. package/dist/presentation.d.ts +310 -0
  44. package/dist/presentation.js +1076 -0
  45. package/dist/provider-diagnostics.d.ts +93 -0
  46. package/dist/provider-diagnostics.js +233 -0
  47. package/dist/providers.d.ts +45 -0
  48. package/dist/providers.js +291 -0
  49. package/dist/report-contract.d.ts +137 -0
  50. package/dist/report-contract.js +248 -0
  51. package/dist/results.d.ts +90 -0
  52. package/dist/results.js +128 -0
  53. package/dist/resume.d.ts +25 -0
  54. package/dist/resume.js +116 -0
  55. package/dist/source.d.ts +167 -0
  56. package/dist/source.js +675 -0
  57. package/dist/verification.d.ts +386 -0
  58. package/dist/verification.js +168 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +9 -0
  61. package/docs/README.md +24 -0
  62. package/docs/action-reference.md +85 -0
  63. package/docs/architecture.md +158 -0
  64. package/docs/configuration.md +83 -0
  65. package/docs/contributing.md +46 -0
  66. package/docs/getting-started.md +92 -0
  67. package/docs/github-actions.md +141 -0
  68. package/docs/operations.md +211 -0
  69. package/docs/review-results.md +189 -0
  70. package/docs/security.md +68 -0
  71. package/docs/standards.md +62 -0
  72. package/examples/assess-pull-request.yml +109 -0
  73. package/package.json +56 -5
package/dist/source.js ADDED
@@ -0,0 +1,675 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { MAX_PREPARATION_BYTES, passiveGitEnvironment, sensitiveGitPath } from './git.js';
4
+ const sensitiveSourcePath = sensitiveGitPath;
5
+ /** Provisional response/operation defaults, never total-source capacity limits. */
6
+ export const DEFAULT_SOURCE_LIMITS = Object.freeze({
7
+ pageEntries: 100,
8
+ searchMatches: 100,
9
+ searchFiles: 100,
10
+ readLines: 200,
11
+ readBytes: 65_536,
12
+ timeoutMs: 30_000,
13
+ });
14
+ export class SourceAccessError extends Error {
15
+ code;
16
+ constructor(code, message) {
17
+ super(message);
18
+ this.code = code;
19
+ }
20
+ }
21
+ function integer(value, name, minimum = 1) {
22
+ if (!Number.isSafeInteger(value) || value < minimum)
23
+ throw new SourceAccessError('invalid_input', `${name} must be a safe integer >= ${minimum}.`);
24
+ }
25
+ function safePath(path) {
26
+ if (typeof path !== 'string' ||
27
+ !path ||
28
+ path.includes('\0') ||
29
+ path.startsWith('/') ||
30
+ path.split('/').some((p) => !p || p === '.' || p === '..'))
31
+ throw new SourceAccessError('invalid_input', 'path must be an exact repository-relative Git path without dot segments.');
32
+ }
33
+ function kind(mode) {
34
+ return mode === '160000' ? 'submodule' : mode === '120000' ? 'symlink' : 'file';
35
+ }
36
+ function acceptPatchLine(item, line, progress, budget, limits) {
37
+ if (progress.line++ < progress.skip)
38
+ return true;
39
+ const size = Buffer.byteLength(line);
40
+ if (budget.bytes + size > limits.readBytes || budget.lines >= limits.readLines) {
41
+ if (!item.patch && budget.bytes === 0 && size > limits.readBytes) {
42
+ item.status = 'unsupported';
43
+ item.reason = 'diff_line_exceeds_response_limit';
44
+ }
45
+ else
46
+ item.status = 'truncated';
47
+ progress.line--;
48
+ return false;
49
+ }
50
+ budget.bytes += size;
51
+ budget.lines++;
52
+ item.patch += line;
53
+ return true;
54
+ }
55
+ /** One bounded read window; positions use UTF-16 columns while budgets count UTF-8 bytes. */
56
+ class ReadWindow {
57
+ start;
58
+ endLine;
59
+ limits;
60
+ fragments = [];
61
+ line = 1;
62
+ column = 0;
63
+ bytes = 0;
64
+ found = false;
65
+ fragment;
66
+ constructor(start, endLine, limits) {
67
+ this.start = start;
68
+ this.endLine = endLine;
69
+ this.limits = limits;
70
+ }
71
+ accept(char) {
72
+ if (this.line === this.start.line && this.column > this.start.column && !this.found)
73
+ throw new SourceAccessError('invalid_input', 'start.column splits a Unicode character or exceeds the line.');
74
+ if (this.line > this.endLine)
75
+ return 'complete';
76
+ const inWindow = this.line > this.start.line || (this.line === this.start.line && this.column >= this.start.column);
77
+ if (inWindow && !this.append(char))
78
+ return 'truncated';
79
+ this.advance(char);
80
+ return null;
81
+ }
82
+ append(char) {
83
+ this.found = true;
84
+ const bytes = Buffer.byteLength(char);
85
+ if ((!this.fragment && this.fragments.length === this.limits.readLines) ||
86
+ this.bytes + bytes > this.limits.readBytes)
87
+ return false;
88
+ if (!this.fragment) {
89
+ this.fragment = { line: this.line, column: this.column, text: '' };
90
+ this.fragments.push(this.fragment);
91
+ }
92
+ this.fragment.text += char;
93
+ this.bytes += bytes;
94
+ return true;
95
+ }
96
+ advance(char) {
97
+ if (char !== '\n') {
98
+ this.column += char.length;
99
+ return;
100
+ }
101
+ if (this.line === this.start.line && !this.found)
102
+ throw new SourceAccessError('invalid_input', 'start.column exceeds the line.');
103
+ this.line++;
104
+ this.column = 0;
105
+ this.fragment = undefined;
106
+ }
107
+ finish() {
108
+ // Empty file and a position exactly at EOF are valid empty reads; trailing LF adds no source line.
109
+ if (!this.found && !(this.line === this.start.line && this.column === this.start.column))
110
+ throw new SourceAccessError('invalid_input', 'start is beyond the source.');
111
+ }
112
+ }
113
+ /** UTF-16 prefix lengths preserve overlapping literal matches across blob chunks. */
114
+ function literalPrefix(literal) {
115
+ const prefix = new Array(literal.length).fill(0);
116
+ for (let i = 1, j = 0; i < literal.length; i++) {
117
+ while (j && literal[i] !== literal[j])
118
+ j = prefix[j - 1];
119
+ if (literal[i] === literal[j])
120
+ j++;
121
+ prefix[i] = j;
122
+ }
123
+ return prefix;
124
+ }
125
+ /** Passive committed-object access. Does not write state or evaluate guidance. */
126
+ export class FixedSnapshotSource {
127
+ limits;
128
+ artifact;
129
+ constructor(artifact, overrides = {}) {
130
+ // Copy identities: caller mutation cannot move an existing accessor.
131
+ this.artifact = structuredClone(artifact);
132
+ for (const side of ['base', 'head']) {
133
+ for (const id of [artifact[side].commit, artifact[side].tree]) {
134
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(id))
135
+ throw new SourceAccessError('invalid_input', 'Captured revisions must be full Git object IDs.');
136
+ }
137
+ }
138
+ this.limits = Object.freeze({ ...DEFAULT_SOURCE_LIMITS, ...overrides });
139
+ for (const [name, value] of Object.entries(this.limits))
140
+ integer(value, name, name === 'readBytes' ? 4 : 1);
141
+ if (this.limits.timeoutMs > 2_147_483_647)
142
+ throw new SourceAccessError('invalid_input', 'timeoutMs exceeds the Node timer interval.');
143
+ }
144
+ snapshot(side) {
145
+ if (side !== 'base' && side !== 'head')
146
+ throw new SourceAccessError('invalid_input', 'side must be base or head.');
147
+ return { side, commit: this.artifact[side].commit, tree: this.artifact[side].tree };
148
+ }
149
+ async operation(control, body) {
150
+ const controller = new AbortController();
151
+ const deadline = Date.now() + this.limits.timeoutMs;
152
+ let timedOut = false;
153
+ const cancel = () => controller.abort();
154
+ const timer = setTimeout(() => {
155
+ timedOut = true;
156
+ controller.abort();
157
+ }, this.limits.timeoutMs);
158
+ control.signal?.addEventListener('abort', cancel, { once: true });
159
+ const check = () => {
160
+ if (control.signal?.aborted)
161
+ throw new SourceAccessError('cancelled', 'Source operation cancelled by caller; no complete result.');
162
+ if (timedOut || Date.now() >= deadline)
163
+ throw new SourceAccessError('timeout', 'Source operation timed out; no complete result.');
164
+ };
165
+ try {
166
+ check();
167
+ const operation = { signal: controller.signal, check };
168
+ let trees = '';
169
+ for await (const chunk of this.git(['rev-parse', `${this.artifact.base.commit}^{tree}`, `${this.artifact.head.commit}^{tree}`], operation))
170
+ trees += chunk.toString('ascii');
171
+ if (trees.trim() !== `${this.artifact.base.tree}\n${this.artifact.head.tree}`)
172
+ throw new SourceAccessError('unavailable', 'Captured commits and trees do not agree or are unavailable.');
173
+ const result = await body(operation);
174
+ check();
175
+ return result;
176
+ }
177
+ catch (error) {
178
+ check();
179
+ throw error;
180
+ }
181
+ finally {
182
+ clearTimeout(timer);
183
+ control.signal?.removeEventListener('abort', cancel);
184
+ }
185
+ }
186
+ async *git(args, operation) {
187
+ operation.check();
188
+ const child = spawn('git', [
189
+ '--no-pager',
190
+ '--no-lazy-fetch',
191
+ '--no-replace-objects',
192
+ `--attr-source=${this.artifact.head.tree}`,
193
+ '-c',
194
+ 'core.fsmonitor=false',
195
+ '-c',
196
+ 'core.attributesFile=/dev/null',
197
+ '-C',
198
+ this.artifact.repository,
199
+ ...args,
200
+ ], {
201
+ env: passiveGitEnvironment(),
202
+ stdio: ['ignore', 'pipe', 'ignore'],
203
+ });
204
+ const closed = new Promise((resolve, reject) => {
205
+ child.once('error', () => reject(new SourceAccessError('unavailable', 'Git could not start.')));
206
+ child.once('close', resolve);
207
+ });
208
+ // Attach immediately so an early spawn failure cannot become an unhandled rejection.
209
+ void closed.catch(() => undefined);
210
+ const stop = () => child.kill('SIGKILL');
211
+ operation.signal.addEventListener('abort', stop, { once: true });
212
+ try {
213
+ if (operation.signal.aborted)
214
+ stop();
215
+ for await (const chunk of child.stdout) {
216
+ operation.check();
217
+ yield chunk;
218
+ }
219
+ operation.check();
220
+ if ((await closed) !== 0)
221
+ throw new SourceAccessError('unavailable', 'Pinned Git object/repository unavailable, or Git lacks required passive options (Git >=2.45).');
222
+ }
223
+ finally {
224
+ operation.signal.removeEventListener('abort', stop);
225
+ if (child.exitCode === null)
226
+ child.kill('SIGKILL');
227
+ await closed.catch(() => undefined);
228
+ }
229
+ }
230
+ async *records(args, operation) {
231
+ let pending = Buffer.alloc(0);
232
+ for await (const chunk of this.git(args, operation)) {
233
+ pending = Buffer.concat([pending, chunk]);
234
+ let end;
235
+ while ((end = pending.indexOf(0)) >= 0) {
236
+ const record = pending.subarray(0, end);
237
+ pending = pending.subarray(end + 1);
238
+ try {
239
+ yield new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(record);
240
+ }
241
+ catch {
242
+ throw new SourceAccessError('unavailable', 'Git path is not representable as UTF-8; no complete listing.');
243
+ }
244
+ }
245
+ }
246
+ if (pending.length)
247
+ throw new SourceAccessError('unavailable', 'Incomplete Git record.');
248
+ }
249
+ async *entries(snapshot, operation) {
250
+ for await (const record of this.records(['ls-tree', '-r', '-z', '--full-tree', snapshot.tree], operation)) {
251
+ const tab = record.indexOf('\t');
252
+ const [mode, , object] = record.slice(0, tab).split(' ');
253
+ yield { ...snapshot, mode: mode, object: object, path: record.slice(tab + 1), kind: kind(mode) };
254
+ }
255
+ }
256
+ async list(request, control = {}) {
257
+ const snapshot = this.snapshot(request.side);
258
+ const offset = request.offset ?? 0;
259
+ integer(offset, 'offset', 0);
260
+ return this.operation(control, async (operation) => {
261
+ const items = [];
262
+ let index = 0;
263
+ for await (const entry of this.entries(snapshot, operation)) {
264
+ if (index++ < offset)
265
+ continue;
266
+ if (items.length === this.limits.pageEntries)
267
+ return {
268
+ snapshot,
269
+ status: 'truncated',
270
+ items,
271
+ next: { side: snapshot.side, offset: offset + items.length },
272
+ };
273
+ items.push(entry);
274
+ }
275
+ if (offset > index)
276
+ throw new SourceAccessError('invalid_cursor', 'offset exceeds snapshot path count.');
277
+ return { snapshot, status: 'complete', items, next: null };
278
+ });
279
+ }
280
+ async changes(request = {}, control = {}) {
281
+ const offset = request.offset ?? 0;
282
+ integer(offset, 'offset', 0);
283
+ const detectRenames = request.detectRenames ?? true;
284
+ if (typeof detectRenames !== 'boolean')
285
+ throw new SourceAccessError('invalid_input', 'detectRenames must be boolean.');
286
+ const base = this.snapshot('base'), head = this.snapshot('head');
287
+ return this.operation(control, async (operation) => {
288
+ const items = [];
289
+ const records = this.records([
290
+ '-c',
291
+ 'diff.renameLimit=0',
292
+ 'diff-tree',
293
+ '--no-commit-id',
294
+ '-r',
295
+ '--raw',
296
+ '-z',
297
+ '--no-abbrev',
298
+ '-O/dev/null',
299
+ '--no-relative',
300
+ '--diff-algorithm=myers',
301
+ '--no-ext-diff',
302
+ '--no-textconv',
303
+ '--ignore-submodules=none',
304
+ detectRenames ? '--find-renames=50%' : '--no-renames',
305
+ base.tree,
306
+ head.tree,
307
+ '--',
308
+ ], operation);
309
+ let header, firstPath, index = 0;
310
+ for await (const record of records) {
311
+ if (!header) {
312
+ header = record;
313
+ continue;
314
+ }
315
+ const [baseMode, headMode, baseObject, headObject, status] = header.slice(1).split(' ');
316
+ if (status.startsWith('R') && firstPath === undefined) {
317
+ firstPath = record;
318
+ continue;
319
+ }
320
+ if (index++ >= offset) {
321
+ if (items.length === this.limits.pageEntries)
322
+ return {
323
+ base,
324
+ head,
325
+ renameDetection: detectRenames ? 'heuristic' : 'disabled',
326
+ status: 'truncated',
327
+ items,
328
+ next: { offset: offset + items.length, detectRenames },
329
+ };
330
+ const source = (snapshot, mode, object, path) => mode === '000000' ? null : { ...snapshot, mode, object, path, kind: kind(mode) };
331
+ items.push({
332
+ offset: index - 1,
333
+ kind: { A: 'addition', D: 'deletion', M: 'modification', R: 'rename', T: 'type_change' }[status[0]],
334
+ base: source(base, baseMode, baseObject, firstPath ?? record),
335
+ head: source(head, headMode, headObject, record),
336
+ similarity: status.startsWith('R') ? Number(status.slice(1)) : null,
337
+ });
338
+ }
339
+ header = undefined;
340
+ firstPath = undefined;
341
+ }
342
+ if (header || offset > index)
343
+ throw new SourceAccessError('invalid_cursor', 'Invalid diff record or offset beyond change count.');
344
+ return {
345
+ base,
346
+ head,
347
+ renameDetection: detectRenames ? 'heuristic' : 'disabled',
348
+ status: 'complete',
349
+ items,
350
+ next: null,
351
+ };
352
+ });
353
+ }
354
+ /** Complete permitted file inventory without reading patches; metadata is navigation, not assessment. */
355
+ async changeInventory(control = {}) {
356
+ const inventory = {
357
+ base: this.snapshot('base'),
358
+ head: this.snapshot('head'),
359
+ status: 'truncated',
360
+ items: [],
361
+ next: { offset: 0, detectRenames: true },
362
+ renameDetection: 'heuristic',
363
+ excludedPaths: [],
364
+ };
365
+ // Reserve bounded room for the final reason/cursor and serialization separators.
366
+ let bytes = Buffer.byteLength(JSON.stringify(inventory)) + 512;
367
+ try {
368
+ return await this.operation(control, async (operation) => {
369
+ while (inventory.next) {
370
+ const cursor = inventory.next;
371
+ const page = await this.changes(cursor, { signal: operation.signal });
372
+ for (const item of page.items) {
373
+ const paths = [item.base?.path, item.head?.path].filter((path) => !!path);
374
+ const excluded = paths.some(sensitiveGitPath);
375
+ const size = Buffer.byteLength(JSON.stringify(excluded ? paths : item)) + 2;
376
+ if (bytes + size > MAX_PREPARATION_BYTES) {
377
+ inventory.reason = 'inventory_output_limit';
378
+ inventory.next = { offset: item.offset, detectRenames: true };
379
+ return inventory;
380
+ }
381
+ bytes += size;
382
+ if (excluded)
383
+ inventory.excludedPaths.push(...paths);
384
+ else
385
+ inventory.items.push(item);
386
+ inventory.next = { offset: item.offset + 1, detectRenames: true };
387
+ }
388
+ if (page.next && page.next.offset <= cursor.offset)
389
+ throw new SourceAccessError('invalid_cursor', 'Change inventory did not advance.');
390
+ inventory.next = page.next;
391
+ }
392
+ inventory.excludedPaths = [...new Set(inventory.excludedPaths)];
393
+ inventory.status = 'complete';
394
+ return inventory;
395
+ });
396
+ }
397
+ catch (error) {
398
+ inventory.status = 'truncated';
399
+ inventory.next ??= { offset: 0, detectRenames: true };
400
+ inventory.reason = error instanceof SourceAccessError ? error.code : 'unavailable';
401
+ return inventory;
402
+ }
403
+ }
404
+ /** Ordinary unified patch fragments; continuations retain the fixed comparison. */
405
+ async diff(request = {}, control = {}) {
406
+ const offset = request.offset ?? 0;
407
+ const patchLineOffset = request.patchLineOffset ?? 0;
408
+ integer(offset, 'offset', 0);
409
+ integer(patchLineOffset, 'patchLineOffset', 0);
410
+ const changes = await this.changes({ offset, detectRenames: request.detectRenames }, control);
411
+ return this.operation(control, async (operation) => {
412
+ const items = [];
413
+ const budget = { bytes: 0, lines: 0 };
414
+ const result = (next) => ({
415
+ base: changes.base,
416
+ head: changes.head,
417
+ renameDetection: changes.renameDetection,
418
+ status: next ? 'truncated' : 'complete',
419
+ items,
420
+ next,
421
+ });
422
+ for (const [index, change] of changes.items.entries()) {
423
+ const fileOffset = offset + index;
424
+ const skipLines = index === 0 ? patchLineOffset : 0;
425
+ const paths = [...new Set([change.base?.path, change.head?.path].filter((p) => !!p))];
426
+ const item = { change, status: 'complete', patch: '', hash: '' };
427
+ const finishItem = () => {
428
+ item.hash = `sha256:${createHash('sha256').update(item.patch).digest('hex')}`;
429
+ items.push(item);
430
+ };
431
+ const reason = await this.diffReason(change, paths, operation);
432
+ if (reason) {
433
+ item.status = 'unsupported';
434
+ item.reason = reason;
435
+ finishItem();
436
+ continue;
437
+ }
438
+ const args = [
439
+ '--literal-pathspecs',
440
+ 'diff',
441
+ '--no-ext-diff',
442
+ '--no-textconv',
443
+ '--no-color',
444
+ '--src-prefix=a/',
445
+ '--dst-prefix=b/',
446
+ '--unified=3',
447
+ '--diff-algorithm=myers',
448
+ '--no-relative',
449
+ changes.renameDetection === 'heuristic' ? '--find-renames=50%' : '--no-renames',
450
+ changes.base.tree,
451
+ changes.head.tree,
452
+ '--',
453
+ ...paths,
454
+ ];
455
+ const patchLine = await this.appendPatch(item, args, skipLines, budget, operation);
456
+ finishItem();
457
+ if (item.status === 'truncated')
458
+ return result({
459
+ offset: fileOffset,
460
+ patchLineOffset: patchLine,
461
+ detectRenames: request.detectRenames ?? true,
462
+ });
463
+ if (budget.lines >= this.limits.readLines || budget.bytes >= this.limits.readBytes)
464
+ return result({
465
+ offset: fileOffset + 1,
466
+ patchLineOffset: 0,
467
+ detectRenames: request.detectRenames ?? true,
468
+ });
469
+ }
470
+ return result(changes.next ? { ...changes.next, patchLineOffset: 0 } : null);
471
+ });
472
+ }
473
+ async diffReason(change, paths, operation) {
474
+ if (paths.some(sensitiveSourcePath))
475
+ return 'sensitive_path_excluded';
476
+ for (const entry of [change.base, change.head]) {
477
+ if (!entry)
478
+ continue;
479
+ const reason = await this.textReason(entry, operation);
480
+ if (reason)
481
+ return reason;
482
+ }
483
+ return null;
484
+ }
485
+ async appendPatch(item, args, skip, budget, operation) {
486
+ const progress = { line: 0, skip };
487
+ const decoder = new TextDecoder('utf-8', { fatal: true });
488
+ let pending = '';
489
+ for await (const chunk of this.git(args, operation)) {
490
+ pending += decoder.decode(chunk, { stream: true });
491
+ let end;
492
+ while ((end = pending.indexOf('\n')) >= 0) {
493
+ const line = pending.slice(0, end + 1);
494
+ pending = pending.slice(end + 1);
495
+ if (!acceptPatchLine(item, line, progress, budget, this.limits))
496
+ return progress.line;
497
+ }
498
+ if (Buffer.byteLength(pending) > this.limits.readBytes) {
499
+ item.status = 'unsupported';
500
+ item.reason = 'diff_line_exceeds_response_limit';
501
+ return progress.line;
502
+ }
503
+ }
504
+ pending += decoder.decode();
505
+ if (pending)
506
+ acceptPatchLine(item, pending, progress, budget, this.limits);
507
+ if (progress.line < skip)
508
+ throw new SourceAccessError('invalid_cursor', 'Patch continuation exceeds file diff.');
509
+ return progress.line;
510
+ }
511
+ async textReason(entry, operation) {
512
+ if (entry.kind === 'submodule')
513
+ return 'submodule_commit_not_source';
514
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
515
+ try {
516
+ for await (const chunk of this.git(['cat-file', 'blob', entry.object], operation)) {
517
+ if (chunk.includes(0))
518
+ return 'binary_nul';
519
+ decoder.decode(chunk, { stream: true });
520
+ }
521
+ decoder.decode();
522
+ }
523
+ catch (error) {
524
+ if (error instanceof TypeError)
525
+ return 'non_utf8';
526
+ throw error;
527
+ }
528
+ return null;
529
+ }
530
+ async *text(entry, operation) {
531
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
532
+ for await (const chunk of this.git(['cat-file', 'blob', entry.object], operation))
533
+ yield decoder.decode(chunk, { stream: true });
534
+ yield decoder.decode();
535
+ }
536
+ async read(request, control = {}) {
537
+ const snapshot = this.snapshot(request.side);
538
+ safePath(request.path);
539
+ request = structuredClone(request);
540
+ const start = request.start ?? { line: 1, column: 0 };
541
+ integer(start.line, 'start.line');
542
+ integer(start.column, 'start.column', 0);
543
+ const endLine = request.endLine ?? Number.MAX_SAFE_INTEGER;
544
+ integer(endLine, 'endLine');
545
+ if (endLine < start.line)
546
+ throw new SourceAccessError('invalid_input', 'endLine must be >= start.line.');
547
+ return this.operation(control, async (operation) => {
548
+ let entry = null;
549
+ for await (const candidate of this.entries(snapshot, operation))
550
+ if (candidate.path === request.path) {
551
+ entry = candidate;
552
+ break;
553
+ }
554
+ if (!entry)
555
+ return { snapshot, entry, status: 'unavailable', reason: 'missing_path', fragments: [], next: null };
556
+ const reason = await this.textReason(entry, operation);
557
+ if (reason)
558
+ return { snapshot, entry, status: 'unsupported', reason, fragments: [], next: null };
559
+ const window = new ReadWindow(start, endLine, this.limits);
560
+ const result = (status) => ({
561
+ snapshot,
562
+ entry,
563
+ status,
564
+ fragments: window.fragments,
565
+ next: status === 'complete'
566
+ ? null
567
+ : {
568
+ side: snapshot.side,
569
+ path: entry.path,
570
+ start: { line: window.line, column: window.column },
571
+ ...(request.endLine === undefined ? {} : { endLine }),
572
+ },
573
+ });
574
+ for await (const chunk of this.text(entry, operation)) {
575
+ for (const char of chunk) {
576
+ operation.check();
577
+ const status = window.accept(char);
578
+ if (status)
579
+ return result(status);
580
+ }
581
+ }
582
+ window.finish();
583
+ return result('complete');
584
+ });
585
+ }
586
+ async *literalMatches(entry, literal, prefix, minimum, operation) {
587
+ let position = 0, line = 1, column = 0, matched = 0;
588
+ for await (const chunk of this.text(entry, operation)) {
589
+ for (let i = 0; i < chunk.length; i++) {
590
+ operation.check();
591
+ const char = chunk[i];
592
+ while (matched && char !== literal[matched])
593
+ matched = prefix[matched - 1];
594
+ if (char === literal[matched])
595
+ matched++;
596
+ if (matched === literal.length) {
597
+ const offset = position - matched + 1;
598
+ if (offset >= minimum)
599
+ yield { match: { entry, line, column: column - matched + 1, endColumn: column + 1 }, offset };
600
+ matched = prefix[matched - 1];
601
+ }
602
+ position++;
603
+ if (char === '\n') {
604
+ line++;
605
+ column = 0;
606
+ }
607
+ else
608
+ column++;
609
+ }
610
+ }
611
+ if (minimum > position)
612
+ throw new SourceAccessError('invalid_cursor', 'Search cursor exceeds file length.');
613
+ }
614
+ async search(request, control = {}) {
615
+ request = structuredClone(request);
616
+ const snapshot = this.snapshot(request.side);
617
+ if (typeof request.literal !== 'string' || !request.literal || /[\n\r\0]/u.test(request.literal))
618
+ throw new SourceAccessError('invalid_input', 'literal must be nonempty single-line text without NUL.');
619
+ if (request.path !== undefined)
620
+ safePath(request.path);
621
+ // Cursor binds the navigation position to this immutable snapshot, exact query and optional path.
622
+ const scope = createHash('sha256')
623
+ .update(JSON.stringify(request.path === undefined
624
+ ? [snapshot, request.literal]
625
+ : [snapshot, request.literal, request.path]))
626
+ .digest('hex');
627
+ const cursor = request.cursor ?? { scope, entryOffset: 0, characterOffset: 0 };
628
+ if (cursor.scope !== scope)
629
+ throw new SourceAccessError('invalid_cursor', 'Cursor belongs to another snapshot, literal or path.');
630
+ integer(cursor.entryOffset, 'cursor.entryOffset', 0);
631
+ integer(cursor.characterOffset, 'cursor.characterOffset', 0);
632
+ return this.operation(control, async (operation) => {
633
+ const items = [], skipped = [];
634
+ let index = 0, scannedFiles = 0, foundPath = request.path === undefined;
635
+ const result = (next) => ({
636
+ snapshot,
637
+ path: request.path ?? null,
638
+ status: next ? 'truncated' : 'complete',
639
+ items,
640
+ skipped,
641
+ scannedFiles,
642
+ next,
643
+ evidence: 'literal_navigation_only',
644
+ });
645
+ const prefix = literalPrefix(request.literal);
646
+ for await (const entry of this.entries(snapshot, operation)) {
647
+ const entryOffset = index++;
648
+ if (request.path !== undefined && entry.path !== request.path)
649
+ continue;
650
+ foundPath = true;
651
+ if (entryOffset < cursor.entryOffset)
652
+ continue;
653
+ if (scannedFiles === this.limits.searchFiles)
654
+ return result({ scope, entryOffset, characterOffset: 0 });
655
+ scannedFiles++;
656
+ const reason = await this.textReason(entry, operation);
657
+ if (reason) {
658
+ skipped.push({ entry, reason });
659
+ continue;
660
+ }
661
+ const minimum = entryOffset === cursor.entryOffset ? cursor.characterOffset : 0;
662
+ for await (const { match, offset } of this.literalMatches(entry, request.literal, prefix, minimum, operation)) {
663
+ items.push(match);
664
+ if (items.length === this.limits.searchMatches)
665
+ return result({ scope, entryOffset, characterOffset: offset + 1 });
666
+ }
667
+ }
668
+ if (cursor.entryOffset > index)
669
+ throw new SourceAccessError('invalid_cursor', 'Search cursor exceeds snapshot paths.');
670
+ if (!foundPath)
671
+ throw new SourceAccessError('unavailable', 'Search path is absent from the pinned snapshot.');
672
+ return result(null);
673
+ });
674
+ }
675
+ }