fascicle 0.3.8 → 0.4.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.4.1 — 2026-05-09
4
+
5
+ ### Added
6
+ - `examples/pr-improve`: an automated PR-improvement pipeline composed as a four-stage fascicle flow — reviewer (sonnet) → pragmatist (opus, default-reject) → builder (sonnet) → build-reviewer (opus) — inside a bounded `loop` with `guard`-driven convergence. Routes every model call through the engine, so the same flow runs against `anthropic`, `openrouter`, or a local `claude_cli` subprocess by changing one env var. Includes `--pr` mode for posting review suggestions back to a GitHub PR via safe-spawn `gh`/`git` wrappers, and a `bin/pr-improve` entrypoint.
7
+
8
+ ### Fixed
9
+ - `@repo/engine` schema validation: `schema.ts` now tolerates fenced JSON code blocks in model output and emits a new `schema_validation_failed` trajectory event when validation fails, instead of throwing without observability. `generate.ts` extracts multiple JSON candidates from a single response and picks the first that parses, recovering from leading prose or partial fences.
10
+ - `@repo/engine` `claude_cli` provider: schema-repair attempt count is now configurable (was: hard-coded), giving callers control over the retry-vs-fail-fast tradeoff.
11
+
12
+ ## v0.4.0 — 2026-05-07
13
+
14
+ ### Fixed
15
+ - `claude_cli` adapter: `build_env` now seeds the standard process-env keys (`PATH`, `HOME`, `SHELL`, `USER`, `LOGNAME`, `LANG`, `TMPDIR`) under every `auth_mode` (was: only inherited under `oauth`). Sandbox-enabled runs under `auto`/`api_key` previously spawned with an empty `PATH` and failed with `ENOENT` looking up `greywall`/`bwrap`. Set `inherit_env: false` to opt out of the standard-key seeding.
16
+ - `claude_cli` adapter: greywall sandbox plan now writes a temp settings JSON (`{ network: { allowHosts }, filesystem: { allowWrite } }`) and forwards `--settings <path>` instead of the removed `--allow-host`/`--rw` flags. greywall 0.3.0+ rejected the old flags as unknown and exited 1. Consumers managing their own settings file can pass `sandbox.settings_path` to skip the temp-file generation.
17
+ - `fascicle-viewer` CLI: replaced the fragile `argv[1].endsWith('/cli.ts'|'/cli.js')` self-execution guard with an `import.meta.url`-based check. The umbrella bundles `cli.ts` into `dist/index.js`, so any consumer whose entry script was named `cli.js` was accidentally hijacked into running the viewer at import time.
18
+
3
19
  ## v0.3.8 — 2026-05-06
4
20
 
5
21
  ### Fixed
package/dist/index.d.ts CHANGED
@@ -325,7 +325,7 @@ type CustomTrajectoryEvent = z.infer<typeof custom_event_schema>;
325
325
  type ParsedTrajectoryEvent = z.infer<typeof trajectory_event_schema>;
326
326
  //#endregion
327
327
  //#region packages/core/src/version.d.ts
328
- declare const version = "0.3.8";
328
+ declare const version = "0.4.1";
329
329
  //#endregion
330
330
  //#region packages/core/src/index.d.ts
331
331
  declare const flow_schema: {
@@ -977,7 +977,7 @@ declare function read_baseline(path: string): Promise<BenchReport>;
977
977
  declare function write_baseline(path: string, report: BenchReport): Promise<void>;
978
978
  //#endregion
979
979
  //#region packages/engine/src/version.d.ts
980
- declare const version$1 = "0.3.8";
980
+ declare const version$1 = "0.4.1";
981
981
  //#endregion
982
982
  //#region packages/engine/src/providers/claude_cli/types.d.ts
983
983
  /**
@@ -997,16 +997,26 @@ type SandboxProviderConfig = {
997
997
  readonly kind: 'greywall';
998
998
  readonly network_allowlist?: ReadonlyArray<string>;
999
999
  readonly additional_write_paths?: ReadonlyArray<string>;
1000
+ /**
1001
+ * greywall 0.3+ takes filesystem/network policy from a JSON settings
1002
+ * file. By default the adapter writes a temp settings file derived
1003
+ * from `network_allowlist`/`additional_write_paths`. Set to forward
1004
+ * a caller-managed settings file directly via `--settings` instead.
1005
+ * The temp-file path is then skipped entirely.
1006
+ */
1007
+ readonly settings_path?: string;
1000
1008
  };
