@wjarka/cezarion 0.17.0-pr2130.3280 → 0.17.0-pr2131.3281

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.
@@ -90,17 +90,6 @@ export declare function createDelegationRoutes(service: DelegationService, crede
90
90
  authFailureId?: string | undefined;
91
91
  runner: "claude" | "codex" | "cursor" | "omp" | "opencode" | "pi";
92
92
  }[];
93
- } | {
94
- runner: "claude" | "codex" | "cursor" | "omp" | "opencode" | "pi";
95
- models: {
96
- id: string;
97
- label: string;
98
- description: string;
99
- effortLevels?: ("high" | "low" | "max" | "medium" | "xhigh")[] | undefined;
100
- }[];
101
- source: "cache" | "live" | "unavailable";
102
- stale: boolean;
103
- reason?: string | undefined;
104
93
  } | {
105
94
  tasks: {
106
95
  id: string;
@@ -113,6 +102,17 @@ export declare function createDelegationRoutes(service: DelegationService, crede
113
102
  reason?: string | undefined;
114
103
  }[];
115
104
  nextOffset?: number | undefined;
105
+ } | {
106
+ runner: "claude" | "codex" | "cursor" | "omp" | "opencode" | "pi";
107
+ models: {
108
+ id: string;
109
+ label: string;
110
+ description: string;
111
+ effortLevels?: ("high" | "low" | "max" | "medium" | "xhigh")[] | undefined;
112
+ }[];
113
+ source: "cache" | "live" | "unavailable";
114
+ stale: boolean;
115
+ reason?: string | undefined;
116
116
  };
117
117
  outputFormat: "json";
118
118
  status: 200;
@@ -221,13 +221,13 @@ export declare function createDelegationRoutes(service: DelegationService, crede
221
221
  status: 200;
222
222
  input: {
223
223
  json: {
224
- workerIds: string[];
225
- timeoutSeconds?: number | undefined;
226
- mode?: "all" | "any" | "one" | undefined;
227
- } | {
228
224
  requestIds: string[];
229
225
  mode?: "all" | "any" | "one" | undefined;
230
226
  timeoutSeconds?: number | undefined;
227
+ } | {
228
+ workerIds: string[];
229
+ timeoutSeconds?: number | undefined;
230
+ mode?: "all" | "any" | "one" | undefined;
231
231
  } | {
232
232
  peerIds: string[];
233
233
  timeoutSeconds?: number | undefined;
@@ -57,6 +57,17 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
57
57
  "/discover": {
58
58
  $post: {
59
59
  output: {
60
+ runner: "claude" | "codex" | "cursor" | "omp" | "opencode" | "pi";
61
+ models: {
62
+ id: string;
63
+ label: string;
64
+ description: string;
65
+ effortLevels?: ("high" | "low" | "max" | "medium" | "xhigh")[] | undefined;
66
+ }[];
67
+ source: "cache" | "live" | "unavailable";
68
+ stale: boolean;
69
+ reason?: string | undefined;
70
+ } | {
60
71
  scope: "host-default-account";
61
72
  runners: {
62
73
  status: "connected" | "disconnected" | "not-installed" | "unknown";
@@ -77,17 +88,6 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
77
88
  reason?: string | undefined;
78
89
  }[];
79
90
  nextOffset?: number | undefined;
80
- } | {
81
- runner: "claude" | "codex" | "cursor" | "omp" | "opencode" | "pi";
82
- models: {
83
- id: string;
84
- label: string;
85
- description: string;
86
- effortLevels?: ("high" | "low" | "max" | "medium" | "xhigh")[] | undefined;
87
- }[];
88
- source: "cache" | "live" | "unavailable";
89
- stale: boolean;
90
- reason?: string | undefined;
91
91
  };
92
92
  outputFormat: "json";
93
93
  status: 200;
@@ -196,13 +196,13 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
196
196
  status: 200;
197
197
  input: {
198
198
  json: {
199
- requestIds: string[];
200
- mode?: "all" | "any" | "one" | undefined;
201
- timeoutSeconds?: number | undefined;
202
- } | {
203
199
  workerIds: string[];
204
200
  timeoutSeconds?: number | undefined;
205
201
  mode?: "all" | "any" | "one" | undefined;
202
+ } | {
203
+ requestIds: string[];
204
+ mode?: "all" | "any" | "one" | undefined;
205
+ timeoutSeconds?: number | undefined;
206
206
  } | {
207
207
  peerIds: string[];
208
208
  timeoutSeconds?: number | undefined;
@@ -0,0 +1,38 @@
1
+ import { type AutosaveReason } from '../../git-worktree.ts';
2
+ import type { ActiveRun } from '../active-run.ts';
3
+ import type { RunModuleContext } from './types.ts';
4
+ interface WorktreeAutosaveHost {
5
+ holdForMaintenance(runIds: readonly string[]): (() => void) | null;
6
+ reapTerminalScratch(runId: string): void;
7
+ releaseSlot(): void;
8
+ saveWorktree(runId: string, state: ActiveRun, reason: AutosaveReason): Promise<void>;
9
+ trackTurn(runId: string, task: Promise<void>): void;
10
+ }
11
+ /** Periodic "cezar autosave" commit in the task worktree (spec 006). */
12
+ export declare const AUTOSAVE_INTERVAL_MS = 90000;
13
+ /**
14
+ * Periodic saves are opt-in. Turn-end, finalization and pre-PR flushes remain enabled; only
15
+ * pre-PR follows a repointed HEAD. Coalesce timer-save evidence in the handoff.
16
+ */
17
+ export declare function periodicAutosaveEnabled(env?: NodeJS.ProcessEnv): boolean;
18
+ export declare class WorktreeAutosave {
19
+ private readonly context;
20
+ private readonly host;
21
+ constructor(context: RunModuleContext, host: WorktreeAutosaveHost);
22
+ /** The save may finish execution while its strict writer proof remains pending. */
23
+ private readonly autosaveTasks;
24
+ /** Cleanup evidence survives manager disposal and store close/reopen. */
25
+ autosaveCleanupBlocker(runId: string): string | undefined;
26
+ /** Keep a separate maintenance hold until autosave proves all its processes exited.
27
+ * Commits only while HEAD is the run's recorded branch (hearsay-tools/cezarion#1004), and
28
+ * records a commit or a skip in the run store, shown in the handoff's records block, and as a
29
+ * note; a periodic save records only a commit, with no note, merged with the
30
+ * periodic commits right before it. A run with no recorded branch keeps committing on
31
+ * whatever HEAD is. */
32
+ saveWorktree(runId: string, state: ActiveRun, reason: AutosaveReason): Promise<void>;
33
+ /** Autosave-commit the worktree every 90 s while the run lives (spec 006).
34
+ * Opt-in via CEZ_AUTOSAVE=1 (open-mercato/cezar#471) — see periodicAutosaveEnabled. */
35
+ armAutosave(runId: string, state: ActiveRun): void;
36
+ dispose(): void;
37
+ }
38
+ export {};
@@ -0,0 +1,153 @@
1
+ import { autosaveCleanupBlocker, retainAutosaveCleanup, clearAutosaveCleanup } from '../../autosave-cleanup.js';
2
+ import { autosaveCommit } from '../../git-worktree.js';
3
+ import { recordHandoffAutosave, recordHandoffPeriodicAutosave } from '../../handoff.js';
4
+ /** Periodic "cezar autosave" commit in the task worktree (spec 006). */
5
+ export const AUTOSAVE_INTERVAL_MS = 90_000;
6
+ /**
7
+ * Periodic saves are opt-in. Turn-end, finalization and pre-PR flushes remain enabled; only
8
+ * pre-PR follows a repointed HEAD. Coalesce timer-save evidence in the handoff.
9
+ */
10
+ export function periodicAutosaveEnabled(env = process.env) {
11
+ return env.CEZ_AUTOSAVE === '1';
12
+ }
13
+ /** The handoff block's autosave record and cockpit note for a save that committed or left work
14
+ * behind (hearsay-tools/cezarion#1004): a resumed session reads this, not `git log`. */
15
+ function autosaveReportLine(reason, outcome, taskBranch) {
16
+ const where = outcome.branch ?? 'detached HEAD';
17
+ if (outcome.result === 'committed') {
18
+ const what = outcome.sha ? `${outcome.sha} on ${where}` : `on ${where} (sha unavailable)`;
19
+ return `${reason}: cezar autosave committed ${what}; ` +
20
+ `to fold it into your own commits while it is HEAD, run \`git reset --soft ${outcome.sha ?? 'HEAD'}~1\``;
21
+ }
22
+ return `${reason}: ${outcome.changedPaths} changed path(s) left uncommitted on ${where}; ` +
23
+ `cezar does not autosave on a branch other than the task branch ${taskBranch ?? '(unrecorded)'}`;
24
+ }
25
+ export class WorktreeAutosave {
26
+ context;
27
+ host;
28
+ constructor(context, host) {
29
+ this.context = context;
30
+ this.host = host;
31
+ }
32
+ /** The save may finish execution while its strict writer proof remains pending. */
33
+ autosaveTasks = new Map();
34
+ /** Cleanup evidence survives manager disposal and store close/reopen. */
35
+ autosaveCleanupBlocker(runId) {
36
+ return this.autosaveTasks.get(runId)?.blocker ?? autosaveCleanupBlocker(this.context.dataDir, runId);
37
+ }
38
+ /** Keep a separate maintenance hold until autosave proves all its processes exited.
39
+ * Commits only while HEAD is the run's recorded branch (hearsay-tools/cezarion#1004), and
40
+ * records a commit or a skip in the run store, shown in the handoff's records block, and as a
41
+ * note; a periodic save records only a commit, with no note, merged with the
42
+ * periodic commits right before it. A run with no recorded branch keeps committing on
43
+ * whatever HEAD is. */
44
+ async saveWorktree(runId, state, reason) {
45
+ if (state.cwd === this.context.repoRoot)
46
+ return;
47
+ for (;;) {
48
+ const previous = this.autosaveTasks.get(runId);
49
+ if (!previous)
50
+ break;
51
+ await previous.settlement;
52
+ // A blocked save still owns the tree. Do not queue another writer behind it.
53
+ if (previous.blocker)
54
+ return;
55
+ }
56
+ const note = (message) => {
57
+ try {
58
+ this.context.store.appendEvent(runId, { type: 'note', message });
59
+ }
60
+ catch { /* Cleanup may outlive the store or its history; reporting cannot interrupt it. */ }
61
+ };
62
+ let settle;
63
+ const entry = { settlement: new Promise(resolve => { settle = resolve; }) };
64
+ this.autosaveTasks.set(runId, entry);
65
+ let release;
66
+ let retained = false;
67
+ let cleanupConfirmed = false;
68
+ let taskBranch;
69
+ try {
70
+ taskBranch = this.context.store.getRun(runId)?.branch;
71
+ }
72
+ catch { /* A closed store keeps the old rule. */ }
73
+ let outcome;
74
+ const task = autosaveCommit(state.cwd, reason, {
75
+ ...(taskBranch ? { taskBranch } : {}),
76
+ onOutcome: reported => { outcome = reported; },
77
+ onWarning: note,
78
+ onBlocked: (message, proof) => {
79
+ retainAutosaveCleanup(this.context.dataDir, runId, state.cwd, message, proof);
80
+ retained = true;
81
+ if (!release) {
82
+ const hold = this.host.holdForMaintenance([runId]);
83
+ if (!hold)
84
+ return; // Never release execution without a replacement writer guard.
85
+ release = hold;
86
+ note(`${reason} autosave unsuccessful; run can settle, working files remain in ${state.cwd}`);
87
+ }
88
+ entry.blocker = message;
89
+ settle();
90
+ },
91
+ });
92
+ void task.then(result => {
93
+ cleanupConfirmed = true;
94
+ if (result === 'failed')
95
+ note(`${reason} autosave failed; working files remain in ${state.cwd}`);
96
+ else if (result === 'refused')
97
+ note(`${reason} autosave refused: unresolved conflicts or an unfinished merge, cherry-pick or revert; working files remain in ${state.cwd}`);
98
+ else if (outcome && reason === 'periodic') {
99
+ // The timer reports its commits too, since a clean closing flush reports nothing
100
+ // (review on hearsay-tools/cezarion#1111): one coalesced handoff line per run of
101
+ // periodic commits and no note, as a note every 90 s would flood the timeline. A
102
+ // periodic skip stays silent; the closing flush reports one with the final count.
103
+ if (outcome.result === 'committed') {
104
+ recordHandoffPeriodicAutosave(this.context.store, this.context.dataDir, runId, outcome);
105
+ }
106
+ }
107
+ else if (outcome) {
108
+ const message = autosaveReportLine(reason, outcome, taskBranch);
109
+ note(message);
110
+ recordHandoffAutosave(this.context.store, this.context.dataDir, runId, message);
111
+ }
112
+ }, error => note(`${reason} autosave failed: ${String(error)}; working files remain in ${state.cwd}`)).finally(() => {
113
+ if (this.autosaveTasks.get(runId) === entry)
114
+ this.autosaveTasks.delete(runId);
115
+ if (retained && cleanupConfirmed) {
116
+ try {
117
+ clearAutosaveCleanup(this.context.dataDir, runId);
118
+ }
119
+ catch {
120
+ note('autosave cleanup confirmed but retained evidence could not be cleared; worktree reuse remains blocked');
121
+ }
122
+ }
123
+ try {
124
+ release?.();
125
+ }
126
+ catch { /* The store may already be closed; durable evidence is independent. */ }
127
+ if (entry.blocker) {
128
+ note(this.autosaveCleanupBlocker(runId) ? 'autosave cleanup confirmed; retained evidence still blocks worktree reuse' : 'autosave cleanup confirmed; worktree reuse is available again');
129
+ if (!this.context.disposed())
130
+ this.host.reapTerminalScratch(runId);
131
+ if (!this.context.disposed())
132
+ this.host.releaseSlot();
133
+ }
134
+ settle();
135
+ });
136
+ await entry.settlement;
137
+ }
138
+ /** Autosave-commit the worktree every 90 s while the run lives (spec 006).
139
+ * Opt-in via CEZ_AUTOSAVE=1 (open-mercato/cezar#471) — see periodicAutosaveEnabled. */
140
+ armAutosave(runId, state) {
141
+ if (!periodicAutosaveEnabled())
142
+ return;
143
+ if (state.cwd === this.context.repoRoot || state.autosaveTimer)
144
+ return;
145
+ state.autosaveTimer = setInterval(() => {
146
+ const task = this.host.saveWorktree(runId, state, 'periodic');
147
+ this.host.trackTurn(runId, task);
148
+ }, AUTOSAVE_INTERVAL_MS);
149
+ state.autosaveTimer.unref?.();
150
+ }
151
+ dispose() { this.autosaveTasks.clear(); }
152
+ }
153
+ //# sourceMappingURL=worktree-autosave.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worktree-autosave.js","sourceRoot":"","sources":["../../../src/workflows/run/worktree-autosave.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAChH,OAAO,EAAE,cAAc,EAA6C,MAAM,uBAAuB,CAAC;AAClG,OAAO,EAAE,qBAAqB,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AAYxF,wEAAwE;AACxE,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAE3C;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAG,GAAsB,OAAO,CAAC,GAAG;IAC1E,OAAO,GAAG,CAAC,YAAY,KAAK,GAAG,CAAC;AAClC,CAAC;AAED;yFACyF;AACzF,SAAS,kBAAkB,CAAC,MAAsB,EAAE,OAAwB,EAAE,UAA8B;IAC1G,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,IAAI,eAAe,CAAC;IAChD,IAAI,OAAO,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;QACnC,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,GAAG,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,oBAAoB,CAAC;QAC1F,OAAO,GAAG,MAAM,8BAA8B,IAAI,IAAI;YACpD,6EAA6E,OAAO,CAAC,GAAG,IAAI,MAAM,MAAM,CAAC;IAC7G,CAAC;IACD,OAAO,GAAG,MAAM,KAAK,OAAO,CAAC,YAAY,wCAAwC,KAAK,IAAI;QACxF,kEAAkE,UAAU,IAAI,cAAc,EAAE,CAAC;AACrG,CAAC;AAED,MAAM,OAAO,gBAAgB;IACE,OAAO;IAAqC,IAAI;IAA7E,YAA6B,OA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EAAE,oBAAoB,CAAC,CAAC;QACzB,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,EAAE,CAAC;IAChC,CAAC;IAED,OAAO,KAAW,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;CAChD"}
@@ -24,14 +24,8 @@ import { WorkspaceSemaphore, type AccountHolds } from '../workspace/semaphore.ts
24
24
  import { type WorkflowDef } from './types.ts';
25
25
  /** An interactive session that hears nothing from the user closes itself. */
26
26
  export declare const IDLE_TIMEOUT_MS: number;
27
- /** Periodic "cezar autosave" commit in the task worktree (spec 006). */
28
- export declare const AUTOSAVE_INTERVAL_MS = 90000;
29
27
  export { CHECK_KILL_GRACE_MS, CHECK_TERMINATION_CONFIRM_MS } from './grouped-command.ts';
30
- /**
31
- * Periodic saves are opt-in. Turn-end, finalization and pre-PR flushes remain enabled; only
32
- * pre-PR follows a repointed HEAD. Coalesce timer-save evidence in the handoff.
33
- */
34
- export declare function periodicAutosaveEnabled(env?: NodeJS.ProcessEnv): boolean;
28
+ export { periodicAutosaveEnabled, AUTOSAVE_INTERVAL_MS } from './run/worktree-autosave.ts';
35
29
  /**
36
30
  * Explicitly opt out of the repository-root lease for runs that execute in the
37
31
  * current checkout. This covers explicit worktree opt-out, non-Git degradation,
@@ -132,6 +126,7 @@ export declare class RunManager {
132
126
  private readonly inputReceiptSteps;
133
127
  private readonly inputReceiptHost;
134
128
  private readonly queue;
129
+ private readonly worktreeAutosave;
135
130
  private readonly workerExecutions;
136
131
  private get executions();
137
132
  private beginWorkerExecution;
@@ -1660,19 +1655,8 @@ export declare class RunManager {
1660
1655
  * over the line.
1661
1656
  */
1662
1657
  private openTimerAlias;
1663
- /** The save may finish execution while its strict writer proof remains pending. */
1664
- private readonly autosaveTasks;
1665
- /** Cleanup evidence survives manager disposal and store close/reopen. */
1666
1658
  autosaveCleanupBlocker(runId: string): string | undefined;
1667
- /** Keep a separate maintenance hold until autosave proves all its processes exited.
1668
- * Commits only while HEAD is the run's recorded branch (hearsay-tools/cezarion#1004), and
1669
- * records a commit or a skip in the run store, shown in the handoff's records block, and as a
1670
- * note; a periodic save records only a commit, with no note, merged with the
1671
- * periodic commits right before it. A run with no recorded branch keeps committing on
1672
- * whatever HEAD is. */
1673
1659
  private saveWorktree;
1674
- /** Autosave-commit the worktree every 90 s while the run lives (spec 006).
1675
- * Opt-in via CEZ_AUTOSAVE=1 (#471) — see periodicAutosaveEnabled. */
1676
1660
  private armAutosave;
1677
1661
  private clearAutosaveTimer;
1678
1662
  /**
@@ -1,3 +1,4 @@
1
+ import { WorktreeAutosave } from './run/worktree-autosave.js';
1
2
  import { RunSkills } from './run/run-skills.js';
2
3
  import { InboxClaims } from './run/inbox-claims.js';
3
4
  import { WorkerExecutions } from './run/worker-executions.js';
@@ -11,7 +12,6 @@ import { MaintenanceClaims } from './run/maintenance-claims.js';
11
12
  import { WorkerOrphans } from './run/worker-orphans.js';
12
13
  import { openCompletionRequests, recordRequestRefusal, repairFailedRootFinish, rootCompletionRefusal, sentRequestInstructions, settledRootFinishPatch } from './completion-policy.js';
13
14
  import * as continuation from './continuation-admission.js';
14
- import { autosaveCleanupBlocker, retainAutosaveCleanup, clearAutosaveCleanup } from '../autosave-cleanup.js';
15
15
  import { workerEvidenceRunIds } from '../runs/worker-execution.js';
16
16
  import { askErrorMessage, doneErrorMessage, waitErrorMessage } from '../ci-wait/errors.js';
17
17
  import { cezarAskRequestSchema, cezarDoneRequestSchema, cezarWaitRequestSchema, computeWaitingOn, hasWorkerDeadline, workerWaitEntryToLegacy, isUsageLimitHold, TIMER_MAX_SECONDS, TIMER_MIN_SECONDS, WAIT_LIMIT } from '../contract/index.js';
@@ -66,7 +66,7 @@ import { parseUsageLimit } from '../core/usage-limit.js';
66
66
  import { startManagedSession } from '../core/managed-session.js';
67
67
  import { createRunner } from '../core/runner-factory.js';
68
68
  import { agentModelsLocked } from '../core/agent-model-policy.js';
69
- import { handoffInstructions, recordHandoffAutosave, recordHandoffPeriodicAutosave, seedHandoffFile, } from '../handoff.js';
69
+ import { handoffInstructions, seedHandoffFile, } from '../handoff.js';
70
70
  // Contract VALUES, like `workspaceUiStateSchema` in workspace/migrations.ts: the attachment
71
71
  // vocabulary the routes validate with is the same one the engine stores and re-reads by, so the
72
72
  // wire and the disk can never disagree about what counts as an image (#950).
@@ -80,7 +80,7 @@ import { discoverSkills } from '../skills.js';
80
80
  import { waitForCachedTeamSkills, waitForTeamSkills } from '../skills-remote.js';
81
81
  import { seedAgentConfigLocalLayer } from '../agent-config/seed.js';
82
82
  import { loadConfig, resolveWorktreeRetention } from '../config.js';
83
- import { autosaveCommit, worktreeDiff } from '../git-worktree.js';
83
+ import { worktreeDiff } from '../git-worktree.js';
84
84
  import { runGroupedCommand } from './grouped-command.js';
85
85
  import { resolveWorktreeSetup, runWorktreeSetup, worktreeSetupAgentNote, worktreeSetupEndNote, worktreeSetupEnv, worktreeSetupRecordError, worktreeSetupStartNote, } from '../worktree-setup.js';
86
86
  import { getHeadCommit, getRepoInfo } from '../server/git.js';
@@ -122,28 +122,8 @@ function isSyntheticContinuation(run, step) {
122
122
  (!!run.workflowDef && !run.workflowDef.steps.some(candidate => candidate.id === step.id) &&
123
123
  step.kind === 'agent' && step.name === 'Continue')) && /^continue-\d+$/.test(step.id);
124
124
  }
125
- /** Periodic "cezar autosave" commit in the task worktree (spec 006). */
126
- export const AUTOSAVE_INTERVAL_MS = 90_000;
127
125
  export { CHECK_KILL_GRACE_MS, CHECK_TERMINATION_CONFIRM_MS } from './grouped-command.js';
128
- /**
129
- * Periodic saves are opt-in. Turn-end, finalization and pre-PR flushes remain enabled; only
130
- * pre-PR follows a repointed HEAD. Coalesce timer-save evidence in the handoff.
131
- */
132
- export function periodicAutosaveEnabled(env = process.env) {
133
- return env.CEZ_AUTOSAVE === '1';
134
- }
135
- /** The handoff block's autosave record and cockpit note for a save that committed or left work
136
- * behind (hearsay-tools/cezarion#1004): a resumed session reads this, not `git log`. */
137
- function autosaveReportLine(reason, outcome, taskBranch) {
138
- const where = outcome.branch ?? 'detached HEAD';
139
- if (outcome.result === 'committed') {
140
- const what = outcome.sha ? `${outcome.sha} on ${where}` : `on ${where} (sha unavailable)`;
141
- return `${reason}: cezar autosave committed ${what}; ` +
142
- `to fold it into your own commits while it is HEAD, run \`git reset --soft ${outcome.sha ?? 'HEAD'}~1\``;
143
- }
144
- return `${reason}: ${outcome.changedPaths} changed path(s) left uncommitted on ${where}; ` +
145
- `cezar does not autosave on a branch other than the task branch ${taskBranch ?? '(unrecorded)'}`;
146
- }
126
+ export { periodicAutosaveEnabled, AUTOSAVE_INTERVAL_MS } from './run/worktree-autosave.js';
147
127
  /**
148
128
  * Explicitly opt out of the repository-root lease for runs that execute in the
149
129
  * current checkout. This covers explicit worktree opt-out, non-Git degradation,
@@ -281,6 +261,7 @@ export class RunManager {
281
261
  // covers the window between shifting a run off the queue and the run
282
262
  // registering in `active`, so parallel-slot counting is never racy.
283
263
  queue = [];
264
+ worktreeAutosave;
284
265
  workerExecutions;
285
266
  get executions() { return this.workerExecutions.executions; }
286
267
  beginWorkerExecution(id, admitted = true) { this.workerExecutions.beginWorkerExecution(id, admitted); }
@@ -507,6 +488,10 @@ export class RunManager {
507
488
  this.noWaitNudgeReplyMs = options.noWaitNudgeReplyMs ?? NO_WAIT_NUDGE_REPLY_MS;
508
489
  this.semaphore = options.semaphore ?? new WorkspaceSemaphore();
509
490
  this.inputReceiptContext = { store, repoRoot, dataDir: this.dataDir, semaphore: this.semaphore, disposed: () => this.disposed };
491
+ this.worktreeAutosave = new WorktreeAutosave(this.inputReceiptContext, { holdForMaintenance: ids => this.holdForMaintenance(ids),
492
+ reapTerminalScratch: id => this.reapTerminalScratch(id), releaseSlot: () => this.releaseSlot(),
493
+ saveWorktree: (id, state, reason) => this.saveWorktree(id, state, reason),
494
+ trackTurn: (id, task) => this.workerExecutions.trackTurn(id, task) });
510
495
  this.orphans = new WorkerOrphans({ store, repoRoot, dataDir: this.dataDir, semaphore: this.semaphore, disposed: () => this.disposed }, { holds: (id, admitting) => this.workerExecutions.has(id) || this.active.has(id) || this.starting.has(id) || (!admitting && this.queue.includes(id)),
511
496
  reapTerminalScratch: id => this.reapTerminalScratch(id),
512
497
  settleOrphanedWorkerExecution: (id, opts) => this.settleOrphanedWorkerExecution(id, opts),
@@ -626,6 +611,7 @@ export class RunManager {
626
611
  this.pendingContinuations.clear();
627
612
  this.memoryPausing.clear();
628
613
  this.turnBookkeeper.clear();
614
+ this.worktreeAutosave.dispose();
629
615
  }
630
616
  /**
631
617
  * Pause any active run whose whole process tree exceeds the WORKSPACE
@@ -7733,124 +7719,14 @@ export class RunManager {
7733
7719
  }
7734
7720
  this.armWait(runId, wait);
7735
7721
  }
7736
- /** The save may finish execution while its strict writer proof remains pending. */
7737
- autosaveTasks = new Map();
7738
- /** Cleanup evidence survives manager disposal and store close/reopen. */
7739
7722
  autosaveCleanupBlocker(runId) {
7740
- return this.autosaveTasks.get(runId)?.blocker ?? autosaveCleanupBlocker(this.dataDir, runId);
7741
- }
7742
- /** Keep a separate maintenance hold until autosave proves all its processes exited.
7743
- * Commits only while HEAD is the run's recorded branch (hearsay-tools/cezarion#1004), and
7744
- * records a commit or a skip in the run store, shown in the handoff's records block, and as a
7745
- * note; a periodic save records only a commit, with no note, merged with the
7746
- * periodic commits right before it. A run with no recorded branch keeps committing on
7747
- * whatever HEAD is. */
7723
+ return this.worktreeAutosave.autosaveCleanupBlocker(runId);
7724
+ }
7748
7725
  async saveWorktree(runId, state, reason) {
7749
- if (state.cwd === this.repoRoot)
7750
- return;
7751
- for (;;) {
7752
- const previous = this.autosaveTasks.get(runId);
7753
- if (!previous)
7754
- break;
7755
- await previous.settlement;
7756
- // A blocked save still owns the tree. Do not queue another writer behind it.
7757
- if (previous.blocker)
7758
- return;
7759
- }
7760
- const note = (message) => {
7761
- try {
7762
- this.store.appendEvent(runId, { type: 'note', message });
7763
- }
7764
- catch { /* Cleanup may outlive the store or its history; reporting cannot interrupt it. */ }
7765
- };
7766
- let settle;
7767
- const entry = { settlement: new Promise(resolve => { settle = resolve; }) };
7768
- this.autosaveTasks.set(runId, entry);
7769
- let release;
7770
- let retained = false;
7771
- let cleanupConfirmed = false;
7772
- let taskBranch;
7773
- try {
7774
- taskBranch = this.store.getRun(runId)?.branch;
7775
- }
7776
- catch { /* A closed store keeps the old rule. */ }
7777
- let outcome;
7778
- const task = autosaveCommit(state.cwd, reason, {
7779
- ...(taskBranch ? { taskBranch } : {}),
7780
- onOutcome: reported => { outcome = reported; },
7781
- onWarning: note,
7782
- onBlocked: (message, proof) => {
7783
- retainAutosaveCleanup(this.dataDir, runId, state.cwd, message, proof);
7784
- retained = true;
7785
- if (!release) {
7786
- const hold = this.holdForMaintenance([runId]);
7787
- if (!hold)
7788
- return; // Never release execution without a replacement writer guard.
7789
- release = hold;
7790
- note(`${reason} autosave unsuccessful; run can settle, working files remain in ${state.cwd}`);
7791
- }
7792
- entry.blocker = message;
7793
- settle();
7794
- },
7795
- });
7796
- void task.then(result => {
7797
- cleanupConfirmed = true;
7798
- if (result === 'failed')
7799
- note(`${reason} autosave failed; working files remain in ${state.cwd}`);
7800
- else if (result === 'refused')
7801
- note(`${reason} autosave refused: unresolved conflicts or an unfinished merge, cherry-pick or revert; working files remain in ${state.cwd}`);
7802
- else if (outcome && reason === 'periodic') {
7803
- // The timer reports its commits too, since a clean closing flush reports nothing
7804
- // (review on hearsay-tools/cezarion#1111): one coalesced handoff line per run of
7805
- // periodic commits and no note, as a note every 90 s would flood the timeline. A
7806
- // periodic skip stays silent; the closing flush reports one with the final count.
7807
- if (outcome.result === 'committed') {
7808
- recordHandoffPeriodicAutosave(this.store, this.dataDir, runId, outcome);
7809
- }
7810
- }
7811
- else if (outcome) {
7812
- const message = autosaveReportLine(reason, outcome, taskBranch);
7813
- note(message);
7814
- recordHandoffAutosave(this.store, this.dataDir, runId, message);
7815
- }
7816
- }, error => note(`${reason} autosave failed: ${String(error)}; working files remain in ${state.cwd}`)).finally(() => {
7817
- if (this.autosaveTasks.get(runId) === entry)
7818
- this.autosaveTasks.delete(runId);
7819
- if (retained && cleanupConfirmed) {
7820
- try {
7821
- clearAutosaveCleanup(this.dataDir, runId);
7822
- }
7823
- catch {
7824
- note('autosave cleanup confirmed but retained evidence could not be cleared; worktree reuse remains blocked');
7825
- }
7826
- }
7827
- try {
7828
- release?.();
7829
- }
7830
- catch { /* The store may already be closed; durable evidence is independent. */ }
7831
- if (entry.blocker) {
7832
- note(this.autosaveCleanupBlocker(runId) ? 'autosave cleanup confirmed; retained evidence still blocks worktree reuse' : 'autosave cleanup confirmed; worktree reuse is available again');
7833
- if (!this.disposed)
7834
- this.reapTerminalScratch(runId);
7835
- if (!this.disposed)
7836
- this.releaseSlot();
7837
- }
7838
- settle();
7839
- });
7840
- await entry.settlement;
7726
+ return this.worktreeAutosave.saveWorktree(runId, state, reason);
7841
7727
  }
7842
- /** Autosave-commit the worktree every 90 s while the run lives (spec 006).
7843
- * Opt-in via CEZ_AUTOSAVE=1 (#471) — see periodicAutosaveEnabled. */
7844
7728
  armAutosave(runId, state) {
7845
- if (!periodicAutosaveEnabled())
7846
- return;
7847
- if (state.cwd === this.repoRoot || state.autosaveTimer)
7848
- return;
7849
- state.autosaveTimer = setInterval(() => {
7850
- const task = this.saveWorktree(runId, state, 'periodic');
7851
- this.workerExecutions.trackTurn(runId, task);
7852
- }, AUTOSAVE_INTERVAL_MS);
7853
- state.autosaveTimer.unref?.();
7729
+ this.worktreeAutosave.armAutosave(runId, state);
7854
7730
  }
7855
7731
  clearAutosaveTimer(state) {
7856
7732
  clearAutosaveTimer(state);