aligndev 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,15 +12,16 @@ You talk to an **assistant**, the way you would to a developer on your team. It
12
12
 
13
13
  For each task, the assistant:
14
14
 
15
- 1. Discusses the task with the agent and has it write a **spec**.
16
- 2. Has it write the **plans**.
17
- 3. Has the plans **executed** in a fresh session.
18
- 4. Has a **code review** done in another session.
19
- 5. Has the review findings **fixed** in yet another session.
20
- 6. For UI changes, **tests manually** and checks the dev-server logs.
15
+ 1. Sets up the task's **workspace**.
16
+ 2. Refreshes the default branch and **merges** it into the task branch.
17
+ 3. Discusses the task with the agent and has it write a **spec**.
18
+ 4. Has it write the **plans**.
19
+ 5. Has the plans **executed** in a fresh session.
20
+ 6. **Tests manually**, takes **screenshots** of UI changes, and checks the dev-server logs.
21
21
  7. Has fixes made as needed.
22
- 8. Takes **screenshots** for good measure.
23
- 9. Has the agent **open a draft PR**.
22
+ 8. Has a **code review** done in another session.
23
+ 9. Has the review findings **fixed** in yet another session.
24
+ 10. Has the agent **open a PR**.
24
25
 
25
26
  A task can also start at any intermediate step.
26
27
 
@@ -34,9 +35,13 @@ For a coding-agent assistant, parent host and delegated child are independent: a
34
35
 
35
36
  ## Start in Claude Code, Codex or Pi
36
37
 
