aligndev 0.28.1 → 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 (37) hide show
  1. package/README.md +13 -5
  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.js +2 -4
  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 +84 -29
  16. package/dist/guide/render-template.d.ts +4 -0
  17. package/dist/guide/render-template.js +51 -12
  18. package/dist/guide/topics.d.ts +8 -3
  19. package/dist/guide/topics.js +26 -7
  20. package/dist/project/plans.js +1 -1
  21. package/dist/worktree/add.d.ts +3 -13
  22. package/dist/worktree/add.js +7 -101
  23. package/dist/worktree/setup.d.ts +18 -0
  24. package/dist/worktree/setup.js +192 -0
  25. package/dist/worktree/worktree-cli.js +29 -11
  26. package/package.json +4 -1
  27. package/templates/guide/code.md +12 -3
  28. package/templates/guide/playbook/channel-handling.md +12 -17
  29. package/templates/guide/playbook/consultation.md +24 -17
  30. package/templates/guide/playbook/dispatcher.md +18 -0
  31. package/templates/guide/playbook/{discord-message-tool.md → message-tool.md} +29 -0
  32. package/templates/guide/playbook/playbook.md +53 -20
  33. package/templates/guide/playbook/project-lifecycle.md +26 -11
  34. package/templates/guide/playbook/project-workspace-setup.md +87 -62
  35. package/templates/guide/playbook/work-files-setup.md +1 -1
  36. package/templates/guide/playbook/working-session.md +195 -112
  37. package/templates/guide/playbook/slack-message-tool.md +0 -23
package/README.md CHANGED
@@ -35,11 +35,15 @@ For a coding-agent assistant, parent host and delegated child are independent: a
35
35
 
36
36
  ## Start in Claude Code, Codex or Pi
37
37
 
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
+ 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.
39
39
 
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.
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.
41
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.
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.
43
47
 
44
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.
45
49
 
@@ -78,11 +82,15 @@ Then ask your session to work with aligndev.
78
82
 
79
83
  ### Requirements
80
84
 
81
- - 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.
82
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.
83
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.
84
88
  - Linux or macOS, or Windows through WSL.
85
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
+
86
94
  ## Configuration
87
95
 
88
96
  `~/.alignfirst/aligndev.settings.json` is optional. Without it, one detected parent kind supplies built-in child defaults. A minimal singleton setup is:
@@ -130,7 +138,7 @@ For multiple accounts and independent quota sources:
130
138
 
131
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.
132
140
 
133
- - `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.
134
142
  - `projectsRoot` — projects directory, required by the OpenClaw playbook. `~/` uses the configured home; relative paths resolve against the settings directory.
135
143
  - `code.profile` — global named child profile, independent of the parent host.
136
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
  }
@@ -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,14 @@
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
9
  import { resolveGuideFile } from "./guide-file.js";
10
- import { renderGuideTemplate } from "./render-template.js";
11
- import { PLAYBOOK_DISPATCHER, PLAYBOOK_TOPICS } from "./topics.js";
10
+ import { isSurface, renderGuideTemplate, SURFACES, } from "./render-template.js";
11
+ import { ENTRY_TOPICS, guideContextOf, PLAYBOOK, PLAYBOOK_DISPATCHER, PLAYBOOK_TOPICS, surfacesServing, } from "./topics.js";
12
12
  export function runGuide(tokens, config, ctx) {
13
13
  try {
14
14
  const args = parseGuideArgs(tokens);
@@ -24,6 +24,7 @@ function parseGuideArgs(tokens) {
24
24
  const { values, positionals } = parseArgs({
25
25
  args: tokens,
26
26
  options: {
27
+ channel: { type: "string" },
27
28
  root: { type: "string" },
28
29
  profile: { type: "string" },
29
30
  help: { type: "boolean", short: "h", default: false },
@@ -40,56 +41,110 @@ function parseGuideArgs(tokens) {
40
41
  if (values.profile !== undefined && topic !== "code") {
41
42
  throw new Error("Error: --profile is valid only with `aligndev guide code`.");
42
43
  }
43
- return { topic, root: values.root, profile: values.profile, help: values.help };
44
+ return {
45
+ topic,
46
+ channel: parseChannel(values.channel),
47
+ root: values.root,
48
+ profile: values.profile,
49
+ help: values.help,
50
+ };
51
+ }
52
+ function parseChannel(value) {
53
+ if (value === undefined || isSurface(value))
54
+ return value;
55
+ throw new Error(`Error: unknown --channel value "${value}". Surfaces: ${SURFACES.join(", ")}.`);
44
56
  }
45
57
  function renderUsage(forms) {
46
- const playbookTopics = PLATFORMS.map((platform) => ` ${platform}: ${PLAYBOOK_TOPICS[platform].join(", ")}`);
47
58
  return `Usage:
