aligndev 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +22 -13
  2. package/dist/alignfirst-cli.js +21 -8
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +16 -4
  5. package/dist/code/claude-agent.js +1 -1
  6. package/dist/code/code-cli.d.ts +2 -1
  7. package/dist/code/code-cli.js +56 -32
  8. package/dist/code/codex-agent.js +1 -1
  9. package/dist/code/machine-id.d.ts +1 -0
  10. package/dist/code/machine-id.js +45 -0
  11. package/dist/code/pi-agent.js +1 -1
  12. package/dist/code/run-agent.js +37 -1
  13. package/dist/code/session-file.d.ts +8 -3
  14. package/dist/code/session-file.js +48 -33
  15. package/dist/command-form.d.ts +5 -2
  16. package/dist/command-form.js +15 -6
  17. package/dist/guide/code-guide.d.ts +2 -2
  18. package/dist/guide/code-guide.js +4 -8
  19. package/dist/guide/guide-cli.js +84 -29
  20. package/dist/guide/render-template.d.ts +4 -0
  21. package/dist/guide/render-template.js +51 -12
  22. package/dist/guide/topics.d.ts +8 -3
  23. package/dist/guide/topics.js +26 -7
  24. package/dist/project/plans.js +1 -1
  25. package/dist/worktree/add.d.ts +3 -13
  26. package/dist/worktree/add.js +7 -101
  27. package/dist/worktree/setup.d.ts +18 -0
  28. package/dist/worktree/setup.js +192 -0
  29. package/dist/worktree/worktree-cli.js +29 -11
  30. package/package.json +4 -1
  31. package/templates/guide/code.md +15 -6
  32. package/templates/guide/playbook/channel-handling.md +12 -17
  33. package/templates/guide/playbook/consultation.md +24 -17
  34. package/templates/guide/playbook/dispatcher.md +18 -0
  35. package/templates/guide/playbook/{discord-message-tool.md → message-tool.md} +29 -0
  36. package/templates/guide/playbook/playbook.md +53 -20
  37. package/templates/guide/playbook/project-lifecycle.md +27 -12
  38. package/templates/guide/playbook/project-workspace-setup.md +87 -62
  39. package/templates/guide/playbook/work-files-setup.md +1 -1
  40. package/templates/guide/playbook/working-session.md +198 -115
  41. package/templates/guide/playbook/slack-message-tool.md +0 -23
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,11 +35,15 @@ 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 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
+ 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 the `work-files-setup` topic of `aligndev guide`; existing project content stays untouched and is not copied.
38
39
 
39
- 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.
40
+ Full workspace tooling is optional. The assistant follows the project's documented tooling when present, including non-Node implementations; otherwise `aligndev worktree` creates or prepares 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.
40
41
 
41
- 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.
42
+ For externally created worktrees, tools such as Paseo can run `npx -y aligndev worktree setup` as a post-creation hook inside the target. With no path, setup discovers the current worktree root even from a subdirectory; an explicit path must name an exact registered root of the same repository. Setup preserves the branch, index and unrelated files. Conflicts remain untouched; repair the reported problem and retry the idempotent setup to complete partial preparation. Setup validates existing plans without provisioning or migrating them.
43
+
44
+ The external tool owns Git creation and deletion, with project-specific preparation and shutdown handled separately. There is no `aligndev worktree teardown` command or lightweight pre-deletion hook. AlignDev's own 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.
45
+
46
+ 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 the `work-files-setup` topic of `aligndev guide`, preserving existing project files. Do not silently bypass the sandbox or grant the whole main repository write access.
42
47
 
43
48
  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.
44
49
 
@@ -77,11 +82,15 @@ Then ask your session to work with aligndev.
77
82
 
78
83
  ### Requirements
79
84
 
80
- - Node.js 22.11 or later. The assistant runs `aligndev` through `npx`, so there is nothing to install.
85
+ - Node.js 22.11 or later with `npx -y aligndev`, or Bun with `bunx --bun aligndev` (`bun x --bun` is equivalent). Bun 1.4.4 is the tested CLI baseline; compatibility with every older release is not promised.
81
86
  - The selected child installed and authenticated under the same effective environment and cwd as the child. Apply the profile's `unset/env/configDir`, including HOME, PATH and credential routing, before using `claude` then `/login`, `codex login`, or `pi` then `/login <provider>` (or configured provider credentials). A bare login in another shell may select another account. Pi requires Node.js 22.19 or later; the Pi adapter and extensions target Pi 1.3.0.
