@yagni-app/code-staging 1.2.14-staging.2317.1 → 1.2.14-staging.2329.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.
@@ -10,7 +10,7 @@
10
10
  * `tool_execution_end`; the example's `tool_result_end` branch is dead/never
11
11
  * emitted, so `collectToolResults` reads the former and ignores the latter.
12
12
  */
13
- import type { JsonEvent, StageUsage } from "./types.js";
13
+ import { type JsonEvent, type StageUsage } from "./types.js";
14
14
  /**
15
15
  * The final assistant text handed forward as the next stage's `{previous}`.
16
16
  * Biased toward the model's GENUINE turn-end: prefer the last assistant message
@@ -38,12 +38,32 @@ export declare function collectToolResults(events: JsonEvent[]): Array<{
38
38
  toolName: string;
39
39
  isError: boolean;
40
40
  }>;
41
+ /**
42
+ * The pi tools that change files. A turn's edits land through these, so they are
43
+ * the only calls the write-stage health gate counts: `bash` errors on any
44
+ * non-zero exit, so a red test run or a `grep` with no match is an errored call
45
+ * that says nothing about whether the edits landed.
46
+ */
47
+ export declare const EDIT_TOOL_NAMES: readonly string[];
48
+ /**
49
+ * The write-stage health gate: true when a turn made enough `edit`/`write`
50
+ * calls (MIN_TOOL_CALLS_FOR_HEALTH) and most of them errored (above
51
+ * TOOL_ERROR_FAIL_RATE), so its edits likely did not land. Absent counts are a
52
+ * caller-injected seam that observed none, which never trips it.
53
+ */
54
+ export declare function editsMostlyFailed(r: {
55
+ editCalls?: number;
56
+ editErrors?: number;
57
+ }): boolean;
41
58
  export interface EventAccumulator {
42
59
  usage: StageUsage;
43
60
  stopReason?: string;
44
61
  errorMessage?: string;
45
62
  toolCalls: number;
46
63
  toolErrors: number;
64
+ /** The `edit` and `write` subset of the tool counts: what the write-stage health gate reads. */
65
+ editCalls: number;
66
+ editErrors: number;
47
67
  /** Last assistant text on a genuine "stop" turn, and on any turn — extractFinalOutput's two tiers. */
48
68
  lastStopText?: string;
49
69
  lastAnyText?: string;
@@ -10,6 +10,7 @@
10
10
  * `tool_execution_end`; the example's `tool_result_end` branch is dead/never
11
11
  * emitted, so `collectToolResults` reads the former and ignores the latter.
12
12
  */
13
+ import { MIN_TOOL_CALLS_FOR_HEALTH, TOOL_ERROR_FAIL_RATE, } from "./types.js";
13
14
  /** True for an assistant `message_end` event carrying a message. */
14
15
  function isAssistantMessage(ev) {
15
16
  return ev.type === "message_end" && ev.message?.role === "assistant";
@@ -92,11 +93,35 @@ export function collectToolResults(events) {
92
93
  }
93
94
  return out;
94
95
  }
96
+ /**
97
+ * The pi tools that change files. A turn's edits land through these, so they are
98
+ * the only calls the write-stage health gate counts: `bash` errors on any
99
+ * non-zero exit, so a red test run or a `grep` with no match is an errored call
100
+ * that says nothing about whether the edits landed.
101
+ */
102
+ export const EDIT_TOOL_NAMES = ["edit", "write"];
103
+ function isEditTool(toolName) {
104
+ return toolName !== undefined && EDIT_TOOL_NAMES.includes(toolName);
105
+ }
106
+ /**
107
+ * The write-stage health gate: true when a turn made enough `edit`/`write`
108
+ * calls (MIN_TOOL_CALLS_FOR_HEALTH) and most of them errored (above
109
+ * TOOL_ERROR_FAIL_RATE), so its edits likely did not land. Absent counts are a
110
+ * caller-injected seam that observed none, which never trips it.
111
+ */
112
+ export function editsMostlyFailed(r) {
113
+ const calls = r.editCalls ?? 0;
114
+ if (calls < MIN_TOOL_CALLS_FOR_HEALTH)
115
+ return false;
116
+ return (r.editErrors ?? 0) / calls > TOOL_ERROR_FAIL_RATE;
117
+ }
95
118
  export function newEventAccumulator() {
96
119
  return {
97
120
  usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
98
121
  toolCalls: 0,
99
122
  toolErrors: 0,
123
+ editCalls: 0,
124
+ editErrors: 0,
100
125
  };
101
126
  }
102
127
  /** The last text part of a single assistant message, or undefined. */
@@ -115,6 +140,11 @@ export function foldEvent(acc, ev) {
115
140
  acc.toolCalls += 1;
116
141
  if (ev.isError)
117
142
  acc.toolErrors += 1;
143
+ if (isEditTool(ev.toolName)) {
144
+ acc.editCalls += 1;
145
+ if (ev.isError)
146
+ acc.editErrors += 1;
147
+ }
118
148
  return;
119
149
  }
120
150
  if (!isAssistantMessage(ev))
@@ -26,6 +26,7 @@
26
26
  */
27
27
  import { addRunUsage, aggregateRunUsage, DEFAULT_RUN_BUDGET, DEFAULT_STAGE_ESTIMATE_MS, EMPTY_RUN_USAGE, exceedsBudget, stageWall, stageWontFit, } from "./budget.js";
28
28
  import { attributeFindings, checkerFindings, composeFixNote, composeResidue, composeSynthesizerInput, mergeFindings, parseOpenFindings, renderFindings, stripOpenFindings, } from "./checker.js";
29
+ import { editsMostlyFailed } from "./events.js";
29
30
  import { auditClaims, parsePartition, } from "./fanout.js";
30
31
  import { extractFindingsBlock, hasBlockingFindings, isBlockingFinding, parseFindings, shouldStop, unionFindings, } from "./findings.js";
31
32
  import { limitedMapFiles, readTouchedFiles } from "./fixRound.js";
@@ -36,7 +37,7 @@ import { makeRunVerify, makeWorkstreamCheck, parseChangedPaths, } from "./verify
36
37
  import { extractPlanJson } from "./planOutput.js";
37
38
  import { builderStage, fixerStage, fixRoundImplementStage, fixRoundMapStage, FULL_LANE, orchestratorStage, partitionReaskStage, PARTITION_CALLER_LABEL, planJsonReaskStage, REQUIRED_LENSES, reaskStage, reviewStage, synthesizerFixStage, synthesizerStage, SYNTHESIZER_CALLER_LABEL, workstreamCallerLabel, } from "./stages.js";
38
39
  import { snapshotWorkspace as defaultSnapshotWorkspace, workspaceChanged } from "./workspace.js";
39
- import { DEFAULT_RESILIENCE_POLICY, MAX_CONCURRENCY, MAX_FANOUT_CONCURRENCY, MAX_FANOUT_CONCURRENCY_ULTRA, MAX_FIX_TURNS, MIN_TOOL_CALLS_FOR_HEALTH, TOOL_ERROR_FAIL_RATE, } from "./types.js";
40
+ import { DEFAULT_RESILIENCE_POLICY, MAX_CONCURRENCY, MAX_FANOUT_CONCURRENCY, MAX_FANOUT_CONCURRENCY_ULTRA, MAX_FIX_TURNS, } from "./types.js";
40
41
  /** Each review round's findings as the host stores them: bounded, messages clipped. */
41
42
  export const MAX_ROUND_ITEMS = 20;
42
43
  const MAX_ROUND_ITEM_MESSAGE = 300;
@@ -64,31 +65,28 @@ export class PipelineStageError extends Error {
64
65
  }
65
66
  const BUILD_STAGE_IDS = ["map", "plan", "implement"];
66
67
  /**
67
- * Stages whose whole value is in landed edits, so a high tool-error rate there is
68
+ * Stages whose whole value is in landed edits, so a high edit-error rate there is
68
69
  * a real failure (R3-a). Read-only recon/review stages are intentionally exempt:
69
- * a grep/read that misses is normal navigation, not a broken stage.
70
+ * they make no edits to fail.
70
71
  */
71
72
  const WRITE_STAGE_IDS = ["implement", "fix"];
72
73
  /**
73
- * R3-a: true when a WRITE stage exited cleanly yet most of its tool calls errored
74
- * — the silent partial-implement landmine, where the model narrates a tidy
75
- * summary while its edits never landed. Conservative on purpose: only write
76
- * stages are gated, and BOTH a meaningful sample (MIN_TOOL_CALLS_FOR_HEALTH) and
77
- * a clear-majority error rate (above TOOL_ERROR_FAIL_RATE) must hold, so a couple
78
- * of expected errors never fail a stage.
74
+ * R3-a: true when a WRITE stage exited cleanly yet most of its edits and writes
75
+ * errored — the silent partial-implement landmine, where the model narrates a
76
+ * tidy summary while its edits never landed. Only write stages are gated, and
77
+ * only their `edit` / `write` calls count (`editsMostlyFailed`): a red test run
78
+ * or an empty search is an errored `bash` call, not a failed edit.
79
79
  */
80
80
  function toolFailureExceeded(r) {
81
81
  if (!WRITE_STAGE_IDS.includes(r.stageId))
82
82
  return false;
83
- if (r.toolCalls < MIN_TOOL_CALLS_FOR_HEALTH)
84
- return false;
85
- return r.toolErrors / r.toolCalls > TOOL_ERROR_FAIL_RATE;
83
+ return editsMostlyFailed(r);
86
84
  }
87
85
  /** The honest reason string for a tool-failure-flagged stage, else undefined. */
88
86
  function toolFailureReason(r) {
89
87
  if (!toolFailureExceeded(r))
90
88
  return undefined;
91
- return `tool failures: ${r.toolErrors} of ${r.toolCalls} tool calls errored, so its edits likely did not land despite a clean-looking summary. Re-run /go.`;
89
+ return `tool failures: ${r.editErrors ?? 0} of ${r.editCalls ?? 0} edits and writes errored, so its edits likely did not land despite a clean-looking summary. Re-run /go.`;
92
90
  }
93
91
  /**
94
92
  * A stage outcome counts as a failure on a non-zero exit, an error/abort stop, or
@@ -796,6 +794,8 @@ export async function runPipeline(ticket, deps) {
796
794
  .join("\n"),
797
795
  toolCalls: builders.reduce((n, r) => n + r.toolCalls, 0),
798
796
  toolErrors: builders.reduce((n, r) => n + r.toolErrors, 0),
797
+ editCalls: builders.reduce((n, r) => n + (r.editCalls ?? 0), 0),
798
+ editErrors: builders.reduce((n, r) => n + (r.editErrors ?? 0), 0),
799
799
  ...(failed.length > 0 ? { stopReason: "error", errorMessage: failureNote } : {}),
800
800
  };
801
801
  log("fanout_done", {
@@ -73,7 +73,22 @@ export interface PlanFile {
73
73
  size?: PlanSize;
74
74
  /** One line on why the size, clipped; absent when the plan wrote none. */
75
75
  sizeReason?: string;
76
+ /**
77
+ * The ticket's problem is already gone, as the ticket check shows: the plan
78
+ * recommends closing the ticket, with its evidence, and has nothing to
79
+ * build. The host opens a Decision a person answers instead of the plan's
80
+ * gate. Absent on every plan that builds something.
81
+ */
82
+ closeTicket?: {
83
+ why: string;
84
+ evidence: string[];
85
+ };
76
86
  }