37
- The project needs an AlignFirst `.plans` directory, in its repository or in a [companion directory](https://github.com/paleo/alignfirst/tree/main/packages/alignfirst#companion-directories). The [setup guide](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/coding-agent-assistant.md) prepares it.
38
+ The project needs usable AlignFirst work files, untracked by the project's own repository or in a [companion directory](https://github.com/paleo/alignfirst/tree/main/packages/alignfirst#companion-directories). A separate work-files repository may track them. The [setup guide](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/coding-agent-assistant.md) prepares it. `alignfirst plans check --json` verifies them, from the main worktree or a linked one. AlignFirst refuses effective plans tracked by the project's own repository. Missing or project-tracked effective plans require authorized companion preparation through `aligndev guide work-files-setup`; existing project content stays untouched and is not copied.
38
39
 
39
- The child needs network access and writes outside the repository. Claude Code/Codex parents request their established sandbox bypass or elevation; approve that request when it comes. Pi uses ordinary OS permissions and saved project trust. It has no implied sandbox or per-command approval boundary, and A profile's `skipPermissions` has no effect on Pi.
40
+ Full workspace tooling is optional. The assistant follows the project's documented tooling when present; otherwise `aligndev worktree` creates or reuses an isolated Git worktree without installation or tracked configuration changes. It shares usable untracked project plans and optional `.local` through locally excluded symlinks, or uses companion plans directly. Readiness covers Git and work files only; dependency installation, builds, tests and application lifecycle follow the repository's commands separately. Removal refuses dirty worktrees, preserves branches and shared targets, and does not stop processes or tear down infrastructure. See `aligndev worktree --help` for the command reference.
41
+
42
+ The child needs network access and access to its selected work files. Parent-host elevation and the child's permission policy are separate. A shared symlink grants no sandbox permission. In native Codex 0.162.1 host probes, normal `workspace-write` denied writes through shared project `.plans` and `.local` links (`Errno 30`). Prepared companion plans passed through the existing `--add-dir <companion>` route; shared `.local` and outside-root writes remained denied. Report denied real paths. For companion plans, obtain approval through `aligndev guide work-files-setup`, preserving existing project files. Do not silently bypass the sandbox or grant the whole main repository write access.
43
+
44
+ Pi uses ordinary OS permissions and saved project trust; a profile's `skipPermissions` has no effect. Native Pi 1.3.0 host probes passed for shared plans, a separate work-files repository, companion plans and `.local`. These results establish OS access, not sandbox confinement. Neither agent's host-user probes establish production service-account or deployment support.
40
45
 
41
46
  ### With the Skill
42
47
 
@@ -177,7 +182,7 @@ npx -y skills add https://github.com/paleo/alignfirst --global --skill alignfirs
177
182
 
178
183
  Deployments require null or a string for every coding profile and enabled explicit quota source; omission is invalid there. Generated service defaults use null. Inventory still records absolute filesystem paths, while native commands unset the directory variable for null or set its resolved value for a string.
179
184
 
180
- Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code, Codex or Pi variant, and writes the installation, security, operation and recovery runbooks. Each managed project receives the full preparation contract: the `alignfirst context` section in its `AGENTS.md`, an optional work-files repository, docmap, isolated workspaces and a project-specific `DEVELOPERS.md`.
185
+ Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code, Codex or Pi variant, and writes the installation, security, operation and recovery runbooks. Each managed project receives the preparation contract: project context, usable work files, docmap, runtime procedures and a project-specific `DEVELOPERS.md`, in the repository or its companion. Full workspace tooling is optional; lightweight worktrees provide isolation when it is absent.
181
186
 
182
187
  ## Under the Hood
183
188
 
package/dist/cli.js CHANGED
@@ -8,6 +8,7 @@ import { errorMessage } from "./errors.js";
8
8
  import { runGuide } from "./guide/guide-cli.js";
9
9
  import { readPackageVersion } from "./package-version.js";
10
10
  import { runProject } from "./project/project-cli.js";
11
+ import { runWorktree } from "./worktree/worktree-cli.js";
11
12
  export async function main(options) {
12
13
  const ctx = resolveContext(options);
13
14
  const [command, ...tokens] = (options?.argv ?? process.argv).slice(2);
@@ -19,12 +20,17 @@ export async function main(options) {
19
20
  ctx.stdout.write(`${readPackageVersion()}\n`);
20
21
  return 0;
21
22
  }
22
- if (command !== "code" && command !== "project" && command !== "guide") {
23
+ if (command !== "code" &&
24
+ command !== "project" &&
25
+ command !== "guide" &&
26
+ command !== "worktree") {
23
27
  const error = command === undefined ? "Error: no command given." : `Error: unknown command "${command}".`;
24
28
  ctx.stderr.write(`${error}\n\n${renderHelp(ctx.forms.aligndev)}`);
25
29
  return 1;
26
30
  }
27
31
  try {
32
+ if (command === "worktree")
33
+ return runWorktree(tokens, ctx);
28
34
  if (command === "code")
29
35
  return await runCode(tokens, () => loadConfig(ctx.home), ctx);
30
36
  const config = loadConfig(ctx.home);
@@ -44,6 +50,10 @@ function renderHelp(aligndev) {
44
50
  `${aligndev} project <command> [<options>]`,
45
51
  "List projects, check their inventory, claim port ranges.",
46
52
  ],
53
+ [
54
+ `${aligndev} worktree <command> [<options>]`,
55
+ "Create, list and safely remove lightweight Git worktrees.",
56
+ ],
47
57
  [`${aligndev} guide [<topic>]`, "Print the assistant's playbook and guides."],
48
58
  [`${aligndev} -h, --help`],
49
59
  [`${aligndev} -v, --version`],
@@ -9,6 +9,7 @@ import { type RunConfig } from "./run-agent.js";
9
9
  import { type SessionRecord } from "./session-file.js";
10
10
  export interface CodeContext {
11
11
  cwd: string;
12
+ home: string;
12
13
  env: NodeJS.ProcessEnv;
13
14
  stdout: Output;
14
15
  stderr: Output;
@@ -60,7 +61,7 @@ export interface SessionArgs {
60
61
  export declare function runCode(tokens: string[], loadSettings: () => LoadedConfig, ctx: CodeContext): Promise<number>;
61
62
  export declare function parseCodeArgs(tokens: string[], aligndev: string): CodeCommand;
62
63
  export declare function validateSessionArgs(args: SessionArgs, models: readonly string[] | undefined): string | undefined;
63
- export declare function checkLaunchGuards(args: SessionArgs, agent: CodingAgent, realCwd: string, ticket: string | undefined, records: SessionRecord[], previous?: SessionRecord): string | undefined;
64
+ export declare function checkLaunchGuards(args: SessionArgs, agent: CodingAgent, realCwd: string, ticket: string | undefined, records: SessionRecord[], machineId: string, previous?: SessionRecord): string | undefined;
64
65
  export declare function resolveTicket(args: SessionArgs, records: SessionRecord[]): string | undefined;
65
66
  export interface RunInput {
66
67
  args: SessionArgs;
@@ -5,12 +5,14 @@ import { loadCatchup, loadContext, openTicket, reserveSideTicket } from "../alig
5
5
  import { resolveCodeConfig, resolveQuotaConfig, } from "../config.js";
6
6
  import { errorMessage } from "../errors.js";
7
7
  import { companionInUse, readProjectReport, } from "../project/layout.js";
8
+ import { validateEffectivePlans } from "../project/plans.js";
8
9
  import { createAgentAdapter } from "./coding-agent.js";
10
+ import { readMachineId } from "./machine-id.js";
9
11
  import { expandModelAlias, resolveModels } from "./models.js";
10
12
  import { describeNativeStorage } from "./native-context.js";
11
13
  import { buildPrompt, PROTOCOLS } from "./prompt.js";
12
14
  import { runAgent } from "./run-agent.js";
13
- import { applyCompletion, createSessionFile, findNewestSessionFile, listSessionRecords, readPidStartTime, reconcileSessionFile, RESULT_MARKER, } from "./session-file.js";
15
+ import { applyCompletion, completedSessionPath, createSessionFile, findNewestSessionFile, listSessionRecords, readPidStartTime, reconcileSessionFile, RESULT_MARKER, } from "./session-file.js";
14
16
  // Distinct from 1 (ordinary run failure) so a script can branch on an auth failure that needs an
15
17
  // operator re-login rather than a retry.
16
18
  const EXIT_AUTH_REQUIRED = 2;
@@ -46,7 +48,10 @@ export async function runCode(tokens, loadSettings, ctx) {
46
48
  }
47
49
  const config = loadSettings();
48
50
  const report = readReport(ctx);
49
- const records = command.kind === "session" ? listSessionRecords(report.locations._aligndev.path) : [];
51
+ if (command.kind === "session")
52
+ validateEffectivePlans(ctx);
53
+ const tree = command.kind === "session" ? sessionTreeOf(report, ctx) : undefined;
54
+ const records = tree === undefined ? [] : listSessionRecords(tree.sessionsDir, tree.machineId);
50
55
  const args = command.kind === "session" ? command.args : undefined;
51
56
  const previous = args?.resume === undefined
52
57
  ? undefined
@@ -72,7 +77,9 @@ export async function runCode(tokens, loadSettings, ctx) {
72
77
  ctx.stderr.write(`${validationError}\n`);
73
78
  return 1;
74
79
  }
75
- return await runSession(command.args, code, ctx, report, records, previous);
80
+ if (tree === undefined)
81
+ throw new Error("Missing session tree.");
82
+ return await runSession(command.args, code, ctx, report, tree, records, previous);
76
83
  }
77
84
  catch (error) {
78
85
  ctx.stderr.write(`${errorMessage(error)}\n`);
@@ -80,10 +87,9 @@ export async function runCode(tokens, loadSettings, ctx) {
80
87
  }
81
88
  }
82
89
  function showStatus(ctx, target, includeResult) {
83
- const tree = sessionTreeOf(readReport(ctx), ctx.cwd);
84
- const sessionFilePath = resolveStatusTargetSessionFile(tree, target);
85
- const completion = reconcileSessionFile(sessionFilePath);
86
- ctx.stdout.write(renderSessionStatus(tree.cwd, sessionFilePath, completion.frontmatter));
90
+ const tree = sessionTreeOf(readReport(ctx), ctx);
91
+ const completion = reconcileSessionFile(resolveStatusTargetSessionFile(tree, target), tree.machineId);
92
+ ctx.stdout.write(renderSessionStatus(tree.cwd, completion.path, completion.frontmatter));
87
93
  if (includeResult &&
88
94
  completion.frontmatter.status !== "running" &&
89
95
  completion.result !== undefined) {
@@ -97,10 +103,11 @@ function readReport(ctx) {
97
103
  throw new Error(report.error);
98
104
  return report;
99
105
  }
100
- function sessionTreeOf(report, cwd) {
106
+ function sessionTreeOf(report, ctx) {
101
107
  return {
102
- cwd: realpathSync(cwd),
108
+ cwd: realpathSync(ctx.cwd),
103
109
  sessionsDir: report.locations._aligndev.path,
110
+ machineId: readMachineId(ctx.home),
104
111
  };
105
112
  }
106
113
  async function showQuota(ctx, code) {
@@ -136,7 +143,7 @@ function resolveStatusTargetSessionFile(tree, target) {
136
143
  // A run tagged with `--meta <key>` is found by that key alone: the session tree is shared across
137
144
  // worktrees, so its newest run may belong to another thread.
138
145
  function resolveMetaSessionFile(tree, meta) {
139
- const matches = listSessionRecords(tree.sessionsDir).filter((record) => record.frontmatter.meta === meta);
146
+ const matches = listSessionRecords(tree.sessionsDir, tree.machineId).filter((record) => record.frontmatter.meta === meta);
140
147
  if (matches.length === 0)
141
148
  throw new Error(`Error: no session file with meta "${meta}".`);
142
149
  const newest = matches.reduce((a, b) => a.frontmatter.startedAt >= b.frontmatter.startedAt ? a : b);
@@ -150,15 +157,20 @@ function loadMessage(args, cwd) {
150
157
  }
151
158
  args.message = readFileSync(args.messageFile === "-" ? 0 : resolve(cwd, args.messageFile), "utf8");
152
159
  }
160
+ // A caller may retain the `.running.md` path of a run that has ended since: it resolves to the
161
+ // completed file.
153
162
  function resolveStatusSessionFile(tree, input) {
154
- const sessionFilePath = resolve(tree.cwd, input);
163
+ const requestedPath = resolve(tree.cwd, input);
155
164
  const sessionsDir = displayPath(tree.cwd, tree.sessionsDir);
156
- if (!isSessionFilePath(tree.sessionsDir, sessionFilePath)) {
165
+ if (!isSessionFilePath(tree.sessionsDir, requestedPath)) {
157
166
  throw new Error(`Error: status requires a session file under ${sessionsDir}/_aligndev/ or ` +
158
167
  `${sessionsDir}/<ticket>/_aligndev/.`);
159
168
  }
169
+ const sessionFilePath = existsSync(requestedPath)
170
+ ? requestedPath
171
+ : completedSessionPath(requestedPath);
160
172
  if (!existsSync(sessionFilePath)) {
161
- throw new Error(`Error: session file not found: ${displayPath(tree.cwd, sessionFilePath)}`);
173
+ throw new Error(`Error: session file not found: ${displayPath(tree.cwd, requestedPath)}`);
162
174
  }
163
175
  if (!isSessionFilePath(realpathSync(tree.sessionsDir), realpathSync(sessionFilePath))) {
164
176
  throw new Error(`Error: the session file resolves outside ${sessionsDir}/.`);
@@ -195,6 +207,7 @@ function renderSessionStatus(cwd, sessionFilePath, frontmatter) {
195
207
  `model: ${frontmatter.model ?? ""}`,
196
208
  `status: ${frontmatter.status}`,
197
209
  `pid: ${frontmatter.pid ?? ""}`,
210
+ `machineId: ${frontmatter.machineId ?? ""}`,
198
211
  `startedAt: ${frontmatter.startedAt}`,
199
212
  `endedAt: ${frontmatter.endedAt ?? ""}`,
200
213
  `exitReason: ${frontmatter.exitReason ?? ""}`,
@@ -376,23 +389,16 @@ function isPathSafeTicket(ticket) {
376
389
  // agent's background task) — aligndev owns no backgrounding or callback of its own. The per-run session
377
390
  // file is the durable result handoff: on completion the frontmatter carries the session id and
378
391
  // status, and the `---- Result ----` block carries the outcome for a waking caller (or a human).
379
- async function runSession(args, code, ctx, report, records, previous) {
392
+ async function runSession(args, code, ctx, report, tree, records, previous) {
380
393
  const { cwd, env, stdout, stderr, forms, alignfirstCommand, modelResolver } = ctx;
381
394
  const { agent } = code;
382
- const tree = sessionTreeOf(report, cwd);
383
- const plans = report.locations[".plans"];
384
- if (!plans.exists) {
385
- stderr.write(`Error: no .plans/ directory at ${displayPath(tree.cwd, plans.path)}. ` +
386
- `Create it, or run \`${forms.alignfirst} plans setup <clone>\`.\n`);
387
- return 1;
388
- }
389
395
  const resolvedTicket = args.noTicket
390
396
  ? undefined
391
397
  : (args.ticket ??
392
398
  (args.resume === undefined
393
399
  ? inferTicketFromMessage(args.message ?? "")
394
400
  : (previous?.frontmatter.ticket ?? undefined)));
395
- const guardError = checkLaunchGuards(args, agent, tree.cwd, resolvedTicket, records, previous);
401
+ const guardError = checkLaunchGuards(args, agent, tree.cwd, resolvedTicket, records, tree.machineId, previous);
396
402
  if (guardError) {
397
403
  stderr.write(`${guardError}\n`);
398
404
  return 1;
@@ -413,7 +419,16 @@ async function runSession(args, code, ctx, report, records, previous) {
413
419
  const contextContent = args.resume === undefined && companionInUse(report, CONTEXT_COMPANION_ITEMS)
414
420
  ? loadContext(alignfirstCommand, cwd, env)
415
421
  : undefined;
416
- const sessionFilePath = createSessionFile(tree.sessionsDir, ticket, now, buildFrontmatter({ args, agent, profile: code.profile, model, now, realCwd: tree.cwd, ticket }));
422
+ const sessionFilePath = createSessionFile(tree.sessionsDir, ticket, now, buildFrontmatter({
423
+ args,
424
+ agent,
425
+ profile: code.profile,
426
+ model,
427
+ now,
428
+ realCwd: tree.cwd,
429
+ ticket,
430
+ machineId: tree.machineId,
431
+ }));
417
432
  stdout.write(`Session file: ${displayPath(tree.cwd, sessionFilePath)}\n\n`);
418
433
  let executableModel;
419
434
  try {
@@ -428,14 +443,14 @@ async function runSession(args, code, ctx, report, records, previous) {
428
443
  (agent === "codex"
429
444
  ? " For Codex aliases, update the Codex CLI or select an explicit full model slug."
430
445
  : "");
431
- applyCompletion(sessionFilePath, {
446
+ const completedPath = applyCompletion(sessionFilePath, {
432
447
  status: "failed",
433
448
  endedAt: new Date().toISOString(),
434
449
  exitReason: "error",
435
450
  sessionId: args.resume ?? null,
436
451
  result: message,
437
452
  });
438
- writeFailureDiagnostic(ctx, sessionFilePath, message);
453
+ writeFailureDiagnostic(ctx, completedPath, message);
439
454
  return 1;
440
455
  }
441
456
  const runConfig = buildRunConfig({
@@ -452,11 +467,12 @@ async function runSession(args, code, ctx, report, records, previous) {
452
467
  });
453
468
  createMissingCompanion(report);
454
469
  const result = await runAgent(runConfig, createAgentAdapter(agent), stdout);
470
+ const completedPath = completedSessionPath(sessionFilePath);
455
471
  if (args.resume === undefined && result.sessionId) {
456
472
  stdout.write(`\nSession ID: ${result.sessionId}\n`);
457
473
  }
458
474
  if (result.authRequired) {
459
- writeFailureDiagnostic(ctx, sessionFilePath, `${nativeContext(code)} not authenticated — an administrator must re-login ` +
475
+ writeFailureDiagnostic(ctx, completedPath, `${nativeContext(code)} not authenticated — an administrator must re-login ` +
460
476
  "with the same effective environment as the child (apply profile unset/env/configDir, " +
461
477
  "including HOME, PATH and credential routing), from the same working directory. " +
462
478
  `Then use ${authenticationInstruction(agent)}. A bare login in another shell may use a different account.`);
@@ -464,7 +480,7 @@ async function runSession(args, code, ctx, report, records, previous) {
464
480
  }
465
481
  if (result.status === "succeeded")
466
482
  return 0;
467
- writeFailureDiagnostic(ctx, sessionFilePath, `${nativeContext(code)}: ${failureDiagnostic(agent, result.result)}${args.resume === undefined ? "" : " Check that the native conversation exists in this configuration; select the correct --profile or start a new session. No account fallback was attempted."}`);
483
+ writeFailureDiagnostic(ctx, completedPath, `${nativeContext(code)}: ${failureDiagnostic(agent, result.result)}${args.resume === undefined ? "" : " Check that the native conversation exists in this configuration; select the correct --profile or start a new session. No account fallback was attempted."}`);
468
484
  return 1;
469
485
  }
470
486
  function nativeContext(code) {
@@ -494,7 +510,7 @@ function failureDiagnostic(agent, result) {
494
510
  }
495
511
  // Fail-fast launch guards, run against the (healed) session records before anything is written.
496
512
  // Returns the error to print, or `undefined` when the launch may proceed.
497
- export function checkLaunchGuards(args, agent, realCwd, ticket, records, previous) {
513
+ export function checkLaunchGuards(args, agent, realCwd, ticket, records, machineId, previous) {
498
514
  if (args.resume !== undefined) {
499
515
  // A resumed run writes a new session file carrying the same sessionId as the original, so one
500
516
  // id can match several records — a running status on any of them blocks.
@@ -503,8 +519,8 @@ export function checkLaunchGuards(args, agent, realCwd, ticket, records, previou
503
519
  return unknownResumeError(args.resume, records);
504
520
  const running = matches.find((r) => r.frontmatter.status === "running");
505
521
  if (running) {
506
- return (`Error: session ${args.resume} is still running (pid ${running.frontmatter.pid}); ` +
507
- "wait for it to finish or kill it.");
522
+ return (`Error: session ${args.resume} is still running (${running.path}, pid ${running.frontmatter.pid}); ` +
523
+ `${runningRecordAdvice(running, machineId)}.`);
508
524
  }
509
525
  const latest = previous ?? latestRecord(matches);
510
526
  if (latest.frontmatter.agent === null) {
@@ -526,10 +542,10 @@ export function checkLaunchGuards(args, agent, realCwd, ticket, records, previou
526
542
  const active = records.filter((r) => r.frontmatter.status === "running" && r.frontmatter.protocol !== null);
527
543
  const sameWorktree = active.find((r) => r.frontmatter.cwd === realCwd);
528
544
  if (sameWorktree)
529
- return busyProtocolError(sameWorktree, "in this worktree");
545
+ return busyProtocolError(sameWorktree, "in this worktree", machineId);
530
546
  const sameTicket = ticket === undefined ? undefined : active.find((r) => r.frontmatter.ticket === ticket);
531
547
  if (sameTicket)
532
- return busyProtocolError(sameTicket, `on ticket ${ticket}`);
548
+ return busyProtocolError(sameTicket, `on ticket ${ticket}`, machineId);
533
549
  }
534
550
  return;
535
551
  }
@@ -543,10 +559,16 @@ function sameRealDirectory(recorded, realCwd) {
543
559
  return false;
544
560
  }
545
561
  }
546
- function busyProtocolError(record, scope) {
562
+ function busyProtocolError(record, scope, machineId) {
547
563
  return (`Error: a ${record.frontmatter.protocol} protocol run is already active ${scope} ` +
548
564
  `(${record.path}, pid ${record.frontmatter.pid}); one protocol run at a time per worktree ` +
549
- "and per ticket.");
565
+ `and per ticket; ${runningRecordAdvice(record, machineId)}.`);
566
+ }
567
+ function runningRecordAdvice(record, machineId) {
568
+ return record.frontmatter.machineId === machineId
569
+ ? "wait for it to finish"
570
+ : "this record was written by another machine or before machine identities: check it on its machine, " +
571
+ "or set its `status` by hand once the run has ended";
550
572
  }
551
573
  // The newest record of a non-empty list: a resumed session has one record per run.
552
574
  function latestRecord(records) {
@@ -624,6 +646,7 @@ function buildFrontmatter(input) {
624
646
  meta: args.meta ?? null,
625
647
  pid: process.pid,
626
648
  pidStartTime: readPidStartTime(process.pid),
649
+ machineId: input.machineId,
627
650
  cwd: input.realCwd,
628
651
  startedAt: now.toISOString(),
629
652
  endedAt: null,
@@ -0,0 +1 @@
1
+ export declare function readMachineId(home: string): string;
@@ -0,0 +1,34 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { errorMessage } from "../errors.js";
5
+ export function readMachineId(home) {
6
+ const path = join(home, ".alignfirst", "machine-id");
7
+ try {
8
+ const id = readOrCreateMachineId(path).trim();
9
+ if (id === "")
10
+ throw new Error("file is empty");
11
+ return id;
12
+ }
13
+ catch (error) {
14
+ throw new Error(`Could not read machine identity at ${path}: ${errorMessage(error)}`);
15
+ }
16
+ }
17
+ function readOrCreateMachineId(path) {
18
+ try {
19
+ return readFileSync(path, "utf8");
20
+ }
21
+ catch (error) {
22
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT")
23
+ throw error;
24
+ }
25
+ mkdirSync(dirname(path), { recursive: true });
26
+ try {
27
+ writeFileSync(path, randomUUID(), { flag: "wx" });
28
+ }
29
+ catch (error) {
30
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
31
+ throw error;
32
+ }
33
+ return readFileSync(path, "utf8");
34
+ }
@@ -11,6 +11,7 @@ export interface SessionFrontmatter {
11
11
  meta: string | null;
12
12
  pid: number | null;
13
13
  pidStartTime: string | null;
14
+ machineId: string | null;
14
15
  cwd: string | null;
15
16
  startedAt: string;
16
17
  endedAt: string | null;
@@ -21,6 +22,7 @@ export interface SessionFrontmatter {
21
22
  }
22
23
  export declare const RESULT_MARKER = "\n---- Result ----\n";
23
24
  export declare function createSessionFile(sessionsDir: string, ticket: string | undefined, now: Date, frontmatter: SessionFrontmatter): string;
25
+ export declare function completedSessionPath(sessionFilePath: string): string;
24
26
  export declare function resolveSessionFilePath(sessionsDir: string, ticket: string | undefined, now: Date, fileExists?: (path: string) => boolean): string;
25
27
  export declare function writeInitialSessionFile(sessionFilePath: string, frontmatter: SessionFrontmatter): void;
26
28
  export interface CompletionUpdate {
@@ -34,20 +36,23 @@ export interface CompletionUpdate {
34
36
  contextTokensError?: string | null;
35
37
  }
36
38
  export declare function formatResults(earlier: readonly string[], last: string): string;
37
- export declare function applyCompletion(sessionFilePath: string, update: CompletionUpdate): void;
39
+ export declare function applyCompletion(sessionFilePath: string, update: CompletionUpdate): string;
38
40
  export declare function appendTranscript(sessionFilePath: string, text: string): void;
39
41
  export interface SessionCompletion {
40
42
  frontmatter: SessionFrontmatter;
41
43
  result: string | undefined;
42
44
  }
43
45
  export declare function readCompletion(sessionFilePath: string): SessionCompletion;
44
- export declare function reconcileSessionFile(sessionFilePath: string, now?: Date): SessionCompletion;
46
+ export interface ReconciledSession extends SessionCompletion {
47
+ path: string;
48
+ }
49
+ export declare function reconcileSessionFile(sessionFilePath: string, machineId: string, now?: Date): ReconciledSession;
45
50
  export declare function readPidStartTime(pid: number): string | null;
46
51
  export interface SessionRecord {
47
52
  path: string;
48
53
  frontmatter: SessionFrontmatter;
49
54
  }
50
- export declare function listSessionRecords(sessionsDir: string): SessionRecord[];
55
+ export declare function listSessionRecords(sessionsDir: string, machineId: string): SessionRecord[];
51
56
  export declare function findNewestSessionFile(dir: string): string | undefined;
52
57
  export declare function serializeFrontmatter(frontmatter: SessionFrontmatter): string;
53
58
  export declare function parseFrontmatter(block: string): SessionFrontmatter;
@@ -1,13 +1,19 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } from "node:fs";
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  export const RESULT_MARKER = "\n---- Result ----\n";
4
4
  const LATER_RESULT_SEPARATOR = "\n\n---- Later result ----\n\n";
5
+ // A run is written as `<stamp>.running.md` and renamed to `<stamp>.md` when it ends, so the
6
+ // work-files sync can leave running logs out by name. Records written before this convention keep
7
+ // their name and their `running` status until their run ends.
8
+ const RUNNING_SUFFIX = ".running.md";
5
9
  export function createSessionFile(sessionsDir, ticket, now, frontmatter) {
6
10
  const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
7
11
  mkdirSync(dir, { recursive: true });
8
12
  const stamp = formatStamp(now);
9
13
  for (let suffix = 1;; ++suffix) {
10
14
  const path = sessionFileCandidate(dir, stamp, suffix);
15
+ if (existsSync(completedSessionPath(path)))
16
+ continue;
11
17
  try {
12
18
  claimSessionFile(path, frontmatter);
13
19
  return path;
@@ -19,7 +25,12 @@ export function createSessionFile(sessionsDir, ticket, now, frontmatter) {
19
25
  }
20
26
  }
21
27
  function sessionFileCandidate(dir, stamp, suffix) {
22
- return join(dir, `${stamp}${suffix === 1 ? "" : `-${suffix}`}.md`);
28
+ return join(dir, `${stamp}${suffix === 1 ? "" : `-${suffix}`}${RUNNING_SUFFIX}`);
29
+ }
30
+ export function completedSessionPath(sessionFilePath) {
31
+ if (!sessionFilePath.endsWith(RUNNING_SUFFIX))
32
+ return sessionFilePath;
33
+ return `${sessionFilePath.slice(0, -RUNNING_SUFFIX.length)}.md`;
23
34
  }
24
35
  function claimSessionFile(path, frontmatter) {
25
36
  writeFileSync(path, `${serializeFrontmatter(frontmatter)}\n`, { flag: "wx" });
@@ -30,7 +41,8 @@ export function resolveSessionFilePath(sessionsDir, ticket, now, fileExists = ex
30
41
  const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
31
42
  const stamp = formatStamp(now);
32
43
  let suffix = 1;
33
- while (fileExists(sessionFileCandidate(dir, stamp, suffix)))
44
+ while (fileExists(sessionFileCandidate(dir, stamp, suffix)) ||
45
+ fileExists(completedSessionPath(sessionFileCandidate(dir, stamp, suffix))))
34
46
  ++suffix;
35
47
  return sessionFileCandidate(dir, stamp, suffix);
36
48
  }
@@ -43,8 +55,9 @@ export function writeInitialSessionFile(sessionFilePath, frontmatter) {
43
55
  export function formatResults(earlier, last) {
44
56
  return [...earlier, last].join(LATER_RESULT_SEPARATOR);
45
57
  }
46
- // Appends the result block, then rewrites the frontmatter in place. Append-first keeps the tailed
47
- // transcript intact until the single terminal rewrite.
58
+ // Appends the result block, then rewrites the frontmatter in place, then renames the file to its
59
+ // completed name. Returns that name. Append-first keeps the tailed transcript intact until the
60
+ // single terminal rewrite.
48
61
  export function applyCompletion(sessionFilePath, update) {
49
62
  const content = readFileSync(sessionFilePath, "utf-8");
50
63
  const { frontmatter, body } = splitSessionFile(content);
@@ -60,6 +73,10 @@ export function applyCompletion(sessionFilePath, update) {
60
73
  };
61
74
  const resultBlock = `${RESULT_MARKER}\n${update.result}\n`;
62
75
  writeFileSync(sessionFilePath, `${serializeFrontmatter(updated)}\n${body}${resultBlock}`);
76
+ const completedPath = completedSessionPath(sessionFilePath);
77
+ if (completedPath !== sessionFilePath)
78
+ renameSync(sessionFilePath, completedPath);
79
+ return completedPath;
63
80
  }
64
81
  export function appendTranscript(sessionFilePath, text) {
65
82
  writeFileSync(sessionFilePath, text, { flag: "a" });
@@ -76,13 +93,13 @@ export function readCompletion(sessionFilePath) {
76
93
  const result = markerIndex === -1 ? undefined : content.slice(markerIndex + RESULT_MARKER.length).trim();
77
94
  return { frontmatter, result };
78
95
  }
79
- export function reconcileSessionFile(sessionFilePath, now = new Date()) {
96
+ export function reconcileSessionFile(sessionFilePath, machineId, now = new Date()) {
80
97
  const completion = readCompletion(sessionFilePath);
81
- const update = interruptedCompletion(completion.frontmatter, now);
98
+ const update = interruptedCompletion(completion.frontmatter, machineId, now);
82
99
  if (!update)
83
- return completion;
84
- applyCompletion(sessionFilePath, update);
100
+ return { ...completion, path: sessionFilePath };
85
101
  return {
102
+ path: applyCompletion(sessionFilePath, update),
86
103
  frontmatter: {
87
104
  ...completion.frontmatter,
88
105
  status: update.status,
@@ -92,8 +109,10 @@ export function reconcileSessionFile(sessionFilePath, now = new Date()) {
92
109
  result: update.result,
93
110
  };
94
111
  }
95
- function interruptedCompletion(frontmatter, now) {
96
- if (frontmatter.status !== "running" || isRecordedProcessAlive(frontmatter))
112
+ function interruptedCompletion(frontmatter, machineId, now) {
113
+ if (frontmatter.status !== "running" ||
114
+ frontmatter.machineId !== machineId ||
115
+ !isRecordedProcessGone(frontmatter))
97
116
  return;
98
117
  return {
99
118
  status: "failed",
@@ -103,22 +122,19 @@ function interruptedCompletion(frontmatter, now) {
103
122
  result: `Sealed as interrupted: process ${frontmatter.pid ?? "(unknown)"} is gone.`,
104
123
  };
105
124
  }
106
- function isRecordedProcessAlive(frontmatter) {
107
- if (frontmatter.pid === null || !isPidAlive(frontmatter.pid))
125
+ function isRecordedProcessGone(frontmatter) {
126
+ if (frontmatter.pid === null)
108
127
  return false;
109
- if (frontmatter.pidStartTime === null)
110
- return true;
111
- const currentStartTime = readPidStartTime(frontmatter.pid);
112
- return currentStartTime === null || currentStartTime === frontmatter.pidStartTime;
113
- }
114
- function isPidAlive(pid) {
115
128
  try {
116
- process.kill(pid, 0);
117
- return true;
129
+ process.kill(frontmatter.pid, 0);
118
130
  }
119
- catch (err) {
120
- return err.code !== "ESRCH";
131
+ catch (error) {
132
+ return error instanceof Error && "code" in error && error.code === "ESRCH";
121
133
  }
134
+ if (frontmatter.pidStartTime === null)
135
+ return false;
136
+ const currentStartTime = readPidStartTime(frontmatter.pid);
137
+ return currentStartTime !== null && currentStartTime !== frontmatter.pidStartTime;
122
138
  }
123
139
  export function readPidStartTime(pid) {
124
140
  if (process.platform !== "linux")
@@ -135,10 +151,9 @@ export function readPidStartTime(pid) {
135
151
  // Lists every active session record: `<sessionsDir>/_aligndev/*.md` plus
136
152
  // `<sessionsDir>/<ticket>/_aligndev/*.md`. Archived tickets move under `_archives/` and leave the
137
153
  // registry. The session files are the registry — no separate registry file.
138
- // Self-healing: a `running` record whose pid is gone is a stale leftover from an interrupted run;
139
- // it gets sealed in passing so the launch guards never block on dead state. The returned records
140
- // reflect the post-healing state.
141
- export function listSessionRecords(sessionsDir) {
154
+ // Seals only this installation's conclusively dead runs. Foreign, legacy and uncertain records
155
+ // stay untouched and continue to block launches.
156
+ export function listSessionRecords(sessionsDir, machineId) {
142
157
  const sessionDirs = [join(sessionsDir, "_aligndev")];
143
158
  for (const entry of readEntries(sessionsDir)) {
144
159
  if (entry.isDirectory() && !entry.name.startsWith("_")) {
@@ -150,10 +165,9 @@ export function listSessionRecords(sessionsDir) {
150
165
  for (const entry of readEntries(dir)) {
151
166
  if (!entry.isFile() || !entry.name.endsWith(".md"))
152
167
  continue;
153
- const path = join(dir, entry.name);
154
- const completion = reconcileSessionFileOrSkip(path);
168
+ const completion = reconcileSessionFileOrSkip(join(dir, entry.name), machineId);
155
169
  if (completion)
156
- records.push({ path, frontmatter: completion.frontmatter });
170
+ records.push({ path: completion.path, frontmatter: completion.frontmatter });
157
171
  }
158
172
  }
159
173
  return records;
@@ -165,7 +179,7 @@ export function findNewestSessionFile(dir) {
165
179
  for (const entry of readEntries(dir)) {
166
180
  if (!entry.isFile())
167
181
  continue;
168
- const match = /^(\d{8}-\d{6})(?:-(\d+))?\.md$/.exec(entry.name);
182
+ const match = /^(\d{8}-\d{6})(?:-(\d+))?(?:\.running)?\.md$/.exec(entry.name);
169
183
  if (!match)
170
184
  continue;
171
185
  const stamp = match[1];
@@ -189,9 +203,9 @@ function readEntries(dir) {
189
203
  }
190
204
  }
191
205
  // A malformed file (e.g. missing its frontmatter block) must not block every future launch.
192
- function reconcileSessionFileOrSkip(path) {
206
+ function reconcileSessionFileOrSkip(path, machineId) {
193
207
  try {
194
- return reconcileSessionFile(path);
208
+ return reconcileSessionFile(path, machineId);
195
209
  }
196
210
  catch {
197
211
  return;
@@ -239,6 +253,7 @@ export function parseFrontmatter(block) {
239
253
  meta: map.meta ?? null,
240
254
  pid: parsePid(map.pid),
241
255
  pidStartTime: map.pidStartTime ?? null,
256
+ machineId: map.machineId ?? null,
242
257
  cwd: map.cwd ?? null,
243
258
  startedAt: map.startedAt ?? "",
244
259
  endedAt: map.endedAt ?? null,
@@ -6,11 +6,12 @@ export const PLAYBOOK_TOPICS = {
6
6
  openclaw: [
7
7
  "channel-handling",
8
8
  "working-session",
9
+ "work-files-setup",
9
10
  "project-workspace-setup",
10
11
  "project-lifecycle",
11
12
  "consultation",
12
13
  "slack-message-tool",
13
14
  "discord-message-tool",
14
15
  ],
15
- codingAgent: ["working-session", "project-workspace-setup", "consultation"],
16
+ codingAgent: ["working-session", "work-files-setup", "project-workspace-setup", "consultation"],
16
17
  };