aligndev 0.28.1 → 0.30.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 (50) hide show
  1. package/README.md +16 -6
  2. package/dist/alignfirst-cli.js +22 -10
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +14 -12
  5. package/dist/code/claude-agent.js +1 -1
  6. package/dist/code/code-cli.js +3 -5
  7. package/dist/code/codex-agent.js +1 -1
  8. package/dist/code/machine-id.js +14 -3
  9. package/dist/code/pi-agent.js +1 -1
  10. package/dist/code/run-agent.js +37 -1
  11. package/dist/command-form.d.ts +5 -2
  12. package/dist/command-form.js +15 -6
  13. package/dist/guide/code-guide.d.ts +2 -2
  14. package/dist/guide/code-guide.js +4 -8
  15. package/dist/guide/guide-cli.js +82 -30
  16. package/dist/guide/render-template.d.ts +4 -4
  17. package/dist/guide/render-template.js +42 -21
  18. package/dist/guide/topics.d.ts +8 -3
  19. package/dist/guide/topics.js +26 -7
  20. package/dist/project/discovery.js +5 -12
  21. package/dist/project/layout.d.ts +22 -9
  22. package/dist/project/layout.js +101 -28
  23. package/dist/project/plans.d.ts +1 -1
  24. package/dist/project/plans.js +1 -1
  25. package/dist/project/render.js +3 -1
  26. package/dist/project/status.d.ts +2 -2
  27. package/dist/project/status.js +2 -2
  28. package/package.json +5 -1
  29. package/templates/guide/code.md +12 -3
  30. package/templates/guide/playbook/channel-handling.md +12 -17
  31. package/templates/guide/playbook/consultation.md +27 -30
  32. package/templates/guide/playbook/dispatcher.md +18 -0
  33. package/templates/guide/playbook/{discord-message-tool.md → message-tool.md} +29 -0
  34. package/templates/guide/playbook/playbook.md +55 -25
  35. package/templates/guide/playbook/project-lifecycle.md +33 -18
  36. package/templates/guide/playbook/project-workspace-setup.md +91 -71
  37. package/templates/guide/playbook/work-files-setup.md +2 -2
  38. package/templates/guide/playbook/working-session.md +207 -158
  39. package/templates/guide/project.md +4 -4
  40. package/dist/guide/guide-file.d.ts +0 -3
  41. package/dist/guide/guide-file.js +0 -26
  42. package/dist/worktree/add.d.ts +0 -20
  43. package/dist/worktree/add.js +0 -175
  44. package/dist/worktree/git.d.ts +0 -24
  45. package/dist/worktree/git.js +0 -103
  46. package/dist/worktree/remove.d.ts +0 -8
  47. package/dist/worktree/remove.js +0 -62
  48. package/dist/worktree/worktree-cli.d.ts +0 -10
  49. package/dist/worktree/worktree-cli.js +0 -122
  50. package/templates/guide/playbook/slack-message-tool.md +0 -23
package/README.md CHANGED
@@ -33,13 +33,19 @@ A task can also start at any intermediate step.
33
33
 