87
+ /**
88
+ * The plan's `closeTicket`, or null when it says neither why nor any
89
+ * evidence. Evidence lines are clipped, and an empty one is dropped.
90
+ */
91
+ export declare function readCloseTicket(value: unknown): PlanFile["closeTicket"] | null;
77
92
  /** The plan's `wrongRepository`, or null when it names no `owner/name`. Confidence is high only when said. */
78
93
  export declare function readWrongRepository(value: unknown): PlanFile["wrongRepository"] | null;
79
94
  /** The plan's `dependsOn`, one entry per distinct repository, in the order written. */
@@ -27,6 +27,24 @@ const MAX_REPOSITORIES_NEEDED = 12;
27
27
  * outside this set is dropped, never the plan.
28
28
  */
29
29
  const PLAN_SIZES = ["small", "standard", "complex"];
30
+ /** At most this many evidence lines on a close recommendation. */
31
+ const MAX_CLOSE_EVIDENCE = 10;
32
+ /**
33
+ * The plan's `closeTicket`, or null when it says neither why nor any
34
+ * evidence. Evidence lines are clipped, and an empty one is dropped.
35
+ */
36
+ export function readCloseTicket(value) {
37
+ if (!isRecord(value))
38
+ return null;
39
+ const why = text(value.why) ?? "";
40
+ const evidence = list(value.evidence)
41
+ .map((entry) => text(entry))
42
+ .filter((entry) => entry !== null)
43
+ .slice(0, MAX_CLOSE_EVIDENCE);
44
+ if (!why && evidence.length === 0)
45
+ return null;
46
+ return { why, evidence };
47
+ }
30
48
  /** The plan's `wrongRepository`, or null when it names no `owner/name`. Confidence is high only when said. */
