@0perator/operator 0.1.358 → 0.1.359-next.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.
@@ -19,6 +19,7 @@ import { signIn, signInWithEmail, signInWithToken } from "./sign-in.js";
19
19
  import { isBetaRefusal, privateBetaMessage } from "./beta.js";
20
20
  import { loadCredentials, clearCredentials } from "./store.js";
21
21
  import { listByoAccounts, hasByoToken, deleteByoToken, setByoTokenInteractive } from "./byo.js";
22
+ import { ghInstalled, ghAuthStatus, ghLogin, ghSwitch } from "./gh-account.js";
22
23
  import { auditControl } from "../telemetry/lifecycle.js";
23
24
  import { loadSettings, saveSettings } from "../config/settings.js";
24
25
  import { BYO_PRESETS } from "../router/models.js";
@@ -237,6 +238,81 @@ async function byoModel(rest) {
237
238
  console.error(`model "${id}" registered but no key stored yet — run: operator auth byo-key ${account}`);
238
239
  return 1;
239
240
  }
241
+ const GH_MISSING = "✗ GitHub CLI (gh) not found — install it from https://cli.github.com, then re-run";
242
+ /** `operator auth gh-account add [--hostname <h>] [--git-protocol https|ssh] [--token-stdin]` — authorize
243
+ * another GitHub account through the gh CLI, which owns the secure credential store (like byo's keychain,
244
+ * but gh's own). A token rides on STDIN (`--token-stdin` → `gh auth login --with-token`), never argv; with
245
+ * no token, gh's interactive sign-in runs on the TTY. */
246
+ async function ghAccountAdd(rest, stdin) {
247
+ if (!ghInstalled()) {
248
+ console.error(GH_MISSING);
249
+ return 1;
250
+ }
251
+ const hostname = flagValue(rest, "--hostname");
252
+ const gitProtocol = flagValue(rest, "--git-protocol");
253
+ let token;
254
+ if (rest.includes("--token-stdin")) {
255
+ token = await readSecretFromStream(stdin);
256
+ if (!token) {
257
+ console.error("✗ --token-stdin: nothing on stdin (pipe the token in, e.g. `pass show gh | operator auth gh-account add --token-stdin`)");
258
+ return 1;
259
+ }
260
+ }
261
+ if (ghLogin({ hostname, gitProtocol, token }) !== 0) {
262
+ console.error("✗ gh auth login failed");
263
+ return 1;
264
+ }
265
+ console.log("✓ GitHub account added — `operator auth gh-account list` to see it, `operator auth gh-account switch <user>` to make it active");
266
+ await audit("credential_stored", `gh-account host=${hostname ?? "github.com"}`);
267
+ return 0;
268
+ }
269
+ /** `operator auth gh-account list [--hostname <h>]` — the GitHub accounts gh knows, active one marked. */
270
+ async function ghAccountList(rest) {
271
+ if (!ghInstalled()) {
272
+ console.error(GH_MISSING);
273
+ return 1;
274
+ }
275
+ const hostname = flagValue(rest, "--hostname");
276
+ const { status, accounts, raw } = ghAuthStatus(undefined, hostname);
277
+ if (!accounts.length) {
278
+ console.log(raw.trim() || "(no GitHub accounts yet — `operator auth gh-account add`)");
279
+ return status === 0 ? 0 : 1; // gh auth status exits non-zero when nothing is signed in
280
+ }
281
+ for (const a of accounts)
282
+ console.log(`${a.active ? "✓" : "○"} ${a.user} @ ${a.host}${a.active ? " (active)" : ""}`);
283
+ return 0;
284
+ }
285
+ /** `operator auth gh-account switch <user> [--hostname <h>]` — make that account the active one for every
286
+ * later git/gh call (`gh auth switch`). No user + several accounts → gh prompts on the TTY. */
287
+ async function ghAccountSwitch(rest) {
288
+ if (!ghInstalled()) {
289
+ console.error(GH_MISSING);
290
+ return 1;
291
+ }
292
+ const user = rest.find((a) => !a.startsWith("--"));
293
+ const hostname = flagValue(rest, "--hostname");
294
+ if (ghSwitch({ user, hostname }) !== 0) {
295
+ console.error(`✗ gh auth switch failed${user ? ` for "${user}"` : ""} — \`operator auth gh-account list\` shows your accounts`);
296
+ return 1;
297
+ }
298
+ await audit("auth_login", `gh-account switch user=${user ?? "prompted"} host=${hostname ?? "github.com"}`);
299
+ return 0;
300
+ }
301
+ /** Dispatch `operator auth gh-account <add|list|switch>` — add + switch GitHub accounts so a reviewer can
302
+ * move between them without re-running `gh auth login` each time. */
303
+ async function ghAccount(rest, stdin) {
304
+ const [sub, ...args] = rest;
305
+ switch (sub) {
306
+ case "add": return ghAccountAdd(args, stdin);
307
+ case "list":
308
+ case "status": return ghAccountList(args);
309
+ case "switch":
310
+ case "use": return ghAccountSwitch(args);
311
+ default:
312
+ console.log("usage: operator auth gh-account <add [--hostname <h>] [--git-protocol https|ssh] [--token-stdin] | list | switch <user> [--hostname <h>]>");
313
+ return sub ? 1 : 0;
314
+ }
315
+ }
240
316
  /** First-run sign-in: the two-choice screen (1 account / 2 token), shown before the TUI mounts when there is
241
317
  * no stored token. Pressing Enter picks the browser path; an empty choice other than 1/2, or Ctrl-C, skips —
242
318
  * the caller still starts the session. Returns the stored token on success, or null when skipped/failed, so
@@ -288,8 +364,10 @@ export async function runAuth(argv, settings, stdin = process.stdin) {
288
364
  case "byo-model": return byoModel(rest);
289
365
  case "byo-key":
290
366
  case "byo": return byoKey(rest); // byo = back-compat alias of byo-key
367
+ case "gh-account":
368
+ case "gh": return ghAccount(rest, stdin); // gh = short alias of gh-account
291
369
  default:
292
- console.log("usage: operator auth <login [--email <addr> | --browser | --token-stdin | --token <pat>] | logout | status | byo-model [--preset <p> | --id <id> --base <url> --model <name> …] | byo-key <account> [--list | --rm]>");
370
+ console.log("usage: operator auth <login [--email <addr> | --browser | --token-stdin | --token <pat>] | logout | status | byo-model [--preset <p> | --id <id> --base <url> --model <name> …] | byo-key <account> [--list | --rm] | gh-account <add | list | switch <user>>>");
293
371
  return sub ? 1 : 0;
294
372
  }
295
373
  }
@@ -0,0 +1,91 @@
1
+ // GitHub-account driver for `operator auth gh-account <add|list|switch>` — multiple GitHub logins so a
2
+ // reviewer can move between accounts without hand-running `gh auth login` each time. GitHub is NOT an LLM
3
+ // provider key (byo.ts): the credential is a `gh` login / a GitHub token, and the `gh` CLI already owns a
4
+ // secure multi-account store (its keyring / OS keychain) plus `gh auth switch`. So this is a THIN wrapper —
5
+ // we store nothing ourselves; we drive gh. Like byo.ts, the secret never rides argv: a token goes to
6
+ // `gh auth login --with-token` on STDIN (`ps` / launchd logs would show argv), and interactive login hands
7
+ // gh the real TTY. The gh invocation is injectable (`spawn`) so tests assert argv without a real gh — and
8
+ // without ever touching the owner's live accounts (reference-jl2-github-auth: never `gh auth switch` blind).
9
+ import { spawnSync } from "node:child_process";
10
+ /** True when the `gh` binary resolves and answers `--version` — mirrors agent-cli availability gating. */
11
+ export function ghInstalled(spawn = spawnSync) {
12
+ // owned-exempt: spawnSync is synchronous — it blocks until gh exits and cannot outlive /exit
13
+ const r = spawn("gh", ["--version"], { stdio: "ignore" });
14
+ return !r.error && (r.status ?? 1) === 0;
15
+ }
16
+ /**
17
+ * `gh auth status` → the logged-in accounts, with the active one flagged. Parsing is best-effort over gh's
18
+ * human output (across versions); `raw` is kept so a caller can fall back to gh's own words when parsing
19
+ * finds nothing (e.g. not signed in). Read-only.
20
+ */
21
+ export function ghAuthStatus(spawn = spawnSync, hostname) {
22
+ const args = ["auth", "status"];
23
+ if (hostname)
24
+ args.push("--hostname", hostname);
25
+ // owned-exempt: spawnSync is synchronous — it blocks until gh exits and cannot outlive /exit
26
+ const r = spawn("gh", args, { encoding: "utf8" });
27
+ // gh writes the report to stdout (2.40+) or stderr (older) — read both.
28
+ const raw = `${r.stdout ?? ""}${r.stderr ?? ""}`;
29
+ return { status: r.status ?? (r.error ? 127 : 1), accounts: parseGhAccounts(raw), raw };
30
+ }
31
+ /**
32
+ * Parse `gh auth status` output into accounts. Handles the multi-account format
33
+ * ("✓ Logged in to github.com account USER (keyring)" + "- Active account: true") and the older
34
+ * single-account one ("✓ Logged in to github.com as USER (oauth_token)"), which has no active marker and so
35
+ * is treated as active when it is the only login. Pure — the unit tests pin it against real gh fixtures.
36
+ */
37
+ export function parseGhAccounts(text) {
38
+ const accounts = [];
39
+ let last = -1;
40
+ for (const line of text.split("\n")) {
41
+ const m = /Logged in to (\S+) (?:account|as) ([^\s(]+)/.exec(line);
42
+ if (m) {
43
+ accounts.push({ host: m[1], user: m[2], active: false });
44
+ last = accounts.length - 1;
45
+ continue;
46
+ }
47
+ if (last >= 0 && /Active account:\s*true/i.test(line))
48
+ accounts[last].active = true;
49
+ }
50
+ if (accounts.length === 1 && !accounts[0].active)
51
+ accounts[0].active = true;
52
+ return accounts;
53
+ }
54
+ /**
55
+ * Add / authorize a GitHub account via `gh auth login`. With a token it is non-interactive
56
+ * (`--with-token`, token on STDIN); without one, gh's interactive sign-in runs on the inherited TTY. Returns
57
+ * gh's exit code (0 = ok, 127 = gh missing). gh persists the credential in its own secure store.
58
+ */
59
+ export function ghLogin(opts) {
60
+ const spawn = opts.spawn ?? spawnSync;
61
+ const args = ["auth", "login"];
62
+ if (opts.hostname)
63
+ args.push("--hostname", opts.hostname);
64
+ if (opts.gitProtocol)
65
+ args.push("--git-protocol", opts.gitProtocol);
66
+ if (opts.token !== undefined) {
67
+ args.push("--with-token");
68
+ // owned-exempt: spawnSync is synchronous — it blocks until gh exits and cannot outlive /exit
69
+ const r = spawn("gh", args, { input: `${opts.token}\n`, stdio: ["pipe", "inherit", "inherit"] });
70
+ return r.status ?? (r.error ? 127 : 1);
71
+ }
72
+ // owned-exempt: spawnSync is synchronous — it blocks until gh exits and cannot outlive /exit
73
+ const r = spawn("gh", args, { stdio: "inherit" });
74
+ return r.status ?? (r.error ? 127 : 1);
75
+ }
76
+ /**
77
+ * Select the active GitHub account with `gh auth switch` — this flips the account every later git/gh call
78
+ * uses, which is the whole point for a reviewer. With no `user` and several accounts, gh prompts on the
79
+ * inherited TTY. Returns gh's exit code (0 = ok, 127 = gh missing).
80
+ */
81
+ export function ghSwitch(opts) {
82
+ const spawn = opts.spawn ?? spawnSync;
83
+ const args = ["auth", "switch"];
84
+ if (opts.hostname)
85
+ args.push("--hostname", opts.hostname);
86
+ if (opts.user)
87
+ args.push("--user", opts.user);
88
+ // owned-exempt: spawnSync is synchronous — it blocks until gh exits and cannot outlive /exit
89
+ const r = spawn("gh", args, { stdio: "inherit" });
90
+ return r.status ?? (r.error ? 127 : 1);
91
+ }
package/dist/cli.js CHANGED
@@ -38,7 +38,7 @@ import { cacheBustNotice } from "./engine/aurora.js";
38
38
  import { seedCalibration } from "./engine/calibration-seed.js";
39
39
  import { AuroraRouter } from "./router/router.js";
40
40
  import { BackgroundAgents } from "./background/index.js";
41
- import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, applySeat, setActiveSeat, buildEndpointChain, parseContextArg, nextContextPin } from "./config/settings.js";
41
+ import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, eagerAuthAtBoot, applySeat, setActiveSeat, buildEndpointChain, parseContextArg, nextContextPin } from "./config/settings.js";
42
42
  import { resolveSeat } from "./auth/identity.js";