34
34
  For a coding-agent assistant, parent host and delegated child are independent: a coding profile selects Claude Code, Codex or Pi. Without a named selection, the detected parent kind selects a matching profile or built-in child defaults. OpenClaw deployment templates offer all three agents on Slack or Discord, with explicit profiles and inventoried default/custom native stores. The Pi overlay uses a protected absolute-Node launcher while retaining project PATH. Its [deployment boundary](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/aligndev-openclaw.md#deployment-gate) explicitly permits writable native `auth.json` and adjacent locks for OAuth renewal. That file can persist same-account executable API-key commands; this is account-level persistence, not administrator privilege escalation. Other managed resources and trust retain controlled-maintenance protection. Project trust is not a sandbox, and offline checks do not certify live deployment.
35
35
 
36
+ ## Configuration boundary
37
+
38
+ AlignDev requires the workspace-aware `alignfirst config --json` report: top-level `workspace` metadata with absolute registry/runtime paths, `selectionOrigins`, logical locations and independent `aligndev` selection. One selected `alignfirst.json`/`.jsonc` with `schemaVersion: 1` holds nested conventions, plans, explicit developer instructions and optional recipes. Project configuration rejects unknown properties. Companion/global settings retain tolerant warnings. Inventory ranges come only from workspace `devServer.ports`; `project free-ports` looks up a free block without reserving it.
39
+
36
40
  ## Start in Claude Code, Codex or Pi
37
41
 
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.
42
+ 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.
43
+
44
+ The assistant directly runs `alignfirst workspace` for configured and manifest-free projects on every stack. Project recipes live in the selected merged `alignfirst.json`/`.jsonc`, from project or companion; no wrapper or local kernel dependency is required. Prepare usable effective plans and selected runtime storage first. Local storage requires ignored, untracked `.local-wt/`; companion storage needs no checkout runtime directory. Without a manifest, readiness is protocol-ready: no installation, build, ports or services are implied. Coding delegation and project-specific commands remain separate.
39
45
 
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.
46
+ External tools such as Paseo run `npx -y alignfirst workspace setup` inside their selected checkout, then `workspace teardown` before their own deletion. Setup preserves the path/branch and retains partial preparation on failure for retry. Teardown stops/purges and releases state while preserving files and Git; remove additionally performs protected Git deletion and preserves branches. Failed cleanup retains identity even after PIDs exit. Adoption does not transfer external deletion ownership. See `alignfirst workspace --guide` and [the upgrade runbook](https://github.com/paleo/alignfirst/blob/main/docs/upgrading-multi-stack-workspaces.md).
41
47
 
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.
48
+ 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.
43
49
 
44
50
  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.
45
51
 
@@ -78,11 +84,15 @@ Then ask your session to work with aligndev.
78
84
 
79
85
  ### Requirements
80
86
 
81
- - Node.js 22.11 or later. The assistant runs `aligndev` through `npx`, so there is nothing to install.
87
+ - 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.
82
88
  - 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.
83
89
  - 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.
84
90
  - Linux or macOS, or Windows through WSL.
85
91
 
92
+ 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.
93
+
94
+ 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.
95
+
86
96
  ## Configuration
87
97
 
88
98
  `~/.alignfirst/aligndev.settings.json` is optional. Without it, one detected parent kind supplies built-in child defaults. A minimal singleton setup is:
@@ -130,7 +140,7 @@ For multiple accounts and independent quota sources:
130
140
 
131
141
  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.
132
142
 
133
- - `platform` — `codingAgent` (default), or `openclaw`.
143
+ - `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.
134
144
  - `projectsRoot` — projects directory, required by the OpenClaw playbook. `~/` uses the configured home; relative paths resolve against the settings directory.
135
145
  - `code.profile` — global named child profile, independent of the parent host.
136
146
  - `code.profiles` — complete profiles, with required `agent` (`claude`, `codex`, `pi`). Names and references are exact, nonblank strings. Profiles have no inheritance or merging.
@@ -182,7 +192,7 @@ npx -y skills add https://github.com/paleo/alignfirst --global --skill alignfirs
182
192
 
183
193
  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.
184
194
 
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.
195
+ 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 an explicitly referenced developer guide, in the repository or its companion. `alignfirst developer-instructions` prints conventions and that content without filename discovery. The workspace recipe is optional; default preparation is protocol-ready.
186
196
 
187
197
  ## Under the Hood
188
198
 
@@ -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;
@@ -36,16 +36,19 @@ export function forwardSettingsWarnings(stderr) {
36
36
  function isSettingsWarning(line) {
37
37
  if (/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(line))
38
38
  return false;
39
- return (/^Warning: ignoring unknown (?:\.alignfirst\.json|companion registry) setting /u.test(line) ||
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));
39
+ return /^Warning: ignoring unknown companion registry setting /u.test(line);
41
40
  }
42
41
  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)
42
+ const runner = ["npx", "bunx", "pnpm", "yarn"].includes(command[0]);
43
+ const reason = command[0] === "npx"
44
+ ? "npm/npx package runner; npx prefers the project's local alignfirst dependency"
45
+ : command[0] === "bunx"
46
+ ? `Bun package runner${command.includes("--bun") ? "; explicit Bun runtime" : "; entry-point shebang runtime"}`
47
+ : runner
48
+ ? `${command[0]} package runner`
49
+ : "direct executable";
50
+ const facts = [`\`${renderCommand(createCommand(command[0], command.slice(1)))}\` (${reason})`];
51
+ if (!runner)
49
52
  facts.push(describeExecutable(command[0], cwd, env));
50
53
  const version = spawnSync(command[0], [...command.slice(1), "--version"], {
51
54
  cwd,
@@ -61,6 +64,15 @@ export function describeAlignfirst(command, cwd, env) {
61
64
  facts.push(`aligndev ${readPackageVersion()}${entry}`);
62
65
  return `alignfirst: ${facts.join("; ")}`.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, " ");
63
66
  }
67
+ function missingExecutableRecovery(command) {
68
+ if (command[0] === "bunx") {
69
+ return "Install Bun and make bunx available on PATH, then relaunch with `bunx --bun aligndev`.";
70
+ }
71
+ if (command[0] === "alignfirst") {
72
+ return "Install alignfirst on PATH, or relaunch with `npx -y aligndev`.";
73
+ }
74
+ return `Make the selected runner or executable available, then retry \`${renderCommand(createCommand(command[0], command.slice(1)))}\`.`;
75
+ }
64
76
  function describeExecutable(command, cwd, env) {
65
77
  if (command.includes(sep)) {
66
78
  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";
@@ -8,7 +9,6 @@ import { errorMessage } from "./errors.js";
8
9
  import { runGuide } from "./guide/guide-cli.js";
9
10
  import { readPackageVersion } from "./package-version.js";
10
11
  import { runProject } from "./project/project-cli.js";
11
- import { runWorktree } from "./worktree/worktree-cli.js";
12
12
  export async function main(options) {
13
13
  const ctx = resolveContext(options);
14
14
  const [command, ...tokens] = (options?.argv ?? process.argv).slice(2);
@@ -20,17 +20,12 @@ export async function main(options) {
20
20
  ctx.stdout.write(`${readPackageVersion()}\n`);
21
21
  return 0;
22
22
  }
23
- if (command !== "code" &&
24
- command !== "project" &&
25
- command !== "guide" &&
26
- command !== "worktree") {
23
+ if (command !== "code" && command !== "project" && command !== "guide") {
27
24
  const error = command === undefined ? "Error: no command given." : `Error: unknown command "${command}".`;
28
25
  ctx.stderr.write(`${error}\n\n${renderHelp(ctx.forms.aligndev)}`);
29
26
  return 1;
30
27
  }
31
28
  try {
32
- if (command === "worktree")
33
- return runWorktree(tokens, ctx);
34
29
  if (command === "code")
35
30
  return await runCode(tokens, () => loadConfig(ctx.home), ctx);
36
31
  const config = loadConfig(ctx.home);
@@ -51,10 +46,9 @@ function renderHelp(aligndev) {
51
46
  "List projects, check their inventory, claim port ranges.",
52
47
  ],
53
48
  [
54
- `${aligndev} worktree <command> [<options>]`,
55
- "Create, list and safely remove lightweight Git worktrees.",
49
+ `${aligndev} guide [--channel <surface>] [<topic>]`,
50
+ "Print the assistant's playbook and guides.",
56
51
  ],
57
- [`${aligndev} guide [<topic>]`, "Print the assistant's playbook and guides."],
58
52
  [`${aligndev} -h, --help`],
59
53
  [`${aligndev} -v, --version`],
60
54
  ]);
@@ -80,7 +74,12 @@ function renderUsageRows(rows) {
80
74
  }
81
75
  function resolveContext(options) {
82
76
  const env = options?.env ?? process.env;
83
- const forms = resolveCommandForms(env);
77
+ const evidence = options?.evidence ?? {
78
+ ...readLaunchEvidence(),
79
+ env,
80
+ cwd: options?.cwd ?? process.cwd(),
81
+ };
82
+ const forms = resolveCommandForms(env, evidence);
84
83
  return {
85
84
  cwd: options?.cwd ?? process.cwd(),
86
85
  env,
@@ -88,7 +87,10 @@ function resolveContext(options) {
88
87
  stdout: options?.stdout ?? process.stdout,
89
88
  stderr: options?.stderr ?? process.stderr,
90
89
  forms,
91
- alignfirstCommand: options?.alignfirstCommand ?? forms.alignfirst.split(" "),
90
+ alignfirstCommand: options?.alignfirstCommand ?? [
91
+ forms.counterpart.executable,
92
+ ...forms.counterpart.args,
93
+ ],
92
94
  modelResolver: options?.modelResolver ?? createExecutableModelResolver(),
93
95
  quotaReader: options?.quotaReader ?? readQuota,
94
96
  };
@@ -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
  }
@@ -30,7 +30,7 @@ const SESSION_OPTIONS = {
30
30
  };
31
31
  // Items the agent would not find in the repository: a new session gets `alignfirst context`.
32
32
  const CONTEXT_COMPANION_ITEMS = [
33
- ".alignfirst.json",
33
+ "alignfirst",
34
34
  ".alignfirst-instructions",
35
35
  "docs",
36
36
  ".plans",
@@ -730,9 +730,7 @@ function renderHelp(code, models, forms) {
730
730
  ? "Codex aliases astra, sol, terra, and luna resolve on demand; configured full slugs pass through."
731
731
  : `${agent === "pi" ? "Pi native selectors (including provider/model:thinking)" : "Claude model values"} pass through unchanged.`;
732
732
  const modelPolicy = models === undefined ? "Any nonblank pi-native selector" : `One of ${models.join(", ")}`;
733
- const requires = forms.viaNpx
734
- ? "Requires: the alignfirst CLI, run through npx, for the project layout, side tickets and the\ndelegated protocols."
735
- : "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.`;
736
734
  return `aligndev code — run a coding agent through AlignFirst protocols.
737
735
 
738
736
  Usage:
@@ -831,6 +829,6 @@ Coding runs can be very long. The host owns background execution and completion
831
829
  verify its capability before launch, use --quiet, and never detach the command. On completion,
832
830
  retrieve status --result with the exact session-file path or a unique per-run --meta key.
833
831
 
834
- Run \`${aligndev} guide code\` for the full delegation guide.
832
+ See the \`code\` topic of \`${aligndev} guide\` for the full delegation guide.
835
833
  `;
836
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
  }
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { errorMessage } from "../errors.js";
5
5
  export function readMachineId(home) {
@@ -23,12 +23,23 @@ function readOrCreateMachineId(path) {
23
23
  throw error;
24
24
  }
25
25
  mkdirSync(dirname(path), { recursive: true });
26
+ const tmp = `${path}.${randomUUID()}.tmp`;
26
27
  try {
27
- writeFileSync(path, randomUUID(), { flag: "wx" });
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);
28
40
  }
29
41
  catch (error) {
30
42
  if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
31
43
  throw error;
32
44
  }
33
- return readFileSync(path, "utf8");
34
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.
@@ -1,6 +1,9 @@
1
+ import { type Invocation, type InvocationCommand, type LaunchEvidence } from "@alignfirst/docmap/invocation";
1
2
  export interface CommandForms {
2
- viaNpx: boolean;
3
+ invocation: Invocation;
4
+ self: InvocationCommand;
5
+ counterpart: InvocationCommand;
3
6
  aligndev: string;
4
7
  alignfirst: string;
5
8
  }
6
- export declare function resolveCommandForms(env: NodeJS.ProcessEnv): CommandForms;
9
+ export declare function resolveCommandForms(env: NodeJS.ProcessEnv, evidence?: LaunchEvidence): CommandForms;
@@ -1,7 +1,16 @@
1
- export function resolveCommandForms(env) {
2
- const userAgent = env.npm_config_user_agent;
3
- const viaNpx = userAgent !== undefined && userAgent !== "";
4
- return viaNpx
5
- ? { viaNpx, aligndev: "npx -y aligndev", alignfirst: "npx -y alignfirst" }
6
- : { viaNpx, aligndev: "aligndev", alignfirst: "alignfirst" };
1
+ import { invocationCommand, packageCommand, readLaunchEvidence, resolveInvocation, } from "@alignfirst/docmap/invocation";
2
+ export function resolveCommandForms(env, evidence = { ...readLaunchEvidence(), env }) {
3
+ const invocation = resolveInvocation({ packageName: "aligndev", binaryName: "aligndev" }, evidence);
4
+ const self = invocationCommand(invocation);
5
+ const counterpart = packageCommand(invocation, {
6
+ packageName: "alignfirst",
7
+ binaryName: "alignfirst",
8
+ });
9
+ return {
10
+ invocation,
11
+ self,
12
+ counterpart,
13
+ aligndev: self.withArgs,
14
+ alignfirst: counterpart.withArgs,
15
+ };
7
16
  }
@@ -1,4 +1,4 @@
1
1
  import type { CodingAgent } from "../code/coding-agent.js";
2
2
  import type { CommandForms } from "../command-form.js";
3
- import { type Platform } from "../config.js";
4
- export declare function renderCodeGuide(platform: Platform, agent: CodingAgent, models: readonly string[] | undefined, defaultModel: string | undefined, forms: CommandForms, profile?: string | null, nativeStorage?: string): string;
3
+ import { type ActiveBlocks } from "./render-template.js";
4
+ export declare function renderCodeGuide(active: ActiveBlocks, agent: CodingAgent, models: readonly string[] | undefined, defaultModel: string | undefined, forms: CommandForms, profile?: string | null, nativeStorage?: string): string;
@@ -1,7 +1,7 @@
1
1
  import { CONFIG_DIRECTORY_VARIABLES } from "../config.js";
2
2
  import { renderGuideTemplate } from "./render-template.js";
3
- export function renderCodeGuide(platform, agent, models, defaultModel, forms, profile = null, nativeStorage = `${CONFIG_DIRECTORY_VARIABLES[agent]}: inherited/default native storage`) {
4
- return renderGuideTemplate("code.md", { platform }, forms, {
3
+ export function renderCodeGuide(active, agent, models, defaultModel, forms, profile = null, nativeStorage = `${CONFIG_DIRECTORY_VARIABLES[agent]}: inherited/default native storage`) {
4
+ return renderGuideTemplate("code.md", active, forms, {
5
5
  AGENT: agent,
6
6
  PROFILE: profile ?? "(built-in)",
7
7
  NATIVE_CONFIG: nativeStorage,
@@ -19,11 +19,7 @@ export function renderCodeGuide(platform, agent, models, defaultModel, forms, pr
19
19
  ? "Any nonblank pi-native selector, preferably `provider/model` (thinking suffixes supported)"
20
20
  : `One of ${models.map((model) => `\`${model}\``).join(", ")}`,
21
21
  DEFAULT_MODEL: defaultModel === undefined ? "the coding agent's default" : `\`${defaultModel}\``,
22
- ALIGNFIRST_SETUP: forms.viaNpx
23
- ? "The project must be prepared for AlignFirst. `npx -y aligndev` runs the `alignfirst` CLI through `npx`."
24
- : "The project must be prepared for AlignFirst, with the `alignfirst` CLI installed (`npm install -g alignfirst`).",
25
- ALIGNFIRST_USE: forms.viaNpx
26
- ? "`npx -y aligndev code` runs the `alignfirst` CLI through `npx`, and so does the agent: it runs `npx -y alignfirst guide <protocol>` in the project."
27
- : "`aligndev code` requires the `alignfirst` CLI on `PATH`. The agent runs `alignfirst guide <protocol>` in the project, so the protocols come from the installed CLI.",
22
+ ALIGNFIRST_SETUP: `The project must be prepared for AlignFirst. AlignDev uses \`${forms.alignfirst}\` for the AlignFirst CLI.`,
23
+ ALIGNFIRST_USE: `\`${forms.aligndev} code\` and the agent use the same AlignFirst command: \`${forms.alignfirst} guide <protocol>\` in the project.`,
28
24
  });
29
25
  }
@@ -1,14 +1,13 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { resolveModels } from "../code/models.js";
3
3
  import { describeNativeStorage } from "../code/native-context.js";
4
- import { PLATFORMS, requireProjectsRoot, resolveCodeConfig, } from "../config.js";
4
+ import { requireProjectsRoot, resolveCodeConfig } from "../config.js";
5
5
  import { errorMessage } from "../errors.js";
6
6
  import { readProjectReport } from "../project/layout.js";
7
7
  import { renderProjectsGuideForRoot } from "../project/project-cli.js";
8
8
  import { renderCodeGuide } from "./code-guide.js";
9
- import { resolveGuideFile } from "./guide-file.js";
10
- import { renderGuideTemplate } from "./render-template.js";
11
- import { PLAYBOOK_DISPATCHER, PLAYBOOK_TOPICS } from "./topics.js";
9
+ import { isSurface, renderGuideTemplate, SURFACES, } from "./render-template.js";
10
+ import { ENTRY_TOPICS, guideContextOf, PLAYBOOK, PLAYBOOK_DISPATCHER, PLAYBOOK_TOPICS, surfacesServing, } from "./topics.js";
12
11
  export function runGuide(tokens, config, ctx) {
13
12
  try {
14
13
  const args = parseGuideArgs(tokens);
@@ -24,6 +23,7 @@ function parseGuideArgs(tokens) {
24
23
  const { values, positionals } = parseArgs({
25
24
  args: tokens,
26
25
  options: {
26
+ channel: { type: "string" },
27
27
  root: { type: "string" },
28
28
  profile: { type: "string" },
29
29
  help: { type: "boolean", short: "h", default: false },
@@ -40,56 +40,108 @@ function parseGuideArgs(tokens) {
40
40
  if (values.profile !== undefined && topic !== "code") {
41
41
  throw new Error("Error: --profile is valid only with `aligndev guide code`.");
42
42
  }
43
- return { topic, root: values.root, profile: values.profile, help: values.help };
43
+ return {
44
+ topic,
45
+ channel: parseChannel(values.channel),
46
+ root: values.root,
47
+ profile: values.profile,
48
+ help: values.help,
49
+ };
50
+ }
51
+ function parseChannel(value) {
52
+ if (value === undefined || isSurface(value))
53
+ return value;
54
+ throw new Error(`Error: unknown --channel value "${value}". Surfaces: ${SURFACES.join(", ")}.`);
44
55
  }
45
56
  function renderUsage(forms) {
46
- const playbookTopics = PLATFORMS.map((platform) => ` ${platform}: ${PLAYBOOK_TOPICS[platform].join(", ")}`);
47
57
  return `Usage:
48
- ${forms.aligndev} guide [<topic>] [--root <path>] [--profile <name>]
58
+ ${forms.aligndev} guide [--channel <slack|discord|app>] [<topic>] [--root <path>] [--profile <name>]
49
59
  ${forms.aligndev} guide --help
50
60
 
51
- Without a topic, prints the playbook of the platform set in the aligndev settings.
61
+ Without a topic, prints the dispatcher; with --channel alone, the surface's playbook. On the openclaw
62
+ platform, every playbook topic requires --channel, code defaults to --channel app, and project
63
+ rejects it. The working-session and channel-handling topics print after the playbook.
52
64
 
53
65
  Topics:
54
66
  code The delegation guide for \`${forms.aligndev} code\`.
55
67
  project The projects guide, openclaw only. --root overrides projectsRoot in the aligndev settings.
56
68
 
57
- Playbook topics, by platform:
58
- ${playbookTopics.join("\n")}
69
+ Playbook topics, by context:
70
+ thread (openclaw, --channel slack|discord): ${PLAYBOOK_TOPICS.thread.join(", ")}
71
+ app (openclaw, --channel app): ${PLAYBOOK_TOPICS.app.join(", ")}
72
+ codingAgent: ${PLAYBOOK_TOPICS.codingAgent.join(", ")}
59
73
  `;
60
74
  }
61
75
  function renderTopic(args, config, ctx) {
62
- if (args.topic === "code")
63
- return renderCodeTopic(config, ctx, args.profile);
64
- if (args.topic === "project" && config.platform === "openclaw") {
76
+ assertChannelUse(args, config);
77
+ const { topic, channel } = args;
78
+ if (topic === "project" && config.platform === "openclaw") {
65
79
  return renderProjectsGuideForRoot({ ...ctx, projectsRoot: config.projectsRoot }, args.root);
66
80
  }
67
- return renderPlaybookTopic(args.topic, config, ctx);
81
+ const active = { platform: config.platform, surface: channel };
82
+ if (topic === undefined) {
83
+ const name = channel === undefined ? PLAYBOOK_DISPATCHER : PLAYBOOK;
84
+ return renderPlaybookTemplate(name, active, config, ctx.forms);
85
+ }
86
+ if (topic === "code")
87
+ return renderCodeTopic(withCodeSurface(active), config, ctx, args.profile);
88
+ return renderPlaybookTopic(topic, active, config, ctx);
89
+ }
90
+ function assertChannelUse({ topic, channel }, config) {
91
+ if (config.platform === "codingAgent") {
92
+ if (channel !== undefined) {
93
+ throw new Error("Error: --channel is valid only on the openclaw platform.");
94
+ }
95
+ return;
96
+ }
97
+ if (topic === "project") {
98
+ if (channel !== undefined) {
99
+ throw new Error("Error: --channel is not valid with `aligndev guide project`.");
100
+ }
101
+ return;
102
+ }
103
+ if (topic !== undefined && topic !== "code" && channel === undefined) {
104
+ throw new Error("Error: --channel is required with a playbook topic on the openclaw platform.");
105
+ }
68
106
  }
69
- function renderCodeTopic(config, ctx, profile) {
107
+ // Operators validate profiles through `guide code` outside any session; the app surface serves them.
108
+ function withCodeSurface(active) {
109
+ if (active.platform !== "openclaw" || active.surface !== undefined)
110
+ return active;
111
+ return { ...active, surface: "app" };
112
+ }
113
+ function renderCodeTopic(active, config, ctx, profile) {
70
114
  const report = readProjectReport(ctx.alignfirstCommand, ctx.cwd, ctx.env);
71
115
  if ("error" in report)
72
116
  throw new Error(report.error);
73
117
  const code = resolveCodeConfig(config, ctx.env, { project: report.aligndev, explicit: profile });
74
118
  const models = resolveModels(code.agent, code.models, code.modelAliases);
75
- return renderCodeGuide(config.platform, code.agent, models, code.defaultModel, ctx.forms, code.profile, describeNativeStorage(code));
119
+ return renderCodeGuide(active, code.agent, models, code.defaultModel, ctx.forms, code.profile, describeNativeStorage(code));
76
120
  }
77
- function renderPlaybookTopic(topic, config, ctx) {
78
- if (topic !== undefined)
79
- assertPlaybookTopic(topic, config.platform);
80
- const name = `playbook/${topic ?? PLAYBOOK_DISPATCHER}.md`;
81
- if (config.platform === "codingAgent") {
82
- const active = { platform: config.platform, guideFile: resolveGuideFile(ctx) };
83
- return renderGuideTemplate(name, active, ctx.forms);
84
- }
85
- return renderGuideTemplate(name, { platform: config.platform }, ctx.forms, {
86
- PROJECTS_ROOT: requireProjectsRoot(config).written,
87
- });
121
+ // An entry topic prints after the playbook.
122
+ function renderPlaybookTopic(topic, active, config, ctx) {
123
+ assertPlaybookTopic(topic, active);
124
+ const text = renderPlaybookTemplate(topic, active, config, ctx.forms);
125
+ if (!ENTRY_TOPICS.includes(topic))
126
+ return text;
127
+ return `${renderPlaybookTemplate(PLAYBOOK, active, config, ctx.forms)}\n\n${text}`;
88
128
  }
89
- function assertPlaybookTopic(topic, platform) {
90
- const topics = PLAYBOOK_TOPICS[platform];
129
+ function assertPlaybookTopic(topic, active) {
130
+ const topics = PLAYBOOK_TOPICS[guideContextOf(active)];
91
131
  if (topics.includes(topic))
92
132
  return;
93
- const specialTopics = platform === "openclaw" ? ["code", "project"] : ["code"];
133
+ const surfaces = surfacesServing(topic);
134
+ if (active.surface !== undefined && surfaces.length > 0) {
135
+ throw new Error(`Error: guide topic "${topic}" is not served on the ${active.surface} surface. Surfaces: ${surfaces.join(", ")}.`);
136
+ }
137
+ const specialTopics = active.platform === "openclaw" ? ["code", "project"] : ["code"];
94
138
  throw new Error(`Error: unknown guide topic "${topic}". Topics: ${[...specialTopics, ...topics].join(", ")}.`);
95
139
  }
140
+ function renderPlaybookTemplate(name, active, config, forms) {
141
+ const template = `playbook/${name}.md`;
142
+ if (config.platform === "codingAgent")
143
+ return renderGuideTemplate(template, active, forms);
144
+ return renderGuideTemplate(template, active, forms, {
145
+ PROJECTS_ROOT: requireProjectsRoot(config).written,
146
+ });
147
+ }
@@ -1,11 +1,11 @@
1
1
  import type { CommandForms } from "../command-form.js";
2
2
  import { type Platform } from "../config.js";
3
- declare const GUIDE_FILE_CONDITIONS: readonly ["developers", "readme", "noGuide"];
4
- export type GuideFileCondition = (typeof GUIDE_FILE_CONDITIONS)[number];
3
+ export declare const SURFACES: readonly ["slack", "discord", "app"];
4
+ export type Surface = (typeof SURFACES)[number];
5
5
  export interface ActiveBlocks {
6
6
  platform: Platform;
7
- guideFile?: GuideFileCondition;
7
+ surface?: Surface;
8
8
  }
9
9
  export declare function renderGuideTemplate(name: string, active: ActiveBlocks, forms: CommandForms, values?: Readonly<Record<string, string>>): string;
10
10
  export declare function renderBlocks(text: string, active: ActiveBlocks, templateName: string): string;
11
- export {};
11
+ export declare function isSurface(name: string): name is Surface;