31
49
  export function readWrongRepository(value) {
32
50
  if (!isRecord(value))
@@ -165,8 +183,10 @@ export function buildPlanFile(planText, fallbackPaths) {
165
183
  if (decisionsCited.length === MAX_LIST)
166
184
  break;
167
185
  }
186
+ const closeTicket = readCloseTicket(block?.closeTicket);
168
187
  const checks = [];
169
- for (const entry of list(block?.checks)) {
188
+ // A close recommendation builds nothing, so it proves nothing and touches no folder.
189
+ for (const entry of closeTicket ? [] : list(block?.checks)) {
170
190
  const command = isRecord(entry) ? text(entry.command) : null;
171
191
  if (!isRecord(entry) || !command)
172
192
  continue;
@@ -181,7 +201,9 @@ export function buildPlanFile(planText, fallbackPaths) {
181
201
  const named = list(block?.paths)
182
202
  .map(repoPath)
183
203
  .filter((path) => path !== null);
184
- const paths = [...new Set(named.length > 0 ? named : fallbackPaths())].slice(0, MAX_LIST);
204
+ const paths = closeTicket
205
+ ? []
206
+ : [...new Set(named.length > 0 ? named : fallbackPaths())].slice(0, MAX_LIST);
185
207
  const repositoriesNeeded = readRepositoriesNeeded(block?.repositoriesNeeded);
186
208
  const wrongRepository = readWrongRepository(block?.wrongRepository);
187
209
  const size = PLAN_SIZES.find((known) => known === block?.size);
@@ -199,6 +221,7 @@ export function buildPlanFile(planText, fallbackPaths) {
199
221
  followUps: readFollowUps(block?.followUps),
200
222
  ...(size ? { size } : {}),
201
223
  ...(size && sizeReason ? { sizeReason } : {}),
224
+ ...(closeTicket ? { closeTicket } : {}),
202
225
  },
203
226
  found: block !== null,
204
227
  };
@@ -38,7 +38,7 @@ export function planReviewTask(inputDir, planText, round) {
38
38
  `Read the ticket, every image it names, and ${at("checks.json")}, ${at("memo.md")} and ${at("playbook.md")} when they exist. Then read the code the plan touches. Change nothing in the repository and commit nothing.`,
39
39
  [
40
40
  "Judge the plan on these questions, and verify each against the code before you answer it:",
41
- '1. Ticket check: does the plan open with a premises table, each premise checked with the command, file or query that shows it, or marked as not checkable, and with "Done when"? Is a premise it marks as checked really true? A missing ticket check, a missing "Done when", or a false premise is major.',
41
+ '1. Ticket check: does the plan open with a premises table, each premise checked with the command, file or query that shows it, or marked as not checkable, and with "Done when"? Is a premise it marks as checked really true? A missing ticket check, a missing "Done when", or a false premise is major. A plan that recommends closing the ticket because its problem is already gone: check that evidence yourself; a close the code does not support is major.',
42
42
  "2. Half-measures: is any step a shortcut where the right fix is known and cheap now?",
43
43
  "3. Needless complexity: a new file, abstraction, option or flag the ticket does not need?",
44
44
  "4. Unintended side effects: other callers of the code it changes, shared state, contracts, data. Search for the callers; do not guess.",
@@ -122,6 +122,8 @@ export async function runStage(stage, ctx, deps) {
122
122
  stderr: "",
123
123
  toolCalls: 0,
124
124
  toolErrors: 0,
125
+ editCalls: 0,
126
+ editErrors: 0,
125
127
  };
126
128
  try {
127
129
  const invocation = buildStageInvocation(stage, {
@@ -329,11 +331,13 @@ export async function runStage(stage, ctx, deps) {
329
331
  result.stderr = stderr;
330
332
  result.finalOutput = capOutput(finalOutputFrom(acc));
331
333
  result.usage = acc.usage;
332
- // R3-a: tap tool-result counts into stage health. The orchestrator turns
333
- // this ratio into a write-stage failure when most edits errored, so a
334
- // clean-looking summary can't mask a silent partial implement.
334
+ // R3-a: tap tool-result counts into stage health. The write-stage gate
335
+ // turns the edit / write ratio into a failure when most edits errored, so
336
+ // a clean-looking summary can't mask a silent partial implement.
335
337
  result.toolCalls = acc.toolCalls;
336
338
  result.toolErrors = acc.toolErrors;
339
+ result.editCalls = acc.editCalls;
340
+ result.editErrors = acc.editErrors;
337
341
  if (acc.stopReason)
338
342
  result.stopReason = acc.stopReason;
339
343
  if (acc.errorMessage)
@@ -47,7 +47,7 @@ import { type AttemptResult, type CloudIdentity, type CloudStage } from "./cloud
47
47
  import type { ContinuationInputs } from "./continuation.js";
48
48
  import { type PlanChange } from "./planChanges.js";
49
49
  import { type RunStageDeps } from "./runner.js";
50
- import { type JsonEvent, type ModelTier, type PipelineStage, type StageId, type StageResult, type StopReason } from "./types.js";
50
+ import type { JsonEvent, ModelTier, PipelineStage, StageId, StageResult, StopReason } from "./types.js";
51
51
  import { type VerifyCheckRun } from "./verify.js";
52
52
  import { snapshotWorkspace } from "./workspace.js";
53
53
  import type { WorktreeExec } from "./worktree.js";
@@ -145,7 +145,9 @@ export declare function childStderrTail(stderr: string): string;
145
145
  /**
146
146
  * The turn's stop as the result names it: aborted, its clock, a model proxy
147
147
  * that refused it for what the run may spend, a child that failed, a writing
148
- * turn whose tools mostly errored (the cloud lane's health gate), else clean.
148
+ * turn whose edits and writes mostly errored (the cloud lane's health gate),
149
+ * else clean. Red tests and empty searches are errored `bash` calls and never
150
+ * count: the gate asks whether the edits landed.
149
151
  */
150
152
  export declare function turnStop(run: StageResult, writes: boolean, aborted: boolean): {
151
153
  stop: StopReason;
@@ -60,7 +60,7 @@ import { runStage as defaultRunStage } from "./runner.js";
60
60
  import { scrubSecrets } from "./scrubSecrets.js";
61
61
  import { DECISIONS_READ_TOOL, PLAN_JSON_CONTRACT } from "./stages.js";
62
62
  import { STAGE_WRAP_UP_GRACE_MS } from "./stageClock.js";
63
- import { MIN_TOOL_CALLS_FOR_HEALTH, TOOL_ERROR_FAIL_RATE, } from "./types.js";
63
+ import { editsMostlyFailed } from "./events.js";
64
64
  import { baselineDirs, parseChangedPaths, planPaths } from "./verify.js";
65
65
  import { snapshotWorkspace } from "./workspace.js";
66
66
  /** The one tier the session's writer runs on; its subagents keep their own. */
@@ -183,13 +183,15 @@ const INPUTS = (inputDir) => [
183
183
  "- playbook.md: the Team's planning rules. Always follow them.",
184
184
  "- plan-line.md: this Team's instructions for planning.",
185
185
  ].join("\n");
186
+ /** A close recommendation sent back is a person's call that the ticket needs work. */
187
+ const PLANNED_ANYWAY = "If the plan sent back recommended closing the ticket, the person chose to plan it anyway: plan the change, and do not recommend closing it again.";
186
188
  const PLAN_RULES = [
187
189
  "This turn you have read, grep, find, ls, bash, ask_yagni, team_read, prototype_read and subagent, and no edit or write tool.",
188
190
  "Run whatever settles a fact: the tests, a type check, the app, Docker, a query. Change no tracked file and commit nothing: anything this turn changes in the repository is put back before the plan's gate.",
189
191
  `Call team_read with tool "${DECISIONS_READ_TOOL}" before you ask a person anything: a question an earlier decision on this repository already answers is not a question.`,
190
192
  "Check the ticket before you plan on it: each premise it states that the plan relies on, against the code, the git history or the data.",
191
193
  "End the turn with the plan as your last message. Open it with ## Ticket check: a table of premise | checked, or not checkable | the command, file:line or query that shows it, one row per premise. Then ## Done when: the ticket's acceptance criteria, or yours when it has none, one line each. Then ## Goal (one sentence), ## Plan (numbered steps, each naming the file or function), ## Files to modify / create (say \"new\" beside a file the plan creates), ## Checks and ## Risks, then the plan-json block. Where there is a real choice of approach, ask it as a decision question with your recommendation and its alternatives; the plan's steps follow your recommendation.",
192
- 'When the ticket check shows the problem is already gone, recommend closing the ticket instead of planning a change: ## Goal says so in one sentence, the ticket check holds the evidence, ## Plan has the one step "Close the ticket: nothing to build", and the plan-json block names no checks and no paths.',
194
+ 'When the ticket check shows the problem is already gone, recommend closing the ticket instead of planning a change: ## Goal says so in one sentence, the ticket check holds the evidence, ## Plan says "Nothing to build." with no numbered steps, and the plan-json block carries "closeTicket" with the evidence and names no checks and no paths. A person then decides whether to close it.',
193
195
  PLAN_JSON_CONTRACT,
194
196
  "Then stop: a fresh reviewer reads the plan next, and its major findings come back to you in this session to revise. A person approves the plan before anything is built.",
195
197
  ].join("\n\n");
@@ -203,7 +205,7 @@ export function turnMessage(facts) {
203
205
  const newSince = facts.newSinceLastTurn?.trim();
204
206
  if (facts.stage === "plan") {
205
207
  if (facts.resumed && facts.sentBack) {
206
- parts.push(`A person sent your plan back. What they asked is in ${at("ticket.md")}, and the plan they sent back is ${at("sent-back-plan.md")}. Plan again: keep what they did not ask to change.`);
208
+ parts.push(`A person sent your plan back. What they asked is in ${at("ticket.md")}, and the plan they sent back is ${at("sent-back-plan.md")}. Plan again: keep what they did not ask to change. ${PLANNED_ANYWAY}`);
207
209
  }
208
210
  else if (facts.resumed) {
209
211
  parts.push(`Plan this ticket again from ${at("ticket.md")}.`);
@@ -211,7 +213,7 @@ export function turnMessage(facts) {
211
213
  else {
212
214
  parts.push("This is the plan turn of a YAGNI attempt. Work the ticket as your playbook says, up to the plan: nothing is built until a person approves it.", INPUTS(facts.inputDir));
213
215
  if (facts.sentBack) {
214
- parts.push(`A person sent an earlier plan back: what they asked is in ${at("ticket.md")}, and that plan is ${at("sent-back-plan.md")}.`);
216
+ parts.push(`A person sent an earlier plan back: what they asked is in ${at("ticket.md")}, and that plan is ${at("sent-back-plan.md")}. ${PLANNED_ANYWAY}`);
215
217
  }
216
218
  }
217
219
  if (newSince)
@@ -371,7 +373,9 @@ export function childStderrTail(stderr) {
371
373
  /**
372
374
  * The turn's stop as the result names it: aborted, its clock, a model proxy
373
375
  * that refused it for what the run may spend, a child that failed, a writing
374
- * turn whose tools mostly errored (the cloud lane's health gate), else clean.
376
+ * turn whose edits and writes mostly errored (the cloud lane's health gate),
377
+ * else clean. Red tests and empty searches are errored `bash` calls and never
378
+ * count: the gate asks whether the edits landed.
375
379
  */
376
380
  export function turnStop(run, writes, aborted) {
377
381
  if (aborted || run.stopReason === "aborted")
@@ -394,12 +398,10 @@ export function turnStop(run, writes, aborted) {
394
398
  : ` (exit ${run.exitCode}, nothing on its stderr)`;
395
399
  return { stop: "failed", note: `The session's turn ended on an error${why}.` };
396
400
  }
397
- if (writes &&
398
- run.toolCalls >= MIN_TOOL_CALLS_FOR_HEALTH &&
399
- run.toolErrors / run.toolCalls > TOOL_ERROR_FAIL_RATE) {
401
+ if (writes && editsMostlyFailed(run)) {
400
402
  return {
401
403
  stop: "failed",
402
- note: `Tool failures: ${run.toolErrors} of ${run.toolCalls} tool calls errored, so its edits likely did not land.`,
404
+ note: `Tool failures: ${run.editErrors ?? 0} of ${run.editCalls ?? 0} edits and writes errored, so its edits likely did not land.`,
403
405
  };
404
406
  }
405
407
  return { stop: "clean" };
@@ -88,6 +88,12 @@ export declare const RIGHT_REPOSITORY_RULE: string;
88
88
  * repository goes in repositoriesNeeded, so the host offers the split.
89
89
  */
90
90
  export declare const FOLLOW_UPS_RULE: string;
91
+ /**
92
+ * A ticket whose problem is already gone (the ticket check shows it) is a
93
+ * close recommendation, not a plan: the host opens a Decision a person
94
+ * answers, Close the ticket or Plan it anyway, and nothing is built.
95
+ */
96
+ export declare const CLOSE_TICKET_RULE: string;
91
97
  export declare const PLAN_JSON_CONTRACT: string;
92
98
  /**
93
99
  * The one-attempt lane's session (`yagni go --headless --cloud`): plan,
@@ -187,6 +187,15 @@ export const FOLLOW_UPS_RULE = '- "followUps" lists what you found that the tick
187
187
  '- Never put off the ticket\'s own work ("for another session", "in a later ticket"). Plan all of ' +
188
188
  "what it asked for. Work it needs in another repository goes in repositoriesNeeded, so the ticket " +
189
189
  "is split, and is never left out of the plan.";
190
+ /**
191
+ * A ticket whose problem is already gone (the ticket check shows it) is a
192
+ * close recommendation, not a plan: the host opens a Decision a person
193
+ * answers, Close the ticket or Plan it anyway, and nothing is built.
194
+ */
195
+ export const CLOSE_TICKET_RULE = '- "closeTicket" is only for a ticket whose problem the ticket check shows is already gone: ' +
196
+ 'say why in one line and list the evidence, each the command, file:line or query and what it showed. ' +
197
+ 'Then the plan has no steps, and "checks" and "paths" stay empty. A person decides whether to close ' +
198
+ "the ticket. Leave it out whenever there is anything to build.";
190
199
  export const PLAN_JSON_CONTRACT = "End your answer with a fenced ```plan-json block and nothing after it:\n" +
191
200
  "```plan-json\n" +
192
201
  "{\n" +
@@ -204,7 +213,8 @@ export const PLAN_JSON_CONTRACT = "End your answer with a fenced ```plan-json bl
204
213
  ' "dependsOn": [{"repository": "owner/name", "what": "one line on what it needs there"}],\n' +
205
214
  ' "size": "small|standard|complex",\n' +
206
215
  ' "sizeReason": "one line on why the size",\n' +
207
- ' "followUps": [{"title": "...", "why": "one line", "repository": "owner/name"}]\n' +
216
+ ' "followUps": [{"title": "...", "why": "one line", "repository": "owner/name"}],\n' +
217
+ ' "closeTicket": {"why": "one line", "evidence": ["the command, file:line or query, and what it showed"]}\n' +
208
218
  "}\n" +
209
219
  "```\n" +
210
220
  "Rules the host enforces, so getting them wrong loses the question:\n" +
@@ -227,7 +237,9 @@ export const PLAN_JSON_CONTRACT = "End your answer with a fenced ```plan-json bl
227
237
  "\n" +
228
238
  RIGHT_REPOSITORY_RULE +
229
239
  "\n" +
230
- FOLLOW_UPS_RULE;
240
+ FOLLOW_UPS_RULE +
241
+ "\n" +
242
+ CLOSE_TICKET_RULE;
231
243
  /**
232
244
  * The cloud plan stage's task: the input folder the host wrote, read first,
233
245
  * then a plan grounded in the installed checkout, inside the stage's own
@@ -143,16 +143,22 @@ export interface StageResult {
143
143
  errorMessage?: string;
144
144
  stderr: string;
145
145
  /**
146
- * Tool-call health for this stage (R3-a). `toolCalls` is how many tools the
147
- * child actually executed (`tool_execution_end` events); `toolErrors` is how
148
- * many of those returned an error. The orchestrator folds the ratio into the
149
- * write-stage health check so an implement / fix stage that exits 0 with a
150
- * clean-looking summary while most of its edits failed is caught rather than
151
- * trusted. Both default to 0 (no tools observed), which is below
152
- * MIN_TOOL_CALLS_FOR_HEALTH and so never trips the guard.
146
+ * Tool-call counts for this stage. `toolCalls` is how many tools the child
147
+ * actually executed (`tool_execution_end` events); `toolErrors` is how many of
148
+ * those returned an error. Kept for logs and handoffs: a red test run or an
149
+ * empty search is an errored `bash` call, so these never feed a health gate.
153
150
  */
154
151
  toolCalls: number;
155
152
  toolErrors: number;
153
+ /**
154
+ * The `edit` / `write` subset of the counts above: the only calls the
155
+ * write-stage health gate (R3-a, `editsMostlyFailed`) reads, so an implement /
156
+ * fix stage that exits 0 with a clean-looking summary while most of its edits
157
+ * failed is caught rather than trusted. Absent means none observed (a
158
+ * caller-injected runStage seam), which never trips the gate.
159
+ */
160
+ editCalls?: number;
161
+ editErrors?: number;
156
162
  /**
157
163
  * How many stdout lines this stage discarded for exceeding the max line size
158
164
  * (`RunStageDeps.maxLineBytes`). A pathologically long single NDJSON line (a
@@ -613,14 +619,16 @@ export interface ResiliencePolicy {
613
619
  export declare const DEFAULT_RESILIENCE_POLICY: ResiliencePolicy;
614
620
  /**
615
621
  * R3-a tool-failure health gate. A WRITE stage (implement / fix) that exits 0 is
616
- * still a failure when most of its tool calls errored: the prose summary reads
617
- * fine while the edits never landed (the recorded silent-partial-implement
618
- * landmine). Conservative by design — BOTH guards must hold before a stage is
619
- * failed for tool errors, so a couple of expected misses never trip it:
620
- * - `TOOL_ERROR_FAIL_RATE`: the error rate must EXCEED this clear majority, so a
621
- * grep that finds nothing or one transient error among many calls is fine.
622
- * - `MIN_TOOL_CALLS_FOR_HEALTH`: require a meaningful sample first, so a stage
623
- * that made only one or two tool calls is never failed on a tiny ratio.
622
+ * still a failure when most of its `edit` / `write` calls errored: the prose
623
+ * summary reads fine while the edits never landed (the recorded
624
+ * silent-partial-implement landmine). Only those calls count: a red test run or
625
+ * a grep that finds nothing is a `bash` call that errored, not a failed edit.
626
+ * Conservative by design — BOTH guards must hold before a stage is failed:
627
+ * - `TOOL_ERROR_FAIL_RATE`: the edit error rate must EXCEED this clear
628
+ * majority, so one stale edit among many is fine.
629
+ * - `MIN_TOOL_CALLS_FOR_HEALTH`: require a meaningful sample of edits and
630
+ * writes first, so a stage that made only one or two is never failed on a
631
+ * tiny ratio.
624
632
  * Tunable per lane if a future stage needs a stricter or looser bar.
625
633
  */
626
634
  export declare const TOOL_ERROR_FAIL_RATE = 0.6;
@@ -54,14 +54,16 @@ export const DEFAULT_RESILIENCE_POLICY = {
54
54
  };
55
55
  /**
56
56
  * R3-a tool-failure health gate. A WRITE stage (implement / fix) that exits 0 is
57
- * still a failure when most of its tool calls errored: the prose summary reads
58
- * fine while the edits never landed (the recorded silent-partial-implement
59
- * landmine). Conservative by design — BOTH guards must hold before a stage is
60
- * failed for tool errors, so a couple of expected misses never trip it:
61
- * - `TOOL_ERROR_FAIL_RATE`: the error rate must EXCEED this clear majority, so a
62
- * grep that finds nothing or one transient error among many calls is fine.
63
- * - `MIN_TOOL_CALLS_FOR_HEALTH`: require a meaningful sample first, so a stage
64
- * that made only one or two tool calls is never failed on a tiny ratio.
57
+ * still a failure when most of its `edit` / `write` calls errored: the prose
58
+ * summary reads fine while the edits never landed (the recorded
59
+ * silent-partial-implement landmine). Only those calls count: a red test run or
60
+ * a grep that finds nothing is a `bash` call that errored, not a failed edit.
61
+ * Conservative by design — BOTH guards must hold before a stage is failed:
62
+ * - `TOOL_ERROR_FAIL_RATE`: the edit error rate must EXCEED this clear
63
+ * majority, so one stale edit among many is fine.
64
+ * - `MIN_TOOL_CALLS_FOR_HEALTH`: require a meaningful sample of edits and
65
+ * writes first, so a stage that made only one or two is never failed on a
66
+ * tiny ratio.
65
67
  * Tunable per lane if a future stage needs a stricter or looser bar.
66
68
  */
67
69
  export const TOOL_ERROR_FAIL_RATE = 0.6;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yagni-app/code-staging",
3
- "version": "1.2.14-staging.2317.1",
3
+ "version": "1.2.14-staging.2329.1",
4
4
  "description": "YAGNI Code: a terminal coding agent that already knows your company. One YAGNI login routes the model and grounds the agent in your team's context.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "YAGNI, Inc. <jack@yagni.app> (https://yagni.app)",
@@ -58,5 +58,5 @@
58
58
  "turndown": "^7.2.4",
59
59
  "typebox": "^1.3.15"
60
60
  },
61
- "yagniSourceSha": "34dfa9bb606273171731d9fb80e50cb00c80acc6"
61
+ "yagniSourceSha": "4009370819d40589e460eec32c9cfdb6e3939930"
62
62
  }