@criogaid/pi-hashline-edit 0.11.0 → 0.13.0

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 (94) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +73 -17
  3. package/README.zh-CN.md +74 -18
  4. package/package.json +8 -7
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +15 -2
  7. package/src/core/apply.ts +6 -10
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -32
  13. package/src/core/replace.test.ts +51 -0
  14. package/src/core/replace.ts +10 -4
  15. package/src/core/search-analysis.test.ts +66 -61
  16. package/src/core/search-analysis.ts +24 -39
  17. package/src/core/search-matrix.test.ts +2 -2
  18. package/src/core/search-matrix.testing.ts +6 -16
  19. package/src/core/search-schema.ts +0 -1
  20. package/src/core/search.test.ts +6 -19
  21. package/src/core/search.ts +10 -8
  22. package/src/index.ts +28 -3
  23. package/src/integration/config-registration.test.ts +77 -4
  24. package/src/integration/fusion-dispatch.test.ts +47 -2
  25. package/src/integration/grep-errors.test.ts +31 -0
  26. package/src/integration/grep-flags.test.ts +13 -196
  27. package/src/integration/grep-js-completeness.test.ts +41 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -33
  29. package/src/integration/grep-matrix.test.ts +1 -1
  30. package/src/integration/grep-path-matrix.test.ts +59 -65
  31. package/src/integration/grep-prefilter-coverage.test.ts +26 -8
  32. package/src/integration/grep-process-limits.test.ts +46 -0
  33. package/src/integration/grep-regex.test.ts +7 -2
  34. package/src/integration/grep-rg.test.ts +106 -12
  35. package/src/integration/grep-translation.test.ts +14 -7
  36. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  37. package/src/integration/npm-package.test.ts +12 -10
  38. package/src/integration/npm-package.testing.ts +147 -1
  39. package/src/integration/replace-package.testing.ts +2 -2
  40. package/src/integration/report-replay.test.ts +4 -0
  41. package/src/pi/AGENTS.md +23 -15
  42. package/src/pi/action-fusion.test.ts +38 -4
  43. package/src/pi/action-fusion.ts +23 -19
  44. package/src/pi/argument-diagnostics.ts +28 -48
  45. package/src/pi/argument-validation.test.ts +103 -6
  46. package/src/pi/argument-validation.ts +55 -31
  47. package/src/pi/budgets.ts +19 -10
  48. package/src/pi/config.test.ts +1 -1
  49. package/src/pi/diagnostic-buffer.test.ts +1 -0
  50. package/src/pi/edit-tool.ts +3 -3
  51. package/src/pi/execute.test.ts +4 -0
  52. package/src/pi/failure-context.test.ts +24 -3
  53. package/src/pi/failure-context.ts +36 -42
  54. package/src/pi/failure-path.test.ts +8 -3
  55. package/src/pi/file-commit.test.ts +109 -52
  56. package/src/pi/file-commit.ts +62 -56
  57. package/src/pi/fusion-card.ts +12 -7
  58. package/src/pi/grep-candidates.test.ts +5 -5
  59. package/src/pi/grep-candidates.ts +80 -48
  60. package/src/pi/grep-matrix.test.ts +14 -29
  61. package/src/pi/grep-order.test.ts +132 -9
  62. package/src/pi/grep-output.ts +173 -48
  63. package/src/pi/grep-render.ts +40 -34
  64. package/src/pi/grep-rg.testing.ts +9 -6
  65. package/src/pi/grep-scope.ts +51 -29
  66. package/src/pi/grep-search.ts +96 -71
  67. package/src/pi/grep-tool.ts +28 -34
  68. package/src/pi/grep.test.ts +348 -83
  69. package/src/pi/model-budgets.test.ts +56 -6
  70. package/src/pi/model-budgets.ts +7 -4
  71. package/src/pi/mutation-result.test.ts +25 -1
  72. package/src/pi/mutation-result.ts +7 -2
  73. package/src/pi/mutation-runner.ts +4 -5
  74. package/src/pi/output-budgets.test.ts +3 -1
  75. package/src/pi/path.ts +18 -4
  76. package/src/pi/pi.test.ts +22 -0
  77. package/src/pi/read-delegation.test.ts +119 -0
  78. package/src/pi/read-tool.ts +109 -61
  79. package/src/pi/read.test.ts +351 -17
  80. package/src/pi/regex-worker.test.ts +42 -0
  81. package/src/pi/regex-worker.ts +17 -11
  82. package/src/pi/registration.test.ts +157 -102
  83. package/src/pi/render.test.ts +97 -0
  84. package/src/pi/render.ts +9 -9
  85. package/src/pi/replace-tool.ts +5 -2
  86. package/src/pi/report-schema.ts +75 -37
  87. package/src/pi/report.test.ts +73 -31
  88. package/src/pi/report.ts +12 -5
  89. package/src/pi/rg-process.ts +41 -5
  90. package/src/pi/rg-regex.test.ts +12 -39
  91. package/src/pi/rg-regex.ts +31 -79
  92. package/src/pi/text-stream.test.ts +3 -0
  93. package/src/pi/text-stream.ts +1 -1
  94. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -153,20 +153,19 @@ export type ArgumentIssue = Static<typeof ARGUMENT_ISSUE_SCHEMA>;
