@unieai/rabi-experimental-worktree 0.2.1-rc.3 → 0.2.2-rc.5

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.
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Archive-triggered reclamation of checkouts this service created. Installed by
3
+ * the service constructor, as the job and Agent registries install their own
4
+ * archive-admission families, so it holds for every Session the Workspace archives.
5
+ */
6
+ import type { Context } from '@unieai/cordis';
7
+ import type { Session, SessionId } from '@unieai/rabi-session';
8
+ import type { ProjectionHandle } from '@unieai/rabi-session-projection';
9
+ import type { WorktreeProjectionState } from './projection.ts';
10
+ import type { CreatedWorktree, WorktreeCleanup } from './types.ts';
11
+ declare module '@unieai/cordis' {
12
+ interface Events {
13
+ /**
14
+ * A cleanup attempt changed state. Fires once at admission with
15
+ * `scheduled` and once at settlement with the final status.
16
+ * @param info - the archived Session, the checkout, and the attempt state.
17
+ * @mode emit
18
+ */
19
+ 'worktree/cleanup'(info: {
20
+ sessionId: SessionId;
21
+ path: string;
22
+ cleanup: WorktreeCleanup;
23
+ }): void;
24
+ }
25
+ }
26
+ /** The service operations reclamation needs; kept narrow so the archive module never reaches Git directly. */
27
+ export interface ReclamationHost {
28
+ /** Whether the deployment keeps every checkout on archive; read at each admission. */
29
+ retainOnArchive(): boolean;
30
+ /** Run `body` after every operation on `path` that was requested earlier, and before any requested later. */
31
+ exclusiveCheckout<T>(path: string, body: () => Promise<T>): Promise<T>;
32
+ /** Inspect and, when eligible and admitted, remove the checkout without force. Rejects on Git failure. */
33
+ removeCheckout(session: Session, request: CreatedWorktree, signal: AbortSignal, admit: () => boolean): Promise<boolean>;
34
+ }
35
+ /** Owns pending cleanup, gates directory entry into a checkout being removed, and drains before the service is released. */
36
+ export declare class WorktreeReclamation {
37
+ private readonly ctx;
38
+ private readonly host;
39
+ private readonly projection;
40
+ private readonly attempts;
41
+ private readonly removing;
42
+ private readonly pending;
43
+ private readonly lifetime;
44
+ private revision;
45
+ /**
46
+ * @param ctx - scope injecting the Workspace registry, Session query, store, working-directory, and
47
+ * sandbox-policy providers; the projection cache is read when mounted.
48
+ * @param host - the service operations the module runs through.
49
+ * @param projection - the `worktree` unit, read live and through the persisted cache.
50
+ */
51
+ constructor(ctx: Context, host: ReclamationHost, projection: ProjectionHandle<WorktreeProjectionState>);
52
+ /**
53
+ * Read the most recent cleanup attempt of a Session; waiting never starts one.
54
+ * @param session - archived Session whose attempt is read.
55
+ * @param revision - null reads at once; a matching revision waits for that attempt to settle.
56
+ * @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
57
+ */
58
+ cleanupOf(session: Session, revision: number | null): Promise<WorktreeCleanup | null>;
59
+ /** Register attempts for the Session's own creations and return; every inspection runs in the background. */
60
+ private schedule;
61
+ private run;
62
+ /**
63
+ * Remove under the path lock; a second use check runs inside it, after
64
+ * competing operations settled. A Session has one attempt and unarchiving
65
+ * awaits it, so removals of one path never overlap.
66
+ */
67
+ private remove;
68
+ /**
69
+ * Whether no unarchived Session still refers to the checkout: by a recorded
70
+ * creation, inherited or own, or by a working directory inside it. A Session
71
+ * beneath an archived subagent ancestor counts as archived, as its own
72
+ * archive admission does. Processes are not consulted: Git refuses a
73
+ * removal that would discard changes, and an idle process in a removed
74
+ * directory fails its next command.
75
+ */
76
+ private unused;
77
+ /** The archived Session itself, prepared cold when not live, whose sandbox policy confines the Git commands. */
78
+ private creatorSession;
79
+ /** The recorded directory of a cold Session, null when its log recorded none: the persisted cache when it has one, else its log. */
80
+ private directoryOf;
81
+ /** The recorded creations of a cold Session: the persisted cache when it has one, else its log. */
82
+ private creationsOf;
83
+ }
84
+ //# sourceMappingURL=archive.d.ts.map
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Whether `path` is `root` or lies below it. Both are canonical absolute
3
+ * directories of one execution world without a trailing separator, so string
4
+ * prefixing is exact.
5
+ */
6
+ function within(root, path) {
7
+ return path === root || path.startsWith(`${root}/`);
8
+ }
9
+ /** Owns pending cleanup, gates directory entry into a checkout being removed, and drains before the service is released. */
10
+ export class WorktreeReclamation {
11
+ ctx;
12
+ host;
13
+ projection;
14
+ attempts = new Map();
15
+ removing = new Map();
16
+ pending = new Set();
17
+ lifetime = new AbortController();
18
+ revision = 0;
19
+ /**
20
+ * @param ctx - scope injecting the Workspace registry, Session query, store, working-directory, and
21
+ * sandbox-policy providers; the projection cache is read when mounted.
22
+ * @param host - the service operations the module runs through.
23
+ * @param projection - the `worktree` unit, read live and through the persisted cache.
24
+ */
25
+ constructor(ctx, host, projection) {
26
+ this.ctx = ctx;
27
+ this.host = host;
28
+ this.projection = projection;
29
+ // Listeners withdraw before the drain so a disposing service never fails
30
+ // unrelated directory access or an unarchive with its own abort.
31
+ ctx.on('working-directory/access', ({ agent, path, signal }, next) => {
32
+ const target = path ?? ctx.workingDirectory.get(agent.session);
33
+ const blocked = [...this.removing.keys()].find(root => within(root, target));
34
+ if (blocked === undefined)
35
+ return next();
36
+ return this.host.exclusiveCheckout(blocked, async () => {
37
+ signal.throwIfAborted();
38
+ return await next();
39
+ });
40
+ });
41
+ ctx.on('workspace/session-archived', ({ sessionId }) => { this.schedule(sessionId); });
42
+ ctx.on('workspace/session-unarchiving', async ({ sessionId }) => {
43
+ const attempt = this.attempts.get(sessionId);
44
+ if (attempt === undefined)
45
+ return;
46
+ attempt.cancelled = true;
47
+ await attempt.done;
48
+ this.attempts.delete(sessionId);
49
+ });
50
+ ctx.effect(() => async () => {
51
+ this.lifetime.abort(new Error('worktree reclamation stopped'));
52
+ for (const attempt of this.attempts.values())
53
+ attempt.cancelled = true;
54
+ await Promise.allSettled(this.pending);
55
+ this.attempts.clear();
56
+ }, 'worktree: drain archive cleanup');
57
+ }
58
+ /**
59
+ * Read the most recent cleanup attempt of a Session; waiting never starts one.
60
+ * @param session - archived Session whose attempt is read.
61
+ * @param revision - null reads at once; a matching revision waits for that attempt to settle.
62
+ * @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
63
+ */
64
+ async cleanupOf(session, revision) {
65
+ const attempt = this.attempts.get(session.id);
66
+ if (attempt === undefined || (revision !== null && revision !== attempt.revision))
67
+ return null;
68
+ if (revision !== null)
69
+ await attempt.done;
70
+ // A cold Session without creations withdraws its placeholder while it settles.
71
+ if (this.lifetime.signal.aborted || this.attempts.get(session.id) !== attempt)
72
+ return null;
73
+ return { revision: attempt.revision, status: attempt.status };
74
+ }
75
+ /** Register attempts for the Session's own creations and return; every inspection runs in the background. */
76
+ schedule(sessionId) {
77
+ if (this.host.retainOnArchive())
78
+ return;
79
+ const live = this.ctx.sessions.get(sessionId);
80
+ // A cold Session's creations come from the persisted cache or its log, below.
81
+ const owned = live === undefined ? undefined : this.projection.stateOf(live).created.filter(creation => creation.owned);
82
+ if (owned !== undefined && owned.length === 0)
83
+ return;
84
+ const attempt = {
85
+ worktree: owned?.[0]?.worktree ?? { path: '', branch: '', baseCommit: '', repositoryRoot: '' },
86
+ revision: ++this.revision, status: 'scheduled', cancelled: false, done: Promise.resolve(),
87
+ };
88
+ this.attempts.set(sessionId, attempt);
89
+ // run() settles every outcome into the attempt, so the task never rejects.
90
+ const task = this.run(sessionId, attempt, owned);
91
+ this.pending.add(task);
92
+ attempt.done = task.then(() => { this.pending.delete(task); });
93
+ }
94
+ async run(sessionId, attempt, owned) {
95
+ const ctx = this.ctx;
96
+ try {
97
+ const creations = owned ?? (await this.creationsOf(sessionId, undefined)).filter(creation => creation.owned);
98
+ const candidate = creations[0]?.worktree;
99
+ if (candidate === undefined) {
100
+ this.attempts.delete(sessionId);
101
+ return;
102
+ }
103
+ Object.assign(attempt, { worktree: candidate });
104
+ ctx.emit('worktree/cleanup', {
105
+ sessionId, path: candidate.path, cleanup: { revision: attempt.revision, status: attempt.status },
106
+ });
107
+ const session = await this.creatorSession(sessionId);
108
+ if (session === undefined || attempt.cancelled || ctx.sandboxPolicy.resolve({ session }).mode === 'read-only'
109
+ || !await this.unused(candidate, sessionId)) {
110
+ attempt.status = 'retained';
111
+ }
112
+ else {
113
+ attempt.status = await this.remove(session, candidate, attempt) ? 'removed' : 'retained';
114
+ }
115
+ }
116
+ catch (error) {
117
+ attempt.status = 'failed';
118
+ ctx.logger.warn('Session %s archived; cleanup of its worktree %s failed and its branch was retained: %s', sessionId, attempt.worktree.path, error);
119
+ }
120
+ ctx.emit('worktree/cleanup', {
121
+ sessionId, path: attempt.worktree.path, cleanup: { revision: attempt.revision, status: attempt.status },
122
+ });
123
+ }
124
+ /**
125
+ * Remove under the path lock; a second use check runs inside it, after
126
+ * competing operations settled. A Session has one attempt and unarchiving
127
+ * awaits it, so removals of one path never overlap.
128
+ */
129
+ async remove(session, worktree, attempt) {
130
+ const operation = this.host.exclusiveCheckout(worktree.path, async () => {
131
+ if (attempt.cancelled || !await this.unused(worktree, undefined))
132
+ return false;
133
+ return await this.host.removeCheckout(session, worktree, this.lifetime.signal, () => !attempt.cancelled);
134
+ });
135
+ this.removing.set(worktree.path, operation.then(() => { }, () => { }));
136
+ try {
137
+ return await operation;
138
+ }
139
+ finally {
140
+ this.removing.delete(worktree.path);
141
+ }
142
+ }
143
+ /**
144
+ * Whether no unarchived Session still refers to the checkout: by a recorded
145
+ * creation, inherited or own, or by a working directory inside it. A Session
146
+ * beneath an archived subagent ancestor counts as archived, as its own
147
+ * archive admission does. Processes are not consulted: Git refuses a
148
+ * removal that would discard changes, and an idle process in a removed
149
+ * directory fails its next command.
150
+ */
151
+ async unused(worktree, archivingId) {
152
+ const ctx = this.ctx;
153
+ const signal = this.lifetime.signal;
154
+ signal.throwIfAborted();
155
+ const records = await ctx.sessionQuery.listSessions(signal);
156
+ const headers = new Map(records.map(record => [record.header.id, record.header]));
157
+ const archived = new Set(ctx.workspaceRegistry.archivedSessionIds);
158
+ if (archivingId !== undefined)
159
+ archived.add(archivingId);
160
+ for (const record of records) {
161
+ const id = record.header.id;
162
+ if (archived.has(id) || ancestorArchived(record.header, headers, archived))
163
+ continue;
164
+ const live = ctx.sessions.get(id);
165
+ const cwd = live === undefined ? await this.directoryOf(record.header) : ctx.workingDirectory.get(live);
166
+ if (cwd !== null && within(worktree.path, cwd))
167
+ return false;
168
+ const creations = live === undefined ? await this.creationsOf(id, record.header) : this.projection.stateOf(live).created;
169
+ if (creations.some(creation => creation.worktree.path === worktree.path))
170
+ return false;
171
+ signal.throwIfAborted();
172
+ }
173
+ return true;
174
+ }
175
+ /** The archived Session itself, prepared cold when not live, whose sandbox policy confines the Git commands. */
176
+ async creatorSession(sessionId) {
177
+ const live = this.ctx.sessions.get(sessionId);
178
+ if (live !== undefined)
179
+ return live;
180
+ return await this.ctx.sessionQuery.inspectSession(sessionId, session => session, this.lifetime.signal);
181
+ }
182
+ /** The recorded directory of a cold Session, null when its log recorded none: the persisted cache when it has one, else its log. */
183
+ async directoryOf(header) {
184
+ const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(header, ['workingDirectory'])?.values.workingDirectory;
185
+ if (cached !== undefined)
186
+ return cached;
187
+ return await this.ctx.sessionQuery.inspectSession(header.id, session => this.ctx.workingDirectory.get(session), this.lifetime.signal);
188
+ }
189
+ /** The recorded creations of a cold Session: the persisted cache when it has one, else its log. */
190
+ async creationsOf(sessionId, header) {
191
+ const cached = header === undefined
192
+ ? undefined
193
+ : this.ctx.get('sessionProjectionCache')?.cachedSnapshot(header, ['worktree'])?.values.worktree;
194
+ if (cached !== undefined)
195
+ return cached;
196
+ return await this.ctx.sessionQuery.inspectSession(sessionId, session => this.projection.stateOf(session).created, this.lifetime.signal);
197
+ }
198
+ }
199
+ /** Whether any subagent ancestor of `header`, followed through the listed headers, is archived. */
200
+ function ancestorArchived(header, headers, archived) {
201
+ const visited = new Set([header.id]);
202
+ let current = header;
203
+ while (current.origin === 'subagent' && current.parentSession !== undefined && !visited.has(current.parentSession)) {
204
+ if (archived.has(current.parentSession))
205
+ return true;
206
+ visited.add(current.parentSession);
207
+ const parent = headers.get(current.parentSession);
208
+ if (parent === undefined)
209
+ return false;
210
+ current = parent;
211
+ }
212
+ return false;
213
+ }
@@ -0,0 +1,24 @@
1
+ /** Static child program for exclusive checkout-directory allocation inside the process sandbox. */
2
+ /**
3
+ * The child receives the configured root and destination as literal argv. Existing roots retain
4
+ * their files; only the process that creates a root writes its self-ignoring .gitignore.
5
+ */
6
+ export const PREPARE_DIRECTORY = `
7
+ import fs from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ async function main() {
10
+ const [root, destination] = process.argv.slice(1);
11
+ await fs.mkdir(path.dirname(root), { recursive: true });
12
+ let created = false;
13
+ try {
14
+ await fs.mkdir(root);
15
+ created = true;
16
+ } catch (error) {
17
+ if (error.code !== 'EEXIST' || !(await fs.stat(root)).isDirectory()) throw error;
18
+ }
19
+ if (created) await fs.writeFile(path.join(root, '.gitignore'), '*\\n', { flag: 'wx' });
20
+ await fs.mkdir(path.dirname(destination), { recursive: true });
21
+ await fs.mkdir(destination);
22
+ }
23
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });
24
+ `;
@@ -1,11 +1,17 @@
1
- /** Creates a new Git branch and checkout, then changes the calling Session's working directory. */
2
- import { Context, Service } from '@unieai/cordis';
1
+ /** Creates a new Git branch and checkout, then changes the calling Session's working directory; restores a removed checkout. */
2
+ import { Context, Service, type Volatile } from '@unieai/cordis';
3
3
  import z from '@unieai/schemastery';
