@open-cr-agent/core 0.5.0 → 0.7.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 (207) hide show
  1. package/README.md +1 -1
  2. package/dist/{pipeline → agent}/budget.d.ts +0 -1
  3. package/dist/{pipeline → agent}/budget.js +0 -1
  4. package/dist/agent/json.d.ts +1 -0
  5. package/dist/agent/json.js +11 -0
  6. package/dist/{pipeline → agent}/pool.d.ts +0 -1
  7. package/dist/{pipeline → agent}/pool.js +2 -2
  8. package/dist/{pipeline/agents.d.ts → agent/settings.d.ts} +9 -5
  9. package/dist/{pipeline/agents.js → agent/settings.js} +14 -6
  10. package/dist/{pipeline → agent}/usage.d.ts +0 -1
  11. package/dist/{pipeline → agent}/usage.js +0 -1
  12. package/dist/anchor/anchor.d.ts +0 -1
  13. package/dist/anchor/anchor.js +0 -1
  14. package/dist/anchor/match.d.ts +0 -1
  15. package/dist/anchor/match.js +5 -5
  16. package/dist/anchor/relocate.d.ts +1 -3
  17. package/dist/anchor/relocate.js +2 -3
  18. package/dist/at.d.ts +1 -0
  19. package/dist/at.js +11 -0
  20. package/dist/bounded-file.d.ts +12 -0
  21. package/dist/bounded-file.js +47 -0
  22. package/dist/bundle/bundle.d.ts +2 -2
  23. package/dist/bundle/bundle.js +3 -3
  24. package/dist/bundle/grouping.d.ts +0 -2
  25. package/dist/bundle/grouping.js +0 -1
  26. package/dist/bundle/runtime-grouper.d.ts +4 -0
  27. package/dist/{pipeline/helpers.js → bundle/runtime-grouper.js} +4 -14
  28. package/dist/contracts.d.ts +16 -15
  29. package/dist/contracts.js +6 -2
  30. package/dist/diff/hunks.d.ts +0 -1
  31. package/dist/diff/hunks.js +3 -3
  32. package/dist/diff/parse.d.ts +0 -1
  33. package/dist/diff/parse.js +5 -5
  34. package/dist/diff/quoted-path.d.ts +0 -1
  35. package/dist/diff/quoted-path.js +16 -16
  36. package/dist/domain.d.ts +14 -3
  37. package/dist/domain.js +2 -3
  38. package/dist/errors.d.ts +3 -2
  39. package/dist/errors.js +12 -1
  40. package/dist/hash.d.ts +1 -0
  41. package/dist/hash.js +6 -0
  42. package/dist/index.d.ts +27 -13
  43. package/dist/index.js +16 -6
  44. package/dist/internal.d.ts +10 -13
  45. package/dist/internal.js +10 -13
  46. package/dist/judge/judge.d.ts +1 -3
  47. package/dist/judge/judge.js +9 -9
  48. package/dist/judge/prompt.d.ts +0 -1
  49. package/dist/judge/prompt.js +0 -1
  50. package/dist/judge/verdict.d.ts +0 -2
  51. package/dist/judge/verdict.js +1 -2
  52. package/dist/memory/memory.d.ts +0 -1
  53. package/dist/memory/memory.js +2 -3
  54. package/dist/net/proxied-fetch.d.ts +0 -1
  55. package/dist/net/proxied-fetch.js +2 -2
  56. package/dist/pipeline/assemble-report.d.ts +21 -0
  57. package/dist/pipeline/assemble-report.js +98 -0
  58. package/dist/pipeline/check-stage.d.ts +12 -0
  59. package/dist/pipeline/check-stage.js +69 -0
  60. package/dist/pipeline/context.d.ts +2 -2
  61. package/dist/pipeline/context.js +8 -5
  62. package/dist/pipeline/coverage.d.ts +1 -2
  63. package/dist/pipeline/coverage.js +38 -17
  64. package/dist/pipeline/execute-stage.d.ts +25 -0
  65. package/dist/pipeline/execute-stage.js +130 -0
  66. package/dist/pipeline/execute.d.ts +11 -6
  67. package/dist/pipeline/execute.js +147 -59
  68. package/dist/pipeline/filter-stage.d.ts +15 -0
  69. package/dist/pipeline/filter-stage.js +45 -0
  70. package/dist/pipeline/findings.d.ts +0 -1
  71. package/dist/pipeline/findings.js +3 -3
  72. package/dist/pipeline/imports.d.ts +1 -2
  73. package/dist/pipeline/imports.js +1 -2
  74. package/dist/pipeline/matrix.d.ts +1 -9
  75. package/dist/pipeline/matrix.js +0 -1
  76. package/dist/pipeline/options.d.ts +66 -0
  77. package/dist/pipeline/options.js +8 -0
  78. package/dist/pipeline/plan-output.d.ts +89 -0
  79. package/dist/pipeline/plan-output.js +108 -0
  80. package/dist/pipeline/plan.d.ts +3 -5
  81. package/dist/pipeline/plan.js +10 -6
  82. package/dist/pipeline/preview.d.ts +23 -10
  83. package/dist/pipeline/preview.js +25 -5
  84. package/dist/pipeline/provenance.d.ts +4 -28
  85. package/dist/pipeline/provenance.js +2 -3
  86. package/dist/pipeline/resume.d.ts +22 -0
  87. package/dist/pipeline/resume.js +24 -0
  88. package/dist/pipeline/run-id.d.ts +0 -1
  89. package/dist/pipeline/run-id.js +0 -1
  90. package/dist/pipeline/run.d.ts +2 -49
  91. package/dist/pipeline/run.js +18 -274
  92. package/dist/pipeline/task.d.ts +5 -10
  93. package/dist/pipeline/task.js +10 -8
  94. package/dist/plugin/builtin.d.ts +1 -1
  95. package/dist/plugin/builtin.js +12 -3
  96. package/dist/plugin/host.d.ts +0 -1
  97. package/dist/plugin/host.js +0 -1
  98. package/dist/plugin/registry.d.ts +5 -5
  99. package/dist/plugin/registry.js +3 -4
  100. package/dist/plugin/types.d.ts +3 -6
  101. package/dist/plugin/types.js +0 -1
  102. package/dist/{pipeline → report}/output-schema.d.ts +95 -63
  103. package/dist/{pipeline → report}/output-schema.js +64 -42
  104. package/dist/report/output.d.ts +7 -0
  105. package/dist/report/output.js +214 -0
  106. package/dist/report/provenance.d.ts +25 -0
  107. package/dist/report/provenance.js +1 -0
  108. package/dist/report/read.d.ts +2 -0
  109. package/dist/report/read.js +36 -0
  110. package/dist/{pipeline → report}/report.d.ts +27 -4
  111. package/dist/{pipeline → report}/report.js +11 -3
  112. package/dist/report/serialize.d.ts +2 -0
  113. package/dist/report/serialize.js +26 -0
  114. package/dist/rereview/presence.d.ts +0 -1
  115. package/dist/rereview/presence.js +1 -2
  116. package/dist/rereview/quote.d.ts +0 -1
  117. package/dist/rereview/quote.js +2 -3
  118. package/dist/rereview/reconcile.d.ts +1 -2
  119. package/dist/rereview/reconcile.js +0 -1
  120. package/dist/review/impact.d.ts +0 -3
  121. package/dist/review/impact.js +2 -3
  122. package/dist/review/plan-phase.d.ts +1 -3
  123. package/dist/review/plan-phase.js +2 -3
  124. package/dist/review/prompt-text.d.ts +1 -2
  125. package/dist/review/prompt-text.js +1 -2
  126. package/dist/review/prompt.d.ts +0 -4
  127. package/dist/review/prompt.js +3 -4
  128. package/dist/review/reviewer.d.ts +0 -1
  129. package/dist/review/reviewer.js +0 -1
  130. package/dist/review/reviewers/agents-md.d.ts +0 -1
  131. package/dist/review/reviewers/agents-md.js +0 -1
  132. package/dist/review/reviewers/correctness.d.ts +0 -1
  133. package/dist/review/reviewers/correctness.js +0 -1
  134. package/dist/review/reviewers/docs.d.ts +0 -1
  135. package/dist/review/reviewers/docs.js +0 -1
  136. package/dist/review/reviewers/performance.d.ts +0 -1
  137. package/dist/review/reviewers/performance.js +0 -1
  138. package/dist/review/reviewers/scopes.d.ts +0 -1
  139. package/dist/review/reviewers/scopes.js +0 -1
  140. package/dist/review/reviewers/security.d.ts +0 -1
  141. package/dist/review/reviewers/security.js +0 -1
  142. package/dist/review/tools.d.ts +0 -1
  143. package/dist/review/tools.js +0 -1
  144. package/dist/rules/builtin/general.d.ts +0 -1
  145. package/dist/rules/builtin/general.js +0 -1
  146. package/dist/rules/builtin/go.d.ts +0 -1
  147. package/dist/rules/builtin/go.js +0 -1
  148. package/dist/rules/builtin/index.d.ts +0 -5
  149. package/dist/rules/builtin/index.js +1 -3
  150. package/dist/rules/builtin/java.d.ts +0 -1
  151. package/dist/rules/builtin/java.js +0 -1
  152. package/dist/rules/builtin/performance.d.ts +0 -1
  153. package/dist/rules/builtin/performance.js +0 -1
  154. package/dist/rules/builtin/python.d.ts +0 -1
  155. package/dist/rules/builtin/python.js +0 -1
  156. package/dist/rules/builtin/security.d.ts +0 -1
  157. package/dist/rules/builtin/security.js +0 -1
  158. package/dist/rules/builtin/typescript.d.ts +0 -1
  159. package/dist/rules/builtin/typescript.js +0 -1
  160. package/dist/rules/languages.d.ts +0 -1
  161. package/dist/rules/languages.js +0 -1
  162. package/dist/rules/repo-rules.d.ts +0 -7
  163. package/dist/rules/repo-rules.js +3 -4
  164. package/dist/rules/resolve.d.ts +0 -1
  165. package/dist/rules/resolve.js +0 -1
  166. package/dist/rules/rule-set.d.ts +0 -1
  167. package/dist/rules/rule-set.js +0 -1
  168. package/dist/runtime/attempt.d.ts +15 -2
  169. package/dist/runtime/attempt.js +47 -1
  170. package/dist/runtime/chain-runner.d.ts +18 -0
  171. package/dist/runtime/chain-runner.js +62 -0
  172. package/dist/runtime/effort-capability.d.ts +13 -0
  173. package/dist/runtime/effort-capability.js +69 -0
  174. package/dist/runtime/failback.d.ts +0 -10
  175. package/dist/runtime/failback.js +52 -13
  176. package/dist/runtime/models.d.ts +1 -3
  177. package/dist/runtime/models.js +14 -13
  178. package/dist/runtime/quota.d.ts +1 -1
  179. package/dist/runtime/quota.js +3 -2
  180. package/dist/runtime/tools.d.ts +0 -17
  181. package/dist/runtime/tools.js +3 -4
  182. package/dist/sarif/candidates.d.ts +2 -2
  183. package/dist/sarif/candidates.js +0 -1
  184. package/dist/sarif/schema.d.ts +2 -3
  185. package/dist/sarif/schema.js +4 -5
  186. package/dist/select/patterns.d.ts +0 -1
  187. package/dist/select/patterns.js +0 -1
  188. package/dist/select/select.d.ts +1 -1
  189. package/dist/select/select.js +16 -3
  190. package/dist/session/jsonl.d.ts +4 -4
  191. package/dist/session/jsonl.js +14 -8
  192. package/dist/session/resume-read.d.ts +2 -0
  193. package/dist/session/resume-read.js +128 -0
  194. package/dist/session/seal.d.ts +5 -0
  195. package/dist/session/seal.js +24 -0
  196. package/dist/triage.d.ts +2 -3
  197. package/dist/triage.js +1 -2
  198. package/dist/vcs.d.ts +14 -0
  199. package/dist/vcs.js +1 -0
  200. package/dist/verify/prompt.d.ts +0 -7
  201. package/dist/verify/prompt.js +1 -2
  202. package/dist/verify/verify.d.ts +2 -4
  203. package/dist/verify/verify.js +4 -5
  204. package/package.json +1 -1
  205. package/dist/pipeline/helpers.d.ts +0 -7
  206. package/dist/pipeline/output.d.ts +0 -79
  207. package/dist/pipeline/output.js +0 -132