43
43
  import { PermissionPolicy } from "./permissions/index.js";
44
44
  import { caps } from "./ui/capabilities.js";
@@ -229,14 +229,17 @@ try {
229
229
  setOperatorToken(process.env.KODE_OPERATOR_TOKEN || creds?.token || undefined);
230
230
  }
231
231
  catch { /* auth is optional — a local engine needs none */ }
232
- // First-run sign-in. The very first interactive launch with no stored token shows the two-choice screen
233
- // (1 sign in with your account · 2 use an API token) BEFORE the session mounts, like Codex / Claude Code.
234
- // Strictly gated so nothing else changes: only a real TTY on a bare `operator` launch (no subcommand), only
235
- // when there is no token at all. A headless `operator run`, any `operator <sub>`, a piped stdin, or an
236
- // OPERATOR_TOKEN / KODE_OPERATOR_TOKEN in the environment all skip it — the headless path stays byte-identical.
232
+ // First-run sign-in. OPT-IN (connectors.eagerAuth / KODE_EAGER_AUTH), OFF by default so launch is SILENT:
233
+ // a fresh install must never fling open a browser device-grant / OAuth-consent page on startup — the account
234
+ // and every BYO connector authorize LAZILY, on first use (`operator auth login`, `/login`, or a signed-in-only
235
+ // feature prompts for it). When eager-auth is opted in, the very first interactive launch with no stored token
236
+ // shows the two-choice screen (1 account · 2 API token) BEFORE the session mounts, like Codex / Claude Code.
237
+ // Still strictly gated: only a real TTY on a bare `operator` launch (no subcommand), only with no token at all.
238
+ // A headless `operator run`, any `operator <sub>`, a piped stdin, or an OPERATOR_TOKEN / KODE_OPERATOR_TOKEN
239
+ // in the environment all skip it — the headless path stays byte-identical.
237
240
  const sub0 = process.argv[2];
238
241
  const envToken = process.env.OPERATOR_TOKEN || process.env.KODE_OPERATOR_TOKEN;
239
- const firstRunEligible = !bootCreds && !envToken && (!sub0 || sub0.startsWith("-"))
242
+ const firstRunEligible = eagerAuthAtBoot(settings) && !bootCreds && !envToken && (!sub0 || sub0.startsWith("-"))
240
243
  && !process.argv.includes("--version") && !process.argv.includes("-V") && !process.argv.includes("--help")
241
244
  && process.stdin.isTTY && process.stdout.isTTY;