4
4
  import type { Agent } from '@unieai/rabi-agent';
5
- import type { CreatedWorktree, CreateWorktreeRequest } from './types.ts';
6
- export type { CreatedWorktree, CreateWorktreeRequest } from './types.ts';
7
- /** Worktree location, generated names, executables, and subprocess resource limits. */
5
+ import type { Session } from '@unieai/rabi-session';
6
+ import type { CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest, WorktreeCleanup } from './types.ts';
7
+ export type { CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest, WorktreeCleanup, WorktreeCreation, } from './types.ts';
8
+ export { generatedWorktreeName } from './name.ts';
9
+ export { CREATED_RECORD, createdWorktreeSchema, worktreeProjection } from './projection.ts';
10
+ export type { WorktreeProjectionState } from './projection.ts';
11
+ /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */
8
12
  export interface Config {
13
+ /** Keep every checkout when its Session is archived; editable live from the Plugins page. */
14
+ retainOnArchive: Volatile<boolean>;
9
15
  /** Relative checkout pool inside the source repository. */
10
16
  directory?: string;
11
17
  /** Prefix for automatically generated branch and checkout names. */
@@ -18,7 +24,11 @@ export interface Config {
18
24
  timeoutMs?: number;
19
25
  /** Subprocess termination grace in milliseconds. */
20
26
  graceMs?: number;
21
- /** Maximum captured bytes per subprocess output stream. */
27
+ /**
28
+ * Maximum captured bytes per subprocess output stream; archive inspection
29
+ * streams `git status`, and inspection and restoration stream the worktree
30
+ * listing, so it bounds only their stderr.
31
+ */
22
32
  maxOutputBytes?: number;
23
33
  }
24
34
  declare module '@unieai/cordis' {
@@ -26,14 +36,40 @@ declare module '@unieai/cordis' {
26
36
  worktrees: WorktreeService;
27
37
  }
28
38
  }
29
- /** Creates retained Git worktrees under the mounted filesystem and sandbox providers. */
39
+ /**
40
+ * Creates retained Git worktrees under the mounted filesystem and sandbox
41
+ * providers, records each creation in the Session log, and reclaims a clean,
42
+ * unreferenced checkout when the Session that created it is archived.
43
+ */
30
44
  export declare class WorktreeService extends Service {
31
45
  static inject: string[];
32
- static Config: z<Config>;
46
+ static Config: z<Schemastery.ObjectS<NoInfer<{
47
+ retainOnArchive: z<boolean, boolean, "volatile-defined">;
48
+ directory: z<string, string, "defined">;
49
+ namePrefix: z<string, string, "defined">;
50
+ gitCommand: z<string, string, "defined">;
51
+ nodeCommand: z<string, string, "defined">;
52
+ timeoutMs: z<number, number, "defined">;
53
+ graceMs: z<number, number, "defined">;
54
+ maxOutputBytes: z<number, number, "defined">;
55
+ }>>, Schemastery.ObjectT<NoInfer<{
56
+ retainOnArchive: z<boolean, boolean, "volatile-defined">;
57
+ directory: z<string, string, "defined">;
58
+ namePrefix: z<string, string, "defined">;
59
+ gitCommand: z<string, string, "defined">;
60
+ nodeCommand: z<string, string, "defined">;
61
+ timeoutMs: z<number, number, "defined">;
62
+ graceMs: z<number, number, "defined">;
63
+ maxOutputBytes: z<number, number, "defined">;
64
+ }>>, "plain">;
33
65
  private readonly config;
34
66
  private readonly lifetime;
35
67
  private readonly pending;
68
+ private readonly checkouts;
69
+ private projection;
70
+ private reclamation;
36
71
  constructor(ctx: Context, config: Config);
72
+ protected [Service.init](): Promise<void>;
37
73
  /**
38
74
  * Create a fresh branch and checkout at a pinned local revision, then enter it.
39
75
  * Existing branches or checkout paths fail. Uncommitted files stay in the source checkout.
@@ -44,11 +80,51 @@ export declare class WorktreeService extends Service {
44
80
  * @param agent - caller whose current directory selects the source repository and file policy.
45
81
  * @param request - optional new name and local revision; defaults are generated name and HEAD.
46
82
  * @param signal - cancellation of lookup, creation, and working-directory publication.
83
+ * @param onPhase - receives each stage before it begins; it must not throw.
47
84
  * @returns canonical checkout path, branch name, pinned commit, and source repository root.
48
85
  */
49
- create(agent: Agent, request?: CreateWorktreeRequest, signal?: AbortSignal): Promise<CreatedWorktree>;
86
+ create(agent: Agent, request?: CreateWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void): Promise<CreatedWorktree>;
87
+ /**
88
+ * Check out a removed worktree again at its recorded directory: its branch
89
+ * when the branch still exists, otherwise a new branch of the same name at
90
+ * `baseCommit`. Only the missing target's unlocked registration is removed, and an
91
+ * existing directory fails. Changes that were never committed are not
92
+ * recovered. Checkout disables configured clean, smudge, and process filters,
93
+ * as creation does. The calling Session's working directory does not change.
94
+ * Failures may retain newly allocated Git/filesystem artifacts.
95
+ * @param agent - caller whose sandbox policy confines the commands.
96
+ * @param request - recorded directory, branch, base commit, and source repository root.
97
+ * @param signal - cancellation of the restoration.
98
+ * @param onPhase - receives each stage before it begins; it must not throw.
99
+ * @returns the directory and whether the branch was created again.
100
+ */
101
+ restore(agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void): Promise<RestoredWorktree>;
102
+ /**
103
+ * Read the archive cleanup of a Session's created checkout; waiting never
104
+ * starts one. Absent without the Workspace and query providers.
105
+ * @param session - archived Session whose cleanup is read.
106
+ * @param revision - null reads at once; a matching revision waits for that attempt to settle.
107
+ * @returns the attempt state, or null when none exists, the revision was superseded, or the service is stopping.
108
+ */
109
+ cleanupOf(session: Session, revision: number | null): Promise<WorktreeCleanup | null>;
110
+ /**
111
+ * Inspect a recorded checkout under the Session's policy and, when eligible
112
+ * and admitted, remove it and its registration without force or branch
113
+ * deletion. A rejection can leave a partial directory; the branch stays.
114
+ */
115
+ private removeCheckout;
116
+ private exclusiveCheckout;
50
117
  private resolve;
51
118
  private createCheckout;
119
+ private restoreCheckout;
120
+ /** Confine Git commands to the caller's sandbox policy, collecting bounded stdout. */
121
+ private gitRunner;
122
+ /** Confine Git commands to the caller's sandbox policy, streaming stdout instead of collecting it. */
123
+ private gitScanner;
124
+ /** The configured Git executable with hooks and the filesystem monitor disabled, followed by `args`. */
125
+ private gitArgv;
126
+ /** Allocate the checkout directory exclusively inside the pool, creating a self-ignoring pool when it is new. */
127
+ private prepareDirectory;
52
128
  }
53
129
  export default WorktreeService;
54
130
  //# sourceMappingURL=index.d.ts.map