fascicle 0.4.0 → 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,14 @@
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
+
3
12
  ## v0.4.0 — 2026-05-07
4
13
 
5
14
  ### 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.4.0";
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.4.0";
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
  /**
package/dist/index.js CHANGED
@@ -1950,7 +1950,7 @@ const trajectory_event_schema = z.union([
1950
1950
  ]);
1951
1951
  //#endregion
1952
1952
  //#region packages/core/src/version.ts
1953
- const version = "0.4.0";
1953
+ const version = "0.4.1";
1954
1954
  //#endregion
1955
1955
  //#region packages/core/src/index.ts
1956
1956
  /**
@@ -3205,7 +3205,7 @@ function validate_report(value, path) {
3205
3205
  }
3206
3206
  //#endregion
3207
3207
  //#region packages/engine/src/version.ts
3208
- const version$1 = "0.4.0";
3208
+ const version$1 = "0.4.1";
3209
3209
  //#endregion
3210
3210
  //#region packages/engine/src/errors.ts
3211
3211
  var rate_limit_error = class extends Error {
@@ -4503,10 +4503,15 @@ async function* build_stdout_lines(child, on_data) {
4503
4503
  * and skip (spec §7.1, §7.4). Neither ever throws.
4504
4504
  *
4505
4505
  * Event shapes are Zod-validated via `cli_event_schema` (a
4506
- * `z.discriminatedUnion` over the four CLI event types). Per-entry content
4507
- * arrays use `.transform` to silently drop invalid entries rather than
4508
- * rejecting the whole event — this preserves forward compatibility with
4509
- * 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.
4510
4515
  */
4511
4516
  const cli_usage_schema = z.object({
4512
4517
  input_tokens: z.number().optional(),
@@ -4571,11 +4576,25 @@ const result_event_schema = z.object({
4571
4576
  usage: cli_usage_schema.optional(),
4572
4577
  result: z.string().optional()
4573
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
+ });
4574
4592
  const cli_event_schema = z.discriminatedUnion("type", [
4575
4593
  system_event_schema,
4576
4594
  assistant_event_schema,
4577
4595
  user_event_schema,
4578
- result_event_schema
4596
+ result_event_schema,
4597
+ rate_limit_event_schema
4579
4598
  ]);
4580
4599
  function create_parser_state() {
4581
4600
  return {
@@ -4631,6 +4650,19 @@ function record_session_started(trajectory, session_id, model) {
4631
4650
  model
4632
4651
  });
4633
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
+ }
4634
4666
  function flush_turn(state) {
4635
4667
  state.turns.push({
4636
4668
  step_index: state.current_step_index,
@@ -4761,6 +4793,9 @@ async function handle_event(state, event, chunks, dispatch, trajectory) {
4761
4793
  case "result":
4762
4794
  await handle_result(state, event, chunks, dispatch);
4763
4795
  return;
4796
+ case "rate_limit_event":
4797
+ record_rate_limit(trajectory, event);
4798
+ return;
4764
4799
  }
4765
4800
  }
4766
4801
  async function consume_line(state, line, chunks, dispatch, trajectory) {
@@ -5009,27 +5044,69 @@ function build_generate_result(input) {
5009
5044
  * Attempt to parse `text` as JSON and validate it with `schema`. Returns a
5010
5045
  * tagged union; the caller decides whether to escalate to repair, throw, or
5011
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.
5012
5060
  */
5013
5061
  function parse_with_schema(schema, text) {
5014
- let parsed_json;
5015
- try {
5016
- parsed_json = JSON.parse(text);
5017
- } catch (err) {
5018
- return {
5019
- ok: false,
5020
- 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
5021
5077
  };
5078
+ if (first_schema_error === void 0) first_schema_error = result.error;
5022
5079
  }
5023
- const result = schema.safeParse(parsed_json);
5024
- if (result.success) return {
5025
- ok: true,
5026
- value: result.data
5027
- };
5028
5080
  return {
5029
5081
  ok: false,
5030
- error: result.error
5082
+ error: first_schema_error ?? json_parse_error
5031
5083
  };
5032
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
+ }
5033
5110
  /**
5034
5111
  * Build the canonical repair message appended after a schema parse failure.
5035
5112
  * Content mirrors spec §6.5 exactly so the repair prompt is predictable and
@@ -5038,10 +5115,18 @@ function parse_with_schema(schema, text) {
5038
5115
  function build_repair_message(zod_error) {
5039
5116
  return {
5040
5117
  role: "user",
5041
- 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)
5042
5119
  };
5043
5120
  }
5044
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
+ /**
5045
5130
  * Throw schema_validation_error carrying the zod error and the raw model text.
5046
5131
  * Called by the orchestrator when all repair attempts are exhausted.
5047
5132
  */
@@ -5135,6 +5220,21 @@ function record_effort_ignored(trajectory, model_id) {
5135
5220
  model_id
5136
5221
  });
5137
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
+ }
5138
5238
  function record_tool_approval(trajectory, kind, meta) {
5139
5239
  if (trajectory === void 0) return;
5140
5240
  trajectory.record({
@@ -5366,24 +5466,32 @@ function create_claude_cli_adapter(init) {
5366
5466
  let parsed = (await run_cli(spawn_runtime, base_args)).parsed;
5367
5467
  let parsed_content;
5368
5468
  if (opts.schema !== void 0) {
5369
- const attempt = parse_with_schema(opts.schema, parsed.final_text);
5370
- if (attempt.ok) parsed_content = attempt.value;
5371
- 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);
5372
5483
  const repair_session_id = parsed.session_id;
5373
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);
5374
- const repair_prompt = "Your previous response did not match the expected schema. Return ONLY a JSON value that conforms to the provided --json-schema.";
5375
5485
  const repair_call_opts = {
5376
5486
  ...call_opts,
5377
5487
  session_id: repair_session_id
5378
5488
  };
5379
5489
  parsed = (await run_cli(spawn_runtime, {
5380
5490
  ...base_args,
5381
- stdin_text: repair_prompt,
5491
+ stdin_text: build_repair_prompt_text(attempt.error),
5382
5492
  call_opts: repair_call_opts
5383
5493
  })).parsed;
5384
- const retry = parse_with_schema(opts.schema, parsed.final_text);
5385
- if (!retry.ok) throw new schema_validation_error("schema validation failed after one repair attempt", retry.error, parsed.final_text);
5386
- parsed_content = retry.value;
5494
+ repairs_done += 1;
5387
5495
  }
5388
5496
  }
5389
5497
  const result_input = {
@@ -6474,6 +6582,11 @@ async function generate(opts_in, engine) {
6474
6582
  schema_satisfied = true;
6475
6583
  break;
6476
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
+ });
6477
6590
  if (repair_remaining <= 0 || total_steps >= max_steps) throw_schema_validation(parse.error, text);
6478
6591
  repair_remaining -= 1;
6479
6592
  messages_mutable.push(build_repair_message(parse.error));