242
245
  if (firstRunEligible) {
@@ -7,6 +7,15 @@ export const FEATURES = {
7
7
  default: false,
8
8
  description: "Enforce the options-vs-act EXCEPTION deterministically via the axe-classifier GLiClass gate",
9
9
  },
10
+ /** Method Ladder (engine/loop-guard.ts MethodLadder, wired in agent.ts): instead of STOPPING when a method is
11
+ * exhausted, name the methods already tried and force a CATEGORICALLY different one, keeping the turn alive until a
12
+ * real check passes or the budget of distinct methods is spent (then an honest partial-with-blocker — never a silent
13
+ * stop, never a spin, never a faked "done"). Replaces the one-shot finish directive. Default OFF: calibrate to zero
14
+ * false-stops + A/B before enabling. DESIGN: _ai-docs/2026-11-11-method-ladder-persist-to-completion.md. */
15
+ methodLadder: {
16
+ default: false,
17
+ description: "Persist by switching to a categorically different method until a harness-verified completion or an honest partial, instead of stopping",
18
+ },
10
19
  /** Cloud agents (autonomy/cloud-agent.ts): spawn an autonomous agent inside an ISOLATED DOCKER CONTAINER on a
11
20
  * configured fleet host (SSH or local), which clones the repo, runs a chosen agent CLI headless on a task,
12
21
  * pushes a branch and opens a PR — tracked/stoppable. Default OFF: the spawn_cloud_agent/list/status/stop
@@ -336,6 +336,17 @@ export function nextContextPin(current) {
336
336
  * else, so it isn't shared broadly until Operator is reliable enough to warrant it — widen the gate here to
337
337
  * roll it out further. Still token-gated at boot (no sign-in → silently starts nothing). Resolved here so
338
338
  * every surface reads it identically. */
339
+ /** Whether Operator may run the interactive first-run sign-in (browser device-grant / OAuth-consent) AT BOOT.
340
+ * Default OFF so a launch is SILENT and connectors/account auth stay LAZY (on first use). Opt in with
341
+ * connectors.eagerAuth:true or KODE_EAGER_AUTH=1. Precedence, first decisive wins: env → settings → false. */
342
+ export function eagerAuthAtBoot(s, env = process.env) {
343
+ const e = env.KODE_EAGER_AUTH?.trim().toLowerCase();
344
+ if (e === "1" || e === "true")
345
+ return true;
346
+ if (e === "0" || e === "false")
347
+ return false;
348
+ return s?.connectors?.eagerAuth === true;
349
+ }
339
350
  export function rcAutostart(s) {
340
351
  if (typeof s.remote?.autostart === "boolean")
341
352
  return s.remote.autostart; // explicit opt-in/out wins
@@ -10,10 +10,11 @@ import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampM
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
11
  import { classifyFailure, failureCause, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
12
  import { hostOf } from "./net-error.js";
13
- import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder } from "./verify-gate.js";
13
+ import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder, pendingVerifyCriterion } from "./verify-gate.js";
14
+ import { isFeatureEnabled } from "../config/features.js";
14
15
  import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
15
16
  import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
16
- import { LoopRecovery, IDEMPOTENT_TOOLS, LoopGuard, PollSpinGuard, NoWriteProgressGuard, YieldAfterDispatchGuard, loopStopNote, resolveLoopGuardConfig, LoopEvidenceTracker, loopRecoveryNote, noEditNudge, repeatedStepNudge, repeatedStepRedirect, reasoningLoopNudge, SELF_LOOP_NUDGE, staleRereadNudge, isSystemNotice, servedTask, CallLedger, callLabel, deadRoundNote, deadRoundStop, loopNudgeKind, refusedResult, resultFailed } from "./loop-guard.js";
17
+ import { LoopRecovery, MethodLadder, methodLadderStopNote, IDEMPOTENT_TOOLS, LoopGuard, PollSpinGuard, NoWriteProgressGuard, YieldAfterDispatchGuard, loopStopNote, resolveLoopGuardConfig, LoopEvidenceTracker, loopRecoveryNote, noEditNudge, repeatedStepNudge, repeatedStepRedirect, reasoningLoopNudge, SELF_LOOP_NUDGE, staleRereadNudge, isSystemNotice, servedTask, CallLedger, callLabel, deadRoundNote, deadRoundStop, loopNudgeKind, refusedResult, resultFailed } from "./loop-guard.js";
17
18
  import { inferType } from "./grandmaster.js";
18
19
  import { RunawayStreamWatch, ReasoningBudgetWatch, isDegenerateReply, REPETITION_INTERRUPTED, REASONING_BUDGET_INTERRUPTED } from "./repetition-guard.js";
19
20
  import { isBetaRefusal, privateBetaMessage } from "../auth/beta.js";
@@ -34,7 +35,7 @@ import { MUTATING_TOOLS, mutationLanded } from "../tools/mutating.js"; // single
34
35
  /** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
35
36
  * "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
36
37
  export const EXECUTOR_REPEAT_REFUSAL = /^loop guard: "[^"]+" called \d+x with identical args this turn/;
37
- import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, EMPTY_REPLY_NUDGE, fallbackLine, noAnswer, closeStopNote, stopQuestion, stopKind, stripEngineEcho, isEngineFinal } from "./continuation.js";
38
+ import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, needsDeliverFindings, DELIVER_FINDINGS_NUDGE, EMPTY_REPLY_NUDGE, fallbackLine, noAnswer, closeStopNote, stopQuestion, stopKind, stripEngineEcho, isEngineFinal } from "./continuation.js";
38
39
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
39
40
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
40
41
  const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
@@ -261,8 +262,9 @@ function observeVerify(v, calls, toolMsgs) {
261
262
  const results = toolMsgs.map((m) => m.content || "");
262
263
  v.observe(names, commands, results);
263
264
  }
264
- /** Feed one settled tool batch to the turn's loop evidence (reads, writes), index-aligned like observeVerify. */
265
- function observeLoop(ev, calls, toolMsgs) {
265
+ /** Feed one settled tool batch to the turn's loop evidence (reads, writes), index-aligned like observeVerify. The
266
+ * method ladder (when active) observes the same settled calls here — its masked skeleton is the method in play. */
267
+ function observeLoop(ev, calls, toolMsgs, ladder) {
266
268
  calls.forEach((c, i) => {
267
269
  let args = {};
268
270
  try {
@@ -272,6 +274,7 @@ function observeLoop(ev, calls, toolMsgs) {
272
274
  }
273
275
  catch { /* unparseable — no targets */ }
274
276
  ev.observe(c.function.name, args, toolMsgs[i]?.content ?? "");
277
+ ladder?.observe(c.function.name, args);
275
278
  });
276
279
  }
277
280
  // A turn the shell starts to deliver a job notice or a sub-agent report serves the LAST request, not the notice.
@@ -700,6 +703,11 @@ export async function runTurn(userInput, conversation, opts) {
700
703
  const callCounts = new Map();
701
704
  const guardCfg = resolveLoopGuardConfig(opts.loopGuard, { unattended: opts.unattended === true });
702
705
  const recovery = new LoopRecovery(guardCfg.recoveryAttempts);
706
+ // Method ladder (config/features.ts `methodLadder`, default OFF): when on, the terminal one-shot finish directive
707
+ // becomes a counted, diversity-gated ladder — a method exhausted forces a categorically different one and the turn
708
+ // stays alive until a real check passes or the budget of distinct methods is spent (then the honest partial). OFF =
709
+ // null everywhere, every path byte-identical to today (proven in test/method-ladder-wire.test.mts).
710
+ const ladder = isFeatureEnabled("methodLadder", { features: opts.features }) ? new MethodLadder(guardCfg.methodSwitches) : null;
703
711
  const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
704
712
  const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
705
713
  const yieldGuard = guardCfg.enabled ? new YieldAfterDispatchGuard(undefined, undefined, (opts.liveSubAgents?.() ?? 0) > 0) : undefined; // after spawn_agent (or from round one of a wake turn with sub-agents live): non-mutating rounds are waiting-with-busywork — yield so the reports resume the turn
@@ -747,6 +755,12 @@ export async function runTurn(userInput, conversation, opts) {
747
755
  const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? 1);
748
756
  let verifyNudges = 0;
749
757
  let unrunNudged = false; // the reported-check reminder fires at most once per turn
758
+ // The method ladder's completion criterion (verify-gate.ts): the pending check for a turn that changed files but has
759
+ // not passed one, named to the model as the "done" fact. undefined when nothing is pending — the ladder then uses its
760
+ // own generic wording. Read fresh at each halt (it tracks the turn's verify state and the model's own narration).
761
+ const ladderCriterion = () => pendingVerifyCriterion(verify, turnNotes.join("\n"));
762
+ let producedFindings = false; // (deliver-findings) a tool batch surfaced real content this turn — the mission has findings to deliver
763
+ let deliverFindingsNudged = false; // the deliver-findings nudge fires at most once per turn
750
764
  const unrestrictedEnabled = opts.unrestricted !== false; // default on — owner's private system
751
765
  // 0perator Computer feed (opt-in, additive): when the host wants a typed action stream, compose the two
752
766
  // tool callbacks here so runToolCalls stays untouched. The tracker pushes normalized start/end events into
@@ -926,12 +940,25 @@ export async function runTurn(userInput, conversation, opts) {
926
940
  if (attempt === undefined) {
927
941
  const d = guard?.halt ?? deadRoundStop(calls, Math.max(0, ...round.repeats.map((c) => callCounts.get(callSignature(c.name, c.args)) ?? 0)));
928
942
  if (guardCfg.finishDirective) {
929
- const dir = recovery.directive(d);
930
- if (dir) {
931
- guard?.resume();
932
- guard?.forgetResults();
933
- engineUser(dir);
934
- return true;
943
+ if (ladder) {
944
+ const sw = ladder.switch(d, ladderCriterion()); // the counted ladder replaces the one-shot directive
945
+ if (sw) {
946
+ guard?.resume();
947
+ guard?.forgetResults();
948
+ engineUser(sw);
949
+ return true;
950
+ }
951
+ if (ladder.switchesUsed > 0)
952
+ return stopTurn(methodLadderStopNote(d, ladder.switchesUsed), rounds + 1); // budget of distinct methods spent → partial-with-blocker
953
+ }
954
+ else {
955
+ const dir = recovery.directive(d);
956
+ if (dir) {
957
+ guard?.resume();
958
+ guard?.forgetResults();
959
+ engineUser(dir);
960
+ return true;
961
+ }
935
962
  }
936
963
  }
937
964
  return stopTurn(loopStopNote({ ...d, message: d.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
@@ -1671,7 +1698,7 @@ export async function runTurn(userInput, conversation, opts) {
1671
1698
  for (const tm of capToolRound(toolMsgs))
1672
1699
  conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
1673
1700
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
1674
- observeLoop(loopEv, response.toolCalls, toolMsgs);
1701
+ observeLoop(loopEv, response.toolCalls, toolMsgs, ladder);
1675
1702
  noteNarration(cleanAssistantProse(response.content));
1676
1703
  toolCallTotal += response.toolCalls.length;
1677
1704
  if (ownerActStage === 1)
@@ -1688,11 +1715,23 @@ export async function runTurn(userInput, conversation, opts) {
1688
1715
  const note = recovery.next(guard.halt);
1689
1716
  if (!note) {
1690
1717
  if (guardCfg.finishDirective) {
1691
- const dir = recovery.directive(guard.halt);
1692
- if (dir) {
1693
- guard.resume();
1694
- engineUser(dir);
1695
- continue;
1718
+ if (ladder) {
1719
+ const sw = ladder.switch(guard.halt, ladderCriterion()); // the counted ladder replaces the one-shot directive
1720
+ if (sw) {
1721
+ guard.resume();
1722
+ engineUser(sw);
1723
+ continue;
1724
+ }
1725
+ if (ladder.switchesUsed > 0)
1726
+ return stopTurn(methodLadderStopNote(guard.halt, ladder.switchesUsed), rounds + 1); // budget of distinct methods spent → partial-with-blocker
1727
+ }
1728
+ else {
1729
+ const dir = recovery.directive(guard.halt);
1730
+ if (dir) {
1731
+ guard.resume();
1732
+ engineUser(dir);
1733
+ continue;
1734
+ }
1696
1735
  }
1697
1736
  }
1698
1737
  return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
@@ -1702,6 +1741,8 @@ export async function runTurn(userInput, conversation, opts) {
1702
1741
  continue;
1703
1742
  }
1704
1743
  progressed = batchProgressed(toolMsgs);
1744
+ if (progressed)
1745
+ producedFindings = true; // (deliver-findings) a batch returned real content — the mission has something to deliver
1705
1746
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1706
1747
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1707
1748
  trackTouchedFiles(response.toolCalls, touchedFiles);
@@ -1786,7 +1827,7 @@ export async function runTurn(userInput, conversation, opts) {
1786
1827
  for (const tm of capToolRound(toolMsgs))
1787
1828
  conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
1788
1829
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
1789
- observeLoop(loopEv, recovered.calls, toolMsgs);
1830
+ observeLoop(loopEv, recovered.calls, toolMsgs, ladder);
1790
1831
  noteNarration(recovered.cleanedContent);
1791
1832
  toolCallTotal += recovered.calls.length;
1792
1833
  if (ownerActStage === 1)
@@ -1803,11 +1844,23 @@ export async function runTurn(userInput, conversation, opts) {
1803
1844
  const note = recovery.next(guard.halt);
1804
1845
  if (!note) {
1805
1846
  if (guardCfg.finishDirective) {
1806
- const dir = recovery.directive(guard.halt);
1807
- if (dir) {
1808
- guard.resume();
1809
- engineUser(dir);
1810
- continue;
1847
+ if (ladder) {
1848
+ const sw = ladder.switch(guard.halt, ladderCriterion()); // the counted ladder replaces the one-shot directive
1849
+ if (sw) {
1850
+ guard.resume();
1851
+ engineUser(sw);
1852
+ continue;
1853
+ }
1854
+ if (ladder.switchesUsed > 0)
1855
+ return stopTurn(methodLadderStopNote(guard.halt, ladder.switchesUsed), rounds + 1); // budget of distinct methods spent → partial-with-blocker
1856
+ }
1857
+ else {
1858
+ const dir = recovery.directive(guard.halt);
1859
+ if (dir) {
1860
+ guard.resume();
1861
+ engineUser(dir);
1862
+ continue;
1863
+ }
1811
1864
  }
1812
1865
  }
1813
1866
  return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
@@ -1817,6 +1870,8 @@ export async function runTurn(userInput, conversation, opts) {
1817
1870
  continue;
1818
1871
  }
1819
1872
  progressed = batchProgressed(toolMsgs);
1873
+ if (progressed)
1874
+ producedFindings = true; // (deliver-findings) a batch returned real content — the mission has something to deliver
1820
1875
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1821
1876
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1822
1877
  trackTouchedFiles(recovered.calls, touchedFiles);
@@ -1985,6 +2040,17 @@ export async function runTurn(userInput, conversation, opts) {
1985
2040
  engineUser(opts.unattended ? CLOSING_NUDGE_UNATTENDED : CLOSING_NUDGE);
1986
2041
  continue;
1987
2042
  }
2043
+ // Deliver-findings (owner-facing): an answer-first mission (review/search/research/plan) that DID the work and
2044
+ // surfaced real findings, then closed by asking the owner which direction to take or offering "another pass" —
2045
+ // holding the review back instead of delivering it (v0.1.358: found 31 repos + a 404 caveat, then "Which direction
2046
+ // — A/B/C?"). ONE nudge to deliver now. Conservative: never on a build/edit task (answerFirst), never a pre-work
2047
+ // clarifier or a blocker with nothing found (producedFindings), at most once; background sub-agents are never nudged.
2048
+ if (final && response.stopReason !== "length" && !deliverFindingsNudged && !opts.background && !isEngineFinal(final) && needsDeliverFindings(final, { answerFirst, hasFindings: producedFindings })) {
2049
+ deliverFindingsNudged = true;
2050
+ conversation.assistant(final);
2051
+ engineUser(DELIVER_FINDINGS_NUDGE);
2052
+ continue;
2053
+ }
1988
2054
  const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
1989
2055
  const answer = (unverified ? NOT_VERIFIED_BANNER : unrunChecks.length ? unrunCheckBanner(unrunChecks) : "") +
1990
2056
  (final || stripScratchpad(response.reasoningContent ?? "") || stripScratchpad(lastReasoning) ||
@@ -166,6 +166,36 @@ export function needsClosingSteer(content, hasOpenTasks) {
166
166
  return false;
167
167
  return true;
168
168
  }
169
+ // ── Deliver-findings (owner-facing) ──────────────────────────────────────────────────────────────────────────────
170
+ // The failure (real, operator v0.1.358, moa): asked to review memjar's repos, Operator DID the work — found 31
171
+ // (mostly private) repos, the local clone, and a 404-on-/readme caveat — then ended the turn with a QUESTION ("Which
172
+ // direction — A/B/C?" / "Want me to take another pass with a different approach?") and HELD the review back, instead of
173
+ // DELIVERING it. A review/research/search/plan mission is answer-first: once the work is done and real findings exist,
174
+ // the deliverable is the findings, not a question. One nudge turns the ask into the delivery.
175
+ //
176
+ // The "asking for direction / offering another pass" shape — anchored on the two documented forms and close variants,
177
+ // kept TIGHT (this ships ON): a trailing follow-up like "want me to also check the CI?" is not a held-back review and
178
+ // must not match, so only direction-choices and re-do offers count, not every closing question.
179
+ const DIRECTION_ASK_RE = /\b(?:which (?:direction|approach|option|route|one|of (?:these|those))|where (?:do you want me to|should i) (?:focus|start|dig|go|look)|(?:want me to|should i|shall i|would you like me to)\s+(?:take |do |make |run |give (?:it|this) )?(?:another|a (?:different|closer|deeper|fresh|new)) (?:pass|look|approach|angle|take|crack|attempt|go)|(?:take|do|make|run) another pass)\b/i;
180
+ export const DELIVER_FINDINGS_NUDGE = "This is a review/research mission and you have already done the work — so DELIVER the findings now, don't ask which " +
181
+ "direction to take or offer another pass. Give the owner the review itself: what you found, the specifics, and any gap " +
182
+ "or caveat (e.g. what you couldn't access and why). Lead with the substance; add ONE concrete next step only if it " +
183
+ "genuinely helps. Don't hold a finished review back behind a question.";
184
+ /** True when a text-only final should be redirected to DELIVER its findings rather than ask. Fires only on an
185
+ * answer-first mission (`answerFirst`: review/search/research/plan) that produced real findings (`hasFindings`), when
186
+ * the final ends on a question AND that question asks the owner for direction or offers "another pass". Conservative by
187
+ * construction: a pre-work clarifier and a blocker-with-nothing-found have `hasFindings` false; a build/edit task has
188
+ * `answerFirst` false; a plain report or a narrow follow-up question matches neither gate. */
189
+ export function needsDeliverFindings(final, o) {
190
+ if (!o.answerFirst || !o.hasFindings)
191
+ return false;
192
+ const text = (final ?? "").trim();
193
+ if (!text)
194
+ return false;
195
+ if (!QUESTION_RE.test(text))
196
+ return false; // it must close ON a question/ask — a report that merely mentions options is fine
197
+ return DIRECTION_ASK_RE.test(text);
198
+ }
169
199
  /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-answer note) rather than the model — the
170
200
  * flywheel must not grade it as the model's answer and a planner must not accept it as a sub-agent's result. "no reply
171
201
  * came back" is the no-answer note before 11/04, still in saved conversations and flywheel rows. */
@@ -27,6 +27,7 @@ export function resolveLoopGuardConfig(raw, ctx) {
27
27
  repetition: s.repetition !== false,
28
28
  recoveryAttempts: Math.min(5, intAtLeast(s.recovery?.maxAttempts, 2, 0)),
29
29
  finishDirective: s.finishDirective !== false,
30
+ methodSwitches: Math.min(5, intAtLeast(s.methodSwitches, 3, 0)),
30
31
  stopOnNoWrite: s.stopOnNoWrite === true,
31
32
  warnIdentical: intAtLeast(s.warnAfter?.identicalCall, d.warnIdentical, 2),
32
33
  warnExactFailure: intAtLeast(s.warnAfter?.exactFailure, d.warnExactFailure, 1),
@@ -592,6 +593,64 @@ export class LoopRecovery {
592
593
  `Finish something this turn. Never bypass a permission denial, invent missing information, or claim unverified success.`;
593
594
  }
594
595
  }
596
+ /** The METHOD LADDER (design: _ai-docs/2026-11-11-method-ladder-persist-to-completion.md). Replaces LoopRecovery's
597
+ * ONE-SHOT finish directive with a counted, diversity-gated ladder: instead of stopping when a method is exhausted,
598
+ * name the methods already tried and force a CATEGORICALLY different one, keeping the turn alive — until a real check
599
+ * passes (the caller's completion gate) or the budget of DISTINCT methods is spent, when the caller emits the honest
600
+ * partial-with-blocker (never a silent stop). Terminates by construction: `switches` is monotone, bounded by
601
+ * maxSwitches, and a method already exhausted never consumes a switch (a reworded retry cannot burn the budget).
602
+ * Side-effect free. Feature-flagged (config/features.ts methodLadder); wired in agent.ts behind that flag. */
603
+ export class MethodLadder {
604
+ maxSwitches;
605
+ tried = new Set(); // every method skeleton observed this turn
606
+ exhausted = new Set(); // methods that reached the ladder (hit their wall)
607
+ last = ""; // the most recent method skeleton
608
+ switches = 0;
609
+ constructor(maxSwitches) {
610
+ this.maxSwitches = maxSwitches;
611
+ }
612
+ get switchesUsed() { return this.switches; }
613
+ /** Feed every settled tool call: its masked skeleton is the method in play. A verified check resets the ladder
614
+ * elsewhere (a new sub-goal gets a fresh budget); within one wall this only accumulates. */
615
+ observe(name, args) {
616
+ this.last = callSkeleton(name, args).skeleton;
617
+ this.tried.add(this.last);
618
+ }
619
+ /** The counted method-switch note that replaces the one-shot finish directive. Returns undefined when the budget of
620
+ * DISTINCT methods is spent — the caller then emits the partial-with-blocker. A method that already hit the ladder
621
+ * does not consume a switch, so a reworded retry can never spend the budget. Caps and a completed-action repeat stay
622
+ * terminal (nothing to pivot to). */
623
+ switch(d, criterion) {
624
+ if (this.maxSwitches <= 0 || d.code === "web_search_cap" || d.code === "subagent_cap" || d.code === "completed_action")
625
+ return undefined;
626
+ const repeat = this.exhausted.has(this.last);
627
+ if (!repeat) {
628
+ if (this.switches >= this.maxSwitches)
629
+ return undefined; // budget of distinct methods spent → partial
630
+ this.switches++;
631
+ this.exhausted.add(this.last);
632
+ }
633
+ else if (this.switches >= this.maxSwitches) {
634
+ return undefined;
635
+ }
636
+ const tried = [...this.exhausted].filter(Boolean).slice(0, 6).map((s) => (s.length > 64 ? s.slice(0, 64) + "…" : s));
637
+ const done = criterion ? `complete only when this check passes: ${criterion}` : `complete only when a real check passes — run it, never claim success`;
638
+ return `Loop guard — method switch ${this.switches}/${this.maxSwitches} (the turn is NOT ending): the pattern is ${d.message}. ` +
639
+ (repeat ? `You returned to a method that already failed — ` : ``) +
640
+ `In ONE line say what you assumed and what happened, then pick a CATEGORICALLY DIFFERENT method for the same goal — a different tool, a different decomposition, a different data source/endpoint, or offline evidence you already have — NOT a reworded version of a method already tried` +
641
+ (tried.length ? ` (already tried and exhausted: ${tried.join(" ; ")})` : ``) + `. ` +
642
+ `The mission is ${done}. If no genuinely new method remains, deliver the best partial with the exact blocker and the one thing needed to clear it. Never bypass a permission denial, invent missing information, or claim unverified success.`;
643
+ }
644
+ }
645
+ /** The method ladder's terminal honest floor (R5): the budget of DISTINCT methods is spent, so the turn ends — but not
646
+ * on a bare stop. It names how many categorically different methods were tried and that they share one failure (the
647
+ * blocker), then frames the best partial + the one thing needed, so the owner is left with a partial-with-blocker, never
648
+ * a silent give-up. Replaces `loopStopNote` only when the ladder actually engaged (switchesUsed > 0). */
649
+ export function methodLadderStopNote(d, methodsTried) {
650
+ return `[stopped — I tried ${methodsTried} categorically different method${methodsTried === 1 ? "" : "s"} for this and each failed the same way (${d.message}). ` +
651
+ `That shared failure is the blocker. Here is the best partial I have, with the exact blocker above and the one input that would clear it — ` +
652
+ `tell me how you'd like to proceed, or give me that one thing and I'll continue.]`;
653
+ }
595
654
  export const noEditNudge = (n) => `You've run ${n} rounds of tools without changing a file. If you've found the root cause, ` +
596
655
  `make the change now and verify it. If you're still gathering context that's fine — but if you're ` +
597
656
  `going in circles, say so and switch to a genuinely different approach.`;
@@ -829,6 +888,128 @@ export function callLabel(name, args) {
829
888
  const c = canonical(args);
830
889
  return `${name} ${c.length > 100 ? c.slice(0, 100) + "…" : c}`;
831
890
  }
891
+ // ─── Struggle detector (advisory) — the same broken command TEMPLATE retried across different targets ────────────
892
+ // A tool/task/model-agnostic signal that complements the loop guard's EXACT-args counters. When a call fails and the
893
+ // SAME normalized skeleton (varying operands masked to §) fails again under the same failure bucket across DISTINCT
894
+ // operands, that is one broken template retargeted — NOT diagnosis, which changes the skeleton or the failure. The
895
+ // motivating cases: `gh … -q '{…defaultBranchRef…}'` retried across ~30 repos, each "(no output; exit 1)", the jq
896
+ // error hidden on stderr; and `gh api orgs/memjar/<repo>` 404'd per repo because memjar is a USER, not an org. This
897
+ // only POPULATES LoopEvidence.struggles — nothing reads it here, so there is no behaviour change until a later phase.
898
+ /** Distinct operands under one (skeleton, failureSig) before a broken template is called out. Conservative, and
899
+ * validated against the flywheel corpus (zero false struggles) before anything acts on it. */
900
+ export const STRUGGLE_MIN_LITERALS = 3;
901
+ const STRUGGLE_MASK = "§";
902
+ /** An operand VALUE that varies between retries of one template (a path, repo or URL). Identifiers and bare numbers
903
+ * are deliberately NOT masked in v1: they can be sub-commands, and over-masking would collapse genuine diagnosis
904
+ * into one bucket — the one load-bearing risk. The corpus calibration widens this only while false struggles stay
905
+ * at zero. */
906
+ function isMaskableOperand(w) {
907
+ if (w.startsWith("-") || w === "/dev/null")
908
+ return false;
909
+ return /^https?:\/\//.test(w) || PATHISH_RE.test(w);
910
+ }
911
+ /** The masked skeleton, the verb (for recovery matching) and the varying operands of one tool call. Shell: mask only
912
+ * POSITIONAL operand values (never a verb, a flag, or a flag's value — so a jq/pattern body stays verbatim, and a
913
+ * different body is a different skeleton = diagnosis). Other tools: canonical args with every scalar leaf replaced by
914
+ * its type tag, keys kept (the scalar values are what vary). Pure. */
915
+ /** The masked skeleton of one tool call (the method's shape) — reused by the self-improvement skill distiller to
916
+ * record the winning METHOD of a verified-success turn. */
917
+ export function toolSkeleton(name, args) {
918
+ return callSkeleton(name, args).skeleton;
919
+ }
920
+ function callSkeleton(name, args) {
921
+ if (SHELL_TOOLS.has(name) && typeof args.command === "string") {
922
+ const literals = [];
923
+ const segs = segments(shellWords(args.command)).map((seg) => seg.map((w, i, arr) => {
924
+ const afterFlag = i > 0 && typeof arr[i - 1] === "string" && arr[i - 1].startsWith("-") && arr[i - 1].length > 1;
925
+ if (i > 0 && !afterFlag && isMaskableOperand(w)) {
926
+ literals.push(w);
927
+ return STRUGGLE_MASK;
928
+ }
929
+ return w;
930
+ }));
931
+ const verb = (segs[0] ?? []).find((w) => !w.startsWith("-")) ?? "";
932
+ return { skeleton: `${name} ${segs.map((s) => s.join(" ")).join(" | ")}`, verb: `${name}:${verb}`, literals };
933
+ }
934
+ const literals = [];
935
+ const typed = (v) => {
936
+ if (Array.isArray(v))
937
+ return "[" + v.map(typed).join(",") + "]";
938
+ if (v && typeof v === "object")
939
+ return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + typed(v[k])).join(",") + "}";
940
+ if (typeof v === "string" && v)
941
+ literals.push(v);
942
+ return v === null ? "null" : `<${typeof v}>`;
943
+ };
944
+ return { skeleton: `${name} ${typed(args)}`, verb: name, literals };
945
+ }
946
+ /** The bucket a FAILED tool result falls in, or undefined when the call did not fail. Shared across retries of one
947
+ * broken template, specific enough that different errors do not group. */
948
+ function failureBucket(name, result) {
949
+ if (!resultFailed(name, result))
950
+ return undefined;
951
+ const t = result.trim();
952
+ const noout = /^\(no output; exit (\d+|\?)\)/.exec(t);
953
+ if (noout)
954
+ return `noout·exit${noout[1]}`;
955
+ const exit = EXIT_TRAILER_RE.exec(t);
956
+ const code = exit ? (exit[1] ?? exit[2]) : "?";
957
+ const lines = t.split("\n").map((l) => l.trim()).filter(Boolean);
958
+ // A Python/JS traceback's FIRST line is a generic header ("Traceback (most recent call last):") — the actual
959
+ // exception is on the LAST line, so bucketing on the first would group every unrelated traceback together.
960
+ let errLine = lines[0] ?? "";
961
+ if (lines.length > 1 && /^(?:traceback \(most recent call last\)|the above exception)/i.test(errLine))
962
+ errLine = lines[lines.length - 1];
963
+ const line = errLine.toLowerCase().replace(/\d+/g, "#").replace(/[^a-z#]+/g, " ").trim().split(" ").filter(Boolean).slice(0, 4).join(" ");
964
+ return `exit${code}·${line}`.slice(0, 48);
965
+ }
966
+ /** The lesson's fix hint: how the recovering call differed from the broken template. */
967
+ function struggleDelta(brokenSkeleton, fixArgs, fixSkeleton) {
968
+ const cmd = typeof fixArgs.command === "string" ? fixArgs.command : "";
969
+ if (/\s2>&1(\s|$)/.test(cmd) && !/\s2>&1(\s|$)/.test(brokenSkeleton))
970
+ return "captured stderr (2>&1)";
971
+ if (/(?:--jq|-q)\s+['"]?\./.test(cmd) && !/(?:--jq|-q)\s+['"]?\./.test(brokenSkeleton))
972
+ return "qualified the jq path (leading dot)";
973
+ const verb = fixSkeleton.replace(/^\S+\s+/, "").split(" ").filter((w) => w && w !== STRUGGLE_MASK && !w.startsWith("-")).slice(0, 3).join(" ");
974
+ return verb ? `used a different command (${verb})` : "changed the command";
975
+ }
976
+ /** Per-turn struggle detector, fed every settled tool call in order (side-effect free). */
977
+ export class StruggleTracker {
978
+ groups = new Map();
979
+ strugglingVerbs = new Set();
980
+ observe(name, args, result = "") {
981
+ if (refusedResult(result) || isRepeatable(name, args))
982
+ return;
983
+ const { skeleton, verb, literals } = callSkeleton(name, args);
984
+ const bucket = failureBucket(name, result);
985
+ if (bucket) {
986
+ const key = `${skeleton}\u0000${bucket}`;
987
+ let g = this.groups.get(key);
988
+ if (!g) {
989
+ g = { tool: name, verb, skeleton, failureSig: bucket, literals: new Set(), firstRaw: callLabel(name, args) };
990
+ this.groups.set(key, g);
991
+ }
992
+ for (const l of literals.length ? literals : [callLabel(name, args)])
993
+ g.literals.add(l);
994
+ if (g.literals.size >= STRUGGLE_MIN_LITERALS)
995
+ this.strugglingVerbs.add(verb);
996
+ }
997
+ else if (this.strugglingVerbs.has(verb)) {
998
+ for (const g of this.groups.values()) {
999
+ if (g.verb === verb && !g.recovered && g.skeleton !== skeleton) {
1000
+ g.recovered = { rawFix: callLabel(name, args), deltaHint: struggleDelta(g.skeleton, args, skeleton) };
1001
+ }
1002
+ }
1003
+ }
1004
+ }
1005
+ /** The broken templates this turn retried across at least STRUGGLE_MIN_LITERALS distinct operands, most-retried first. */
1006
+ struggles() {
1007
+ return [...this.groups.values()]
1008
+ .filter((g) => g.literals.size >= STRUGGLE_MIN_LITERALS)
1009
+ .sort((a, b) => b.literals.size - a.literals.size)
1010
+ .map((g) => ({ tool: g.tool, skeleton: g.skeleton, failureSig: g.failureSig, literals: [...g.literals], firstRaw: g.firstRaw, ...(g.recovered ? { recovered: g.recovered } : {}) }));
1011
+ }
1012
+ }
832
1013
  /** Per-turn loop evidence, fed in the order things happened: every nudge, every model reply, every settled tool call.
833
1014
  * Side-effect free. */
834
1015
  export class LoopEvidenceTracker {
@@ -853,6 +1034,7 @@ export class LoopEvidenceTracker {
853
1034
  staleFileReads = 0;
854
1035
  staleFresh = false; // a stale file re-read since the last staleRereadDue()
855
1036
  staleWarned = 0;
1037
+ struggle = new StruggleTracker();
856
1038
  constructor(cwd) {
857
1039
  this.cwd = cwd;
858
1040
  }
@@ -907,6 +1089,7 @@ export class LoopEvidenceTracker {
907
1089
  return [...this.staleFiles].map(([target, count]) => ({ target, count })).sort((a, b) => b.count - a.count);
908
1090
  }
909
1091
  observe(name, args, result = "") {
1092
+ this.struggle.observe(name, args, result); // advisory: populates evidence().struggles, changes nothing this phase
910
1093
  const head = result.trimStart();
911
1094
  if (REFUSED_RE.test(head))
912
1095
  return; // the call never ran
@@ -983,9 +1166,11 @@ export class LoopEvidenceTracker {
983
1166
  .map(([target, count]) => ({ target, count }))
984
1167
  .sort((a, b) => b.count - a.count)
985
1168
  .slice(0, top);
1169
+ const struggles = this.struggle.struggles();
986
1170
  return {
987
1171
  nudges: this.nudgeCount, kinds: { ...this.kinds }, ignored: this.ignoredCount, compactions: this.compactionCount, stale: this.staleCount, rereads,
988
1172
  ...(this.recoveryCount ? { recoveries: this.recoveryCount } : {}),
1173
+ ...(struggles.length ? { struggles } : {}),
989
1174
  };
990
1175
  }
991
1176
  }
@@ -157,6 +157,19 @@ export function unrunCheckReminder(checks) {
157
157
  export function unrunCheckBanner(checks) {
158
158
  return `⚠ Not verified — this answer reports ${checks.map((k) => (k === "tests" ? "passing tests" : "a clean type-check")).join(" and ")}, but ${checks.length > 1 ? "neither" : "it never"} ran this turn.\n\n`;
159
159
  }
160
+ /** The pending completion criterion for a turn that changed files but has not passed a check — handed to the method
161
+ * ladder's switch note so "done" is named as a fact to compute, not a phrase to emit. When the model's own narration
162
+ * (`claimed`) already reports a check that never ran, that exact check (via CHECK_COMMAND) is the criterion; otherwise
163
+ * a generic real-check criterion. undefined when nothing has changed (no pending verification — the ladder then uses
164
+ * its own generic wording). */
165
+ export function pendingVerifyCriterion(v, claimed = "") {
166
+ if (!v.gate())
167
+ return undefined;
168
+ const unrun = v.unrun(claimed);
169
+ if (unrun.length)
170
+ return unrun.map((k) => CHECK_COMMAND[k]).join(" and ") + " passes";
171
+ return "a real build, test, or run of what you changed passes — run it, never claim success";
172
+ }
160
173
  /** Injected as a user-role message for the ONE extra round. Prefixed so its provenance is unmistakably the
161
174
  * harness, not the user. Authorizes an honest escape so a docs edit / no-test repo ends cleanly, not stuck. */
162
175
  export const VERIFY_REMINDER = "[verify-before-done] You changed files this turn and are wrapping up, but no test, build, or run was " +
@@ -7,7 +7,9 @@ import { operatorPath, globalMemoriesPath } from "../config/home.js";
7
7
  import { redactSecrets } from "../engine/redact.js";
8
8
  import { isEngineFinal } from "../engine/continuation.js"; // a stop/pause/no-reply note is the engine's text, never a promotable answer
9
9
  import { isLooped } from "../engine/loop-guard.js";
10
- import { isSubagentBrief, loopLessonLine, ownerWords, reinforcedRules, stuckLessonLine, upsertLesson } from "./lessons.js";
10
+ import { fixLessonLine, isSubagentBrief, loopLessonLine, ownerWords, reinforcedRules, stuckLessonLine, upsertLesson } from "./lessons.js";
11
+ import { inferType } from "../engine/grandmaster.js";
12
+ import { methodFromSteps, mergeSkill, skillClassSlug } from "./skills.js";
11
13
  const nodeImport = (m) => import(/* @vite-ignore */ m);
12
14
  // GW-18 (flywheel gate): markers of a STRUCTURED tool call that leaked into the assistant's plain text instead
13
15
  // of being parsed into tool_calls — the documented Qwen3 failure when the server runs without `--jinja` (the
@@ -26,6 +28,13 @@ export function hasLeakedToolCall(content) {
26
28
  /** FLYWHEEL sink — append the turn as one JSONL row to a daily capture the fleet's training pipeline reads.
27
29
  * A turn that produced content, ran ≥1 round, and wasn't cut for repetition/abort is marked graded:true,
28
30
  * so downstream can filter to promotable trajectories without re-judging every row. */
31
+ /** A PROMOTABLE trajectory / a VERIFIED-SUCCESS turn: produced content, ran ≥1 round, not cut for repetition/abort,
32
+ * NOT unverified (the verify-before-done gate — a hollow "done" never counts), no leaked tool-call, not an
33
+ * engine-final note, not looped, not interrupted. The one source of this predicate: flywheelRow tags rows with it and
34
+ * the skill distiller (captureSkill) gates on it (the second save-time verify gate). */
35
+ export function isGraded(r) {
36
+ return !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !hasLeakedToolCall(r.content) && !isEngineFinal(r.content) && !isLooped(r.loop) && !r.interrupted;
37
+ }
29
38
  /** One turn's flywheel row: the day file it goes in (under the operator home's flywheel/) and the JSONL line. Pure. */
30
39
  export function flywheelRow(r, ts) {
31
40
  // graded = a promotable trajectory. A turn that changed files but never ran a passing check
@@ -38,7 +47,7 @@ export function flywheelRow(r, ts) {
38
47
  // A turn that ignored its loop warnings is the trajectory the loop must NOT learn from: the 11/02 review loop
39
48
  // (37 rounds re-reading five files) was graded:true. Tagged looped so the pipeline can count them.
40
49
  const looped = isLooped(r.loop);
41
- const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback && !isEngineFinal(r.content) && !looped && !r.interrupted;
50
+ const graded = isGraded(r);
42
51
  // The row carries the user's PROMPT and the full answer, and the corpus is read by the training pipeline —
43
52
  // mask known secret shapes before they reach disk (the same boundary events.jsonl enforces) and keep the
44
53
  // file owner-only; this used to be a 0644 file in a 0755 dir with raw prompts in it.
@@ -78,6 +87,57 @@ async function captureFailureLesson(r, ts = Date.now(), cap) {
78
87
  }
79
88
  catch { /* best-effort — never blocks or fails a turn */ }
80
89
  }
90
+ /** MEMORY sink for a RECOVERED struggle (engine/loop-guard.ts StruggleTracker): one broken command TEMPLATE retried
91
+ * across targets, then FIXED. This is the save-time VERIFY GATE — only a struggle whose fix actually SUCCEEDED
92
+ * (`recovered` is set, which the detector records only on a real success) mints a prescriptive `fix·class` lesson, so
93
+ * the loop never teaches a fix it did not see work. A turn can recover without looping or stopping (the fix lands
94
+ * mid-turn, as in the gh retry-storm), so this is separate from captureFailureLesson. Owner-taught corrections ride
95
+ * the `taught` path; these are the ones the model found and verified itself. Through the same curateLessons as every
96
+ * other writer; a sub-agent's turn leaves none. Best-effort, never blocks a turn. */
97
+ async function captureFixLessons(r, ts = Date.now(), cap) {
98
+ try {
99
+ const recovered = (r.loop?.struggles ?? []).filter((s) => s.recovered); // VERIFY GATE: a confirmed fix only
100
+ if (!recovered.length || isSubagentBrief(r.task || r.input))
101
+ return;
102
+ const { readFile } = await nodeImport("node:fs/promises");
103
+ const file = globalMemoriesPath();
104
+ let text = "";
105
+ try {
106
+ text = await readFile(file, "utf8");
107
+ }
108
+ catch { /* none yet */ }
109
+ const before = text;
110
+ for (const s of recovered)
111
+ text = upsertLesson(text, fixLessonLine({ task: r.task || r.input, struggle: s, ts }), ts, { cap }).text;
112
+ if (text !== before)
113
+ await writeMemoriesAtomic(file, text);
114
+ }
115
+ catch { /* best-effort — never blocks or fails a turn */ }
116
+ }
117
+ /** MEMORY sink for the winning METHOD of a VERIFIED-SUCCESS turn (`isGraded` — the second save-time VERIFY GATE): the
118
+ * ordered tool-skeletons it ran become / strengthen the task class's Skill (selfimprove/skills.ts), so the next
119
+ * mission of that class can start on the known-good method instead of re-exploring (the compounding). Only a turn that
120
+ * actually ran a passing check contributes, so the loop never learns a method from a hollow "done". A sub-agent's turn
121
+ * leaves none. Best-effort, never blocks a turn. */
122
+ async function captureSkill(r, ts = Date.now()) {
123
+ try {
124
+ if (!isGraded(r) || !r.steps?.length || isSubagentBrief(r.task || r.input))
125
+ return; // VERIFY GATE: a verified-success turn only
126
+ const method = methodFromSteps(r.steps).map(redactSecrets);
127
+ if (!method.length)
128
+ return;
129
+ const cls = inferType(ownerWords(redactSecrets(r.task || r.input)));
130
+ const file = operatorPath("selfimprove", "skills", `${skillClassSlug(cls)}.json`);
131
+ const { readFile } = await nodeImport("node:fs/promises");
132
+ let existing = null;
133
+ try {
134
+ existing = JSON.parse(await readFile(file, "utf8"));
135
+ }
136
+ catch { /* none yet */ }
137
+ await writeMemoriesAtomic(file, JSON.stringify(mergeSkill(existing, cls, method, ts), null, 2) + "\n");
138
+ }
139
+ catch { /* best-effort — never blocks or fails a turn */ }
140
+ }
81
141
  /** The lesson a turn leaves: a loop, a stuck stop, or none — a sub-agent's turn never leaves one. */
82
142
  export function lessonKind(r) {
83
143
  if (isSubagentBrief(r.task || r.input))
@@ -192,6 +252,10 @@ export async function runSelfImprove(cfg, r) {
192
252
  await captureFlywheel(r, ts);
193
253
  if (cfg.memory)
194
254
  await captureFailureLesson(r, r.lessonTs ?? ts, cfg.maxLessons); // the closed loop: a looped or stuck turn leaves a durable lesson (under the stamp a recovery already wrote it with)
255
+ if (cfg.memory)
256
+ await captureFixLessons(r, r.lessonTs ?? ts, cfg.maxLessons); // the near-miss: a RECOVERED struggle teaches its verified fix (verify-gated)
257
+ if (cfg.memory)
258
+ await captureSkill(r, r.lessonTs ?? ts); // the positive: a VERIFIED-SUCCESS turn's method becomes the class Skill (verify-gated)
195
259
  // skills / reflect sinks hang off this same hook — implemented incrementally.
196
260
  }
197
261
  // Exposed for tests: the stuck-detection predicate is the trigger for the memory sink.
@@ -28,7 +28,7 @@ export const LESSON_MAX_CHARS = 480; // 440 until the rule named line ranges and
28
28
  /** Lines one lessons section keeps (settings.autonomy.sleepConsolidation.maxLessonsPerFile overrides). 49 distinct
29
29
  * mentor traps (11/02) plus a line per loop / stuck class fit with room; past it the oldest taught lines go first. */
30
30
  export const MAX_LESSONS = 100;
31
- export const KIND_ORDER = ["loop", "stuck", "taught"];
31
+ export const KIND_ORDER = ["loop", "stuck", "fix", "taught"];
32
32
  const TAG_RE = /^- \[(\w+)·([\w-]+) ×(\d+) · last (\d{4}-\d{2}-\d{2}T\d{2}:\d{2})Z\]/;
33
33
  export function parseLessonTag(line) {
34
34
  const m = TAG_RE.exec(line);
@@ -134,6 +134,21 @@ const STUCK_CLASSES = [
134
134
  ];
135
135
  /** A stuck turn's stop class and what happened, from its final text (the engine's "[stopped — …]" note) or its
136
136
  * repetition stopReason; a turn cut for repetition mid-answer keeps the model's own text, so it is "repetition". */
137
+ /** The corrective lesson for a RECOVERED struggle (loop-guard.ts StruggleTracker): one broken command template retried
138
+ * across several targets, then fixed. Only a confirmed recovery reaches here — the save-time VERIFY GATE lives in
139
+ * selfimprove/index.ts captureFixLessons — so the Rule names the fix that actually worked, never a guess. Masked and
140
+ * capped at LESSON_MAX_CHARS like every other lesson. */
141
+ export function fixLessonLine(o) {
142
+ const words = ownerWords(redactSecrets(o.task));
143
+ const cls = inferType(words);
144
+ const s = o.struggle;
145
+ const fix = s.recovered?.deltaHint || "a different command";
146
+ const skeleton = redactSecrets(s.skeleton).replace(/\s+/g, " ").slice(0, 72);
147
+ const what = `retried a failing \`${skeleton}\` across ${s.literals.length} targets (${s.failureSig}) before it worked — ${fix}`;
148
+ const rule = ruleClause("when a command fails with empty or no output, read the error (2>&1) before retrying; never re-apply a failing command to new targets — fix the template first.");
149
+ const line = `${tag({ kind: "fix", cls, count: o.count ?? 1, last: o.last ?? minute(o.ts) })} "${words.slice(0, 80)}" — ${what}. ${rule}`;
150
+ return line.length > LESSON_MAX_CHARS ? line.slice(0, LESSON_MAX_CHARS - 1) + "…" : line;
151
+ }
137
152
  export function stuckClass(content, stopReason) {
138
153
  const c = STUCK_CLASSES.find(([, re]) => re.test(content));
139
154
  if (c)
@@ -0,0 +1,45 @@
1
+ // Positive SKILLS for the self-improvement ladder — the winning METHOD (the ordered tool-call skeletons) for a task
2
+ // class, accumulated across VERIFIED-SUCCESS turns (the second save-time verify gate; selfimprove/index.ts
3
+ // captureSkill gates on isGraded). Pure string work. Phase 3 retrieval injects the high-count steps so the next
4
+ // mission of the class starts on the known-good method instead of re-exploring. Stored per class at
5
+ // operatorPath("selfimprove/skills/<class>.json"). The skeletons are already operand-masked (loop-guard toolSkeleton)
6
+ // and redacted before they land, so a skill carries a method's SHAPE, never a literal secret or path.
7
+ import { toolSkeleton } from "../engine/loop-guard.js";
8
+ const MAX_SKILL_STEPS = 24;
9
+ /** The ordered, de-duplicated tool-skeletons a turn's steps ran — the method it used. Pure; unparsable args are skipped. */
10
+ export function methodFromSteps(steps) {
11
+ const out = [];
12
+ const seen = new Set();
13
+ for (const s of steps) {
14
+ if (s.role !== "assistant")
15
+ continue;
16
+ for (const c of s.tool_calls ?? []) {
17
+ let args = {};
18
+ try {
19
+ const a = JSON.parse(c.function?.arguments || "{}");
20
+ if (a && typeof a === "object")
21
+ args = a;
22
+ }
23
+ catch { /* unparsable — skip */ }
24
+ const sk = toolSkeleton(c.function?.name ?? "", args);
25
+ if (sk && !seen.has(sk)) {
26
+ seen.add(sk);
27
+ out.push(sk);
28
+ }
29
+ }
30
+ }
31
+ return out;
32
+ }
33
+ /** Merge one verified run's method into the class skill: bump `runs`, bump each step's count, keep the most-used steps
34
+ * (the recurring method across runs — that is the compounding). Pure. */
35
+ export function mergeSkill(existing, cls, method, ts) {
36
+ const counts = new Map();
37
+ for (const st of existing?.steps ?? [])
38
+ counts.set(st.skeleton, st.count);
39
+ for (const sk of method)
40
+ counts.set(sk, (counts.get(sk) ?? 0) + 1);
41
+ const steps = [...counts].map(([skeleton, count]) => ({ skeleton, count })).sort((a, b) => b.count - a.count).slice(0, MAX_SKILL_STEPS);
42
+ return { class: cls, runs: (existing?.runs ?? 0) + 1, steps, updated: new Date(ts).toISOString() };
43
+ }
44
+ /** The class → file-stem for operatorPath("selfimprove/skills/<slug>.json"). */
45
+ export const skillClassSlug = (cls) => cls.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "generic";
package/dist/session.js CHANGED
@@ -370,6 +370,7 @@ export class Session {
370
370
  maxTurnTokens;
371
371
  maxTurnWallClockMs;
372
372
  loopGuard;
373
+ features; // settings.features — threaded to runTurn so the engine gates flag-gated behavior (e.g. the method ladder)
373
374
  liveAgents;
374
375
  slotSharers;
375
376
  wakeTurn = false; // the turn in flight was started by the shell to deliver a report / job notice, not typed by the owner
@@ -520,6 +521,7 @@ export class Session {
520
521
  this.maxTurnTokens = cfg.maxTurnTokens;
521
522
  this.maxTurnWallClockMs = cfg.maxTurnWallClockMs;
522
523
  this.loopGuard = cfg.loopGuard;
524
+ this.features = cfg.features;
523
525
  this.liveAgents = cfg.liveAgents;
524
526
  this.slotSharers = cfg.slotSharers;
525
527
  this.hooks = cfg.hooks;
@@ -1596,6 +1598,7 @@ export class Session {
1596
1598
  maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
1597
1599
  maxTurnWallClockMs: this.maxTurnWallClockMs, // opt-in per-turn TIME ceiling; the brake on hour-long crawling turns
1598
1600
  loopGuard: this.loopGuard, // settings.loopGuard thresholds; undefined → engine defaults
1601
+ features: this.features, // settings.features — the engine gates the method ladder (default OFF) on this
1599
1602
  unattended: this.unattended, // headless runs hard-stop a tool loop by default; interactive sessions only warn
1600
1603
  maxRounds: this.maxRounds, // soft round budget from settings.maxRounds (undefined → runTurn default)
1601
1604
  maxRoundsHard: this.maxRoundsHard, // absolute ceiling; undefined → runTurn default 400, tighter for bg sub-agents
@@ -102,6 +102,11 @@ export function assertShellHomeWideSearch(command) {
102
102
  }
103
103
  c = c.replace(/(^|[\s"'=(])~(?=\/|[\s"')|;&#`$]|$)/g, "$1$HOME");
104
104
  c = c.replace(/\$\{HOME\}/g, "$HOME");
105
+ // A `cd $HOME && …` (operator prefixes its shells with the home cwd) sets the CWD — it is NOT a search scope.
106
+ // Strip each cd's path arg so a narrow search run after it (e.g. `cd $HOME && find $HOME/.operator/skills -name …`)
107
+ // is judged on its real target, not false-refused as a search over $HOME. A broad root passed AS a find/grep/rg
108
+ // ARGUMENT (`find $HOME …`, `grep -r x ~`, `… /`) still trips the gate below.
109
+ c = c.replace(/\bcd\s+("[^"]*"|'[^']*'|\S+)/g, "cd");
105
110
  // Bare roots only — `$HOME/work/foo` must still be allowed. Trailing slash OK; a subpath is not.
106
111
  // (Avoid template literals here — a backtick in the char class would terminate them.)
107
112
  const bare = "(?:^|[\\s\"'=(])(?:\\$HOME|/Users|/home|/tmp|/)\\/?(?=[\\s\"')|;&#`]|$)";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.358",
3
+ "version": "0.1.359-next.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",