82
87
  - For Pi, select a usable native model, preferably `provider/model` (optional thinking suffix). Authenticate in the same account/configuration used by the child; never expose credential values in diagnostics.
83
88
  - Linux or macOS, or Windows through WSL.
84
89
 
90
+ Published bins retain Node shebangs. Ordinary `bunx aligndev` normally runs Node when it is installed; Bun-only hosts should explicitly select `--bun`. Direct `bun <installed-entry.mjs>` and transparent project scripts launched with `bun --bun run <script>` preserve Bun in follow-up commands and internal AlignFirst calls. npm scripts retain their `--` argument separator.
91
+
92
+ Bun support covers this CLI, not its selected coding agent, Docker or an OpenClaw deployment. Those tools keep their own runtime, installation and authentication requirements; selecting Bun for AlignDev never forces the coding agent to use Bun.
93
+
85
94
  ## Configuration
86
95
 
87
96
  `~/.alignfirst/aligndev.settings.json` is optional. Without it, one detected parent kind supplies built-in child defaults. A minimal singleton setup is:
@@ -129,7 +138,7 @@ For multiple accounts and independent quota sources:
129
138
 
130
139
  The Pi targets illustrate native shorthand; availability depends on Pi's catalog and account. Exact provider-qualified IDs pin a model. Provider-qualified fuzzy selectors and thinking suffixes pass unchanged to Pi, which owns their resolution. AlignDev neither guesses providers nor implements newest-family ordering.
131
140
 
132
- - `platform` — `codingAgent` (default), or `openclaw`.
141
+ - `platform` — `codingAgent` (default), or `openclaw`. On `openclaw`, `aligndev guide` takes `--channel <slack|discord|app>`: a Slack or Discord thread and an app conversation are separate contexts, each with its own topics. Every playbook topic requires it, `code` defaults to `app`, and `project` rejects it.
133
142
  - `projectsRoot` — projects directory, required by the OpenClaw playbook. `~/` uses the configured home; relative paths resolve against the settings directory.
134
143
  - `code.profile` — global named child profile, independent of the parent host.
135
144
  - `code.profiles` — complete profiles, with required `agent` (`claude`, `codex`, `pi`). Names and references are exact, nonblank strings. Profiles have no inheritance or merging.
@@ -1,3 +1,4 @@
1
+ import { createCommand, renderCommand } from "@alignfirst/docmap/invocation";
1
2
  import { spawnSync } from "node:child_process";
2
3
  import { accessSync, constants, existsSync, statSync } from "node:fs";
3
4
  import { delimiter, resolve, sep } from "node:path";
@@ -9,8 +10,7 @@ export function runAlignfirst(command, args, cwd, env = process.env) {
9
10
  encoding: "utf8",
10
11
  });
11
12
  if (result.error && isErrnoException(result.error) && result.error.code === "ENOENT") {
12
- throw new Error("alignfirst is not installed. Install it globally (`npm install -g alignfirst`), or run " +
13
- `aligndev through npx (\`npx -y aligndev\`). ${describeAlignfirst(command, cwd, env)}`);
13
+ throw new Error(`alignfirst is not installed or its runner is unavailable. Missing executable \`${command[0]}\`. ${missingExecutableRecovery(command)} ${describeAlignfirst(command, cwd, env)}`);
14
14
  }
15
15
  if (result.error)
16
16
  throw result.error;
@@ -40,12 +40,16 @@ function isSettingsWarning(line) {
40
40
  /^Warning: .+: plans\.folder is deprecated; rename it to plans\.repositoryFolder\. See "Rename the Work-Files Folder Setting" in the setup guide's alignfirst-upgrade reference\.$/u.test(line));
41
41
  }