153
153
  * facts must also state the decision their value changes; TUI-only facts omit it.
154
154
  */
155
155
  type FactAudience = "model" | "tui";
156
- type FactDefinition<T extends TSchema = TSchema> = {
156
+ type FactDefinition<T extends TSchema = TSchema, A extends FactAudience = FactAudience> = {
157
157
  schema: T;
158
- audience: FactAudience;
159
- decision?: string;
160
- };
158
+ audience: A;
159
+ } & (A extends "model" ? { decision: string } : { decision?: never });
161
160
 
162
161
  function modelFact<T extends TSchema, const D extends string>(
163
162
  schema: T,
164
163
  decision: D extends "" ? never : D,
165
- ): FactDefinition<T> {
164
+ ): FactDefinition<T, "model"> {
166
165
  return { schema, audience: "model", decision };
167
166
  }
168
167
 
169
- function tuiFact<T extends TSchema>(schema: T): FactDefinition<T> {
168
+ function tuiFact<T extends TSchema>(schema: T): FactDefinition<T, "tui"> {
170
169
  return { schema, audience: "tui" };
171
170
  }
172
171
 
@@ -194,7 +193,7 @@ const FACT_FIELDS = {
194
193
  Type.Array(Type.String(), {
195
194
  description: "Resolved paths that do not exist; shows where a relative path led.",
196
195
  }),
197
- "Use the resolved missing paths to correct the target or choose create mode.",
196
+ "Correct the missing paths and search them again, or use create mode for a new file.",
198
197
  ),
199
198
 
200
199
  // Anchor verification (failure-context.ts).
@@ -274,11 +273,11 @@ const FACT_FIELDS = {
274
273
  ),
275
274
  outputLimit: modelFact(
276
275
  Type.String({ description: "The output byte budget that cut the result." }),
277
- "Narrow the scope to see omitted output.",
276
+ "Remove context or narrow the scope to see omitted output.",
278
277
  ),
279
278
  linePreviewLimit: modelFact(
280
279
  Type.Integer({ description: "UTF-16 units kept in a cut line preview." }),
281
- "Read the full line before rewriting it from a partial preview.",
280
+ "Inspect the full line with a tool that supports its encoding before rewriting a partial preview.",
282
281
  ),
283
282
  invalidUtf8: modelFact(
284
283
  Type.Array(Type.String(), {
@@ -391,7 +390,7 @@ export const ERROR_DEFINITIONS = {
391
390
  OVERLAPPING_EDITS: {
392
391
  facts: facts(["conflict"]),
393
392
  next: {
394
- default: "Merge them into one edit per range or position.",
393
+ default: "Merge them into one step per range or position.",
395
394
  },
396
395
  },
397
396
  NO_MATCH: {
@@ -425,7 +424,7 @@ export const ERROR_DEFINITIONS = {
425
424
  SYMLINK_UNRESOLVED: { facts: NONE },
426
425
  PUBLISH_FAILED: { facts: NONE },
427
426
  POST_PROCESS_FAILED: { facts: NONE },
428
- SEARCH_INCOMPLETE: { facts: facts(["diagnostics"], ["scanLimit"]) },
427
+ SEARCH_INCOMPLETE: { facts: facts(["diagnostics"], ["scanLimit", "missing"]) },
429
428
  RIPGREP_FAILED: { facts: NONE },
430
429
  UNSUPPORTED_PATH: { facts: NONE },
431
430
  UNCLASSIFIED: { facts: NONE },
@@ -464,10 +463,24 @@ export const PUBLICATION_NEXT = {
464
463
  "The change may or may not be saved. Read the file, and repeat the change only if it is missing.",
465
464
  } as const satisfies Record<Exclude<PublicationStatus, "NOT_PUBLISHED">, string>;
466
465
 
466
+ /** The byte budget cut a grep payload: context rows go first, and without them only a narrower search helps. */
467
+ const OUTPUT_LIMIT_NEXT = {
468
+ default: "Narrow path, glob, or pattern to see the omitted output.",
469
+ contextRows: "Set context to 0 to see more of the omitted matches.",
470
+ } as const;
471
+
472
+ /** Recovery alternatives the producing layer may select for a successful result. */
473
+ export type OutcomeVariant = Exclude<keyof typeof OUTPUT_LIMIT_NEXT, "default">;
474
+
475
+ /** One recovery, or a default with the named alternatives its producer may select. */
476
+ type OutcomeNext =
477
+ | string
478
+ | ({ readonly default: string } & Partial<Record<OutcomeVariant, string>>);
479
+
467
480
  /** One fact's recovery; `except` is a value of that fact which needs none. */
468
481
  type OutcomeRule =
469
482
  | {
470
- [F in FactName]: readonly [fact: F, next: string, except?: Static<FactSchema<F>>];
483
+ [F in FactName]: readonly [fact: F, next: OutcomeNext, except?: Static<FactSchema<F>>];
471
484
  }[FactName]
472
485
  | readonly [fact: "publication", next: string, except?: PublicationStatus];
473
486
 
@@ -488,8 +501,13 @@ export const OUTCOME_NEXT: readonly OutcomeRule[] = [
488
501
  "Inspect the line in chunks with bash, or use replace for a known literal or regex change; a smaller limit cannot split a line.",
489
502
  ],
490
503
  ["nextOffset", "If you need more lines, set offset to nextOffset."],
504
+ // Ahead of grep's limits: repeating the corrected search states them again.
505
+ [
506
+ "missing",
507
+ "Only the existing paths were searched. Correct the paths in missing and repeat the search.",
508
+ ],
491
509
  // Ahead of matchLimit: once the byte budget cuts the output, raising limit shows nothing more.
492
- ["outputLimit", "Narrow path, glob, or pattern to see the omitted output."],
510
+ ["outputLimit", OUTPUT_LIMIT_NEXT],
493
511
  ["matchLimit", "If you need more matches, raise limit to include rows after the last one shown."],
494
512
  [
495
513
  "literalPipe",
@@ -499,7 +517,10 @@ export const OUTCOME_NEXT: readonly OutcomeRule[] = [
499
517
  "scanLimit",
500
518
  "Narrow path or glob, or add text every match must contain, to search the remaining files.",
501
519
  ],
502
- ["linePreviewLimit", "Read the full line before rewriting it from a partial preview."],
520
+ [
521
+ "linePreviewLimit",
522
+ "For paths listed in invalidUtf8, inspect the full line with bash; otherwise use read before rewriting a partial preview.",
523
+ ],
503
524
  ];
504
525
 
505
526
  /** The report envelope and facts, in output order; `next` is always last. */
@@ -524,6 +545,7 @@ const SUCCESS_DEFINITIONS = {
524
545
  [
525
546
  "matches",
526
547
  "files",
548
+ "missing",
527
549
  "matchLimit",
528
550
  "scanLimit",
529
551
  "outputLimit",
@@ -544,30 +566,40 @@ export type MutationToolName = (typeof MUTATION_TOOLS)[number];
544
566
  /** Argument rejections may omit message; Pi supplies none for them. */
545
567
  const MESSAGE_OPTIONAL = "INVALID_ARGUMENTS" satisfies ErrorCode;
546
568
 
547
- const TOOL_SCHEMA = literalUnion(Object.keys(SUCCESS_DEFINITIONS) as ReportTool[]);
569
+ const NON_MUTATION_TOOLS = (Object.keys(SUCCESS_DEFINITIONS) as ReportTool[]).filter(
570
+ (tool): tool is Exclude<ReportTool, MutationToolName> =>
571
+ !(MUTATION_TOOLS as readonly ReportTool[]).includes(tool),
572
+ );
548
573
  const COMMON_WIRE_FIELDS = {
549
- tool: TOOL_SCHEMA,
550
574
  path: REPORT_SCHEMA.properties.path,
551
575
  next: REPORT_SCHEMA.properties.next,
552
576
  };
553
577
  const MUTATION_WIRE_FIELDS = {
554
578
  publication: REPORT_SCHEMA.properties.publication,
555
- freshness: REPORT_SCHEMA.properties.freshness,
556
- freshnessError: REPORT_SCHEMA.properties.freshnessError,
557
579
  then_run: REPORT_SCHEMA.properties.then_run,
558
580
  progressError: REPORT_SCHEMA.properties.progressError,
559
581
  };
560
- const FAILURE_SCHEMAS = ERROR_CODES.map((code) =>
561
- Type.Object(
562
- {
563
- ...COMMON_WIRE_FIELDS,
564
- ...MUTATION_WIRE_FIELDS,
565
- cause: REPORT_SCHEMA.properties.cause,
566
- error: Type.Literal(code),
567
- message: code === MESSAGE_OPTIONAL ? opt(Type.String()) : Type.String(),
568
- ...ERROR_DEFINITIONS[code].facts.properties,
569
- },
570
- { additionalProperties: false },
582
+ const MUTATION_SUCCESS_WIRE_FIELDS = {
583
+ ...MUTATION_WIRE_FIELDS,
584
+ freshness: REPORT_SCHEMA.properties.freshness,
585
+ freshnessError: REPORT_SCHEMA.properties.freshnessError,
586
+ };
587
+ const FAILURE_SCHEMAS = [
588
+ { tool: literalUnion(NON_MUTATION_TOOLS) },
589
+ { tool: literalUnion(MUTATION_TOOLS), ...MUTATION_WIRE_FIELDS },
590
+ ].flatMap((toolFields) =>
591
+ ERROR_CODES.map((code) =>
592
+ Type.Object(
593
+ {
594
+ ...COMMON_WIRE_FIELDS,
595
+ ...toolFields,
596
+ cause: REPORT_SCHEMA.properties.cause,
597
+ error: Type.Literal(code),
598
+ message: code === MESSAGE_OPTIONAL ? REPORT_SCHEMA.properties.message : Type.String(),
599
+ ...ERROR_DEFINITIONS[code].facts.properties,
600
+ },
601
+ { additionalProperties: false },
602
+ ),
571
603
  ),
572
604
  );
573
605
  const SUCCESS_SCHEMAS = Object.entries(SUCCESS_DEFINITIONS).map(([tool, schema]) =>
@@ -575,7 +607,7 @@ const SUCCESS_SCHEMAS = Object.entries(SUCCESS_DEFINITIONS).map(([tool, schema])
575
607
  {
576
608
  ...COMMON_WIRE_FIELDS,
577
609
  tool: Type.Literal(tool),
578
- ...((MUTATION_TOOLS as readonly string[]).includes(tool) ? MUTATION_WIRE_FIELDS : {}),
610
+ ...((MUTATION_TOOLS as readonly string[]).includes(tool) ? MUTATION_SUCCESS_WIRE_FIELDS : {}),
579
611
  ...schema.properties,
580
612
  },
581
613
  { additionalProperties: false },
@@ -592,26 +624,32 @@ type ErrorFactNames = {
592
624
  [Code in ErrorCode]: keyof Static<(typeof ERROR_DEFINITIONS)[Code]["facts"]>;
593
625
  }[ErrorCode] &
594
626
  string;
595
- type MutationWireFactNames = keyof Fields<typeof MUTATION_WIRE_FIELDS> & string;
627
+ type MutationWireFactNames = keyof Fields<typeof MUTATION_SUCCESS_WIRE_FIELDS> & string;
596
628
  type UnusedFactNames = Exclude<FactName, SuccessFactNames | ErrorFactNames | MutationWireFactNames>;
597
629
  // Compilation fails here, naming the fact, when no tool, code, or mutation field carries it.
598
630
  ({}) satisfies Record<UnusedFactNames, never>;
599
631
 
600
632
  // Static counterparts of the per-tool and per-code wire schemas above, built from the same fields.
601
633
  type Fields<P extends TProperties> = Static<TObject<P>>;
602
- type Envelope = Omit<Fields<typeof COMMON_WIRE_FIELDS>, "tool">;
603
- type MutationFields = Fields<typeof MUTATION_WIRE_FIELDS>;
634
+ type Envelope = Fields<typeof COMMON_WIRE_FIELDS>;
635
+ type FailureToolFields =
636
+ | ({ tool: MutationToolName } & Fields<typeof MUTATION_WIRE_FIELDS>)
637
+ | { tool: (typeof NON_MUTATION_TOOLS)[number] };
604
638
 
605
639
  /** Facts owned by one successful tool, derived from its wire schema. */
606
640
  export type SuccessFacts<T extends ReportTool> = Static<(typeof SUCCESS_DEFINITIONS)[T]>;
607
641
 
608
642
  // Absent fields stay readable as undefined without admitting another variant's facts.
609
- type ReportVariant<T> = T & { [K in Exclude<keyof ReportFields, keyof T>]?: never };
643
+ type ReportVariant<T> = T extends unknown
644
+ ? T & { [K in Exclude<keyof ReportFields, keyof T>]?: never }
645
+ : never;
610
646
 
611
647
  /** A success report a tool may produce: its own facts, and mutation facts only for mutation tools. */
612
648
  export type SuccessReport = {
613
649
  [T in ReportTool]: ReportVariant<
614
- Envelope & { tool: T } & (T extends MutationToolName ? MutationFields : unknown) &
650
+ Envelope & { tool: T } & (T extends MutationToolName
651
+ ? Fields<typeof MUTATION_SUCCESS_WIRE_FIELDS>
652
+ : unknown) &
615
653
  SuccessFacts<T>
616
654
  >;
617
655
  }[ReportTool];
@@ -619,8 +657,8 @@ export type SuccessReport = {
619
657
  /** A failure report: its code's facts, with message required except where MESSAGE_OPTIONAL allows. */
620
658
  export type FailureReport = {
621
659
  [C in ErrorCode]: ReportVariant<
622
- Envelope & { tool: ReportTool; error: C } & MutationFields &
623
- Pick<ReportFields, "cause"> &
660
+ Envelope &
661
+ FailureToolFields & { error: C } & Pick<ReportFields, "cause"> &
624
662
  (C extends typeof MESSAGE_OPTIONAL ? { message?: string } : { message: string }) &
625
663
  Static<Definitions[C]["facts"]>
626
664
  >;
@@ -358,46 +358,43 @@ test("success facts survive details and model serialization", () => {
358
358
  }
359
359
  });
360
360
 
361
- test("match and scan limits → recovery prioritizes the match limit", () => {
362
- const next = OUTCOME_NEXT.find(([fact]) => fact === "matchLimit")?.[1];
363
- assert.ok(next);
361
+ test("grep preview from invalid UTF-8 → recovery selects bash for the listed paths", () => {
364
362
  const result = reportResult({
365
363
  tool: "grep",
366
- matches: 1,
367
- matchLimit: 1,
368
- scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
364
+ linePreviewLimit: DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits,
365
+ invalidUtf8: ["invalid.txt"],
369
366
  });
370
- assert.equal(reportOf(result, "grep")?.next, next);
367
+ const next = reportOf(result, "grep")?.next ?? "";
368
+ assert.match(next, /invalidUtf8.*bash/);
371
369
  });
372
370
 
373
- for (const { name, report, fact } of [
374
- {
375
- name: "output limit with grep match limit → recovery prioritizes the output limit",
376
- report: {
371
+ test("grep limits coincide → recovery prioritizes output, then match, then scan", () => {
372
+ for (const key of ["matchLimit", "outputLimit"] as const) {
373
+ const next = OUTCOME_NEXT.find(([fact]) => fact === key)?.[1];
374
+ assert.ok(next);
375
+ const result = reportResult({
377
376
  tool: "grep",
378
377
  matches: 1,
379
378
  matchLimit: 1,
380
- outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.grepBytes),
381
- },
382
- fact: "outputLimit",
383
- },
384
- {
385
- name: "output limit with read next offset → recovery prioritizes the next offset",
386
- report: {
387
- tool: "read",
388
- nextOffset: 2,
389
- outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.readBytes),
390
- },
391
- fact: "nextOffset",
392
- },
393
- ] satisfies { name: string; report: SuccessReport; fact: "outputLimit" | "nextOffset" }[]) {
394
- test(name, () => {
395
- const next = OUTCOME_NEXT.find(([key]) => key === fact)?.[1];
396
- assert.ok(next);
397
- const result = reportResult(report);
398
- assert.equal(reportOf(result, report.tool)?.next, next);
379
+ scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
380
+ ...(key === "outputLimit" && {
381
+ outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.grepBytes),
382
+ }),
383
+ });
384
+ assert.equal(reportOf(result, "grep")?.next, typeof next === "string" ? next : next.default);
385
+ }
386
+ });
387
+
388
+ test("output limit with read next offset → recovery prioritizes the next offset", () => {
389
+ const next = OUTCOME_NEXT.find(([key]) => key === "nextOffset")?.[1];
390
+ assert.ok(next);
391
+ const result = reportResult({
392
+ tool: "read",
393
+ nextOffset: 2,
394
+ outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.readBytes),
399
395
  });
400
- }
396
+ assert.equal(reportOf(result, "read")?.next, next);
397
+ });
401
398
 
402
399
  test("text-only error contains facts invalid for the originating tool → preserves the raw diagnostic", () => {
403
400
  const diagnostic = '{"publication":"PUBLISHED"}';
@@ -489,3 +486,48 @@ test("mutation freshness → retains the fact and requests reread only for an ex
489
486
  assert.equal(Object.hasOwn(JSON.parse(block.text), "next"), freshness !== "missing");
490
487
  }
491
488
  });
489
+
490
+ test("text-only error resembles a success report → keeps the original diagnostic visible", () => {
491
+ const diagnostic = '{"matches":1}';
492
+ assert.equal(displayed({ content: [text(diagnostic)] }, "grep").trimEnd(), diagnostic);
493
+ });
494
+
495
+ test("read and grep failures cannot carry mutation state → reject invalid replay facts", () => {
496
+ for (const tool of ["read", "grep"] as const) {
497
+ const raw = {
498
+ error: "FILESYSTEM_ERROR",
499
+ message: "disk read failed",
500
+ publication: "PUBLISHED",
501
+ };
502
+ const content = [text(JSON.stringify(raw))];
503
+ assert.equal(reportOf({ content }, tool), undefined);
504
+ assert.equal(
505
+ splitReport({ details: { report: { tool, ...raw } }, content }, tool).report,
506
+ undefined,
507
+ );
508
+ }
509
+ });
510
+
511
+ test("mutation failure carries a freshness fact → rejects the invalid replay report", () => {
512
+ const tool = "edit";
513
+ const failure = {
514
+ error: "PUBLISH_FAILED",
515
+ message: "Publication failed.",
516
+ publication: "NOT_PUBLISHED",
517
+ };
518
+ const valid = {
519
+ content: [text(JSON.stringify(failure))],
520
+ details: { report: { tool, ...failure } },
521
+ };
522
+ assert.deepEqual(reportOf(valid, tool), valid.details.report);
523
+ for (const facts of [
524
+ { freshness: "changed" },
525
+ { freshnessError: { message: "Could not inspect target." } },
526
+ ]) {
527
+ const raw = { ...failure, ...facts };
528
+ const content = [text(JSON.stringify(raw))];
529
+ const details = { report: { tool, ...raw } };
530
+ assert.equal(splitReport({ content, details }, tool).report, undefined);
531
+ assert.equal(reportOf({ content }, tool), undefined);
532
+ }
533
+ });
package/src/pi/report.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  WIRE_REPORT_SCHEMA,
38
38
  type ErrorCode,
39
39
  type FailureReport,
40
+ type OutcomeVariant,
40
41
  type ModelOmittedField,
41
42
  type Report,
42
43
  type ReportTool,
@@ -121,24 +122,30 @@ export function reportOf(
121
122
  return last?.type === "text" ? decodeReport(last.text, tool) : undefined;
122
123
  }
123
124
 
124
- /** The recovery a successful result's facts call for: the first in OUTCOME_NEXT order. */
125
- function outcomeNext(report: Report): string | undefined {
126
- return OUTCOME_NEXT.find(
125
+ /**
126
+ * The recovery a successful result's facts call for: the first in OUTCOME_NEXT order, in the
127
+ * producer's selected alternative when that rule names it.
128
+ */
129
+ function outcomeNext(report: Report, variant: OutcomeVariant | undefined): string | undefined {
130
+ const next = OUTCOME_NEXT.find(
127
131
  ([fact, , except]) => report[fact] !== undefined && report[fact] !== except,
128
132
  )?.[1];
133
+ return typeof next === "object" ? ((variant && next[variant]) ?? next.default) : next;
129
134
  }
130
135
 
131
136
  /**
132
137
  * A successful result: the tool's payload, then its report when it states
133
- * anything beyond tool and path or when there is no payload.
138
+ * anything beyond tool and path or when there is no payload. `variant` is the recovery
139
+ * alternative the producing layer selected.
134
140
  */
135
141
  export function reportResult<TDetails extends object | undefined>(
136
142
  report: SuccessReport,
137
143
  payload: Content = [],
138
144
  details?: TDetails,
145
+ variant?: OutcomeVariant,
139
146
  ): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
140
147
  const complete = Object.fromEntries(
141
- reportEntries({ ...report, next: outcomeNext(report) }),
148
+ reportEntries({ ...report, next: outcomeNext(report, variant) }),
142
149
  ) as SuccessReport;
143
150
  const stated = Object.keys(complete).some(
144
151
  (key) => !MODEL_OMITTED_FIELDS.has(key as ModelOmittedField),
@@ -11,7 +11,7 @@ import { rgPath } from "@vscode/ripgrep";
11
11
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
12
12
  import { spawn, type ChildProcessByStdio } from "node:child_process";
13
13
  import type { Readable } from "node:stream";
14
- import { HashlineError } from "../core/errors.ts";
14
+ import { errnoCode, HashlineError } from "../core/errors.ts";
15
15
  import { throwIfCancelled, type SearchWarning } from "./error-text.ts";
16
16
  import { formatByteSize } from "./budgets.ts";
17
17
 
@@ -23,6 +23,14 @@ import { formatByteSize } from "./budgets.ts";
23
23
  export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--sort=path"];
24
24
  /** Leave room for rg's arguments and paths on hosts with small command-line limits. */
25
25
  export const MAX_RG_PATTERN_UNITS = 24 * 1024;
26
+ export const RG_PATTERN_FLAG = "-e";
27
+
28
+ /** Command-line cost of a translated pattern and its flag, including separators. */
29
+ export function rgPatternArgUnits(pattern: string): number {
30
+ // Translations use ASCII without whitespace or quotes; Windows quotes an empty argument.
31
+ return RG_PATTERN_FLAG.length + 2 + (pattern.length || 2);
32
+ }
33
+
26
34
  const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
27
35
  const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${formatByteSize(MAX_RG_RECORD_BYTES)}.`;
28
36
 
@@ -58,8 +66,17 @@ export function searchDiagnostic(result: RgRunResult): SearchWarning | undefined
58
66
  }
59
67
 
60
68
  /** spawn reports a failure to start by throwing or by an error event, depending on the errno. */
61
- function startFailure(cause: unknown): HashlineError {
62
- return new HashlineError("RIPGREP_FAILED", "Failed to run ripgrep.", { cause });
69
+ class RgStartError extends HashlineError<"RIPGREP_FAILED"> {
70
+ constructor(cause: unknown) {
71
+ super("RIPGREP_FAILED", "Failed to run ripgrep.", { cause });
72
+ }
73
+ }
74
+
75
+ /** Whether rg could not start because the OS rejected its command line length. */
76
+ export function isRgArgumentLimit(error: unknown): boolean {
77
+ if (!(error instanceof RgStartError)) return false;
78
+ const code = errnoCode(error.cause);
79
+ return code === "ENAMETOOLONG" || code === "E2BIG";
63
80
  }
64
81
 
65
82
  function startRg(args: readonly string[], signal?: AbortSignal): RunningProcess {
@@ -71,7 +88,7 @@ function startRg(args: readonly string[], signal?: AbortSignal): RunningProcess
71
88
  shell: false,
72
89
  });
73
90
  } catch (cause) {
74
- throw startFailure(cause);
91
+ throw new RgStartError(cause);
75
92
  }
76
93
  const stderr = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
77
94
  const stderrDecoder = new StringDecoder("utf8");
@@ -139,7 +156,7 @@ async function runRg(
139
156
  if (stopped) rg.kill();
140
157
  const result = await rg.done;
141
158
  throwIfCancelled(signal);
142
- if (result.error) throw startFailure(result.error);
159
+ if (result.error) throw new RgStartError(result.error);
143
160
  return { code: result.code, stderr: result.stderr, stopped };
144
161
  } finally {
145
162
  rg.kill();
@@ -162,6 +179,25 @@ export function runRgPaths(
162
179
  });
163
180
  }
164
181
 
182
+ /**
183
+ * Whether rg rejects pattern arguments. Exit code 2 also covers paths rg could not read, so the
184
+ * patterns run alone against empty standard input, where only a pattern error fails.
185
+ */
186
+ export async function rgRejectsPatterns(
187
+ patternArgs: readonly string[],
188
+ signal: AbortSignal | undefined,
189
+ ): Promise<boolean> {
190
+ const result = await runRg(
191
+ [...COMMON_RG_ARGS, ...patternArgs, "--", "-"],
192
+ signal,
193
+ async (stdout) => {
194
+ for await (const _ of stdout);
195
+ return true;
196
+ },
197
+ );
198
+ return result.code === 2;
199
+ }
200
+
165
201
  /** A path rg reported; one that is not valid UTF-8 cannot be addressed by tools. */
166
202
  function decodePath(record: Buffer): string {
167
203
  const path = record.toString("utf8");
@@ -3,52 +3,25 @@ import { test } from "node:test";
3
3
  import { lineCandidatePatterns } from "./rg-regex.ts";
4
4
 
5
5
  // These expressions are the byte-level boundary contract, including deliberate widening.
6
- for (const [pattern, flags, expected] of [
7
- ["a$", "", "a\\r?$"],
8
- ["[A-Z]{10,}", "m", "(?:[A-Z]){10,}"],
9
- ["(?m:^)b", "", "(?:^|[\\r\\x{2028}\\x{2029}])b"],
10
- ["(\\w)\\1{4}", "m", "[0-9A-Z_a-z](?:[0-9A-Z_a-z]){4,4}"],
11
- ] as const) {
12
- test(`line candidates ${pattern} /${flags} → preserve required byte positions`, () => {
13
- assert.deepEqual(
14
- lineCandidatePatterns({ patterns: [pattern], literal: false, flags, multiline: false }),
15
- [expected],
16
- );
17
- });
18
- }
19
-
20
6
  for (const [pattern, expected] of [
21
- ["[[a-c]&&[b-d]]", "[b-c]"],
22
- ["[[a-c]--[b]]", "[ac]"],
23
- ["[\\p{ASCII}&&\\p{Letter}]", "[A-Za-z]"],
24
- ["[\\p{Letter}&&[a-c]]", "[a-c]"],
25
- ["[[a-c]--\\p{Uppercase_Letter}]", "[a-c]"],
26
- ["[a[bc]\\q{de|fg}]", "(?:[a-c]|(?:de|fg))"],
27
- ["[\\q{ab|cd}&&\\q{cd|ef}]", "cd"],
28
- ["[\\q{ab|cd}--\\q{cd}]", "ab"],
29
- ["[\\q{ab|}]", "(?:ab|)"],
30
- ["[[a]--[a]]", "[^\\x{0}-\\x{10ffff}]"],
7
+ ["a$", "a(?:[\\r\\x{2028}\\x{2029}]|\\r?$)"],
8
+ ["[A-Z]{10,}", "(?:[A-Z]){10,}"],
9
+ ["(?m:^)b", "(?:^|[\\r\\x{2028}\\x{2029}])b"],
10
+ ["(\\w)\\1{4}", "[0-9A-Z_a-z](?:[0-9A-Z_a-z]){4,4}"],
31
11
  ] as const) {
32
- test(`finite v class ${pattern} → narrow candidates without discarding strings`, () => {
12
+ test(`line candidates ${pattern} → preserve required byte positions`, () => {
33
13
  assert.deepEqual(
34
- lineCandidatePatterns({ patterns: [pattern], literal: false, flags: "v", multiline: false }),
14
+ lineCandidatePatterns({
15
+ patterns: [pattern],
16
+ literal: false,
17
+ ignoreCase: false,
18
+ multiline: false,
19
+ }),
35
20
  [expected],
36
21
  );
37
22
  });
38
23
  }
39
24
 
40
- test("capture disables i inside a caseless reference → retain the reference's case variants", () => {
41
- assert.deepEqual(
42
- lineCandidatePatterns({
43
- patterns: ["((?-i:[[a]--[A]]))(?i:\\1)"],
44
- literal: false,
45
- flags: "v",
46
- multiline: false,
47
- }),
48
- ["a[Aa]"],
49
- );
50
- });
51
-
52
25
  test("deeply nested pattern → line candidates retain the native match", () => {
53
26
  for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
54
27
  const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
@@ -56,7 +29,7 @@ test("deeply nested pattern → line candidates retain the native match", () =>
56
29
  const candidates = lineCandidatePatterns({
57
30
  patterns: [pattern],
58
31
  literal: false,
59
- flags: "",
32
+ ignoreCase: false,
60
33
  multiline: false,
61
34
  });
62
35
  // An unavailable line analysis delegates candidate discovery to the file prefilter.