48
- ${forms.aligndev} guide [<topic>] [--root <path>] [--profile <name>]
59
+ ${forms.aligndev} guide [--channel <slack|discord|app>] [<topic>] [--root <path>] [--profile <name>]
49
60
  ${forms.aligndev} guide --help
50
61
 
51
- Without a topic, prints the playbook of the platform set in the aligndev settings.
62
+ Without a topic, prints the dispatcher; with --channel alone, the surface's playbook. On the openclaw
63
+ platform, every playbook topic requires --channel, code defaults to --channel app, and project
64
+ rejects it. The working-session and channel-handling topics print after the playbook.
52
65
 
53
66
  Topics:
54
67
  code The delegation guide for \`${forms.aligndev} code\`.
55
68
  project The projects guide, openclaw only. --root overrides projectsRoot in the aligndev settings.
56
69
 
57
- Playbook topics, by platform:
58
- ${playbookTopics.join("\n")}
70
+ Playbook topics, by context:
71
+ thread (openclaw, --channel slack|discord): ${PLAYBOOK_TOPICS.thread.join(", ")}
72
+ app (openclaw, --channel app): ${PLAYBOOK_TOPICS.app.join(", ")}
73
+ codingAgent: ${PLAYBOOK_TOPICS.codingAgent.join(", ")}
59
74
  `;
60
75
  }
61
76
  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") {
77
+ assertChannelUse(args, config);
78
+ const { topic, channel } = args;
79
+ if (topic === "project" && config.platform === "openclaw") {
65
80
  return renderProjectsGuideForRoot({ ...ctx, projectsRoot: config.projectsRoot }, args.root);
66
81
  }
67
- return renderPlaybookTopic(args.topic, config, ctx);
82
+ const active = { platform: config.platform, surface: channel };
83
+ if (topic === undefined) {
84
+ const name = channel === undefined ? PLAYBOOK_DISPATCHER : PLAYBOOK;
85
+ return renderPlaybookTemplate(name, active, config, ctx.forms);
86
+ }
87
+ if (topic === "code")
88
+ return renderCodeTopic(withCodeSurface(active), config, ctx, args.profile);
89
+ return renderPlaybookTopic(topic, active, config, ctx);
90
+ }
91
+ function assertChannelUse({ topic, channel }, config) {
92
+ if (config.platform === "codingAgent") {
93
+ if (channel !== undefined) {
94
+ throw new Error("Error: --channel is valid only on the openclaw platform.");
95
+ }
96
+ return;
97
+ }
98
+ if (topic === "project") {
99
+ if (channel !== undefined) {
100
+ throw new Error("Error: --channel is not valid with `aligndev guide project`.");
101
+ }
102
+ return;
103
+ }
104
+ if (topic !== undefined && topic !== "code" && channel === undefined) {
105
+ throw new Error("Error: --channel is required with a playbook topic on the openclaw platform.");
106
+ }
68
107
  }