@@ -1,6 +1,6 @@
1
+ import { addUsage, emptyUsage } from "../agent/usage.js";
1
2
  import { CompletionError } from "../errors.js";
2
- import { addUsage, emptyUsage } from "../pipeline/usage.js";
3
- import { attemptSummary } from "./attempt.js";
3
+ import { attemptEnding, attemptRecord, attemptSummary, } from "./attempt.js";
4
4
  import { sleep } from "./quota.js";
5
5
  // Findings from a failed attempt are still emitted: the pipeline deduplicates
6
6
  // by fingerprint, so a retry on the next model cannot double-report them.
@@ -18,10 +18,13 @@ export async function* withFailback(options) {
18
18
  taskId,
19
19
  message: `${model} is rate limited; waiting ${Math.ceil(pause / 1000)}s`,
20
20
  };
21
- await sleep(pause, signal);
21
+ await pauseOver(health, model, signal);
22
22
  if (signal.aborted)
23
23
  return;
24
24
  }
25
+ // Another task may have found it out of quota since the chain was read.
26
+ if (health.isOutOfQuota(model))
27
+ break;
25
28
  yield { type: "progress", taskId, message: `reviewing with ${model}` };
26
29
  // Spend is reported while the attempt runs, so a run's spend limit
27
30
  // can stop it; the finished attempt's total settles the rest.