42
42
  export function describeAlignfirst(command, cwd, env) {
43
- const npx = command[0] === "npx";
44
- const reason = npx
45
- ? "aligndev was launched through npm/npx; npx prefers the project's local alignfirst dependency"
46
- : "aligndev runs alignfirst from PATH when launched directly";
47
- const facts = [`\`${command.join(" ")}\` (${reason})`];
48
- if (!npx)
43
+ const runner = ["npx", "bunx", "pnpm", "yarn"].includes(command[0]);
44
+ const reason = command[0] === "npx"
45
+ ? "npm/npx package runner; npx prefers the project's local alignfirst dependency"
46
+ : command[0] === "bunx"
47
+ ? `Bun package runner${command.includes("--bun") ? "; explicit Bun runtime" : "; entry-point shebang runtime"}`
48
+ : runner
49
+ ? `${command[0]} package runner`
50
+ : "direct executable";
51
+ const facts = [`\`${renderCommand(createCommand(command[0], command.slice(1)))}\` (${reason})`];
52
+ if (!runner)
49
53
  facts.push(describeExecutable(command[0], cwd, env));
50
54
  const version = spawnSync(command[0], [...command.slice(1), "--version"], {
51
55
  cwd,
@@ -61,6 +65,15 @@ export function describeAlignfirst(command, cwd, env) {
61
65
  facts.push(`aligndev ${readPackageVersion()}${entry}`);
62
66
  return `alignfirst: ${facts.join("; ")}`.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, " ");
63
67
  }
68
+ function missingExecutableRecovery(command) {
69
+ if (command[0] === "bunx") {
70
+ return "Install Bun and make bunx available on PATH, then relaunch with `bunx --bun aligndev`.";
71
+ }
72
+ if (command[0] === "alignfirst") {
73
+ return "Install alignfirst on PATH, or relaunch with `npx -y aligndev`.";
74
+ }
75
+ return `Make the selected runner or executable available, then retry \`${renderCommand(createCommand(command[0], command.slice(1)))}\`.`;
76
+ }
64
77
  function describeExecutable(command, cwd, env) {
65
78
  if (command.includes(sep)) {
66
79
  return `executable ${command}${existsSync(resolve(cwd, command)) ? "" : " (not found)"}`;
package/dist/cli.d.ts CHANGED
@@ -1,8 +1,10 @@
1
+ import { type LaunchEvidence } from "@alignfirst/docmap/invocation";
1
2
  import { type ExecutableModelResolver } from "./code/models.js";
2
3
  import { type QuotaReader } from "./code/quota.js";
3
4
  import type { Output } from "./output.js";
4
5
  export interface MainOptions {
5
6
  argv?: string[];
7
+ evidence?: LaunchEvidence;
6
8
  stdout?: Output;
7
9
  stderr?: Output;
8
10
  cwd?: string;
package/dist/cli.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { readLaunchEvidence } from "@alignfirst/docmap/invocation";
1
2
  import { homedir } from "node:os";
2
3
  import { runCode } from "./code/code-cli.js";
3
4
  import { createExecutableModelResolver } from "./code/models.js";
@@ -52,9 +53,12 @@ function renderHelp(aligndev) {
52
53
  ],
53
54
  [
54
55
  `${aligndev} worktree <command> [<options>]`,
55
- "Create, list and safely remove lightweight Git worktrees.",
56
+ "Create or prepare lightweight Git worktrees; list and safely remove them.",
57
+ ],
58
+ [
59
+ `${aligndev} guide [--channel <surface>] [<topic>]`,
60
+ "Print the assistant's playbook and guides.",
56
61
  ],
57
- [`${aligndev} guide [<topic>]`, "Print the assistant's playbook and guides."],
58
62
  [`${aligndev} -h, --help`],
59
63
  [`${aligndev} -v, --version`],
60
64
  ]);
@@ -80,7 +84,12 @@ function renderUsageRows(rows) {
80
84
  }
81
85
  function resolveContext(options) {
82
86
  const env = options?.env ?? process.env;
83
- const forms = resolveCommandForms(env);
87
+ const evidence = options?.evidence ?? {
88
+ ...readLaunchEvidence(),
89
+ env,
90
+ cwd: options?.cwd ?? process.cwd(),
91
+ };
92
+ const forms = resolveCommandForms(env, evidence);
84
93
  return {
85
94
  cwd: options?.cwd ?? process.cwd(),
86
95
  env,
@@ -88,7 +97,10 @@ function resolveContext(options) {
88
97
  stdout: options?.stdout ?? process.stdout,
89
98
  stderr: options?.stderr ?? process.stderr,
90
99
  forms,
91
- alignfirstCommand: options?.alignfirstCommand ?? forms.alignfirst.split(" "),
100
+ alignfirstCommand: options?.alignfirstCommand ?? [
101
+ forms.counterpart.executable,
102
+ ...forms.counterpart.args,
103
+ ],
92
104
  modelResolver: options?.modelResolver ?? createExecutableModelResolver(),
93
105
  quotaReader: options?.quotaReader ?? readQuota,
94
106
  };
@@ -167,7 +167,7 @@ function claudeAuthenticationMessage(detail) {
167
167
  const base = "Coding agent not authenticated (authentication_failed): the host session is missing, " +
168
168
  "expired, or rejected. An administrator must re-login with the same effective environment and cwd as the child " +
169
169
  "(apply profile unset/env/configDir, including HOME, PATH and credential routing; run `claude`, then " +
170
- "`/login`) before `aligndev code` can run again.";
170
+ "`/login`) before another coding run.";
171
171
  const reason = detail?.trim();
172
172
  return reason === undefined || reason === "" ? base : `${base}\n\n${reason}`;
173
173
  }
@@ -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;
@@ -7,11 +7,12 @@ import { errorMessage } from "../errors.js";
7
7
  import { companionInUse, readProjectReport, } from "../project/layout.js";
8
8
  import { validateEffectivePlans } from "../project/plans.js";
9
9
  import { createAgentAdapter } from "./coding-agent.js";
10
+ import { readMachineId } from "./machine-id.js";
10
11
  import { expandModelAlias, resolveModels } from "./models.js";
11
12
  import { describeNativeStorage } from "./native-context.js";
12
13
  import { buildPrompt, PROTOCOLS } from "./prompt.js";
13
14
  import { runAgent } from "./run-agent.js";
14
- 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";
15
16
  // Distinct from 1 (ordinary run failure) so a script can branch on an auth failure that needs an
16
17
  // operator re-login rather than a retry.
17
18
  const EXIT_AUTH_REQUIRED = 2;
@@ -49,7 +50,8 @@ export async function runCode(tokens, loadSettings, ctx) {
49
50
  const report = readReport(ctx);
50
51
  if (command.kind === "session")
51
52
  validateEffectivePlans(ctx);
52
- const records = command.kind === "session" ? listSessionRecords(report.locations._aligndev.path) : [];
53
+ const tree = command.kind === "session" ? sessionTreeOf(report, ctx) : undefined;
54
+ const records = tree === undefined ? [] : listSessionRecords(tree.sessionsDir, tree.machineId);
53
55
  const args = command.kind === "session" ? command.args : undefined;
54
56
  const previous = args?.resume === undefined
55
57
  ? undefined
@@ -75,7 +77,9 @@ export async function runCode(tokens, loadSettings, ctx) {
75
77
  ctx.stderr.write(`${validationError}\n`);
76
78
  return 1;
77
79
  }
78
- 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);
79
83
  }
80
84
  catch (error) {
81
85
  ctx.stderr.write(`${errorMessage(error)}\n`);
@@ -83,10 +87,9 @@ export async function runCode(tokens, loadSettings, ctx) {
83
87
  }
84
88
  }
85
89
  function showStatus(ctx, target, includeResult) {
86
- const tree = sessionTreeOf(readReport(ctx), ctx.cwd);
87
- const sessionFilePath = resolveStatusTargetSessionFile(tree, target);
88
- const completion = reconcileSessionFile(sessionFilePath);
89
- 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));
90
93
  if (includeResult &&
91
94
  completion.frontmatter.status !== "running" &&
92
95
  completion.result !== undefined) {
@@ -100,10 +103,11 @@ function readReport(ctx) {
100
103
  throw new Error(report.error);
101
104
  return report;
102
105
  }
103
- function sessionTreeOf(report, cwd) {
106
+ function sessionTreeOf(report, ctx) {
104
107
  return {
105
- cwd: realpathSync(cwd),
108
+ cwd: realpathSync(ctx.cwd),
106
109
  sessionsDir: report.locations._aligndev.path,
110
+ machineId: readMachineId(ctx.home),
107
111
  };
108
112
  }
109
113
  async function showQuota(ctx, code) {
@@ -139,7 +143,7 @@ function resolveStatusTargetSessionFile(tree, target) {
139
143
  // A run tagged with `--meta <key>` is found by that key alone: the session tree is shared across
140
144
  // worktrees, so its newest run may belong to another thread.
141
145
  function resolveMetaSessionFile(tree, meta) {
142
- 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);
143
147
  if (matches.length === 0)
144
148
  throw new Error(`Error: no session file with meta "${meta}".`);
145
149
  const newest = matches.reduce((a, b) => a.frontmatter.startedAt >= b.frontmatter.startedAt ? a : b);
@@ -153,15 +157,20 @@ function loadMessage(args, cwd) {
153
157
  }
154
158
  args.message = readFileSync(args.messageFile === "-" ? 0 : resolve(cwd, args.messageFile), "utf8");
155
159
  }
160
+ // A caller may retain the `.running.md` path of a run that has ended since: it resolves to the
161
+ // completed file.
156
162
  function resolveStatusSessionFile(tree, input) {
157
- const sessionFilePath = resolve(tree.cwd, input);
163
+ const requestedPath = resolve(tree.cwd, input);
158
164
  const sessionsDir = displayPath(tree.cwd, tree.sessionsDir);
159
- if (!isSessionFilePath(tree.sessionsDir, sessionFilePath)) {
165
+ if (!isSessionFilePath(tree.sessionsDir, requestedPath)) {
160
166
  throw new Error(`Error: status requires a session file under ${sessionsDir}/_aligndev/ or ` +
161
167
  `${sessionsDir}/<ticket>/_aligndev/.`);
162
168
  }
169
+ const sessionFilePath = existsSync(requestedPath)
170
+ ? requestedPath
171
+ : completedSessionPath(requestedPath);
163
172
  if (!existsSync(sessionFilePath)) {
164
- 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)}`);
165
174
  }
166
175
  if (!isSessionFilePath(realpathSync(tree.sessionsDir), realpathSync(sessionFilePath))) {
167
176
  throw new Error(`Error: the session file resolves outside ${sessionsDir}/.`);
@@ -198,6 +207,7 @@ function renderSessionStatus(cwd, sessionFilePath, frontmatter) {
198
207
  `model: ${frontmatter.model ?? ""}`,
199
208
  `status: ${frontmatter.status}`,
200
209
  `pid: ${frontmatter.pid ?? ""}`,
210
+ `machineId: ${frontmatter.machineId ?? ""}`,
201
211
  `startedAt: ${frontmatter.startedAt}`,
202
212
  `endedAt: ${frontmatter.endedAt ?? ""}`,
203
213
  `exitReason: ${frontmatter.exitReason ?? ""}`,
@@ -379,17 +389,16 @@ function isPathSafeTicket(ticket) {
379
389
  // agent's background task) — aligndev owns no backgrounding or callback of its own. The per-run session
380
390
  // file is the durable result handoff: on completion the frontmatter carries the session id and
381
391
  // status, and the `---- Result ----` block carries the outcome for a waking caller (or a human).
382
- async function runSession(args, code, ctx, report, records, previous) {
392
+ async function runSession(args, code, ctx, report, tree, records, previous) {
383
393
  const { cwd, env, stdout, stderr, forms, alignfirstCommand, modelResolver } = ctx;
384
394
  const { agent } = code;
385
- const tree = sessionTreeOf(report, cwd);
386
395
  const resolvedTicket = args.noTicket
387
396
  ? undefined
388
397
  : (args.ticket ??
389
398
  (args.resume === undefined
390
399
  ? inferTicketFromMessage(args.message ?? "")
391
400
  : (previous?.frontmatter.ticket ?? undefined)));
392
- const guardError = checkLaunchGuards(args, agent, tree.cwd, resolvedTicket, records, previous);
401
+ const guardError = checkLaunchGuards(args, agent, tree.cwd, resolvedTicket, records, tree.machineId, previous);
393
402
  if (guardError) {
394
403
  stderr.write(`${guardError}\n`);
395
404
  return 1;
@@ -410,7 +419,16 @@ async function runSession(args, code, ctx, report, records, previous) {
410
419
  const contextContent = args.resume === undefined && companionInUse(report, CONTEXT_COMPANION_ITEMS)
411
420
  ? loadContext(alignfirstCommand, cwd, env)
412
421
  : undefined;
413
- 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
+ }));
414
432
  stdout.write(`Session file: ${displayPath(tree.cwd, sessionFilePath)}\n\n`);
415
433
  let executableModel;
416
434
  try {
@@ -425,14 +443,14 @@ async function runSession(args, code, ctx, report, records, previous) {
425
443
  (agent === "codex"
426
444
  ? " For Codex aliases, update the Codex CLI or select an explicit full model slug."
427
445
  : "");
428
- applyCompletion(sessionFilePath, {
446
+ const completedPath = applyCompletion(sessionFilePath, {
429
447
  status: "failed",
430
448
  endedAt: new Date().toISOString(),
431
449
  exitReason: "error",
432
450
  sessionId: args.resume ?? null,
433
451
  result: message,
434
452
  });
435
- writeFailureDiagnostic(ctx, sessionFilePath, message);
453
+ writeFailureDiagnostic(ctx, completedPath, message);
436
454
  return 1;
437
455
  }
438
456
  const runConfig = buildRunConfig({
@@ -449,11 +467,12 @@ async function runSession(args, code, ctx, report, records, previous) {
449
467
  });
450
468
  createMissingCompanion(report);
451
469
  const result = await runAgent(runConfig, createAgentAdapter(agent), stdout);
470
+ const completedPath = completedSessionPath(sessionFilePath);
452
471
  if (args.resume === undefined && result.sessionId) {
453
472
  stdout.write(`\nSession ID: ${result.sessionId}\n`);
454
473
  }
455
474
  if (result.authRequired) {
456
- 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 ` +
457
476
  "with the same effective environment as the child (apply profile unset/env/configDir, " +
458
477
  "including HOME, PATH and credential routing), from the same working directory. " +
459
478
  `Then use ${authenticationInstruction(agent)}. A bare login in another shell may use a different account.`);
@@ -461,7 +480,7 @@ async function runSession(args, code, ctx, report, records, previous) {
461
480
  }
462
481
  if (result.status === "succeeded")
463
482
  return 0;
464
- 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."}`);
465
484
  return 1;
466
485
  }
467
486
  function nativeContext(code) {
@@ -491,7 +510,7 @@ function failureDiagnostic(agent, result) {
491
510
  }
492
511
  // Fail-fast launch guards, run against the (healed) session records before anything is written.
493
512
  // Returns the error to print, or `undefined` when the launch may proceed.
494
- export function checkLaunchGuards(args, agent, realCwd, ticket, records, previous) {
513
+ export function checkLaunchGuards(args, agent, realCwd, ticket, records, machineId, previous) {
495
514
  if (args.resume !== undefined) {
496
515
  // A resumed run writes a new session file carrying the same sessionId as the original, so one
497
516
  // id can match several records — a running status on any of them blocks.
@@ -500,8 +519,8 @@ export function checkLaunchGuards(args, agent, realCwd, ticket, records, previou
500
519
  return unknownResumeError(args.resume, records);
501
520
  const running = matches.find((r) => r.frontmatter.status === "running");
502
521
  if (running) {
503
- return (`Error: session ${args.resume} is still running (pid ${running.frontmatter.pid}); ` +
504
- "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)}.`);
505
524
  }
506
525
  const latest = previous ?? latestRecord(matches);
507
526
  if (latest.frontmatter.agent === null) {
@@ -523,10 +542,10 @@ export function checkLaunchGuards(args, agent, realCwd, ticket, records, previou
523
542
  const active = records.filter((r) => r.frontmatter.status === "running" && r.frontmatter.protocol !== null);
524
543
  const sameWorktree = active.find((r) => r.frontmatter.cwd === realCwd);
525
544
  if (sameWorktree)
526
- return busyProtocolError(sameWorktree, "in this worktree");
545
+ return busyProtocolError(sameWorktree, "in this worktree", machineId);
527
546
  const sameTicket = ticket === undefined ? undefined : active.find((r) => r.frontmatter.ticket === ticket);
528
547
  if (sameTicket)
529
- return busyProtocolError(sameTicket, `on ticket ${ticket}`);
548
+ return busyProtocolError(sameTicket, `on ticket ${ticket}`, machineId);
530
549
  }
531
550
  return;
532
551
  }
@@ -540,10 +559,16 @@ function sameRealDirectory(recorded, realCwd) {
540
559
  return false;
541
560
  }
542
561
  }
543
- function busyProtocolError(record, scope) {
562
+ function busyProtocolError(record, scope, machineId) {
544
563
  return (`Error: a ${record.frontmatter.protocol} protocol run is already active ${scope} ` +
545
564
  `(${record.path}, pid ${record.frontmatter.pid}); one protocol run at a time per worktree ` +
546
- "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";
547
572
  }
548
573
  // The newest record of a non-empty list: a resumed session has one record per run.
549
574
  function latestRecord(records) {
@@ -621,6 +646,7 @@ function buildFrontmatter(input) {
621
646
  meta: args.meta ?? null,
622
647
  pid: process.pid,
623
648
  pidStartTime: readPidStartTime(process.pid),
649
+ machineId: input.machineId,
624
650
  cwd: input.realCwd,
625
651
  startedAt: now.toISOString(),
626
652
  endedAt: null,
@@ -704,9 +730,7 @@ function renderHelp(code, models, forms) {
704
730
  ? "Codex aliases astra, sol, terra, and luna resolve on demand; configured full slugs pass through."
705
731
  : `${agent === "pi" ? "Pi native selectors (including provider/model:thinking)" : "Claude model values"} pass through unchanged.`;
706
732
  const modelPolicy = models === undefined ? "Any nonblank pi-native selector" : `One of ${models.join(", ")}`;
707
- const requires = forms.viaNpx
708
- ? "Requires: the alignfirst CLI, run through npx, for the project layout, side tickets and the\ndelegated protocols."
709
- : "Requires: the alignfirst CLI on PATH (npm install -g alignfirst), for the project layout, side\ntickets and the delegated protocols.";
733
+ const requires = `Requires: the AlignFirst CLI through \`${forms.alignfirst}\`, for the project layout, side\ntickets and the delegated protocols.`;
710
734
  return `aligndev code — run a coding agent through AlignFirst protocols.
711
735
 
712
736
  Usage:
@@ -805,6 +829,6 @@ Coding runs can be very long. The host owns background execution and completion
805
829
  verify its capability before launch, use --quiet, and never detach the command. On completion,
806
830
  retrieve status --result with the exact session-file path or a unique per-run --meta key.
807
831
 
808
- Run \`${aligndev} guide code\` for the full delegation guide.
832
+ See the \`code\` topic of \`${aligndev} guide\` for the full delegation guide.
809
833
  `;
810
834
  }
@@ -169,7 +169,7 @@ function missingCodexOutcome(state) {
169
169
  function codexAuthenticationMessage(detail) {
170
170
  const base = "Coding agent not authenticated: an administrator must run `codex login` with the same effective environment " +
171
171
  "and cwd as the child (apply profile unset/env/configDir, including HOME, PATH and credential routing) before " +
172
- "`aligndev code` can run again.";
172
+ "another coding run.";
173
173
  const reason = detail?.trim();
174
174
  return reason === undefined || reason === "" ? base : `${base}\n\n${reason}`;
175
175
  }
@@ -0,0 +1 @@
1
+ export declare function readMachineId(home: string): string;
@@ -0,0 +1,45 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { linkSync, mkdirSync, readFileSync, rmSync, 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
+ const tmp = `${path}.${randomUUID()}.tmp`;
27
+ try {
28
+ writeFileSync(tmp, randomUUID());
29
+ publishMachineId(tmp, path);
30
+ }
31
+ finally {
32
+ rmSync(tmp, { force: true });
33
+ }
34
+ return readFileSync(path, "utf8");
35
+ }
36
+ // The link publishes the complete file; the first creator wins.
37
+ function publishMachineId(tmp, path) {
38
+ try {
39
+ linkSync(tmp, path);
40
+ }
41
+ catch (error) {
42
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
43
+ throw error;
44
+ }
45
+ }
@@ -235,6 +235,6 @@ function isPiAuthenticationError(message) {
235
235
  function piAuthenticationMessage(detail) {
236
236
  const base = "Coding agent not authenticated: run `pi`, then `/login <provider>`, or configure " +
237
237
  "the provider's credentials with the same effective environment and cwd as the child " +
238
- "(apply profile unset/env/configDir, including HOME, PATH and credential routing) before running `aligndev code` again.";
238
+ "(apply profile unset/env/configDir, including HOME, PATH and credential routing) before another coding run.";
239
239
  return detail === undefined || detail.trim() === "" ? base : `${base}\n\n${detail}`;
240
240
  }
@@ -1,4 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import { basename, delimiter, join } from "node:path";
2
4
  import { appendTranscript, applyCompletion, formatResults, } from "./session-file.js";
3
5
  const TERMINATION_GRACE_MS = 2000;
4
6
  // A coding-agent session exports its own identity to every command it runs; when the assistant
@@ -146,7 +148,7 @@ export function captureNativeSession(state, id, agent) {
146
148
  state.sessionId = id;
147
149
  }
148
150
  export function buildAgentEnv(baseEnv, unset, overrides = {}, required = {}) {
149
- const inherited = { ...baseEnv };
151
+ const inherited = externalProcessBaseline(baseEnv);
150
152
  for (const name of unset)
151
153
  delete inherited[name];
152
154
  const env = { ...inherited, ...overrides };
@@ -158,6 +160,40 @@ export function buildAgentEnv(baseEnv, unset, overrides = {}, required = {}) {
158
160
  delete env.AI_AGENT;
159
161
  return { ...env, ...required };
160
162
  }
163
+ function externalProcessBaseline(baseEnv) {
164
+ const env = { ...baseEnv };
165
+ if (env.PATH === undefined)
166
+ return env;
167
+ const entries = env.PATH.split(delimiter);
168
+ const shims = new Set(entries.filter(isBunRuntimeShim));
169
+ if (shims.size === 0)
170
+ return env;
171
+ env.PATH = entries.filter((entry) => !shims.has(entry)).join(delimiter);
172
+ for (const name of ["NODE", "npm_node_execpath"]) {
173
+ const value = env[name];
174
+ if (value !== undefined && shims.has(value))
175
+ delete env[name];
176
+ }
177
+ return env;
178
+ }
179
+ function isBunRuntimeShim(directory) {
180
+ // Forced Bun runners inject a dedicated node/bun symlink pair. A Bun installation or
181
+ // a directory name alone does not establish a launcher override.
182
+ if (!/^bun-node-(?:\d+-)?[a-f0-9]+$/.test(basename(directory)))
183
+ return false;
184
+ const extension = process.platform === "win32" ? ".exe" : "";
185
+ const node = join(directory, `node${extension}`);
186
+ const bun = join(directory, `bun${extension}`);
187
+ try {
188
+ if (!lstatSync(node).isSymbolicLink() || !lstatSync(bun).isSymbolicLink())
189
+ return false;
190
+ const target = realpathSync(bun);
191
+ return /^bunx?(?:\.exe)?$/.test(basename(target)) && realpathSync(node) === target;
192
+ }
193
+ catch {
194
+ return false;
195
+ }
196
+ }
161
197
  function guardChildLifecycle(child, sessionFilePath, state) {
162
198
  // Seal the session, ask the child to stop, then force-kill it after a short grace period so
163
199
  // interrupted runs leave neither a stale session record nor an orphaned child process.