69
- function renderCodeTopic(config, ctx, profile) {
108
+ // Operators validate profiles through `guide code` outside any session; the app surface serves them.
109
+ function withCodeSurface(active) {
110
+ if (active.platform !== "openclaw" || active.surface !== undefined)
111
+ return active;
112
+ return { ...active, surface: "app" };
113
+ }
114
+ function renderCodeTopic(active, config, ctx, profile) {
70
115
  const report = readProjectReport(ctx.alignfirstCommand, ctx.cwd, ctx.env);
71
116
  if ("error" in report)
72
117
  throw new Error(report.error);
73
118
  const code = resolveCodeConfig(config, ctx.env, { project: report.aligndev, explicit: profile });
74
119
  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));
120
+ return renderCodeGuide(active, code.agent, models, code.defaultModel, ctx.forms, code.profile, describeNativeStorage(code));
76
121
  }
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
- });
122
+ // An entry topic prints after the playbook. Under codingAgent, the playbook topics read the
123
+ // project's guide file; no other guide has a condition block.
124
+ function renderPlaybookTopic(topic, active, config, ctx) {
125
+ assertPlaybookTopic(topic, active);
126
+ const topicActive = active.platform === "codingAgent" ? { ...active, guideFile: resolveGuideFile(ctx) } : active;
127
+ const text = renderPlaybookTemplate(topic, topicActive, config, ctx.forms);
128
+ if (!ENTRY_TOPICS.includes(topic))
129
+ return text;
130
+ return `${renderPlaybookTemplate(PLAYBOOK, topicActive, config, ctx.forms)}\n\n${text}`;
88
131
  }
89
- function assertPlaybookTopic(topic, platform) {
90
- const topics = PLAYBOOK_TOPICS[platform];
132
+ function assertPlaybookTopic(topic, active) {
133
+ const topics = PLAYBOOK_TOPICS[guideContextOf(active)];
91
134
  if (topics.includes(topic))
92
135
  return;
93
- const specialTopics = platform === "openclaw" ? ["code", "project"] : ["code"];
136
+ const surfaces = surfacesServing(topic);
137
+ if (active.surface !== undefined && surfaces.length > 0) {
138
+ throw new Error(`Error: guide topic "${topic}" is not served on the ${active.surface} surface. Surfaces: ${surfaces.join(", ")}.`);
139
+ }
140
+ const specialTopics = active.platform === "openclaw" ? ["code", "project"] : ["code"];
94
141
  throw new Error(`Error: unknown guide topic "${topic}". Topics: ${[...specialTopics, ...topics].join(", ")}.`);
95
142
  }
143
+ function renderPlaybookTemplate(name, active, config, forms) {
144
+ const template = `playbook/${name}.md`;
145
+ if (config.platform === "codingAgent")
146
+ return renderGuideTemplate(template, active, forms);
147
+ return renderGuideTemplate(template, active, forms, {
148
+ PROJECTS_ROOT: requireProjectsRoot(config).written,
149
+ });
150
+ }
@@ -1,11 +1,15 @@
1
1
  import type { CommandForms } from "../command-form.js";
2
2
  import { type Platform } from "../config.js";
3
+ export declare const SURFACES: readonly ["slack", "discord", "app"];
3
4
  declare const GUIDE_FILE_CONDITIONS: readonly ["developers", "readme", "noGuide"];
5
+ export type Surface = (typeof SURFACES)[number];
4
6
  export type GuideFileCondition = (typeof GUIDE_FILE_CONDITIONS)[number];
5
7
  export interface ActiveBlocks {
6
8
  platform: Platform;
9
+ surface?: Surface;
7
10
  guideFile?: GuideFileCondition;
8
11
  }
9
12
  export declare function renderGuideTemplate(name: string, active: ActiveBlocks, forms: CommandForms, values?: Readonly<Record<string, string>>): string;
10
13
  export declare function renderBlocks(text: string, active: ActiveBlocks, templateName: string): string;
14
+ export declare function isSurface(name: string): name is Surface;
11
15
  export {};