1001
1009
  type ClaudeCliProviderConfig = {
1002
1010
  readonly binary?: string;
1003
1011
  readonly auth_mode?: AuthMode;
1004
1012
  readonly api_key?: string;
1005
1013
  /**
1006
- * Under `auth_mode: 'oauth'` the subprocess env seeds from `process.env`
1007
- * by default so it can reach the logged-in `claude` session. Set to
1008
- * `false` to opt out and start from an empty env (the api_key-mode
1009
- * default). Ignored outside oauth mode.
1014
+ * The subprocess env seeds the standard process-env keys
1015
+ * (PATH/HOME/SHELL/USER/LOGNAME/LANG/TMPDIR) by default under every
1016
+ * auth mode so the spawn target (sandbox wrapper or the claude binary)
1017
+ * can be resolved on PATH. Under `auth_mode: 'oauth'` the *full*
1018
+ * `process.env` is inherited so the CLI can reach the logged-in OAuth
1019
+ * session. Set to `false` to opt out and start from an empty env.
1010
1020
  */
1011
1021
  readonly inherit_env?: boolean;
1012
1022
  readonly default_cwd?: string;
package/dist/index.js CHANGED
@@ -2,7 +2,8 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { z } from "zod";
3
3
  import { mkdir, open, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
- import { appendFileSync, createReadStream, existsSync, mkdirSync, statSync, watch } from "node:fs";
5
+ import { appendFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, statSync, watch, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
6
7
  import { spawn } from "node:child_process";
7
8
  import { generateText, stepCountIs, streamText, tool } from "ai";
8
9
  import { createServer } from "node:http";
@@ -1949,7 +1950,7 @@ const trajectory_event_schema = z.union([
1949
1950
  ]);
1950
1951
  //#endregion
1951
1952
  //#region packages/core/src/version.ts
1952
- const version = "0.3.8";
1953
+ const version = "0.4.1";
1953
1954
  //#endregion
1954
1955
  //#region packages/core/src/index.ts
1955
1956
  /**
@@ -3204,7 +3205,7 @@ function validate_report(value, path) {
3204
3205
  }
3205
3206
  //#endregion
3206
3207
  //#region packages/engine/src/version.ts
3207
- const version$1 = "0.3.8";
3208
+ const version$1 = "0.4.1";
3208
3209
  //#endregion
3209
3210
  //#region packages/engine/src/errors.ts
3210
3211
  var rate_limit_error = class extends Error {
@@ -4053,17 +4054,38 @@ const DEFAULT_SETTING_SOURCES = Object.freeze(["project", "local"]);
4053
4054
  * Authentication enforcement for the claude_cli adapter (spec §4, §6.1).
4054
4055
  *
4055
4056
  * - build_env composes the subprocess env from config + caller overrides.
4056
- * Under `auth_mode: 'oauth'` it seeds from `process.env` (the CLI needs
4057
- * HOME/PATH to reach the logged-in session) unless `config.inherit_env`
4058
- * is explicitly `false`. Under 'api_key' and 'auto' it starts empty and
4059
- * only copies caller-supplied keys. Auth-mode scrub runs last on the
4060
- * merged result so nothing — caller env, inherited env, or config —
4061
- * can re-introduce ANTHROPIC_API_KEY under 'oauth'.
4057
+ * Regardless of auth_mode, it seeds the standard process-env keys
4058
+ * (PATH, HOME, SHELL, USER, LOGNAME, LANG, TMPDIR) so the spawned
4059
+ * subprocess can locate the sandbox wrapper (greywall/bwrap) and the
4060
+ * claude binary on PATH. Set `inherit_env: false` to opt out and start
4061
+ * from an empty env. Under oauth mode the *full* process.env is also
4062
+ * inherited (the CLI needs HOME/etc plus session-specific vars to reach
4063
+ * the logged-in OAuth session). Auth-mode scrub runs last on the merged
4064
+ * result so nothing — caller env, inherited env, or config — can
4065
+ * re-introduce ANTHROPIC_API_KEY under 'oauth'.
4062
4066
  * - validate_auth_config throws engine_config_error synchronously when
4063
4067
  * auth_mode === 'api_key' without a non-empty api_key.
4064
4068
  * - stderr_is_auth_failure matches captured stderr against the frozen
4065
4069
  * CLI_AUTH_ERROR_PATTERNS list, case-insensitively.
4066
4070
  */
4071
+ /**
4072
+ * Standard env keys forwarded from process.env so the spawn target
4073
+ * (greywall/bwrap on PATH, then `claude`) can be resolved and run.
4074
+ *
4075
+ * Mirrors `STANDARD_KEYS` in
4076
+ * packages/fascicle/src/forward_standard_env.ts. Keep the two lists in
4077
+ * sync; engine cannot import from fascicle (the umbrella depends on
4078
+ * engine, not the other way).
4079
+ */
4080
+ const STANDARD_ENV_KEYS = [
4081
+ "PATH",
4082
+ "HOME",
4083
+ "SHELL",
4084
+ "USER",
4085
+ "LOGNAME",
4086
+ "LANG",
4087
+ "TMPDIR"
4088
+ ];
4067
4089
  function validate_auth_config(config) {
4068
4090
  if ((config.auth_mode ?? "auto") === "api_key") {
4069
4091
  if ((typeof config.api_key === "string" ? config.api_key : "").length === 0) throw new engine_config_error("api_key is required for auth_mode: api_key", "claude_cli");
@@ -4071,8 +4093,11 @@ function validate_auth_config(config) {
4071
4093
  }
4072
4094
  function build_env(config, caller_env, auth_mode) {
4073
4095
  const env = {};
4074
- if (auth_mode === "oauth" && config.inherit_env !== false) {
4096
+ if (config.inherit_env !== false) if (auth_mode === "oauth") {
4075
4097
  for (const [k, v] of Object.entries(process.env)) if (typeof v === "string") env[k] = v;
4098
+ } else for (const key of STANDARD_ENV_KEYS) {
4099
+ const v = process.env[key];
4100
+ if (typeof v === "string") env[key] = v;
4076
4101
  }
4077
4102
  if (caller_env !== void 0) {
4078
4103
  for (const [k, v] of Object.entries(caller_env)) if (typeof v === "string") env[k] = v;
@@ -4135,6 +4160,31 @@ function merge_allowed_tools(call_allowlist, tool_names) {
4135
4160
  }
4136
4161
  //#endregion
4137
4162
  //#region packages/engine/src/providers/claude_cli/sandbox.ts
4163
+ /**
4164
+ * Sandbox wrapper for the claude_cli adapter (spec §5.1, F30).
4165
+ *
4166
+ * Builds the `{ spawn_cmd, prefix_args }` pair for bwrap and greywall. When no
4167
+ * sandbox is configured, returns { spawn_cmd: binary, prefix_args: [] } — the
4168
+ * caller then concatenates prefix_args before the CLI argv.
4169
+ *
4170
+ * Both wrappers allow the binary to execute while restricting network reach
4171
+ * to the allowlist and write access to additional paths on top of the
4172
+ * sandbox's default-read-only filesystem.
4173
+ *
4174
+ * greywall 0.3+ removed the `--allow-host` and `--rw` flags; policy now
4175
+ * lives in a JSON settings file passed via `--settings <path>`. Schema is
4176
+ * documented in `greywall --help`:
4177
+ *
4178
+ * {
4179
+ * "network": { "allowHosts": [...] },
4180
+ * "filesystem": { "allowWrite": [...] }
4181
+ * }
4182
+ *
4183
+ * `filesystem.allowWrite` is honored directly; `network.allowHosts` is
4184
+ * preserved for documentation/forward-compat (greywall ignores unknown
4185
+ * fields and host-level allowlisting is currently enforced at the
4186
+ * greyproxy layer).
4187
+ */
4138
4188
  function build_sandbox_plan(binary, sandbox) {
4139
4189
  if (sandbox === void 0) return {
4140
4190
  spawn_cmd: binary,
@@ -4177,14 +4227,21 @@ function build_bwrap_args(binary, sandbox) {
4177
4227
  return args;
4178
4228
  }
4179
4229
  function build_greywall_args(binary, sandbox) {
4180
- const args = [];
4181
- const allowlist = sandbox.network_allowlist ?? [];
4182
- for (const host of allowlist) args.push("--allow-host", host);
4183
- const write_paths = sandbox.additional_write_paths ?? [];
4184
- for (const p of write_paths) args.push("--rw", p);
4185
- args.push("--");
4186
- args.push(binary);
4187
- return args;
4230
+ return [
4231
+ "--settings",
4232
+ sandbox.settings_path ?? write_greywall_settings(sandbox),
4233
+ "--",
4234
+ binary
4235
+ ];
4236
+ }
4237
+ function write_greywall_settings(sandbox) {
4238
+ const path = join(mkdtempSync(join(tmpdir(), `fascicle-greywall-${process.pid}-`)), "greywall.json");
4239
+ const payload = {
4240
+ network: { allowHosts: [...sandbox.network_allowlist ?? []] },
4241
+ filesystem: { allowWrite: [...sandbox.additional_write_paths ?? []] }
4242
+ };
4243
+ writeFileSync(path, JSON.stringify(payload, null, 2), "utf8");
4244
+ return path;
4188
4245
  }
4189
4246
  //#endregion
4190
4247
  //#region packages/engine/src/providers/claude_cli/spawn.ts
@@ -4446,10 +4503,15 @@ async function* build_stdout_lines(child, on_data) {
4446
4503
  * and skip (spec §7.1, §7.4). Neither ever throws.
4447
4504
  *
4448
4505
  * Event shapes are Zod-validated via `cli_event_schema` (a
4449
- * `z.discriminatedUnion` over the four CLI event types). Per-entry content
4450
- * arrays use `.transform` to silently drop invalid entries rather than
4451
- * rejecting the whole event — this preserves forward compatibility with
4452
- * new CLI content types.
4506
+ * `z.discriminatedUnion` over the recognized CLI event types: system,
4507
+ * assistant, user, result, rate_limit_event). Per-entry content arrays use
4508
+ * `.transform` to silently drop invalid entries rather than rejecting the
4509
+ * whole event — this preserves forward compatibility with new CLI content
4510
+ * types.
4511
+ *
4512
+ * `rate_limit_event` is informational: the CLI emits it between turns to
4513
+ * report current rate-limit budget. The parser records a structured
4514
+ * `cli_rate_limit_event` to trajectory and does not affect turn state.
4453
4515
  */
4454
4516
  const cli_usage_schema = z.object({
4455
4517
  input_tokens: z.number().optional(),
@@ -4514,11 +4576,25 @@ const result_event_schema = z.object({
4514
4576
  usage: cli_usage_schema.optional(),
4515
4577
  result: z.string().optional()
4516
4578
  });
4579
+ const rate_limit_info_schema = z.object({
4580
+ status: z.string().optional(),
4581
+ resetsAt: z.number().optional(),
4582
+ rateLimitType: z.string().optional(),
4583
+ overageStatus: z.string().optional(),
4584
+ overageResetsAt: z.number().optional(),
4585
+ isUsingOverage: z.boolean().optional()
4586
+ });
4587
+ const rate_limit_event_schema = z.object({
4588
+ type: z.literal("rate_limit_event"),
4589
+ rate_limit_info: rate_limit_info_schema.optional(),
4590
+ session_id: z.string().optional()
4591
+ });
4517
4592
  const cli_event_schema = z.discriminatedUnion("type", [
4518
4593
  system_event_schema,
4519
4594
  assistant_event_schema,
4520
4595
  user_event_schema,
4521
- result_event_schema
4596
+ result_event_schema,
4597
+ rate_limit_event_schema
4522
4598
  ]);
4523
4599
  function create_parser_state() {
4524
4600
  return {
@@ -4574,6 +4650,19 @@ function record_session_started(trajectory, session_id, model) {
4574
4650
  model
4575
4651
  });
4576
4652
  }
4653
+ function record_rate_limit(trajectory, event) {
4654
+ const info = event.rate_limit_info;
4655
+ trajectory?.record({
4656
+ kind: "cli_rate_limit_event",
4657
+ session_id: event.session_id,
4658
+ status: info?.status,
4659
+ rate_limit_type: info?.rateLimitType,
4660
+ resets_at: info?.resetsAt,
4661
+ overage_status: info?.overageStatus,
4662
+ overage_resets_at: info?.overageResetsAt,
4663
+ is_using_overage: info?.isUsingOverage
4664
+ });
4665
+ }
4577
4666
  function flush_turn(state) {
4578
4667
  state.turns.push({
4579
4668
  step_index: state.current_step_index,
@@ -4704,6 +4793,9 @@ async function handle_event(state, event, chunks, dispatch, trajectory) {
4704
4793
  case "result":
4705
4794
  await handle_result(state, event, chunks, dispatch);
4706
4795
  return;
4796
+ case "rate_limit_event":
4797
+ record_rate_limit(trajectory, event);
4798
+ return;
4707
4799
  }
4708
4800
  }
4709
4801
  async function consume_line(state, line, chunks, dispatch, trajectory) {
@@ -4952,27 +5044,69 @@ function build_generate_result(input) {
4952
5044
  * Attempt to parse `text` as JSON and validate it with `schema`. Returns a
4953
5045
  * tagged union; the caller decides whether to escalate to repair, throw, or
4954
5046
  * surface the failure.
5047
+ *
5048
+ * Even with --json-schema enforcement, models occasionally wrap structured
5049
+ * output in markdown fences and surrounding prose. We try a sequence of
5050
+ * candidates in increasing leniency: the trimmed text as-is, every fenced
5051
+ * block in the text, and the outermost {…} / […] slice. The first candidate
5052
+ * that both parses as JSON and matches the schema wins.
5053
+ *
5054
+ * When every candidate fails, we prefer the schema-validation error from the
5055
+ * FIRST candidate that parsed as JSON — that error reflects the model's
5056
+ * primary output and is what a repair prompt should feed back. Later
5057
+ * candidates (e.g. the bracket-slice fallback) often produce noisy errors
5058
+ * like "expected object, received array" that misdirect the model. Only when
5059
+ * NO candidate parses as JSON do we surface the JSON parse error.
4955
5060
  */
4956
5061
  function parse_with_schema(schema, text) {
4957
- let parsed_json;
4958
- try {
4959
- parsed_json = JSON.parse(text);
4960
- } catch (err) {
4961
- return {
4962
- ok: false,
4963
- error: err
5062
+ const candidates = json_candidates(text);
5063
+ let json_parse_error = /* @__PURE__ */ new Error("No JSON-parseable content found in model output");
5064
+ let first_schema_error;
5065
+ for (const candidate of candidates) {
5066
+ let parsed;
5067
+ try {
5068
+ parsed = JSON.parse(candidate);
5069
+ } catch (err) {
5070
+ json_parse_error = err;
5071
+ continue;
5072
+ }
5073
+ const result = schema.safeParse(parsed);
5074
+ if (result.success) return {
5075
+ ok: true,
5076
+ value: result.data
4964
5077
  };
5078
+ if (first_schema_error === void 0) first_schema_error = result.error;
4965
5079
  }
4966
- const result = schema.safeParse(parsed_json);
4967
- if (result.success) return {
4968
- ok: true,
4969
- value: result.data
4970
- };
4971
5080
  return {
4972
5081
  ok: false,
4973
- error: result.error
5082
+ error: first_schema_error ?? json_parse_error
4974
5083
  };
4975
5084
  }
5085
+ const FENCE_BLOCK = /```(?:[\w-]*)\s*\n?([\s\S]*?)\n?```/g;
5086
+ function json_candidates(text) {
5087
+ const candidates = [];
5088
+ const seen = /* @__PURE__ */ new Set();
5089
+ const push = (s) => {
5090
+ const trimmed = s.trim();
5091
+ if (trimmed.length === 0 || seen.has(trimmed)) return;
5092
+ seen.add(trimmed);
5093
+ candidates.push(trimmed);
5094
+ };
5095
+ push(text);
5096
+ for (const match of text.matchAll(FENCE_BLOCK)) {
5097
+ const body = match[1];
5098
+ if (body !== void 0) push(body);
5099
+ }
5100
+ push(slice_outermost(text, "{", "}"));
5101
+ push(slice_outermost(text, "[", "]"));
5102
+ return candidates;
5103
+ }
5104
+ function slice_outermost(text, open, close) {
5105
+ const first = text.indexOf(open);
5106
+ const last = text.lastIndexOf(close);
5107
+ if (first === -1 || last <= first) return "";
5108
+ return text.slice(first, last + 1);
5109
+ }
4976
5110
  /**
4977
5111
  * Build the canonical repair message appended after a schema parse failure.
4978
5112
  * Content mirrors spec §6.5 exactly so the repair prompt is predictable and
@@ -4981,10 +5115,18 @@ function parse_with_schema(schema, text) {
4981
5115
  function build_repair_message(zod_error) {
4982
5116
  return {
4983
5117
  role: "user",
4984
- content: `Your previous response did not match the expected schema. Error: ${format_zod_error(zod_error)}. Please provide a corrected response that strictly conforms to the schema.`
5118
+ content: build_repair_prompt_text(zod_error)
4985
5119
  };
4986
5120
  }
4987
5121
  /**
5122
+ * String form of the repair prompt for transports (subprocess CLIs) that take
5123
+ * a single stdin string rather than a Message. Same wording as
5124
+ * build_repair_message so the on-wire instruction is identical across providers.
5125
+ */
5126
+ function build_repair_prompt_text(zod_error) {
5127
+ return `Your previous response did not match the expected schema. Error: ${format_zod_error(zod_error)}. Please provide a corrected response that strictly conforms to the schema. Return ONLY the JSON value: no markdown code fences, no surrounding prose, no commentary.`;
5128
+ }
5129
+ /**
4988
5130
  * Throw schema_validation_error carrying the zod error and the raw model text.
4989
5131
  * Called by the orchestrator when all repair attempts are exhausted.
4990
5132
  */
@@ -5078,6 +5220,21 @@ function record_effort_ignored(trajectory, model_id) {
5078
5220
  model_id
5079
5221
  });
5080
5222
  }
5223
+ /**
5224
+ * Emit a structured event when a schema-driven generate call returns text
5225
+ * that fails parse + zod validation. Persists the raw model output and a
5226
+ * formatted zod issues summary to the trajectory so the failure is debuggable
5227
+ * without needing stdout. Spec §6.5.
5228
+ */
5229
+ function record_schema_validation_failed(trajectory, meta) {
5230
+ if (trajectory === void 0) return;
5231
+ trajectory.record({
5232
+ kind: "schema_validation_failed",
5233
+ attempt: meta.attempt,
5234
+ zod_issues: meta.zod_issues,
5235
+ raw_text: meta.raw_text
5236
+ });
5237
+ }
5081
5238
  function record_tool_approval(trajectory, kind, meta) {
5082
5239
  if (trajectory === void 0) return;
5083
5240
  trajectory.record({
@@ -5309,24 +5466,32 @@ function create_claude_cli_adapter(init) {
5309
5466
  let parsed = (await run_cli(spawn_runtime, base_args)).parsed;
5310
5467
  let parsed_content;
5311
5468
  if (opts.schema !== void 0) {
5312
- const attempt = parse_with_schema(opts.schema, parsed.final_text);
5313
- if (attempt.ok) parsed_content = attempt.value;
5314
- else {
5469
+ const max_repairs = opts.schema_repair_attempts ?? 1;
5470
+ let repairs_done = 0;
5471
+ for (;;) {
5472
+ const attempt = parse_with_schema(opts.schema, parsed.final_text);
5473
+ if (attempt.ok) {
5474
+ parsed_content = attempt.value;
5475
+ break;
5476
+ }
5477
+ record_schema_validation_failed(trajectory, {
5478
+ attempt: repairs_done === 0 ? "initial" : "repair",
5479
+ zod_issues: format_zod_error(attempt.error),
5480
+ raw_text: parsed.final_text
5481
+ });
5482
+ if (repairs_done >= max_repairs) throw new schema_validation_error(max_repairs === 0 ? "schema validation failed and repair is disabled (schema_repair_attempts: 0)" : `schema validation failed after ${String(max_repairs)} repair attempt${max_repairs === 1 ? "" : "s"}`, attempt.error, parsed.final_text);
5315
5483
  const repair_session_id = parsed.session_id;
5316
5484
  if (repair_session_id === void 0) throw new schema_validation_error("schema validation failed and no session_id available for repair", attempt.error, parsed.final_text);
5317
- const repair_prompt = "Your previous response did not match the expected schema. Return ONLY a JSON value that conforms to the provided --json-schema.";
5318
5485
  const repair_call_opts = {
5319
5486
  ...call_opts,
5320
5487
  session_id: repair_session_id
5321
5488
  };
5322
5489
  parsed = (await run_cli(spawn_runtime, {
5323
5490
  ...base_args,
5324
- stdin_text: repair_prompt,
5491
+ stdin_text: build_repair_prompt_text(attempt.error),
5325
5492
  call_opts: repair_call_opts
5326
5493
  })).parsed;
5327
- const retry = parse_with_schema(opts.schema, parsed.final_text);
5328
- if (!retry.ok) throw new schema_validation_error("schema validation failed after one repair attempt", retry.error, parsed.final_text);
5329
- parsed_content = retry.value;
5494
+ repairs_done += 1;
5330
5495
  }
5331
5496
  }
5332
5497
  const result_input = {
@@ -6417,6 +6582,11 @@ async function generate(opts_in, engine) {
6417
6582
  schema_satisfied = true;
6418
6583
  break;
6419
6584
  }
6585
+ record_schema_validation_failed(trajectory, {
6586
+ attempt: repair_remaining === schema_repair_attempts ? "initial" : "repair",
6587
+ zod_issues: format_zod_error(parse.error),
6588
+ raw_text: text
6589
+ });
6420
6590
  if (repair_remaining <= 0 || total_steps >= max_steps) throw_schema_validation(parse.error, text);
6421
6591
  repair_remaining -= 1;
6422
6592
  messages_mutable.push(build_repair_message(parse.error));
@@ -7192,7 +7362,7 @@ function describe_error(err) {
7192
7362
  return String(err);
7193
7363
  }
7194
7364
  }
7195
- if (typeof process.argv[1] === "string" && (process.argv[1].endsWith("/cli.ts") || process.argv[1].endsWith("/cli.js"))) run_viewer_cli(process.argv.slice(2)).catch((err) => {
7365
+ if (process.argv[1] !== void 0 && process.argv[1] === fileURLToPath(import.meta.url)) run_viewer_cli(process.argv.slice(2)).catch((err) => {
7196
7366
  process.stderr.write(`fascicle-viewer: ${describe_error(err)}\n`);
7197
7367
  process.exit(1);
7198
7368
  });