@indigoai-us/hq-cli 5.221.0 → 5.223.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [5.223.0] — 2026-09-26
6
+
7
+ ### Fixed
8
+
9
+ - Manual resume and explicitly opted-in keep-alive reconcile can move a lane
10
+ off a disabled or logged-out Claude account on the same host, preserving the
11
+ provider session, provider, and model. `hq lanes watch` reports each
12
+ logged-in-to-logged-out transition once with the affected lane ids. The
13
+ watcher stops polling terminal keep-alive lanes when no resume can run and
14
+ shares one local account probe across matching lanes per poll. Quota and
15
+ model failures keep their existing account-selection path and reason.
16
+
17
+ ## [5.222.0] — 2026-09-26
18
+
19
+ - Checkpoint ontology, behind `checkpoint.ontology.multi-writer` (off by
20
+ default): entity versions that sync set aside after losing a push race are
21
+ merged back at the start of each plan (aliases, back-references, the higher
22
+ `signal_count`, the later `last_updated`). Any other difference keeps both
23
+ and leaves the set-aside copy, and an entity deleted since is not
24
+ re-created. Every entity file the step writes is recorded in
25
+ `.hq/ontology-outbox/<company>.json`. The apply report counts duplicate
26
+ entity groups, and `hq core ontology duplicates --company <slug> [--json]`
27
+ lists them.
28
+
5
29
  ## [5.221.0] — 2026-09-26
6
30
 
7
31
  ### Added
@@ -5124,6 +5124,24 @@ export declare const COMMAND_CATALOG: readonly [{
5124
5124
  readonly description: "HQ installation to operate on";
5125
5125
  }];
5126
5126
  readonly subcommands: readonly [];
5127
+ }, {
5128
+ readonly name: "duplicates";
5129
+ readonly description: "List same-type entities whose names collide, with a proposed survivor (read-only)";
5130
+ readonly aliases: readonly [];
5131
+ readonly hidden: false;
5132
+ readonly usage: "[options]";
5133
+ readonly arguments: readonly [];
5134
+ readonly options: readonly [{
5135
+ readonly flags: "--company <slug>";
5136
+ readonly description: "company to scan";
5137
+ }, {
5138
+ readonly flags: "--json";
5139
+ readonly description: "print JSON";
5140
+ }, {
5141
+ readonly flags: "--hq-root <path>";
5142
+ readonly description: "HQ installation to operate on";
5143
+ }];
5144
+ readonly subcommands: readonly [];
5127
5145
  }, {
5128
5146
  readonly name: "apply";
5129
5147
  readonly description: "Validate the run's entity candidates and write them to the payload company";
@@ -6626,6 +6626,29 @@ export const COMMAND_CATALOG = [
6626
6626
  ],
6627
6627
  "subcommands": []
6628
6628
  },
