@llm4ts/flow 0.9.1 → 0.11.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.
package/src/Context.ts ADDED
@@ -0,0 +1,207 @@
1
+ import * as Context from "effect/Context"
2
+ import * as Effect from "effect/Effect"
3
+ import * as Ref from "effect/Ref"
4
+ import { FlowLlmError, type FlowError } from "./FlowError.ts"
5
+ import { FlowEvents, Info } from "./FlowEvents.ts"
6
+ import { isContextOverflow, isContextOverflowMessage } from "./TransientRetry.ts"
7
+
8
+ // Context budgeting for LLM prompts: bound what a call ships, and make every
9
+ // truncation visible. Budgets are in CHARACTERS, not tokens — deterministic, no
10
+ // tokenizer dependency. Rule of thumb ~3.5 chars/token for code, so the 400k
11
+ // default is ~115k tokens: conservative against every provider.
12
+
13
+ const marker = "\n\n… [truncated] …\n\n"
14
+
15
+ export interface CappedText {
16
+ readonly text: string
17
+ readonly originalChars: number
18
+ readonly truncated: boolean
19
+ }
20
+
21
+ /**
22
+ * Bound `text` to `limit` characters — the result is NEVER longer than `limit`,
23
+ * marker included. Keeps the head (3/4 of the remaining room) and the tail (1/4)
24
+ * so both the entry points and the trailing rules survive; the middle is where
25
+ * boilerplate lives. For `limit <= 0` the closest achievable result is the
26
+ * empty string, since length can't go negative.
27
+ */
28
+ export const cap = (text: string, limit: number): CappedText => {
29
+ if (text.length <= limit) {
30
+ return { text, originalChars: text.length, truncated: false }
31
+ }
32
+ if (limit <= marker.length) {
33
+ return { text: text.slice(0, Math.max(limit, 0)), originalChars: text.length, truncated: true }
34
+ }
35
+ const room = limit - marker.length
36
+ const head = Math.floor((room * 3) / 4)
37
+ const tail = room - head
38
+ return {
39
+ text: `${text.slice(0, head)}${marker}${text.slice(text.length - tail)}`,
40
+ originalChars: text.length,
41
+ truncated: true
42
+ }
43
+ }
44
+
45
+ export const defaultContextBudget = 400_000
46
+
47
+ /**
48
+ * The default character budget: `LLM4TS_CONTEXT_BUDGET`, else the deprecated
49
+ * `LLM4TS_JUDGE_SOURCES_LIMIT`, else 400_000.
50
+ */
51
+ export const budget = (
52
+ environment: Readonly<Record<string, string | undefined>> = process.env
53
+ ): number => {
54
+ const raw = environment["LLM4TS_CONTEXT_BUDGET"] ?? environment["LLM4TS_JUDGE_SOURCES_LIMIT"]
55
+ if (raw === undefined) {
56
+ return defaultContextBudget
57
+ }
58
+ const parsed = Number.parseInt(raw.trim(), 10)
59
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : defaultContextBudget
60
+ }
61
+
62
+ /**
63
+ * Which kind of shrinking produced a truncation — the two are NOT
64
+ * interchangeable. "capped" numbers are literal character counts of shortened
65
+ * text; "shrunk" numbers are attempted budget CEILINGS after an oversized
66
+ * prompt failed. Conflating them would misreport how much content a
67
+ * clean-room audit actually lost.
68
+ */
69
+ export type TruncationKind = "capped" | "shrunk"
70
+
71
+ export interface Truncation {
72
+ readonly label: string
73
+ readonly originalChars: number
74
+ readonly keptChars: number
75
+ readonly kind: TruncationKind
76
+ }
77
+
78
+ export const renderTruncation = (truncation: Truncation): string =>
79
+ truncation.kind === "capped"
80
+ ? `${truncation.label}: truncated ${truncation.originalChars} → ${truncation.keptChars} chars`
81
+ : `${truncation.label}: retried at a lower budget, ${truncation.originalChars} → ${truncation.keptChars} chars (ceilings, not text size)`
82
+
83
+ // The ambient truncation log, written only by `capped` and `withShrink` so no
84
+ // call site can truncate without recording. The Reference default is a single
85
+ // process-wide cell; `isolateTruncations` scopes a fresh one so concurrent
86
+ // flows don't cross-contaminate and a phase reads back exactly what its own
87
+ // calls truncated.
88
+ const CurrentTruncations = Context.Reference<Ref.Ref<ReadonlyArray<Truncation>>>(
89
+ "@llm4ts/flow/Context/CurrentTruncations",
90
+ { defaultValue: () => Ref.makeUnsafe<ReadonlyArray<Truncation>>([]) }
91
+ )
92
+
93
+ const record = (truncation: Truncation): Effect.Effect<void> =>
94
+ Effect.flatMap(Effect.service(CurrentTruncations), (log) =>
95
+ Ref.update(log, (recorded) => [...recorded, truncation])
96
+ )
97
+
98
+ /** Truncations recorded so far. Phases write these into `provenance.json`. */
99
+ export const truncations: Effect.Effect<ReadonlyArray<Truncation>> = Effect.flatMap(
100
+ Effect.service(CurrentTruncations),
101
+ Ref.get
102
+ )
103
+
104
+ /** Run `effect` against a fresh, private truncation log. */
105
+ export const isolateTruncations = <A, E, R>(
106
+ effect: Effect.Effect<A, E, R>
107
+ ): Effect.Effect<A, E, R> =>
108
+ Effect.flatMap(Ref.make<ReadonlyArray<Truncation>>([]), (fresh) =>
109
+ Effect.provideService(effect, CurrentTruncations, fresh)
110
+ )
111
+
112
+ /**
113
+ * `cap`, publishing a `FlowEvent` and recording the truncation when one
114
+ * happens. `label` names what was shortened, so the event and the provenance
115
+ * entry are readable ("specs", "branch diff", "judge context").
116
+ */
117
+ export const capped = Effect.fn("@llm4ts/flow/Context.capped")(function* (
118
+ label: string,
119
+ text: string,
120
+ limit: number
121
+ ): Effect.fn.Return<string, never, FlowEvents> {
122
+ const out = cap(text, limit)
123
+ if (!out.truncated) {
124
+ return out.text
125
+ }
126
+ const events = yield* FlowEvents
127
+ yield* events.publish(
128
+ Info.make({
129
+ message: `⚠ context: ${label} truncated ${out.originalChars} → ${out.text.length} chars`
130
+ })
131
+ )
132
+ yield* record({
133
+ label,
134
+ originalChars: out.originalChars,
135
+ keptChars: out.text.length,
136
+ kind: "capped"
137
+ })
138
+ return out.text
139
+ })
140
+
141
+ // True for the two failure classes a smaller prompt can fix: a deterministic
142
+ // context overflow, and the empty response gemini returns when a prompt is too
143
+ // large for it to even start. The overflow check delegates to TransientRetry's
144
+ // phrasing list so a message-only failure (no surviving typed LlmError) is
145
+ // still caught — a second, shorter copy here would drift.
146
+ const shrinkable = (error: FlowError): boolean =>
147
+ error._tag === "Llm" &&
148
+ ((error.cause !== undefined && isContextOverflow(error.cause)) ||
149
+ isContextOverflowMessage(error.message) ||
150
+ error.message.toLowerCase().includes("empty response"))
151
+
152
+ export interface WithShrinkOptions {
153
+ readonly start?: number
154
+ readonly environment?: Readonly<Record<string, string | undefined>>
155
+ }
156
+
157
+ /**
158
+ * Run `f` at `start` characters (default: `budget()`); on a shrinkable failure
159
+ * retry at 1/2, then 1/4, then give up. Repeating the same oversized prompt
160
+ * cannot succeed, so shrinking is the only retry that makes sense for this
161
+ * failure class — which is why context overflow is deliberately excluded from
162
+ * `TransientRetry`'s budget. Each shrink publishes a `FlowEvent` and is
163
+ * recorded like any other truncation. The terminal failure deliberately drops
164
+ * the typed cause: a resume layer classifying an "empty response" cause as
165
+ * flaky would replay this exact, permanently-failing budget sequence forever.
166
+ */
167
+ export const withShrink = <A, E extends FlowError, R>(
168
+ label: string,
169
+ f: (chars: number) => Effect.Effect<A, E, R>,
170
+ options: WithShrinkOptions = {}
171
+ ): Effect.Effect<A, E | FlowLlmError, R | FlowEvents> => {
172
+ const start = options.start ?? budget(options.environment)
173
+ const attempt = (
174
+ atChars: number,
175
+ rest: ReadonlyArray<number>
176
+ ): Effect.Effect<A, E | FlowLlmError, R | FlowEvents> =>
177
+ Effect.catchIf(
178
+ f(atChars),
179
+ () => true,
180
+ (error): Effect.Effect<A, E | FlowLlmError, R | FlowEvents> => {
181
+ if (!shrinkable(error)) {
182
+ return Effect.fail(error)
183
+ }
184
+ if (rest.length === 0) {
185
+ return Effect.fail(
186
+ FlowLlmError.make({
187
+ message:
188
+ `${label} exceeded the model's input limit even after shrinking to ${atChars} chars — ` +
189
+ `lower LLM4TS_CONTEXT_BUDGET or scope this phase further (cause: ${error.message})`
190
+ })
191
+ )
192
+ }
193
+ const [next, ...remaining] = rest
194
+ return Effect.gen(function* () {
195
+ const events = yield* FlowEvents
196
+ yield* events.publish(
197
+ Info.make({
198
+ message: `⚠ context: ${label} did not fit at ${atChars} chars — shrinking to ${next}: ${error.message}`
199
+ })
200
+ )
201
+ yield* record({ label, originalChars: atChars, keptChars: next, kind: "shrunk" })
202
+ return yield* attempt(next, remaining)
203
+ })
204
+ }
205
+ )
206
+ return attempt(start, [Math.floor(start / 2), Math.floor(start / 4)])
207
+ }
package/src/GitTool.ts CHANGED
@@ -29,6 +29,11 @@ export interface GitToolShape {
29
29
  readonly diffAll: Effect.Effect<string, FlowError>
30
30
  readonly defaultBase: Effect.Effect<string, FlowError>
31
31
  readonly diffVsBase: (base: string, threeDot?: boolean) => Effect.Effect<string, FlowError>
32
+ readonly diffVsBaseScoped: (
33
+ base: string,
34
+ paths: ReadonlyArray<string>,
35
+ threeDot?: boolean
36
+ ) => Effect.Effect<string, FlowError>
32
37
  readonly changedFilesVsBase: (
33
38
  base: string,
34
39
  threeDot?: boolean
@@ -206,6 +211,22 @@ export const makeGitTool = (
206
211
  defaultBase: read("git defaultBase", defaultBaseEffect),
207
212
  diffVsBase: (base, threeDot = true) =>
208
213
  read("git diffVsBase", runOrFail(["diff", `${base}${threeDot ? "..." : ".."}HEAD`])),
214
+ // Diff vs base restricted to paths — the per-program / per-lens scoping
215
+ // primitive. An EMPTY paths list returns the empty string rather than the
216
+ // whole diff: bare `git diff <range> --` means "everything", which would
217
+ // silently defeat every caller that scopes by a computed, possibly-empty
218
+ // file set. The empty check lives INSIDE read(...), not before it — a
219
+ // pre-guard early return would let diffVsBaseScoped(base, []) silently
220
+ // succeed under grants that deny GitRead, with no CapabilityDenied audit.
221
+ diffVsBaseScoped: (base, paths, threeDot = true) =>
222
+ read(
223
+ "git diffVsBase (scoped)",
224
+ Effect.suspend(() =>
225
+ paths.length === 0
226
+ ? Effect.succeed("")
227
+ : runOrFail(["diff", `${base}${threeDot ? "..." : ".."}HEAD`, "--", ...paths])
228
+ )
229
+ ),
209
230
  changedFilesVsBase: (base, threeDot = true) =>
210
231
  read(
211
232
  "git changedFilesVsBase",
package/src/Pack.ts CHANGED
@@ -33,9 +33,17 @@ export interface Pack {
33
33
  readonly prompts: Readonly<Record<string, string>>
34
34
  readonly lenses: ReadonlyArray<Reviewer>
35
35
  readonly lessons: string | undefined
36
+ // Regex template locating a program's TARGET implementation files (relative
37
+ // paths), `<NAME>` substituted with the program name. The seam that makes
38
+ // per-program judging possible.
39
+ readonly programFiles: string | undefined
36
40
  readonly dir: string
37
41
  readonly gate: (name: string) => ReadonlyArray<string> | undefined
38
42
  readonly prompt: (name: string) => string | undefined
43
+ // The regex for `program`'s implementation files: the `programFiles:`
44
+ // template with `<NAME>` substituted, or a case-insensitive "path contains
45
+ // the program name" fallback.
46
+ readonly filesFor: (program: string) => RegExp
39
47
  }
40
48
 
41
49
  interface ParsedManifest {
@@ -134,6 +142,17 @@ const dimensions = (body: string | undefined): ReadonlyArray<Dimension> =>
134
142
  : [Dimension.make({ name, rubric, maxScore })]
135
143
  })
136
144
 
145
+ const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
146
+
147
+ const isValidRegExp = (source: string): boolean => {
148
+ try {
149
+ new RegExp(source)
150
+ return true
151
+ } catch {
152
+ return false
153
+ }
154
+ }
155
+
137
156
  const markdownSidecars = Effect.fn("@llm4ts/flow/Pack.markdownSidecars")(function* (
138
157
  workspace: WorkspaceShape,
139
158
  directory: string
@@ -173,6 +192,16 @@ export const loadPack = Effect.fn("@llm4ts/flow/Pack.load")(function* (
173
192
  .sort(([left], [right]) => left.localeCompare(right))
174
193
  .map(([name, text]) => parseReviewer(name, text))
175
194
  const fields = manifest.fields
195
+ const programFiles = fields["programFiles"]
196
+ // Validated at load so a mis-typed template fails the pack, not a later
197
+ // phase; substitution cannot introduce invalid syntax because the fallback
198
+ // probe uses an alphanumeric stand-in and real substitutions are escaped
199
+ // only in the no-template fallback, mirroring the reference behavior.
200
+ if (programFiles !== undefined && !isValidRegExp(programFiles.replaceAll("<NAME>", "PROBE"))) {
201
+ return yield* PlanParseError.make({
202
+ message: `pack manifest 'programFiles:' is not a valid regex template: ${programFiles}`
203
+ })
204
+ }
176
205
  const pack: Pack = {
177
206
  name: manifest.name,
178
207
  source: fields.source ?? "",
@@ -198,9 +227,16 @@ export const loadPack = Effect.fn("@llm4ts/flow/Pack.load")(function* (
198
227
  prompts,
199
228
  lenses,
200
229
  lessons: lessons === undefined || lessons.length === 0 ? undefined : lessons,
230
+ programFiles,
201
231
  dir: directory,
202
232
  gate: (name) => gates[name],
203
- prompt: (name) => prompts[name]
233
+ prompt: (name) => prompts[name],
234
+ // The template is anchored to the whole path (the reference full-matches);
235
+ // the fallback is a deliberate substring "path contains the name" match.
236
+ filesFor: (program) =>
237
+ programFiles === undefined
238
+ ? new RegExp(escapeRegExp(program), "i")
239
+ : new RegExp(`^(?:${programFiles.replaceAll("<NAME>", program)})$`)
204
240
  }
205
241
  return pack
206
242
  })
@@ -0,0 +1,186 @@
1
+ import * as Effect from "effect/Effect"
2
+ import { Sample, type Dimension, type EvalResult } from "@llm4ts/core/eval/Eval"
3
+ import type { Evaluator } from "@llm4ts/core/eval/Evaluator"
4
+ import { capped, withShrink } from "./Context.ts"
5
+ import { FlowLlmError, type FlowError } from "./FlowError.ts"
6
+ import { FlowEvents, Info } from "./FlowEvents.ts"
7
+ import type { GitToolShape } from "./GitTool.ts"
8
+ import type { Pack } from "./Pack.ts"
9
+ import type { PlainFileStoreShape } from "./Persistence.ts"
10
+ import { ReviewIssue, ReviewResult, mergeReviewResults } from "./Review.ts"
11
+ import { cachedReview } from "./ReviewCache.ts"
12
+
13
+ // Per-program spec-compliance judging, shared by the implement and review
14
+ // phases. A whole-branch judge call carries every spec and every diff hunk in
15
+ // the estate, which is what blows a provider's input window. Judging one
16
+ // program at a time against only that program's slice of the diff keeps each
17
+ // call small, and — wrapped in the review cache — makes the gate resumable: an
18
+ // unchanged program reuses its stored verdict with no LLM call.
19
+
20
+ export interface GroupedFiles {
21
+ readonly byProgram: Readonly<Record<string, ReadonlyArray<string>>>
22
+ readonly unassigned: ReadonlyArray<string>
23
+ }
24
+
25
+ /**
26
+ * Partition `changed` by which program's file regex matches. A file matching
27
+ * several programs is judged with each of them (a shared bridge class is
28
+ * genuinely part of both). The remainder — build files, shared utilities — is
29
+ * returned separately for the unassigned pass.
30
+ */
31
+ export const groupFiles = (
32
+ pack: Pack,
33
+ programs: ReadonlyArray<string>,
34
+ changed: ReadonlyArray<string>
35
+ ): GroupedFiles => {
36
+ const byProgram = Object.fromEntries(
37
+ programs.map((program) => {
38
+ const matches = pack.filesFor(program)
39
+ return [program, changed.filter((file) => matches.test(file))] as const
40
+ })
41
+ )
42
+ const assigned = new Set(Object.values(byProgram).flat())
43
+ return {
44
+ byProgram,
45
+ unassigned: changed.filter((file) => !assigned.has(file))
46
+ }
47
+ }
48
+
49
+ export interface ProgramJudgeOptions {
50
+ readonly pack: Pack
51
+ readonly judge: Evaluator<Sample>
52
+ readonly dimensions: ReadonlyArray<Dimension>
53
+ readonly git: GitToolShape
54
+ readonly files: PlainFileStoreShape
55
+ /** Directory holding the per-program verdict cache (`<gateDir>/<NAME>.json`). */
56
+ readonly gateDir: string
57
+ readonly base: string
58
+ readonly programs: ReadonlyArray<string>
59
+ /** A program's spec text; the caller owns where specs live. */
60
+ readonly specFor: (program: string) => Effect.Effect<string, FlowError>
61
+ readonly query: string
62
+ /** Content fingerprint for the verdict cache (hashing lives outside flow). */
63
+ readonly fingerprint: (...parts: ReadonlyArray<string>) => string
64
+ }
65
+
66
+ const join = (root: string, path: string): string =>
67
+ `${root.replace(/[\\/]+$/, "")}/${path.replace(/^[\\/]+/, "")}`
68
+
69
+ const rubricText = (dimensions: ReadonlyArray<Dimension>): string =>
70
+ dimensions
71
+ .map((dimension) => `${dimension.name} (0..${dimension.maxScore}): ${dimension.rubric}`)
72
+ .join("\n")
73
+
74
+ /**
75
+ * Sub-bar dimensions as Critical review issues, titled with the program they
76
+ * belong to — the same shape the extract gate produces, so fix loops and
77
+ * `ReviewResult.isClean` work unchanged.
78
+ */
79
+ const issues = (
80
+ scored: EvalResult,
81
+ dimensions: ReadonlyArray<Dimension>,
82
+ program: string
83
+ ): ReviewResult => {
84
+ const subBar = scored.scores.filter(
85
+ (score) =>
86
+ score.score < (dimensions.find((dimension) => dimension.name === score.name)?.maxScore ?? 2)
87
+ )
88
+ return ReviewResult.make({
89
+ issues: subBar.map((score) =>
90
+ ReviewIssue.make({
91
+ severity: "Critical",
92
+ title: `judge[${program}]: ${score.name} scored ${score.score}`,
93
+ description: score.reasoning
94
+ })
95
+ ),
96
+ summary: `judge:${program}`
97
+ })
98
+ }
99
+
100
+ /**
101
+ * A spec'd program with NO matching changed file is a deterministic gate
102
+ * failure, not a silent pass. Skipping it would let the branch clear a bar the
103
+ * old whole-branch judge would have failed. It also surfaces a mis-set
104
+ * `programFiles:` immediately — the top documented risk of the per-program
105
+ * design — instead of quietly degrading coverage.
106
+ */
107
+ export const unimplemented = (programs: ReadonlyArray<string>): ReviewResult =>
108
+ ReviewResult.make({
109
+ issues: programs.map((program) =>
110
+ ReviewIssue.make({
111
+ severity: "Critical",
112
+ title: `judge[${program}]: spec'd but no implementation files changed`,
113
+ description:
114
+ `${program} has a committed spec but no file on this branch matches the pack's ` +
115
+ "programFiles regex for it. Either the program is unimplemented, or the pack's " +
116
+ "`programFiles:` template does not match this repo's layout — check that before " +
117
+ "assuming the former."
118
+ })
119
+ ),
120
+ summary: "judge:unimplemented"
121
+ })
122
+
123
+ const judgeSlice = Effect.fn("@llm4ts/flow/ProgramJudge.judgeSlice")(function* (
124
+ options: ProgramJudgeOptions,
125
+ label: string,
126
+ spec: string,
127
+ diff: string
128
+ ): Effect.fn.Return<ReviewResult, FlowError, FlowEvents> {
129
+ const events = yield* FlowEvents
130
+ const rubric = rubricText(options.dimensions)
131
+ return yield* cachedReview(
132
+ options.files,
133
+ join(options.gateDir, `${label}.json`),
134
+ options.fingerprint(spec, diff, rubric),
135
+ events.publish(Info.make({ message: `judging ${label}` })).pipe(
136
+ Effect.andThen(
137
+ withShrink(`judge[${label}]`, (cap) =>
138
+ Effect.gen(function* () {
139
+ const cappedSpec = yield* capped(`spec[${label}]`, spec, cap)
140
+ const cappedDiff = yield* capped(`diff[${label}]`, diff, cap)
141
+ return yield* options.judge
142
+ .evaluate(
143
+ Sample.make({ response: cappedDiff, context: cappedSpec, query: options.query })
144
+ )
145
+ .pipe(Effect.mapError(FlowLlmError.from))
146
+ })
147
+ )
148
+ ),
149
+ Effect.map((scored) => issues(scored, options.dimensions, label))
150
+ )
151
+ )
152
+ })
153
+
154
+ /**
155
+ * Judge every program whose files changed, plus one pass over the unassigned
156
+ * remainder. Each verdict is cached at `gateDir/<NAME>.json`, fingerprinted
157
+ * over the spec, the diff slice, and the rubric it judged — so re-running
158
+ * after a crash re-judges only what changed.
159
+ */
160
+ export const judgeAllPrograms = Effect.fn("@llm4ts/flow/ProgramJudge.judgeAll")(function* (
161
+ options: ProgramJudgeOptions
162
+ ): Effect.fn.Return<ReviewResult, FlowError, FlowEvents> {
163
+ const changed = yield* options.git.changedFilesVsBase(options.base)
164
+ const { byProgram, unassigned } = groupFiles(options.pack, options.programs, changed)
165
+ const active = options.programs.filter((program) => (byProgram[program] ?? []).length > 0)
166
+ const untouched = options.programs.filter((program) => (byProgram[program] ?? []).length === 0)
167
+
168
+ const perProgram: Array<ReviewResult> = []
169
+ for (const program of active) {
170
+ const spec = yield* options.specFor(program)
171
+ // The file slice comes from groupFiles — re-deriving it per program would
172
+ // be N+1 git invocations for the same answer.
173
+ const diff = yield* options.git.diffVsBaseScoped(options.base, byProgram[program] ?? [])
174
+ perProgram.push(yield* judgeSlice(options, program, spec, diff))
175
+ }
176
+
177
+ if (unassigned.length > 0) {
178
+ const diff = yield* options.git.diffVsBaseScoped(options.base, unassigned)
179
+ const specs = yield* Effect.forEach(options.programs, options.specFor).pipe(
180
+ Effect.map((all) => all.join("\n\n"))
181
+ )
182
+ perProgram.push(yield* judgeSlice(options, "unassigned", specs, diff))
183
+ }
184
+
185
+ return mergeReviewResults([...perProgram, unimplemented(untouched)])
186
+ })
package/src/Provenance.ts CHANGED
@@ -13,7 +13,16 @@ export class Provenance extends Schema.Class<Provenance>("Provenance")({
13
13
  specs: Schema.Record(Schema.String, Schema.String),
14
14
  gateVerdicts: Schema.Record(Schema.String, Schema.String),
15
15
  equivalenceReport: Schema.optionalKey(Schema.String),
16
- fixSpecs: Schema.Array(Schema.String)
16
+ fixSpecs: Schema.Array(Schema.String),
17
+ // Context truncations recorded while producing this evidence
18
+ // (Context.renderTruncation strings). A gate verdict rendered on a
19
+ // partially-read spec pack says so HERE — that visibility is the whole
20
+ // reason truncation is allowed at all. Defaulted so manifests written
21
+ // before this field still load.
22
+ contextTruncations: Schema.Array(Schema.String).pipe(
23
+ Schema.withDecodingDefaultKey(Effect.succeed([])),
24
+ Schema.withConstructorDefault(Effect.succeed([]))
25
+ )
17
26
  }) {}
18
27
 
19
28
  const join = (root: string, path: string): string =>
package/src/Survey.ts CHANGED
@@ -29,6 +29,43 @@ export class SurveyGraph extends Schema.Class<SurveyGraph>("SurveyGraph")({
29
29
  }
30
30
  }
31
31
 
32
+ /**
33
+ * The transitive dependency closure of `program` as repo-relative paths,
34
+ * breadth-first, excluding the program itself. The `seen` set is required, not
35
+ * optional bookkeeping: COBOL copybook graphs genuinely contain cycles (a
36
+ * copybook that COPYs something which eventually COPYs back), and without it
37
+ * this walk would never terminate on a real estate. Truncated to `maxFiles` so
38
+ * a program pulling hundreds of copybooks still gets a bounded, visible subset
39
+ * instead of an unbounded read.
40
+ */
41
+ export const closureFor = (
42
+ graph: SurveyGraph,
43
+ program: string,
44
+ maxFiles: number
45
+ ): ReadonlyArray<string> => {
46
+ const pathOf = new Map(graph.nodes.map((node) => [node.name, node.path]))
47
+ const walk = (
48
+ frontier: ReadonlyArray<string>,
49
+ seen: ReadonlySet<string>,
50
+ acc: ReadonlyArray<string>
51
+ ): ReadonlyArray<string> => {
52
+ if (frontier.length === 0 || acc.length >= maxFiles) {
53
+ return acc.slice(0, maxFiles)
54
+ }
55
+ const next = [
56
+ ...new Set(frontier.flatMap((from) => graph.outgoing(from).map((edge) => edge.to)))
57
+ ].filter((name) => !seen.has(name))
58
+ return walk(next, new Set([...seen, ...next]), [
59
+ ...acc,
60
+ ...next.flatMap((name) => {
61
+ const path = pathOf.get(name)
62
+ return path === undefined ? [] : [path]
63
+ })
64
+ ])
65
+ }
66
+ return walk([program], new Set([program]), [])
67
+ }
68
+
32
69
  const unitName = (path: string): string => {
33
70
  const base = path.split("/").at(-1) ?? path
34
71
  const dot = base.lastIndexOf(".")
@@ -27,12 +27,40 @@ const transientSignals: ReadonlyArray<string> = [
27
27
  " 504"
28
28
  ]
29
29
 
30
+ // An "empty response" is ambiguous: gemini returns one both for a random mid-stream
31
+ // flake and for a prompt too large to start on. This classifier sees only the message,
32
+ // so it deliberately treats both as flaky — a fresh process fixes the common (flake)
33
+ // case, and the oversized-prompt case is resolved a layer up by Context.withShrink.
34
+ // Do not route empty responses into isContextOverflow.
30
35
  const flakyStreamSignals: ReadonlyArray<string> = [
31
36
  "empty response",
32
37
  "malformed tool call",
33
38
  "invalid stream"
34
39
  ]
35
40
 
41
+ // Deterministic client errors a retry can never fix. Gemini wraps every error in
42
+ // "[API Error: {...}]", including 400s, so the "api error" transient signal would
43
+ // otherwise swallow them.
44
+ const deterministic4xxSignals: ReadonlyArray<string> = [
45
+ "invalid_argument",
46
+ '"code": 400',
47
+ '"code":400',
48
+ "code=400",
49
+ "exceeds the maximum number of tokens"
50
+ ]
51
+
52
+ // The message signatures of a prompt-too-large failure, in one place: isContextOverflow
53
+ // matches them on a typed LlmError, and Context.withShrink matches them on a bare
54
+ // message string when no typed cause survived. Two copies of this list would drift.
55
+ const contextOverflowSignals: ReadonlyArray<string> = [
56
+ "exceeds the maximum number of tokens",
57
+ "input token count exceeds",
58
+ "context length exceeded",
59
+ "maximum context length",
60
+ "prompt is too long",
61
+ "request too large"
62
+ ]
63
+
36
64
  const includesSignal = (message: string, signals: ReadonlyArray<string>): boolean => {
37
65
  const normalized = message.toLowerCase()
38
66
  return signals.some((signal) => normalized.includes(signal))
@@ -41,13 +69,29 @@ const includesSignal = (message: string, signals: ReadonlyArray<string>): boolea
41
69
  export const isFlakyStream = (error: LlmError): boolean =>
42
70
  error._tag === "ProviderError" && includesSignal(error.message, flakyStreamSignals)
43
71
 
72
+ const isDeterministic4xx = (message: string): boolean =>
73
+ includesSignal(message, deterministic4xxSignals)
74
+
75
+ export const isContextOverflowMessage = (message: string): boolean =>
76
+ includesSignal(message, contextOverflowSignals)
77
+
78
+ // The prompt was larger than the model's input window. Deterministic: the same prompt
79
+ // always fails, so it is not transient — it routes to Context.withShrink, which retries
80
+ // at a smaller budget.
81
+ export const isContextOverflow = (error: LlmError): boolean =>
82
+ error._tag === "ProviderError" && isContextOverflowMessage(error.message)
83
+
44
84
  export const isTransient = (error: LlmError): boolean => {
45
85
  switch (error._tag) {
46
86
  case "TimeoutError":
47
87
  case "RateLimitError":
48
88
  return true
49
89
  case "ProviderError":
50
- return !isFlakyStream(error) && includesSignal(error.message, transientSignals)
90
+ return (
91
+ !isFlakyStream(error) &&
92
+ !isDeterministic4xx(error.message) &&
93
+ includesSignal(error.message, transientSignals)
94
+ )
51
95
  default:
52
96
  return false
53
97
  }