@@ -32,18 +35,27 @@ export async function* withFailback(options) {
32
35
  yield { type: "usage", taskId, ...live.take() };
33
36
  }
34
37
  const outcome = await running;
38
+ const ended = attemptEnding(outcome);
35
39
  yield { type: "usage", taskId, ...live.rest(outcome.usage) };
36
- yield { type: "progress", taskId, message: attemptSummary(model, outcome) };
40
+ yield {
41
+ type: "progress",
42
+ taskId,
43
+ message: attemptSummary(model, outcome),
44
+ attempt: attemptRecord(model, outcome),
45
+ };
37
46
  for (const finding of outcome.findings)
38
47
  yield { type: "finding", taskId, finding, model };
39
- // A cancelled attempt is neither finished nor the model's fault.
40
- if (signal.aborted)
41
- return;
48
+ // Ended without an error, the attempt finished even if the task was
49
+ // stopped meanwhile, as when the spend its last report added reached
50
+ // the run's limit: the pipeline decides what that stop means.
42
51
  if (!outcome.error) {
43
52
  health.recordSuccess(model);
44
- yield { type: "done", taskId };
53
+ yield doneEvent(taskId, ended);
45
54
  return;
46
55
  }
56
+ // A cancelled attempt is neither finished nor the model's fault.
57
+ if (signal.aborted)
58
+ return;
47
59
  if (!outcome.error.retryable) {
48
60
  yield {
49
61
  type: "error",
@@ -72,10 +84,15 @@ export async function* withFailback(options) {
72
84
  retryable: true,
73
85
  };
74
86
  }
87
+ function doneEvent(taskId, ended) {
88
+ return ended === "step_cap" || ended === "stopped_early"
89
+ ? { type: "done", taskId, ended }
90
+ : { type: "done", taskId };
91
+ }
75
92
  // Hands out what an attempt has spent in increments, each what grew since the
76
93
  // last one; `rest` settles the finished attempt's total, so the increments
77
94
  // add up to it and nothing is counted twice.
78
- export class LiveUsage {
95
+ class LiveUsage {
79
96
  seen = emptyUsage();
80
97
  given = emptyUsage();
81
98
  wake;
@@ -113,11 +130,21 @@ const FIELDS = [
113
130
  "cachedTokens",
114
131
  "costUsd",
115
132
  ];
133
+ // Each field of a usage from the same field of two others.
134
+ function mapUsage(a, b, combine) {
135
+ return {
136
+ inputTokens: combine(a.inputTokens, b.inputTokens),
137
+ outputTokens: combine(a.outputTokens, b.outputTokens),
138
+ reasoningTokens: combine(a.reasoningTokens, b.reasoningTokens),
139
+ cachedTokens: combine(a.cachedTokens, b.cachedTokens),
140
+ costUsd: combine(a.costUsd, b.costUsd),
141
+ };
142
+ }
116
143
  function larger(a, b) {
117
- return Object.fromEntries(FIELDS.map((f) => [f, Math.max(a[f], b[f])]));
144
+ return mapUsage(a, b, Math.max);
118
145
  }
119
146
  function beyond(a, b) {
120
- return Object.fromEntries(FIELDS.map((f) => [f, Math.max(0, a[f] - b[f])]));
147
+ return mapUsage(a, b, (x, y) => Math.max(0, x - y));
121
148
  }
122
149
  function ahead(a, b) {
123
150
  return FIELDS.some((f) => a[f] > b[f]);
@@ -131,9 +158,11 @@ export async function completeWithFailback(options) {
131
158
  let lastError = "";
132
159
  for (const model of health.order(options.chain)) {
133
160
  for (;;) {
134
- await sleep(health.pausedFor(model), signal);
161
+ await pauseOver(health, model, signal);
135
162
  if (signal.aborted)
136
163
  throw new CompletionError("cancelled", usage);
164
+ if (health.isOutOfQuota(model))
165
+ break;
137
166
  const outcome = await options.attempt(model);
138
167
  usage = addUsage(usage, outcome.usage);
139
168
  if (!outcome.error) {
@@ -157,9 +186,19 @@ export async function completeWithFailback(options) {
157
186
  }
158
187
  throw new CompletionError(`every ${chainName(options)} failed (${lastError})`, usage);
159
188
  }
189
+ // Waits until the model's pause ends as it stands on waking, not as it stood
190
+ // on falling asleep: another task's limit may have lengthened it, and a
191
+ // request sent inside it would only join it again.
192
+ async function pauseOver(health, model, signal) {
193
+ for (;;) {
194
+ const pause = health.pausedFor(model);
195
+ if (pause <= 0 || signal.aborted || health.isOutOfQuota(model))
196
+ return;
197
+ await sleep(pause, signal);
198
+ }
199
+ }
160
200
  function chainName(options) {
161
201
  return options.agent === undefined
162
202
  ? `${options.tier} model`
163
203
  : `model of ${options.agent}'s own chain`;
164
204
  }
165
- //# sourceMappingURL=failback.js.map
@@ -1,5 +1,4 @@
1
- import type { ModelTier } from "../contracts.js";
2
- import type { ModelChains } from "../plugin/types.js";
1
+ import type { ModelChains, ModelTier } from "../contracts.js";
3
2
  import { type QuotaError } from "./quota.js";
4
3
  export interface ModelRef {
5
4
  providerID: string;
@@ -30,4 +29,3 @@ export declare class ModelHealth {
30
29
  isOutOfQuota(model: string): boolean;
31
30
  recordQuota(model: string, quota: QuotaError): "wait" | "out_of_quota";
32
31
  }
33
- //# sourceMappingURL=models.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { OcraError } from "../errors.js";
2
- import { MAX_QUOTA_WAIT_MS, QUOTA_RETRIES } from "./quota.js";
2
+ import { MAX_QUOTA_WAIT_MS, QUOTA_RETRIES, UNSTATED_QUOTA_WAIT_MS, } from "./quota.js";
3
3
  export function parseModel(model) {
4
4
  const slash = model.indexOf("/");
5
5
  if (slash <= 0 || slash === model.length - 1) {
@@ -73,23 +73,24 @@ export class ModelHealth {
73
73
  isOutOfQuota(model) {
74
74
  return this.outOfQuota.has(model);
75
75
  }
76
- // A rate limit with a short, stated wait pauses the model for every task;
77
- // a daily limit, no stated wait, a long one, or too many waits in a row
78
- // mean the model is out of quota for the rest of the run.
76
+ // A rate limit with a short wait pauses the model for every task; a daily
77
+ // limit, a long stated wait, or too many waits in a row mean the model is
78
+ // out of quota for the rest of the run. Vertex AI's shared quota answers
79
+ // 429 without a wait when it is busy, so a missing wait backs off instead.
80
+ // Tasks running at once are refused together: a limit that arrives while
81
+ // the model is paused joins that pause rather than counting another wait,
82
+ // and only a wait it states can lengthen the pause.
79
83
  recordQuota(model, quota) {
84
+ const now = this.now();
80
85
  const state = this.quotas.get(model) ?? { waits: 0, pausedUntil: 0 };
81
- const wait = quota.retryAfterMs;
82
- if (quota.daily ||
83
- wait === undefined ||
84
- wait > MAX_QUOTA_WAIT_MS ||
85
- state.waits >= QUOTA_RETRIES) {
86
+ const joins = state.pausedUntil > now;
87
+ const waits = joins ? state.waits : state.waits + 1;
88
+ const wait = quota.retryAfterMs ?? (joins ? 0 : UNSTATED_QUOTA_WAIT_MS * 2 ** (waits - 1));
89
+ if (quota.daily || wait > MAX_QUOTA_WAIT_MS || waits > QUOTA_RETRIES) {
86
90
  this.outOfQuota.add(model);
87
91
  return "out_of_quota";
88
92
  }
89
- state.waits += 1;
90
- state.pausedUntil = Math.max(state.pausedUntil, this.now() + wait);
91
- this.quotas.set(model, state);
93
+ this.quotas.set(model, { waits, pausedUntil: Math.max(state.pausedUntil, now + wait) });
92
94
  return "wait";
93
95
  }
94
96
  }
95
- //# sourceMappingURL=models.js.map
@@ -3,7 +3,7 @@ export interface QuotaError {
3
3
  daily: boolean;
4
4
  }
5
5
  export declare const MAX_QUOTA_WAIT_MS = 90000;
6
+ export declare const UNSTATED_QUOTA_WAIT_MS = 15000;
6
7
  export declare const QUOTA_RETRIES = 3;
7
8
  export declare function parseQuotaError(message: string, statusCode?: number): QuotaError | undefined;
8
9
  export declare function sleep(ms: number, signal: AbortSignal): Promise<void>;
9
- //# sourceMappingURL=quota.d.ts.map
@@ -1,11 +1,13 @@
1
1
  // Longest wait for a rate limit inside a run; per-minute limits ask for less.
2
2
  export const MAX_QUOTA_WAIT_MS = 90_000;
3
+ // First wait for a rate limit that states none, doubled on each repeat.
4
+ export const UNSTATED_QUOTA_WAIT_MS = 15_000;
3
5
  // Waits per model before it counts as out of quota for the rest of the run.
4
6
  export const QUOTA_RETRIES = 3;
5
7
  const QUOTA_MESSAGE = /exceeded your current quota|quota exceeded|resource[_ ]exhausted|rate limit/i;
6
8
  const RETRY_IN = /retry in ([\d.]+)\s*(ms|s)\b/i;
7
9
  const RETRY_DELAY = /"retryDelay"\s*:\s*"([\d.]+)s"/i;
8
- const DAILY = /per ?day|daily/i;
10
+ const DAILY = /per[- ]?day|daily/i;
9
11
  export function parseQuotaError(message, statusCode) {
10
12
  if (statusCode !== 429 && !QUOTA_MESSAGE.test(message))
11
13
  return undefined;
@@ -35,4 +37,3 @@ export function sleep(ms, signal) {
35
37
  signal.addEventListener("abort", done, { once: true });
36
38
  });
37
39
  }
38
- //# sourceMappingURL=quota.js.map
@@ -1,21 +1,4 @@
1
- import { z } from "zod";
2
1
  import type { ToolDefinition } from "../plugin/types.js";
3
- export declare const MAX_READ_LINES = 400;
4
- export declare const MAX_SEARCH_RESULTS = 50;
5
2
  export declare const MAX_LINE_CHARS = 2000;
6
3
  export declare const MAX_RESULT_CHARS = 50000;
7
- export declare const reportFindingInput: z.ZodObject<{
8
- file: z.ZodString;
9
- existingCode: z.ZodString;
10
- severity: z.ZodEnum<{
11
- critical: "critical";
12
- suggestion: "suggestion";
13
- warning: "warning";
14
- }>;
15
- title: z.ZodString;
16
- body: z.ZodString;
17
- suggestion: z.ZodOptional<z.ZodString>;
18
- evidence: z.ZodOptional<z.ZodArray<z.ZodString>>;
19
- }, z.core.$strip>;
20
4
  export declare const reviewTools: readonly ToolDefinition[];
21
- //# sourceMappingURL=tools.d.ts.map
@@ -2,8 +2,8 @@ import { z } from "zod";
2
2
  import { severitySchema } from "../domain.js";
3
3
  import { data as promptData } from "../review/prompt-text.js";
4
4
  import { REVIEW_TOOLS } from "../review/tools.js";
5
- export const MAX_READ_LINES = 400;
6
- export const MAX_SEARCH_RESULTS = 50;
5
+ const MAX_READ_LINES = 400;
6
+ const MAX_SEARCH_RESULTS = 50;
7
7
  // Lines and results are also capped in characters: one line of a minified
8
8
  // bundle or a JSON fixture can be megabytes, and every step resends it.
9
9
  export const MAX_LINE_CHARS = 2_000;
@@ -23,7 +23,7 @@ function fitting(lines) {
23
23
  }
24
24
  return kept;
25
25
  }
26
- export const reportFindingInput = z.object({
26
+ const reportFindingInput = z.object({
27
27
  file: z.string().min(1).describe("Path of a file in <ocra_review_files>"),
28
28
  existingCode: z
29
29
  .string()
@@ -110,4 +110,3 @@ export const reviewTools = [
110
110
  reportFinding,
111
111
  taskDone,
112
112
  ];
113
- //# sourceMappingURL=tools.js.map
@@ -1,6 +1,6 @@
1
1
  import type { LineRange, Severity } from "../domain.js";
2
2
  import type { SarifRun } from "./schema.js";
3
- export interface SarifTool {
3
+ interface SarifTool {
4
4
  name: string;
5
5
  slug: string;
6
6
  version?: string;
@@ -24,4 +24,4 @@ export interface SarifCandidates {
24
24
  };
25
25
  }
26
26
  export declare function sarifCandidates(run: SarifRun): SarifCandidates;
27
- //# sourceMappingURL=candidates.d.ts.map
27
+ export {};
@@ -99,4 +99,3 @@ function repositoryPath(uri, base) {
99
99
  return undefined;
100
100
  return path;
101
101
  }
102
- //# sourceMappingURL=candidates.js.map
@@ -37,7 +37,7 @@ declare const result: z.ZodObject<{
37
37
  }, z.core.$loose>>;
38
38
  }, z.core.$loose>>>;
39
39
  }, z.core.$loose>;
40
- export declare const sarifRunSchema: z.ZodObject<{
40
+ declare const sarifRunSchema: z.ZodObject<{
41
41
  tool: z.ZodObject<{
42
42
  driver: z.ZodObject<{
43
43
  name: z.ZodString;
@@ -83,7 +83,7 @@ export declare const sarifRunSchema: z.ZodObject<{
83
83
  }, z.core.$loose>>>;
84
84
  }, z.core.$loose>>>;
85
85
  }, z.core.$loose>;
86
- export declare const sarifLogSchema: z.ZodObject<{
86
+ declare const sarifLogSchema: z.ZodObject<{
87
87
  version: z.ZodLiteral<"2.1.0">;
88
88
  runs: z.ZodArray<z.ZodObject<{
89
89
  tool: z.ZodObject<{
@@ -141,4 +141,3 @@ export declare class SarifError extends OcraError {
141
141
  }
142
142
  export declare function parseSarifLog(text: string): SarifLog;
143
143
  export {};
144
- //# sourceMappingURL=schema.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { OcraError } from "../errors.js";
2
+ import { errorMessage, OcraError } from "../errors.js";
3
3
  // The part of SARIF 2.1.0 an import reads. Objects are loose: a log carries
4
4
  // far more than this, and none of it is trusted beyond what is checked here.
5
5
  // https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html
@@ -34,7 +34,7 @@ const result = z.looseObject({
34
34
  message,
35
35
  locations: z.array(location).optional(),
36
36
  });
37
- export const sarifRunSchema = z.looseObject({
37
+ const sarifRunSchema = z.looseObject({
38
38
  tool: z.looseObject({
39
39
  driver: z.looseObject({
40
40
  name: z.string().min(1),
@@ -45,7 +45,7 @@ export const sarifRunSchema = z.looseObject({
45
45
  }),
46
46
  results: z.array(result).optional(),
47
47
  });
48
- export const sarifLogSchema = z.looseObject({
48
+ const sarifLogSchema = z.looseObject({
49
49
  version: z.literal("2.1.0"),
50
50
  runs: z.array(sarifRunSchema),
51
51
  });
@@ -61,11 +61,10 @@ export function parseSarifLog(text) {
61
61
  data = JSON.parse(text);
62
62
  }
63
63
  catch (error) {
64
- throw new SarifError(`not valid JSON: ${error.message}`);
64
+ throw new SarifError(`not valid JSON: ${errorMessage(error)}`);
65
65
  }
66
66
  const parsed = sarifLogSchema.safeParse(data);
67
67
  if (!parsed.success)
68
68
  throw new SarifError(`not a SARIF 2.1.0 log: ${z.prettifyError(parsed.error)}`);
69
69
  return parsed.data;
70
70
  }
71
- //# sourceMappingURL=schema.js.map
@@ -3,4 +3,3 @@ export declare const ENV_TEMPLATE_PATTERNS: string[];
3
3
  export declare const NON_REVIEWABLE_EXTENSIONS: string[];
4
4
  export declare const GENERATED_PATTERNS: string[];
5
5
  export declare const MIGRATION_PATTERNS: string[];
6
- //# sourceMappingURL=patterns.d.ts.map
@@ -129,4 +129,3 @@ export const GENERATED_PATTERNS = [
129
129
  "**/__snapshots__/**",
130
130
  ];
131
131
  export const MIGRATION_PATTERNS = ["**/migrations/**", "**/migrate/**", "**/*.migration.*"];
132
- //# sourceMappingURL=patterns.js.map
@@ -25,5 +25,5 @@ export interface SelectionPolicy {
25
25
  }
26
26
  export declare const defaultSelectionPolicy: SelectionPolicy;
27
27
  export declare function isSecretPath(path: string): boolean;
28
+ export declare function foldPath(path: string): string;
28
29
  export declare function selectFiles(diffs: readonly FileDiff[], policy?: SelectionPolicy): FileDecision[];
29
- //# sourceMappingURL=select.d.ts.map
@@ -20,8 +20,22 @@ const isSecret = picomatch(SECRET_PATTERNS, { ...globOptions, ignore: ENV_TEMPLA
20
20
  const isGenerated = picomatch(GENERATED_PATTERNS, globOptions);
21
21
  const isMigration = picomatch(MIGRATION_PATTERNS, globOptions);
22
22
  const nonReviewableExtensions = new Set(NON_REVIEWABLE_EXTENSIONS);
23
+ // The raw path is matched too: NFKC can fold a character into "/", which a
24
+ // pattern's "*" matches only in the raw path.
23
25
  export function isSecretPath(path) {
24
- return isSecret(path);
26
+ return isSecret(path) || isSecret(foldPath(path));
27
+ }
28
+ const IGNORABLE = /\p{Default_Ignorable_Code_Point}/gu;
29
+ // A case-insensitive file system opens a file under any name that folds to
30
+ // the same as its own. APFS normalizes and applies full Unicode case folding,
31
+ // so a Kelvin sign opens "k", a long s "s", "ß" "ss" and a ligature its
32
+ // letters; HFS+ also skips some invisible characters. The access policy
33
+ // compares this form, which folds the ASCII names it refuses at least as far,
34
+ // so that no spelling of such a name passes. NFKC takes the Kelvin sign, the
35
+ // long s and ligatures to ASCII; upper-casing expands "ß" (and "ẞ", once
36
+ // lower-cased), which lower-casing keeps.
37
+ export function foldPath(path) {
38
+ return path.normalize("NFKC").replace(IGNORABLE, "").toLowerCase().toUpperCase().toLowerCase();
25
39
  }
26
40
  export function selectFiles(diffs, policy = defaultSelectionPolicy) {
27
41
  const isUserExcluded = matcher(policy.exclude);
@@ -35,7 +49,7 @@ function exclusionReason(diff, policy, isUserExcluded, isUserIncluded) {
35
49
  const path = diff.newPath;
36
50
  if (diff.isBinary)
37
51
  return "binary";
38
- if (isSecret(diff.oldPath) || isSecret(path))
52
+ if (isSecretPath(diff.oldPath) || isSecretPath(path))
39
53
  return "secret";
40
54
  if (diff.kind === "deleted")
41
55
  return "deleted";
@@ -59,4 +73,3 @@ function extension(path) {
59
73
  const dot = name.lastIndexOf(".");
60
74
  return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
61
75
  }
62
- //# sourceMappingURL=select.js.map
@@ -1,10 +1,10 @@
1
- import type { ReviewEvent } from "../pipeline/report.js";
1
+ import type { ReviewEvent } from "../report/report.js";
2
2
  export declare const EVENTS_FILE = "events.jsonl";
3
3
  export declare const REPORT_FILE = "report.json";
4
4
  export declare class JsonlSessionWriter {
5
- readonly id: string;
6
5
  readonly dir: string;
7
- constructor(sessionsDir: string, id?: string);
6
+ readonly id: string;
7
+ private readonly sealKey;
8
+ constructor(sessionsDir: string, id?: string, sealKey?: string);
8
9
  write(event: ReviewEvent): void;
9
10
  }
10
- //# sourceMappingURL=jsonl.d.ts.map
@@ -1,17 +1,23 @@
1
1
  import { appendFileSync, closeSync, constants, lstatSync, mkdirSync, openSync, writeFileSync, writeSync, } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
- import { OcraError } from "../errors.js";
4
- import { serializeOutput, toReportOutput } from "../pipeline/output.js";
3
+ import { isNotFound, OcraError } from "../errors.js";
5
4
  import { newRunId } from "../pipeline/run-id.js";
5
+ import { toReportOutput } from "../report/output.js";
6
+ import { serializeOutput } from "../report/serialize.js";
7
+ import { sealLine } from "./seal.js";
6
8
  export const EVENTS_FILE = "events.jsonl";
7
9
  export const REPORT_FILE = "report.json";
8
10
  // Events are appended synchronously, one JSON object per line, so the log
9
- // stays valid and ordered even if the process dies mid-run.
11
+ // stays valid and ordered even if the process dies mid-run. With a seal key
12
+ // (this machine's, seal.ts), each line is sealed so that --resume can tell
13
+ // it from a line a change brought into the tree.
10
14
  export class JsonlSessionWriter {
11
- id;
12
15
  dir;
13
- constructor(sessionsDir, id = newRunId()) {
16
+ id;
17
+ sealKey;
18
+ constructor(sessionsDir, id = newRunId(), sealKey) {
14
19
  this.id = id;
20
+ this.sealKey = sealKey;
15
21
  // The sessions directory lives in the reviewed tree, which may carry
16
22
  // links planted to send the logs, or the .gitignore write, elsewhere.
17
23
  for (const dir of [dirname(sessionsDir), sessionsDir])
@@ -29,7 +35,8 @@ export class JsonlSessionWriter {
29
35
  }
30
36
  }
31
37
  write(event) {
32
- const line = serializeOutput({ time: new Date().toISOString(), ...event }, 0);
38
+ const serialized = serializeOutput({ time: new Date().toISOString(), ...event }, 0);
39
+ const line = this.sealKey ? sealLine(this.sealKey, this.id, serialized) : serialized;
33
40
  appendFileSync(join(this.dir, EVENTS_FILE), `${line}\n`);
34
41
  if (event.type === "run_finished") {
35
42
  const report = toReportOutput(event.report);
@@ -44,8 +51,7 @@ function refuseSymlink(path) {
44
51
  }
45
52
  }
46
53
  catch (error) {
47
- if (error.code !== "ENOENT")
54
+ if (!isNotFound(error))
48
55
  throw error;
49
56
  }
50
57
  }
51
- //# sourceMappingURL=jsonl.js.map
@@ -0,0 +1,2 @@
1
+ import type { ResumedRun } from "../pipeline/resume.js";
2
+ export declare function readResumedRun(sessionsDir: string, runId: string, sealKey: string, warn?: (message: string) => void): Promise<ResumedRun>;
@@ -0,0 +1,128 @@
1
+ import { lstat } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { readBoundedFile } from "../bounded-file.js";
5
+ import { reportedFindingSchema } from "../domain.js";
6
+ import { errorMessage, OcraError } from "../errors.js";
7
+ import { boundFinding, MAX_FINDINGS_PER_TASK } from "../pipeline/task.js";
8
+ import { taskOutcomeSchema } from "../report/output-schema.js";
9
+ import { EVENTS_FILE } from "./jsonl.js";
10
+ import { unsealLine } from "./seal.js";
11
+ // A session log is bounded by the run's task and finding limits; anything
12
+ // far larger was not written by ocra.
13
+ const MAX_EVENTS_BYTES = 64 * 1024 * 1024;
14
+ const RUN_ID = /^[\w@-][\w.@-]*$/;
15
+ const reportedEventSchema = z.object({
16
+ type: z.literal("task_reported"),
17
+ taskId: z.string(),
18
+ key: z.string(),
19
+ findings: z.array(z.object({ reported: reportedFindingSchema, model: z.string().exactOptional() })),
20
+ });
21
+ const finishedEventSchema = z.object({
22
+ type: z.literal("task_finished"),
23
+ outcome: taskOutcomeSchema,
24
+ });
25
+ const bundledEventSchema = z.object({
26
+ type: z.literal("files_bundled"),
27
+ groups: z.array(z.object({ label: z.string(), files: z.array(z.string()) })),
28
+ });
29
+ // The completed tasks of an earlier run, from its session log, which a run
30
+ // killed before it finished still has. The session lives in the reviewed
31
+ // tree, where a change can bring one of its own: only lines sealed with this
32
+ // machine's key (seal.ts) are read, the rest is skipped and counted, and a
33
+ // log with no such line is refused. Sealed lines are still validated and
34
+ // bounded like a model's answer. The bundles come from the log too; report.json
35
+ // carries no seal.
36
+ export async function readResumedRun(sessionsDir, runId, sealKey, warn = () => { }) {
37
+ if (!RUN_ID.test(runId)) {
38
+ throw new OcraError("INPUT_INVALID", `--resume: ${JSON.stringify(runId)} is not a run id`);
39
+ }
40
+ const dir = join(sessionsDir, runId);
41
+ for (const path of [dirname(sessionsDir), sessionsDir, dir])
42
+ await refuseLink(path, runId);
43
+ const text = await readEvents(join(dir, EVENTS_FILE), runId);
44
+ const reported = new Map();
45
+ let groups = [];
46
+ const finished = new Map();
47
+ let sealed = 0;
48
+ let unsealed = 0;
49
+ for (const raw of text.split("\n")) {
50
+ if (!raw.trim())
51
+ continue;
52
+ const line = unsealLine(sealKey, runId, raw);
53
+ if (line === undefined) {
54
+ unsealed += 1;
55
+ continue;
56
+ }
57
+ sealed += 1;
58
+ let data;
59
+ try {
60
+ data = JSON.parse(line);
61
+ }
62
+ catch {
63
+ continue;
64
+ }
65
+ const r = reportedEventSchema.safeParse(data);
66
+ if (r.success)
67
+ reported.set(r.data.taskId, r.data);
68
+ const f = finishedEventSchema.safeParse(data);
69
+ if (f.success)
70
+ finished.set(f.data.outcome.taskId, f.data.outcome);
71
+ const b = bundledEventSchema.safeParse(data);
72
+ if (b.success)
73
+ groups = b.data.groups;
74
+ }
75
+ if (sealed === 0) {
76
+ throw new OcraError("INPUT_INVALID", `--resume: the session of ${runId} was not written by ocra on this machine, so none of it is reused`);
77
+ }
78
+ if (unsealed > 0) {
79
+ warn(`--resume: ignored ${unsealed} line(s) of the session of ${runId} that ocra on this machine did not write`);
80
+ }
81
+ const tasks = [];
82
+ for (const [taskId, outcome] of finished) {
83
+ const event = reported.get(taskId);
84
+ if (!event || !reusable(outcome))
85
+ continue;
86
+ tasks.push({ key: event.key, outcome, findings: bounded(event.findings) });
87
+ }
88
+ return { runId, bundles: groups, tasks };
89
+ }
90
+ // Only a task that finished its review, with a plausible outcome: one cut
91
+ // off before it finished is reviewed again (ADR-0030).
92
+ function reusable(outcome) {
93
+ const { usage } = outcome;
94
+ return (outcome.status === "completed" &&
95
+ outcome.ended === undefined &&
96
+ (outcome.reusedFrom === undefined || RUN_ID.test(outcome.reusedFrom)) &&
97
+ outcome.durationMs >= 0 &&
98
+ Object.values(usage).every((n) => Number.isFinite(n) && n >= 0));
99
+ }
100
+ // The same bounds a live task's findings get, so a session written by hand
101
+ // cannot bring in more or longer findings than a model could.
102
+ function bounded(findings) {
103
+ return findings.slice(0, MAX_FINDINGS_PER_TASK).map(({ reported, model }) => ({
104
+ reported: boundFinding(reported),
105
+ ...(model === undefined ? {} : { model }),
106
+ }));
107
+ }
108
+ async function readEvents(path, runId) {
109
+ try {
110
+ return await readBoundedFile(path, { maxBytes: MAX_EVENTS_BYTES, followLinks: false });
111
+ }
112
+ catch (error) {
113
+ if (error instanceof OcraError) {
114
+ throw new OcraError(error.code, `--resume: the session log of ${runId}: ${error.message}`, {
115
+ cause: error,
116
+ });
117
+ }
118
+ throw new OcraError("INPUT_INVALID", `--resume: no session log for run ${runId}: ${errorMessage(error)}`, { cause: error });
119
+ }
120
+ }
121
+ // Like the writer, follow no link planted in the reviewed tree to make
122
+ // another directory read as this run's.
123
+ async function refuseLink(path, runId) {
124
+ const info = await lstat(path).catch(() => undefined);
125
+ if (info?.isSymbolicLink()) {
126
+ throw new OcraError("ACCESS_DENIED", `--resume: the session of ${runId} is reached through the symbolic link ${path}`);
127
+ }
128
+ }
@@ -0,0 +1,5 @@
1
+ export declare const SEAL_KEY: RegExp;
2
+ /** The serialized JSON object with its seal as a last field. */
3
+ export declare function sealLine(key: string, runId: string, line: string): string;
4
+ /** The line as it was before sealing; undefined unless key sealed it for this run. */
5
+ export declare function unsealLine(key: string, runId: string, sealed: string): string | undefined;
@@ -0,0 +1,24 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ // A session log lives in the reviewed tree, where a change can bring one of
3
+ // its own. Every line ocra writes ends with a seal: the HMAC of the run id and
4
+ // the line, keyed by a secret of this machine's user kept outside every
5
+ // repository. Only lines it sealed are read back as earlier results (--resume,
6
+ // ADR-0031). The seal is appended to the serialized line as its last field,
7
+ // so the bytes it covers need no canonical form and the line stays JSON.
8
+ export const SEAL_KEY = /^[0-9a-f]{64}$/;
9
+ const SEALED = /,"seal":"([0-9a-f]{64})"\}$/;
10
+ /** The serialized JSON object with its seal as a last field. */
11
+ export function sealLine(key, runId, line) {
12
+ return `${line.slice(0, -1)},"seal":"${mac(key, runId, line).toString("hex")}"}`;
13
+ }
14
+ /** The line as it was before sealing; undefined unless key sealed it for this run. */
15
+ export function unsealLine(key, runId, sealed) {
16
+ const match = SEALED.exec(sealed);
17
+ if (!match?.[1])
18
+ return undefined;
19
+ const line = `${sealed.slice(0, match.index)}}`;
20
+ return timingSafeEqual(Buffer.from(match[1], "hex"), mac(key, runId, line)) ? line : undefined;
21
+ }
22
+ function mac(key, runId, line) {
23
+ return createHmac("sha256", Buffer.from(key, "hex")).update(`${runId}\n${line}`).digest();
24
+ }
package/dist/triage.d.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  import type { FileDiff, RiskTier } from "./domain.js";
2
- export interface TriagePolicy {
2
+ interface TriagePolicy {
3
3
  trivialMaxLines: number;
4
4
  liteMaxLines: number;
5
5
  maxFilesBeforeFull: number;
6
6
  sensitivePathPatterns: RegExp[];
7
7
  sensitivePathWords: ReadonlySet<string>;
8
8
  }
9
- export declare const defaultTriagePolicy: TriagePolicy;
10
9
  export declare function triage(diffs: readonly FileDiff[], policy?: TriagePolicy): RiskTier;
11
- //# sourceMappingURL=triage.d.ts.map
10
+ export {};