6629
+ {
6630
+ "name": "duplicates",
6631
+ "description": "List same-type entities whose names collide, with a proposed survivor (read-only)",
6632
+ "aliases": [],
6633
+ "hidden": false,
6634
+ "usage": "[options]",
6635
+ "arguments": [],
6636
+ "options": [
6637
+ {
6638
+ "flags": "--company <slug>",
6639
+ "description": "company to scan"
6640
+ },
6641
+ {
6642
+ "flags": "--json",
6643
+ "description": "print JSON"
6644
+ },
6645
+ {
6646
+ "flags": "--hq-root <path>",
6647
+ "description": "HQ installation to operate on"
6648
+ }
6649
+ ],
6650
+ "subcommands": []
6651
+ },
6629
6652
  {
6630
6653
  "name": "apply",
6631
6654
  "description": "Validate the run's entity candidates and write them to the payload company",
@@ -18,5 +18,11 @@ export interface OntologyCommandDeps {
18
18
  }
19
19
  export declare function runOntologyPlan(hqRoot: string, runDirOption: string | undefined, deps?: OntologyCommandDeps): Promise<string>;
20
20
  export declare function runOntologyApply(hqRoot: string, runDirOption: string | undefined, deps?: OntologyCommandDeps): string;
21
+ /**
22
+ * `hq core ontology duplicates`: every group of same-type entities whose
23
+ * names collide, with a proposed survivor. Read-only; gated by
24
+ * `checkpoint.ontology.multi-writer`.
25
+ */
26
+ export declare function runOntologyDuplicates(hqRoot: string, slug: string | undefined, json: boolean, deps?: OntologyCommandDeps): Promise<string>;
21
27
  export declare function registerCoreOntologyCommand(core: Command): void;
22
28
  //# sourceMappingURL=core-ontology.d.ts.map
@@ -11,9 +11,11 @@ import * as fs from "node:fs";
11
11
  import * as path from "node:path";
12
12
  import { resolveLiveRoot } from "../utils/hq-roots.js";
13
13
  import { readLanesRegistryFlag } from "../lib/lanes/registry-flag.js";
14
- import { planOntologyRun } from "../lib/checkpoint-ontology/plan.js";
14
+ import { MULTI_WRITER_FLAG, planOntologyRun, } from "../lib/checkpoint-ontology/plan.js";
15
15
  import { applyOntologyRun, ApplyError } from "../lib/checkpoint-ontology/apply.js";
16
- import { WriteBoundsError } from "../lib/checkpoint-ontology/company.js";
16
+ import { resolveOntologyCompany, WriteBoundsError } from "../lib/checkpoint-ontology/company.js";
17
+ import { findDuplicateGroups, summarizeMergeBack, } from "../lib/checkpoint-ontology/multi-writer.js";
18
+ import { buildEntityIndex } from "../lib/checkpoint-ontology/tree.js";
17
19
  export const ONTOLOGY_PAYLOAD_FILE = "payload.json";
18
20
  class OntologyUsageError extends Error {
19
21
  }
@@ -49,6 +51,16 @@ function companyBriefSuffix(brief) {
49
51
  return "";
50
52
  return `; company brief ${brief.status}${brief.reason ? ` (${brief.reason})` : ""}`;
51
53
  }
54
+ function multiWriterSuffix(start) {
55
+ if (!start)
56
+ return "";
57
+ const parts = [];
58
+ if (start.merge_back.length > 0)
59
+ parts.push(`set-aside versions: ${summarizeMergeBack(start.merge_back)}`);
60
+ if (start.error)
61
+ parts.push(`multi-writer error ${start.error}`);
62
+ return parts.length > 0 ? `; ${parts.join("; ")}` : "";
63
+ }
52
64
  export async function runOntologyPlan(hqRoot, runDirOption, deps = {}) {
53
65
  const runDir = requireRunDir(runDirOption);
54
66
  const outcome = await planOntologyRun({
@@ -59,12 +71,13 @@ export async function runOntologyPlan(hqRoot, runDirOption, deps = {}) {
59
71
  now: deps.now?.(),
60
72
  });
61
73
  if (outcome.status === "skipped") {
62
- return `ontology: skipped (${outcome.reason})${companyBriefSuffix(outcome.companyBrief)}`;
74
+ return `ontology: skipped (${outcome.reason})${companyBriefSuffix(outcome.companyBrief)}${multiWriterSuffix(outcome.multiWriter)}`;
63
75
  }
64
76
  const { plan } = outcome;
65
77
  return (`ontology: planned ${plan.inputs.length} input(s), ~${plan.budget.planned_tokens} tokens, ` +
66
78
  `${plan.pending_after_run} left for later runs; plan at ${outcome.planPath}` +
67
- companyBriefSuffix(outcome.companyBrief));
79
+ companyBriefSuffix(outcome.companyBrief) +
80
+ multiWriterSuffix(plan.multi_writer));
68
81
  }
69
82
  export function runOntologyApply(hqRoot, runDirOption, deps = {}) {
70
83
  const runDir = requireRunDir(runDirOption);
@@ -78,7 +91,36 @@ export function runOntologyApply(hqRoot, runDirOption, deps = {}) {
78
91
  return (`ontology: ${report.created.length} created, ${report.updated.length} updated, ` +
79
92
  `${report.matched} matched, ${report.rejected.length} rejected, ${report.deferred.length} deferred, ` +
80
93
  `${report.suspect_duplicates.length} suspect duplicate(s), ${report.write_errors.length} write error(s)` +
81
- companyBriefSuffix(report.company_brief));
94
+ companyBriefSuffix(report.company_brief) +
95
+ (report.multi_writer?.duplicates ? `; ${report.multi_writer.duplicates.groups} duplicate group(s) in the company` : "") +
96
+ (report.multi_writer?.error ? `; multi-writer error ${report.multi_writer.error}` : ""));
97
+ }
98
+ /**
99
+ * `hq core ontology duplicates`: every group of same-type entities whose
100
+ * names collide, with a proposed survivor. Read-only; gated by
101
+ * `checkpoint.ontology.multi-writer`.
102
+ */
103
+ export async function runOntologyDuplicates(hqRoot, slug, json, deps = {}) {
104
+ const resolution = resolveOntologyCompany(hqRoot, slug);
105
+ if (!resolution.ok)
106
+ throw new OntologyUsageError(`ontology: company rejected: ${resolution.reason}`);
107
+ const company = resolution.company;
108
+ if (!(await (deps.readFlag ?? registryFlagReader)(MULTI_WRITER_FLAG, company))) {
109
+ return json ? JSON.stringify({ company: company.slug, skipped: "flag off" }) : `ontology duplicates: skipped (${MULTI_WRITER_FLAG} is off)`;
110
+ }
111
+ const groups = findDuplicateGroups(buildEntityIndex(company.dir));
112
+ if (json)
113
+ return JSON.stringify({ company: company.slug, groups }, null, 2);
114
+ if (groups.length === 0)
115
+ return `ontology duplicates: none in ${company.slug}`;
116
+ const lines = [`ontology duplicates: ${groups.length} group(s) in ${company.slug}`];
117
+ for (const group of groups) {
118
+ lines.push(`${group.type} (${group.reason.replaceAll("_", " ")}), keep ${group.survivor}`);
119
+ for (const rel of group.paths)
120
+ if (rel !== group.survivor)
121
+ lines.push(` ${rel}`);
122
+ }
123
+ return lines.join("\n");
82
124
  }
83
125
  function fail(error) {
84
126
  if (error instanceof OntologyUsageError || error instanceof ApplyError || error instanceof WriteBoundsError) {
@@ -105,6 +147,20 @@ export function registerCoreOntologyCommand(core) {
105
147
  fail(error);
106
148
  }
107
149
  });
150
+ ontology
151
+ .command("duplicates")
152
+ .description("List same-type entities whose names collide, with a proposed survivor (read-only)")
153
+ .requiredOption("--company <slug>", "company to scan")
154
+ .option("--json", "print JSON")
155
+ .option("--hq-root <path>", "HQ installation to operate on")
156
+ .action(async (options) => {
157
+ try {
158
+ process.stdout.write(`${await runOntologyDuplicates(rootFor(options), options.company, options.json === true)}\n`);
159
+ }
160
+ catch (error) {
161
+ fail(error);
162
+ }
163
+ });
108
164
  ontology
109
165
  .command("apply")
110
166
  .description("Validate the run's entity candidates and write them to the payload company")
@@ -42,7 +42,7 @@ import { effectiveAccountHome } from "../lib/lanes/account-home.js";
42
42
  import { AccountResolutionError, compareLaneQueueOrder, coveredLaneIds, DEFAULT_ACCOUNT_HOMES, LANE_PROVIDERS, LANE_STATES, PROVIDER_HOME_ENV, QUESTION_STATUSES, SENIOR_KINDS, accountStatus, appendCappedHistory, canonicalizeHome, createLane, createQuestion, decideAdmission, defaultLivenessDeps, defaultSystemdUserDir, defaultThrottleDeps, installDrainHook, installReconcileTimer, providerPathEnv, probeDrainHookRegistration, isLanesError, isLaneVersionConflict, isTerminalLaneState, aliveDirectChildren, assignedChildHireGrants, hireGrantCapacityError, LANE_HIRE_GRANTS_FLAG, planHireGrantBackfill, terminalChildResumeHireGrantError, withHireGrantAdmission, laneStoryLedgerEnabled, validateProjectStories, buildLaneStatusSnapshot, formatLaneStatusHuman, listAccountStatuses, listLaneIds, listQuestionIds, listSessionLiveness, loadLanesConfig, laneRunsHere, MAX_LANE_DEPTH, MONITOR_ERROR_EXIT_CODE, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_UNCOVERED_EXIT_CODE, MAX_WATCHED_LANES, monitorReminderText, readLiveMonitorEvidence, resolveMachineIdentity as lookupMachineIdentity, loadLivenessIndex, parseLaneProvider, parseLaneRecord, parseLaneState, parseLivenessState, parseQuestionRecord, parseQuestionStatus, parseSeniorKind, readDaemonPresenceConnected, readLane, retryUpdateLane, syncLaneRecordFromOwner, readQuestion, resolveAccount, resolveLaneWorker, ignoredWorkerProfileFields, loadWorkerProfile, runReconcilePass, wakeAnsweredLaneNow, runLaneWatch, sessionLiveness, tryReadLane, uninstallReconcileTimer, updateLane, updateQuestion, writeLanesConfig, appendDropboxMessage, answerDropboxMessage, deliveryRefusalReason, resumeCommandRefusal, dropboxDir, dropboxInboxPath, laneAcceptsDropboxDelivery, laneAcceptsOperatorMessage, laneDeliveryMechanism, hasActiveAdmissionReservation, hasActivePendingResume, hasRecordedSessionId, hasEarlierEligibleQueuedLane, laneAdmissionCapReason, providerSupportsSessionResume, providerSessionPortable, sessionNotPortableMessage, withLaneAdmissionLock, withAllLaneAdmissionLocks, withLaneHireLocks, laneIdForAnswerDelivery, operatorMessageRefusalReason, raiseLaneQuestion, sha256Text, writeQuestionBody, } from "../lib/lanes/index.js";
43
43
  import { activeLaneStories, laneStories, laneStory, storyWarning, } from "../lib/lanes/stories.js";
44
44
  import { resolveLaneKeepAlive } from "../lib/lanes/profile.js";
45
- import { keepAliveExclusion, loadRetiredLaneIds, } from "../lib/lanes/keep-alive.js";
45
+ import { keepAliveExclusion, LEAD_LANE_KEEP_ALIVE_FLAG, loadRetiredLaneIds, } from "../lib/lanes/keep-alive.js";
46
46
  import { questionBodyAbsPath, resolveQuestionCompanyWithFallback, resolveProjectQuestionCompany, } from "../lib/lanes/questions.js";
47
47
  import { assertQuestionBodySecretSafe } from "../lib/lanes/questions.js";
48
48
  import { compactionAfterUsage, } from "../lib/lanes/compaction.js";
@@ -1262,10 +1262,75 @@ function resolveMonitorEngine(requested, env) {
1262
1262
  }
1263
1263
  async function runWatch(ctx, laneIds, opts) {
1264
1264
  const rawInterval = opts.intervalMs === undefined ? undefined : Number(opts.intervalMs);
1265
- await runLaneWatch(ctx.hqRoot(), laneIds, {
1265
+ const hqRoot = ctx.hqRoot();
1266
+ await runLaneWatch(hqRoot, laneIds, {
1266
1267
  intervalMs: rawInterval,
1267
1268
  sleep: ctx.sleep,
1269
+ keepAliveEnabled: (lane) => readLanesRegistryFlag(LEAD_LANE_KEEP_ALIVE_FLAG, {
1270
+ company: lane.company,
1271
+ env: ctx.env,
1272
+ }),
1273
+ readAccountStatuses: async (lanes) => {
1274
+ if (lanes.length === 0)
1275
+ return [];
1276
+ const config = loadLanesConfig(hqRoot);
1277
+ const currentHost = laneHostFromCtx(ctx);
1278
+ const currentHostname = ctx.hostname().trim();
1279
+ const isCurrentHost = (host) => (host.kind === currentHost.kind && host.id === currentHost.id) ||
1280
+ (host.kind === "local" && host.id === currentHostname);
1281
+ const remoteOutpostIds = [...new Set(lanes
1282
+ .filter((lane) => lane.host.kind === "outpost" && !isCurrentHost(lane.host))
1283
+ .map((lane) => lane.host.id))];
1284
+ const remoteOutposts = await Promise.all(remoteOutpostIds.map(async (id) => [id, await readOutpostCapacity(ctx, id)]));
1285
+ const outpostSnapshots = new Map(remoteOutposts);
1286
+ const remoteLocalLanes = lanes.filter((lane) => lane.host.kind === "local" && !isCurrentHost(lane.host));
1287
+ const remoteLocalHosts = remoteLocalLanes.length > 0
1288
+ ? await loadClaudeBalanceHostSnapshots(ctx, hqRoot, config)
1289
+ : undefined;
1290
+ const localStatusCache = new Map();
1291
+ return lanes.map((lane) => {
1292
+ if (config.providers[lane.provider].accounts[lane.account] === undefined) {
1293
+ throw new LanesError("watch_account_unconfigured", `Lane ${lane.lane_id} records unconfigured ${lane.provider} account ${lane.account}`, { lane_id: lane.lane_id, provider: lane.provider, account: lane.account, host: lane.host });
1294
+ }
1295
+ let loggedIn;
1296
+ if (isCurrentHost(lane.host)) {
1297
+ const key = JSON.stringify([lane.provider, lane.account, currentHost.kind, currentHost.id]);
1298
+ if (!localStatusCache.has(key)) {
1299
+ localStatusCache.set(key, accountStatus(lane.provider, lane.account, config, {
1300
+ existsSync: ctx.existsSync,
1301
+ probe: ctx.probeProvider,
1302
+ env: ctx.env,
1303
+ hostname: currentHostname,
1304
+ }).logged_in);
1305
+ }
1306
+ loggedIn = localStatusCache.get(key);
1307
+ }
1308
+ else if (lane.host.kind === "outpost") {
1309
+ loggedIn = outpostSnapshots.get(lane.host.id)?.providers[lane.provider].accounts[lane.account]?.logged_in;
1310
+ }
1311
+ else {
1312
+ const snapshot = remoteLocalHosts?.snapshots.find((candidate) => candidate.capacity.host.kind === lane.host.kind &&
1313
+ candidate.capacity.host.id === lane.host.id);
1314
+ if (!snapshot) {
1315
+ const gap = remoteLocalHosts?.unavailableHosts.find((candidate) => candidate.host.kind === lane.host.kind && candidate.host.id === lane.host.id);
1316
+ throw new LanesError("watch_account_host_unavailable", `Cannot check ${lane.provider} account ${lane.account} on ${lane.host.kind}:${lane.host.id}${gap ? `: ${gap.reason}` : ""}`, { lane_id: lane.lane_id, provider: lane.provider, account: lane.account, host: lane.host });
1317
+ }
1318
+ loggedIn = snapshot.capacity.providers[lane.provider].accounts[lane.account]?.logged_in;
1319
+ }
1320
+ if (loggedIn === undefined) {
1321
+ throw new LanesError("watch_account_unconfigured", `Lane ${lane.lane_id} records unconfigured ${lane.provider} account ${lane.account} on ${lane.host.kind}:${lane.host.id}`, { lane_id: lane.lane_id, provider: lane.provider, account: lane.account, host: lane.host });
1322
+ }
1323
+ return {
1324
+ lane_id: lane.lane_id,
1325
+ provider: lane.provider,
1326
+ account: lane.account,
1327
+ host: lane.host,
1328
+ logged_in: loggedIn,
1329
+ };
1330
+ });
1331
+ },
1268
1332
  writeLine: (line) => console.log(opts.json ? JSON.stringify({ event: line }) : line),
1333
+ writeAccountEvent: (event) => console.log(opts.json ? JSON.stringify(event) : `account_logged_out provider=${event.provider} account=${event.account} host=${event.host.kind}:${event.host.id} lane_ids=${event.lane_ids.join(",")}`),
1269
1334
  writeError: (line) => process.stderr.write(`${line}\n`),
1270
1335
  });
1271
1336
  return 0;
@@ -5002,7 +5067,8 @@ function resolveResumeProfile(ctx, lane, workerId) {
5002
5067
  function validateResumeProfileModel(ctx, lane, profile) {
5003
5068
  if (profile.meta.provider !== lane.provider ||
5004
5069
  profile.meta.model === undefined ||
5005
- lane.model_source === "cli") {
5070
+ lane.model_source === "cli" ||
5071
+ lane.model_source === "preserved") {
5006
5072
  return;
5007
5073
  }
5008
5074
  const hqRoot = ctx.hqRoot();
@@ -5036,7 +5102,7 @@ function applyResumeProfileAndEffort(current, next, input) {
5036
5102
  : undefined;
5037
5103
  next.keep_alive_blocked_reason = undefined;
5038
5104
  }
5039
- if (next.model_source !== "cli") {
5105
+ if (next.model_source !== "cli" && next.model_source !== "preserved") {
5040
5106
  if (profile.meta.provider === current.provider && profile.meta.model !== undefined) {
5041
5107
  next.model = profile.meta.model;
5042
5108
  next.model_source = "profile";
@@ -5130,7 +5196,7 @@ function resolveResumeEffort(ctx, lane, input) {
5130
5196
  ? undefined
5131
5197
  : providerConfig.accounts[accountId];
5132
5198
  const profileDefaultsApply = input.profile?.profile.meta.provider === lane.provider;
5133
- const pinnedModel = lane.model_source === undefined || lane.model_source === "cli"
5199
+ const pinnedModel = lane.model_source === undefined || lane.model_source === "cli" || lane.model_source === "preserved"
5134
5200
  ? lane.model
5135
5201
  : undefined;
5136
5202
  const model = resolveLaneModel({
@@ -5225,11 +5291,11 @@ async function prepareAccountMove(ctx, lane, input) {
5225
5291
  ? loadWorkerProfile(hqRoot, lane.worker_profile)
5226
5292
  : undefined);
5227
5293
  const profileDefaultsApply = profile !== undefined && profile.meta.provider === lane.provider;
5228
- const pinnedModel = input.workerProfile !== undefined
5229
- ? lane.model_source === "cli" ? lane.model : undefined
5230
- : lane.model_source === undefined || lane.model_source === "cli"
5294
+ const pinnedModel = input.preservedModel ?? (input.workerProfile !== undefined
5295
+ ? lane.model_source === "cli" || lane.model_source === "preserved" ? lane.model : undefined
5296
+ : lane.model_source === undefined || lane.model_source === "cli" || lane.model_source === "preserved"
5231
5297
  ? lane.model
5232
- : undefined;
5298
+ : undefined);
5233
5299
  const profileModel = profileDefaultsApply ? profile?.meta.model : undefined;
5234
5300
  if (input.cliModel === undefined && profileDefaultsApply && profileModel !== undefined && pinnedModel === undefined) {
5235
5301
  validateProfileLaneModel(lane.provider, profileModel, targetHome, profile.id, {
@@ -5313,12 +5379,14 @@ async function prepareAccountMove(ctx, lane, input) {
5313
5379
  provider_session_id_absent: undefined,
5314
5380
  ...(input.cliModel !== undefined
5315
5381
  ? { model: input.cliModel, model_source: "cli" }
5316
- : {}),
5382
+ : input.preservedModel !== undefined
5383
+ ? { model: input.preservedModel, model_source: "preserved" }
5384
+ : {}),
5317
5385
  account_history: appendCappedHistory(current.account_history ?? [], {
5318
5386
  from,
5319
5387
  to: target,
5320
5388
  at,
5321
- reason: SESSION_MOVE_REASON,
5389
+ reason: input.accountHistoryReason ?? SESSION_MOVE_REASON,
5322
5390
  }),
5323
5391
  pending_resume: input.deferTurnStart
5324
5392
  ? undefined
@@ -5345,31 +5413,39 @@ async function prepareAccountMove(ctx, lane, input) {
5345
5413
  return { lane: moved, from, to: target, copy, queued };
5346
5414
  }, ctx.sleep);
5347
5415
  }
5348
- async function selectAutomaticClaudeResumeAccount(ctx, lane, workerProfile) {
5416
+ async function selectAutomaticClaudeResumeAccount(ctx, lane, workerProfile, options = {}) {
5349
5417
  if (lane.provider !== "claude")
5350
5418
  return undefined;
5351
- if (!await ctx.laneClaudeAccountBalanceEnabled(lane.company)) {
5419
+ const balanceEnabled = await ctx.laneClaudeAccountBalanceEnabled(lane.company);
5420
+ const hqRoot = ctx.hqRoot();
5421
+ const config = loadLanesConfig(hqRoot);
5422
+ const currentConfig = lane.account === undefined
5423
+ ? undefined
5424
+ : config.providers.claude.accounts[lane.account];
5425
+ const currentLogin = lane.account === undefined || currentConfig === undefined
5426
+ ? false
5427
+ : accountStatus("claude", lane.account, config, {
5428
+ existsSync: ctx.existsSync,
5429
+ hostname: ctx.hostname(),
5430
+ probe: ctx.probeProvider,
5431
+ env: ctx.env,
5432
+ }).logged_in;
5433
+ const accountNeedsRepair = lane.account !== undefined &&
5434
+ (currentConfig?.enabled !== true || currentLogin === false);
5435
+ const repairUnavailableAccount = options.repairUnavailableAccount === true && accountNeedsRepair;
5436
+ if (!balanceEnabled && !(options.repairUnavailableAccount && accountNeedsRepair)) {
5352
5437
  if (lane.account === undefined)
5353
5438
  return undefined;
5354
- const config = loadLanesConfig(ctx.hqRoot());
5355
- const currentConfig = config.providers.claude.accounts[lane.account];
5356
5439
  if (currentConfig === undefined || !currentConfig.enabled) {
5357
5440
  throw new AccountResolutionError(currentConfig === undefined ? "unknown_account" : "account_disabled", currentConfig === undefined
5358
5441
  ? `Lane ${lane.lane_id} records account ${JSON.stringify(lane.account)} which is not configured for claude`
5359
5442
  : `Account ${JSON.stringify(lane.account)} is unavailable for claude`, { provider: "claude", account: lane.account });
5360
5443
  }
5361
- if (accountStatus("claude", lane.account, config, {
5362
- existsSync: ctx.existsSync,
5363
- hostname: ctx.hostname(),
5364
- probe: ctx.probeProvider,
5365
- env: ctx.env,
5366
- }).logged_in === false) {
5444
+ if (currentLogin === false) {
5367
5445
  throw new LanesError("account_not_logged_in", `Account ${lane.account} for claude is not logged in`, { provider: "claude", account: lane.account, lane_id: lane.lane_id });
5368
5446
  }
5369
5447
  return undefined;
5370
5448
  }
5371
- const hqRoot = ctx.hqRoot();
5372
- const config = loadLanesConfig(hqRoot);
5373
5449
  const profile = workerProfile?.profile ?? (lane.worker_profile !== undefined
5374
5450
  ? loadWorkerProfile(hqRoot, lane.worker_profile)
5375
5451
  : undefined);
@@ -5380,33 +5456,45 @@ async function selectAutomaticClaudeResumeAccount(ctx, lane, workerProfile) {
5380
5456
  const allowedAccounts = profilePin !== undefined && lane.admission_accounts !== undefined
5381
5457
  ? profilePin.filter((account) => lane.admission_accounts.includes(account))
5382
5458
  : profilePin ?? lane.admission_accounts;
5383
- const currentConfig = lane.account === undefined
5384
- ? undefined
5385
- : config.providers.claude.accounts[lane.account];
5386
- const currentLogin = lane.account === undefined || currentConfig === undefined
5387
- ? false
5388
- : accountStatus("claude", lane.account, config, {
5389
- existsSync: ctx.existsSync,
5390
- hostname: ctx.hostname(),
5391
- probe: ctx.probeProvider,
5392
- env: ctx.env,
5393
- }).logged_in;
5394
5459
  const pinnedModel = workerProfile !== undefined
5395
- ? lane.model_source === "cli" ? lane.model : undefined
5396
- : lane.model_source === undefined || lane.model_source === "cli"
5460
+ ? lane.model_source === "cli" || lane.model_source === "preserved" ? lane.model : undefined
5461
+ : lane.model_source === undefined || lane.model_source === "cli" || lane.model_source === "preserved"
5397
5462
  ? lane.model
5398
5463
  : undefined;
5464
+ const preservedModel = repairUnavailableAccount && lane.model_source === "account"
5465
+ ? lane.model ?? currentConfig?.model
5466
+ : undefined;
5399
5467
  const model = resolveLaneModel({
5400
- cliModel: pinnedModel,
5468
+ cliModel: preservedModel ?? pinnedModel,
5401
5469
  profileModel: profileDefaultsApply ? profile?.meta.model : undefined,
5402
5470
  accountModel: lane.account === undefined ? undefined : config.providers.claude.accounts[lane.account]?.model,
5403
5471
  providerModel: config.providers.claude.model,
5404
5472
  });
5405
- const accountNeedsRepair = currentConfig?.enabled !== true || currentLogin === false;
5406
5473
  const mayRebalance = BALANCE_MOVABLE_STATES.includes(lane.state);
5407
5474
  if (!accountNeedsRepair && !mayRebalance)
5408
5475
  return undefined;
5409
- const balanceHosts = await loadClaudeBalanceHostSnapshots(ctx, hqRoot, config);
5476
+ const balanceHosts = balanceEnabled
5477
+ ? await loadClaudeBalanceHostSnapshots(ctx, hqRoot, config)
5478
+ : (() => {
5479
+ const lanes = loadAllLanes(hqRoot).filter((candidate) => candidate.host.kind === lane.host.kind && candidate.host.id === lane.host.id);
5480
+ return {
5481
+ snapshots: [{
5482
+ capacity: buildHostCapacitySnapshot({
5483
+ host: lane.host,
5484
+ lanes,
5485
+ config,
5486
+ existsSync: ctx.existsSync,
5487
+ probe: ctx.probeProvider,
5488
+ env: ctx.env,
5489
+ hostname: ctx.hostname(),
5490
+ now: ctx.now(),
5491
+ }),
5492
+ lanes,
5493
+ laneListAvailable: true,
5494
+ }],
5495
+ unavailableHosts: [],
5496
+ };
5497
+ })();
5410
5498
  const targetHost = balanceHosts.snapshots.find((host) => host.capacity.host.kind === lane.host.kind && host.capacity.host.id === lane.host.id);
5411
5499
  const currentTargetAccount = lane.account === undefined
5412
5500
  ? undefined
@@ -5423,11 +5511,15 @@ async function selectAutomaticClaudeResumeAccount(ctx, lane, workerProfile) {
5423
5511
  hosts: balanceHosts.snapshots,
5424
5512
  targetHost: lane.host,
5425
5513
  config,
5426
- ...(allowedAccounts !== undefined ? { allowedAccounts } : {}),
5514
+ ...(!repairUnavailableAccount && allowedAccounts !== undefined ? { allowedAccounts } : {}),
5427
5515
  ...(model !== undefined ? { model } : {}),
5428
5516
  unavailableHosts: balanceHosts.unavailableHosts,
5429
5517
  });
5430
- return { ...selected, selected_at: ctx.now().toISOString() };
5518
+ return {
5519
+ selection: { ...selected, selected_at: ctx.now().toISOString() },
5520
+ ...(repairUnavailableAccount ? { historyReason: "recorded_account_logged_out" } : {}),
5521
+ ...(preservedModel !== undefined ? { preservedModel } : {}),
5522
+ };
5431
5523
  }
5432
5524
  function accountRequestKeepsCurrentLane(lane, rawAccount) {
5433
5525
  const raw = rawAccount.trim();
@@ -5525,7 +5617,7 @@ async function runMessage(ctx, laneId, opts) {
5525
5617
  const resumeEffort = resolveResumeEffort(ctx, lane, {
5526
5618
  cliEffort,
5527
5619
  profile: resumeProfile,
5528
- account: keepCurrentAccount ? lane.account : opts.account ?? automaticAccountSelection?.account,
5620
+ account: keepCurrentAccount ? lane.account : opts.account ?? automaticAccountSelection?.selection.account,
5529
5621
  model: opts.model,
5530
5622
  });
5531
5623
  const messageId = mintMessageId();
@@ -5585,12 +5677,14 @@ async function runMessage(ctx, laneId, opts) {
5585
5677
  }
5586
5678
  }
5587
5679
  else if (mechanism === "resume") {
5588
- const selection = automaticAccountSelection;
5589
- if (selection !== undefined) {
5680
+ const automatic = automaticAccountSelection;
5681
+ if (automatic !== undefined) {
5682
+ const selection = automatic.selection;
5590
5683
  if (selection.account !== lane.account) {
5591
5684
  move = await prepareAccountMove(ctx, lane, {
5592
5685
  account: selection.account,
5593
5686
  cliModel: undefined,
5687
+ ...(automatic.historyReason !== undefined ? { accountHistoryReason: automatic.historyReason } : {}),
5594
5688
  ...(resumeProfile !== undefined ? { workerProfile: resumeProfile } : {}),
5595
5689
  ...(resumeEffort !== undefined ? { effort: resumeEffort } : {}),
5596
5690
  pending: {
@@ -6063,12 +6157,12 @@ async function runResume(ctx, laneId, opts) {
6063
6157
  validateResumeProfileModel(ctx, lane, resumeProfile.profile);
6064
6158
  }
6065
6159
  const automaticAccountSelection = opts.account === undefined
6066
- ? await selectAutomaticClaudeResumeAccount(ctx, lane, resumeProfile)
6160
+ ? await selectAutomaticClaudeResumeAccount(ctx, lane, resumeProfile, { repairUnavailableAccount: true })
6067
6161
  : undefined;
6068
6162
  const resumeEffort = resolveResumeEffort(ctx, lane, {
6069
6163
  cliEffort,
6070
6164
  profile: resumeProfile,
6071
- account: keepCurrentAccount ? lane.account : opts.account ?? automaticAccountSelection?.account,
6165
+ account: keepCurrentAccount ? lane.account : opts.account ?? automaticAccountSelection?.selection.account,
6072
6166
  model: opts.model,
6073
6167
  });
6074
6168
  let move = null;
@@ -6089,10 +6183,17 @@ async function runResume(ctx, laneId, opts) {
6089
6183
  lane = move.lane;
6090
6184
  }
6091
6185
  else if (automaticAccountSelection !== undefined) {
6092
- if (automaticAccountSelection.account !== lane.account) {
6186
+ const selection = automaticAccountSelection.selection;
6187
+ if (selection.account !== lane.account) {
6093
6188
  move = await prepareAccountMove(ctx, lane, {
6094
- account: automaticAccountSelection.account,
6189
+ account: selection.account,
6095
6190
  cliModel: undefined,
6191
+ ...(automaticAccountSelection.historyReason !== undefined
6192
+ ? { accountHistoryReason: automaticAccountSelection.historyReason }
6193
+ : {}),
6194
+ ...(automaticAccountSelection.preservedModel !== undefined
6195
+ ? { preservedModel: automaticAccountSelection.preservedModel }
6196
+ : {}),
6096
6197
  ...(resumeProfile !== undefined ? { workerProfile: resumeProfile } : {}),
6097
6198
  ...(resumeEffort !== undefined ? { effort: resumeEffort } : {}),
6098
6199
  pending: {
@@ -6102,12 +6203,12 @@ async function runResume(ctx, laneId, opts) {
6102
6203
  ...(messageId !== undefined ? { message_id: messageId } : {}),
6103
6204
  compact: opts.compact !== false,
6104
6205
  },
6105
- accountSelection: automaticAccountSelection,
6206
+ accountSelection: selection,
6106
6207
  });
6107
6208
  lane = move.lane;
6108
6209
  }
6109
6210
  else {
6110
- lane = persistClaudeAccountSelection(hqRoot, lane, automaticAccountSelection);
6211
+ lane = persistClaudeAccountSelection(hqRoot, lane, selection);
6111
6212
  }
6112
6213
  }
6113
6214
  lane = recordResumeSetup(ctx, lane, {
@@ -8412,6 +8513,11 @@ async function runReconcile(ctx, opts) {
8412
8513
  dryRun: Boolean(opts.dryRun),
8413
8514
  spawnLaneDeps: {
8414
8515
  env: ctx.env,
8516
+ modelDeps: {
8517
+ readFileSync: ctx.readFileSync,
8518
+ probe: ctx.probeProvider,
8519
+ env: ctx.env,
8520
+ },
8415
8521
  existsSync: ctx.existsSync,
8416
8522
  spawnProcess: ctx.spawnProcess,
8417
8523
  proveDetached: ctx.proveDetached,
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Alias rules shared by `apply` and the multi-writer merge-back.
3
+ */
4
+ import type { EntityIndex } from "./tree.js";
5
+ /** Longest canonical name or alias the writer accepts. */
6
+ export declare const MAX_NAME_LENGTH = 200;
7
+ /** The index key for a normalised name of one type. */
8
+ export declare function entityKey(type: string, normalized: string): string;
9
+ /**
10
+ * Aliases worth adding to the entity at `self`: new to it, and held by no
11
+ * other entity of any type, so an alias can never make a later match
12
+ * ambiguous. `own` holds the normalised names the entity already answers to.
13
+ */
14
+ export declare function freshAliases(index: EntityIndex, type: string, self: string, own: Set<string>, names: string[]): string[];
15
+ /** The normalised names an indexed entity answers to, plus aliases queued this run. */
16
+ export declare function ownNames(index: EntityIndex, rel: string, queued: string[]): Set<string>;
17
+ //# sourceMappingURL=aliases.d.ts.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Alias rules shared by `apply` and the multi-writer merge-back.
3
+ */
4
+ import { canonicalizeName, isRejectedName, normalizeEntityName } from "./identity.js";
5
+ /** Longest canonical name or alias the writer accepts. */
6
+ export const MAX_NAME_LENGTH = 200;
7
+ /** The index key for a normalised name of one type. */
8
+ export function entityKey(type, normalized) {
9
+ return `${type}\0${normalized}`;
10
+ }
11
+ /**
12
+ * Aliases worth adding to the entity at `self`: new to it, and held by no
13
+ * other entity of any type, so an alias can never make a later match
14
+ * ambiguous. `own` holds the normalised names the entity already answers to.
15
+ */
16
+ export function freshAliases(index, type, self, own, names) {
17
+ const seen = new Set(own);
18
+ const out = [];
19
+ for (const raw of names) {
20
+ const alias = canonicalizeName(raw);
21
+ if (!alias || alias.length > MAX_NAME_LENGTH)
22
+ continue;
23
+ const normalized = normalizeEntityName(alias, type);
24
+ if (!normalized || seen.has(normalized) || isRejectedName(normalized))
25
+ continue;
26
+ const holders = [
27
+ ...(index.canonical.get(entityKey(type, normalized)) ?? []),
28
+ ...(index.alias.get(entityKey(type, normalized)) ?? []),
29
+ ];
30
+ if (holders.some((holder) => holder !== self))
31
+ continue;
32
+ if ([...(index.types.get(normalized) ?? [])].some((other) => other !== type))
33
+ continue;
34
+ seen.add(normalized);
35
+ out.push(alias);
36
+ }
37
+ return out;
38
+ }
39
+ /** The normalised names an indexed entity answers to, plus aliases queued this run. */
40
+ export function ownNames(index, rel, queued) {
41
+ const entity = index.byRel.get(rel);
42
+ return new Set([entity.canonical_name, ...entity.aliases, ...queued].map((name) => normalizeEntityName(name, entity.type)));
43
+ }
44
+ //# sourceMappingURL=aliases.js.map