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
@@ -11,6 +11,7 @@ export interface SessionFrontmatter {
11
11
  meta: string | null;
12
12
  pid: number | null;
13
13
  pidStartTime: string | null;
14
+ machineId: string | null;
14
15
  cwd: string | null;
15
16
  startedAt: string;
16
17
  endedAt: string | null;
@@ -21,6 +22,7 @@ export interface SessionFrontmatter {
21
22
  }
22
23
  export declare const RESULT_MARKER = "\n---- Result ----\n";
23
24
  export declare function createSessionFile(sessionsDir: string, ticket: string | undefined, now: Date, frontmatter: SessionFrontmatter): string;
25
+ export declare function completedSessionPath(sessionFilePath: string): string;
24
26
  export declare function resolveSessionFilePath(sessionsDir: string, ticket: string | undefined, now: Date, fileExists?: (path: string) => boolean): string;
25
27
  export declare function writeInitialSessionFile(sessionFilePath: string, frontmatter: SessionFrontmatter): void;
26
28
  export interface CompletionUpdate {
@@ -34,20 +36,23 @@ export interface CompletionUpdate {
34
36
  contextTokensError?: string | null;
35
37
  }
36
38
  export declare function formatResults(earlier: readonly string[], last: string): string;
37
- export declare function applyCompletion(sessionFilePath: string, update: CompletionUpdate): void;
39
+ export declare function applyCompletion(sessionFilePath: string, update: CompletionUpdate): string;
38
40
  export declare function appendTranscript(sessionFilePath: string, text: string): void;
39
41
  export interface SessionCompletion {
40
42
  frontmatter: SessionFrontmatter;
41
43
  result: string | undefined;
42
44
  }
43
45
  export declare function readCompletion(sessionFilePath: string): SessionCompletion;
44
- export declare function reconcileSessionFile(sessionFilePath: string, now?: Date): SessionCompletion;
46
+ export interface ReconciledSession extends SessionCompletion {
47
+ path: string;
48
+ }
49
+ export declare function reconcileSessionFile(sessionFilePath: string, machineId: string, now?: Date): ReconciledSession;
45
50
  export declare function readPidStartTime(pid: number): string | null;
46
51
  export interface SessionRecord {
47
52
  path: string;
48
53
  frontmatter: SessionFrontmatter;
49
54
  }
50
- export declare function listSessionRecords(sessionsDir: string): SessionRecord[];
55
+ export declare function listSessionRecords(sessionsDir: string, machineId: string): SessionRecord[];
51
56
  export declare function findNewestSessionFile(dir: string): string | undefined;
52
57
  export declare function serializeFrontmatter(frontmatter: SessionFrontmatter): string;
53
58
  export declare function parseFrontmatter(block: string): SessionFrontmatter;
@@ -1,13 +1,19 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } from "node:fs";
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  export const RESULT_MARKER = "\n---- Result ----\n";
4
4
  const LATER_RESULT_SEPARATOR = "\n\n---- Later result ----\n\n";
5
+ // A run is written as `<stamp>.running.md` and renamed to `<stamp>.md` when it ends, so the
6
+ // work-files sync can leave running logs out by name. Records written before this convention keep
7
+ // their name and their `running` status until their run ends.
8
+ const RUNNING_SUFFIX = ".running.md";
5
9
  export function createSessionFile(sessionsDir, ticket, now, frontmatter) {
6
10
  const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
7
11
  mkdirSync(dir, { recursive: true });
8
12
  const stamp = formatStamp(now);
9
13
  for (let suffix = 1;; ++suffix) {
10
14
  const path = sessionFileCandidate(dir, stamp, suffix);
15
+ if (existsSync(completedSessionPath(path)))
16
+ continue;
11
17
  try {
12
18
  claimSessionFile(path, frontmatter);
13
19
  return path;
@@ -19,7 +25,12 @@ export function createSessionFile(sessionsDir, ticket, now, frontmatter) {
19
25
  }
20
26
  }
21
27
  function sessionFileCandidate(dir, stamp, suffix) {
22
- return join(dir, `${stamp}${suffix === 1 ? "" : `-${suffix}`}.md`);
28
+ return join(dir, `${stamp}${suffix === 1 ? "" : `-${suffix}`}${RUNNING_SUFFIX}`);
29
+ }
30
+ export function completedSessionPath(sessionFilePath) {
31
+ if (!sessionFilePath.endsWith(RUNNING_SUFFIX))
32
+ return sessionFilePath;
33
+ return `${sessionFilePath.slice(0, -RUNNING_SUFFIX.length)}.md`;
23
34
  }
24
35
  function claimSessionFile(path, frontmatter) {
25
36
  writeFileSync(path, `${serializeFrontmatter(frontmatter)}\n`, { flag: "wx" });
@@ -30,7 +41,8 @@ export function resolveSessionFilePath(sessionsDir, ticket, now, fileExists = ex
30
41
  const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
31
42
  const stamp = formatStamp(now);
32
43
  let suffix = 1;
33
- while (fileExists(sessionFileCandidate(dir, stamp, suffix)))
44
+ while (fileExists(sessionFileCandidate(dir, stamp, suffix)) ||
45
+ fileExists(completedSessionPath(sessionFileCandidate(dir, stamp, suffix))))
34
46
  ++suffix;
35
47
  return sessionFileCandidate(dir, stamp, suffix);
36
48
  }
@@ -43,8 +55,9 @@ export function writeInitialSessionFile(sessionFilePath, frontmatter) {
43
55
  export function formatResults(earlier, last) {
44
56
  return [...earlier, last].join(LATER_RESULT_SEPARATOR);
45
57
  }
46
- // Appends the result block, then rewrites the frontmatter in place. Append-first keeps the tailed
47
- // transcript intact until the single terminal rewrite.
58
+ // Appends the result block, then rewrites the frontmatter in place, then renames the file to its
59
+ // completed name. Returns that name. Append-first keeps the tailed transcript intact until the
60
+ // single terminal rewrite.
48
61
  export function applyCompletion(sessionFilePath, update) {
49
62
  const content = readFileSync(sessionFilePath, "utf-8");
50
63
  const { frontmatter, body } = splitSessionFile(content);
@@ -60,6 +73,10 @@ export function applyCompletion(sessionFilePath, update) {
60
73
  };
61
74
  const resultBlock = `${RESULT_MARKER}\n${update.result}\n`;
62
75
  writeFileSync(sessionFilePath, `${serializeFrontmatter(updated)}\n${body}${resultBlock}`);
76
+ const completedPath = completedSessionPath(sessionFilePath);
77
+ if (completedPath !== sessionFilePath)
78
+ renameSync(sessionFilePath, completedPath);
79
+ return completedPath;
63
80
  }
64
81
  export function appendTranscript(sessionFilePath, text) {
65
82
  writeFileSync(sessionFilePath, text, { flag: "a" });
@@ -76,13 +93,13 @@ export function readCompletion(sessionFilePath) {
76
93
  const result = markerIndex === -1 ? undefined : content.slice(markerIndex + RESULT_MARKER.length).trim();
77
94
  return { frontmatter, result };
78
95
  }
79
- export function reconcileSessionFile(sessionFilePath, now = new Date()) {
96
+ export function reconcileSessionFile(sessionFilePath, machineId, now = new Date()) {
80
97
  const completion = readCompletion(sessionFilePath);
81
- const update = interruptedCompletion(completion.frontmatter, now);
98
+ const update = interruptedCompletion(completion.frontmatter, machineId, now);
82
99
  if (!update)
83
- return completion;
84
- applyCompletion(sessionFilePath, update);
100
+ return { ...completion, path: sessionFilePath };
85
101
  return {
102
+ path: applyCompletion(sessionFilePath, update),
86
103
  frontmatter: {
87
104
  ...completion.frontmatter,
88
105
  status: update.status,
@@ -92,8 +109,10 @@ export function reconcileSessionFile(sessionFilePath, now = new Date()) {
92
109
  result: update.result,
93
110
  };
94
111
  }
95
- function interruptedCompletion(frontmatter, now) {
96
- if (frontmatter.status !== "running" || isRecordedProcessAlive(frontmatter))
112
+ function interruptedCompletion(frontmatter, machineId, now) {
113
+ if (frontmatter.status !== "running" ||
114
+ frontmatter.machineId !== machineId ||
115
+ !isRecordedProcessGone(frontmatter))
97
116
  return;
98
117
  return {
99
118
  status: "failed",
@@ -103,22 +122,19 @@ function interruptedCompletion(frontmatter, now) {
103
122
  result: `Sealed as interrupted: process ${frontmatter.pid ?? "(unknown)"} is gone.`,
104
123
  };
105
124
  }
106
- function isRecordedProcessAlive(frontmatter) {
107
- if (frontmatter.pid === null || !isPidAlive(frontmatter.pid))
125
+ function isRecordedProcessGone(frontmatter) {
126
+ if (frontmatter.pid === null)
108
127
  return false;
109
- if (frontmatter.pidStartTime === null)
110
- return true;
111
- const currentStartTime = readPidStartTime(frontmatter.pid);
112
- return currentStartTime === null || currentStartTime === frontmatter.pidStartTime;
113
- }
114
- function isPidAlive(pid) {
115
128
  try {
116
- process.kill(pid, 0);
117
- return true;
129
+ process.kill(frontmatter.pid, 0);
118
130
  }
119
- catch (err) {
120
- return err.code !== "ESRCH";
131
+ catch (error) {
132
+ return error instanceof Error && "code" in error && error.code === "ESRCH";
121
133
  }
134
+ if (frontmatter.pidStartTime === null)
135
+ return false;
136
+ const currentStartTime = readPidStartTime(frontmatter.pid);
137
+ return currentStartTime !== null && currentStartTime !== frontmatter.pidStartTime;
122
138
  }
123
139
  export function readPidStartTime(pid) {
124
140
  if (process.platform !== "linux")
@@ -135,10 +151,9 @@ export function readPidStartTime(pid) {
135
151
  // Lists every active session record: `<sessionsDir>/_aligndev/*.md` plus
136
152
  // `<sessionsDir>/<ticket>/_aligndev/*.md`. Archived tickets move under `_archives/` and leave the
137
153
  // registry. The session files are the registry — no separate registry file.
138
- // Self-healing: a `running` record whose pid is gone is a stale leftover from an interrupted run;
139
- // it gets sealed in passing so the launch guards never block on dead state. The returned records
140
- // reflect the post-healing state.
141
- export function listSessionRecords(sessionsDir) {
154
+ // Seals only this installation's conclusively dead runs. Foreign, legacy and uncertain records
155
+ // stay untouched and continue to block launches.
156
+ export function listSessionRecords(sessionsDir, machineId) {
142
157
  const sessionDirs = [join(sessionsDir, "_aligndev")];
143
158
  for (const entry of readEntries(sessionsDir)) {
144
159
  if (entry.isDirectory() && !entry.name.startsWith("_")) {
@@ -150,10 +165,9 @@ export function listSessionRecords(sessionsDir) {
150
165
  for (const entry of readEntries(dir)) {
151
166
  if (!entry.isFile() || !entry.name.endsWith(".md"))
152
167
  continue;
153
- const path = join(dir, entry.name);
154
- const completion = reconcileSessionFileOrSkip(path);
168
+ const completion = reconcileSessionFileOrSkip(join(dir, entry.name), machineId);
155
169
  if (completion)
156
- records.push({ path, frontmatter: completion.frontmatter });
170
+ records.push({ path: completion.path, frontmatter: completion.frontmatter });
157
171
  }
158
172
  }
159
173
  return records;
@@ -165,7 +179,7 @@ export function findNewestSessionFile(dir) {
165
179
  for (const entry of readEntries(dir)) {
166
180
  if (!entry.isFile())
167
181
  continue;
168
- const match = /^(\d{8}-\d{6})(?:-(\d+))?\.md$/.exec(entry.name);
182
+ const match = /^(\d{8}-\d{6})(?:-(\d+))?(?:\.running)?\.md$/.exec(entry.name);
169
183
  if (!match)
170
184
  continue;
171
185
  const stamp = match[1];
@@ -189,9 +203,9 @@ function readEntries(dir) {
189
203
  }
190
204
  }
191
205
  // A malformed file (e.g. missing its frontmatter block) must not block every future launch.
192
- function reconcileSessionFileOrSkip(path) {
206
+ function reconcileSessionFileOrSkip(path, machineId) {
193
207
  try {
194
- return reconcileSessionFile(path);
208
+ return reconcileSessionFile(path, machineId);
195
209
  }
196
210
  catch {
197
211
  return;
@@ -239,6 +253,7 @@ export function parseFrontmatter(block) {
239
253
  meta: map.meta ?? null,
240
254
  pid: parsePid(map.pid),
241
255
  pidStartTime: map.pidStartTime ?? null,
256
+ machineId: map.machineId ?? null,
242
257
  cwd: map.cwd ?? null,
243
258
  startedAt: map.startedAt ?? "",
244
259
  endedAt: map.endedAt ?? null,
@@ -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 {};
@@ -1,27 +1,43 @@
1
1
  import { PLATFORMS } from "../config.js";
2
2
  import { readTemplate } from "../templates.js";
3
+ export const SURFACES = ["slack", "discord", "app"];
3
4
  const GUIDE_FILE_CONDITIONS = ["developers", "readme", "noGuide"];
4
5
  // Active for both guide files: `developers` and `readme`.
5
6
  const HAS_GUIDE = "hasGuide";
7
+ // Derived facts: `thread` holds on Slack and Discord; `conversation` in an app conversation and
8
+ // under codingAgent.
9
+ const THREAD = "thread";
10
+ const CONVERSATION = "conversation";
6
11
  const MARKER = /^\{\{([#/])([A-Za-z]+)\}\}$/;
7
- // Renders `templates/guide/<name>`: the blocks first, then the placeholders — the command forms
8
- // and every key of `values`.
12
+ // Renders `templates/guide/<name>`: the blocks first, then the placeholders — the command forms,
13
+ // the guide command of the render, and every key of `values`.
9
14
  export function renderGuideTemplate(name, active, forms, values = {}) {
10
15
  const placeholders = {
11
16
  ALIGNDEV: forms.aligndev,
12
17
  ALIGNFIRST: forms.alignfirst,
18
+ ...guidePlaceholder(active, forms),
19
+ BACKGROUND_COMMAND_JSON: JSON.stringify(`${forms.aligndev} code new --message-file '/tmp/aligndev-request.txt' --quiet --meta 'a20bc7c1-c056-4d07-8cc2-90fe491a6df6'`),
13
20
  ...values,
14
21
  };
15
22
  let text = renderBlocks(readTemplate(`guide/${name}`), active, name);
16
23
  for (const [key, value] of Object.entries(placeholders)) {
17
- text = text.replaceAll(`{{${key}}}`, value);
24
+ text = text.replaceAll(`{{${key}}}`, () => value);
18
25
  }
19
26
  return text.trimEnd();
20
27
  }
21
- // A block is `{{#<name>}}` … `{{/<name>}}`, each marker alone on its line. A platform block sits
22
- // at the top level; a condition block sits directly inside a `codingAgent` block. A line
23
- // is kept when every block around it is active. The runs of empty lines that removed blocks leave
24
- // collapse to one.
28
+ // `{{GUIDE}}` carries the surface into every later guide call. An OpenClaw render without a surface
29
+ // has none.
30
+ function guidePlaceholder(active, forms) {
31
+ if (active.surface !== undefined) {
32
+ return { GUIDE: `${forms.aligndev} guide --channel ${active.surface}` };
33
+ }
34
+ return active.platform === "codingAgent" ? { GUIDE: `${forms.aligndev} guide` } : {};
35
+ }
36
+ // A block is `{{#<name>}}` … `{{/<name>}}`, each marker alone on its line, and names a fact. A
37
+ // platform block sits at the top level. A surface block and `thread` never sit inside a
38
+ // `codingAgent` block; a condition block always does, at any depth; `conversation` sits anywhere.
39
+ // A line is kept when every block around it holds. The runs of empty lines that removed blocks
40
+ // leave collapse to one.
25
41
  export function renderBlocks(text, active, templateName) {
26
42
  const kept = [];
27
43
  const open = [];
@@ -46,20 +62,34 @@ export function renderBlocks(text, active, templateName) {
46
62
  return collapseEmptyLines(kept).join("\n");
47
63
  }
48
64
  function isActive(name, active) {
65
+ if (name === THREAD)
66
+ return active.surface === "slack" || active.surface === "discord";
67
+ if (name === CONVERSATION)
68
+ return active.surface === "app" || active.platform === "codingAgent";
49
69
  if (name === HAS_GUIDE)
50
70
  return active.guideFile === "developers" || active.guideFile === "readme";
51
- return name === active.platform || name === active.guideFile;
71
+ return name === active.platform || name === active.surface || name === active.guideFile;
52
72
  }
53
73
  function openBlock(name, line, open, templateName) {
54
- const outer = open.at(-1);
74
+ const insideCodingAgent = open.some((block) => block.name === "codingAgent");
55
75
  if (isPlatform(name)) {
76
+ const outer = open.at(-1);
56
77
  if (outer !== undefined) {
57
78
  throw blockError(templateName, line, `platform block "${name}" inside "${outer.name}"`);
58
79
  }
59
80
  return { name, line };
60
81
  }
82
+ if (isSurface(name) || name === THREAD) {
83
+ if (insideCodingAgent) {
84
+ const block = isSurface(name) ? `surface block "${name}"` : `block "${name}"`;
85
+ throw blockError(templateName, line, `${block} inside a codingAgent block`);
86
+ }
87
+ return { name, line };
88
+ }
89
+ if (name === CONVERSATION)
90
+ return { name, line };
61
91
  if (isCondition(name)) {
62
- if (outer?.name !== "codingAgent") {
92
+ if (!insideCodingAgent) {
63
93
  throw blockError(templateName, line, `condition block "${name}" outside a codingAgent block`);
64
94
  }
65
95
  return { name, line };
@@ -67,17 +97,26 @@ function openBlock(name, line, open, templateName) {
67
97
  throw blockError(templateName, line, `unknown block "${name}"`);
68
98
  }
69
99
  function closeBlock(name, line, open, templateName) {
70
- if (!isPlatform(name) && !isCondition(name)) {
100
+ if (!isBlockName(name))
71
101
  throw blockError(templateName, line, `unknown block "${name}"`);
72
- }
73
102
  if (open.at(-1)?.name !== name) {
74
103
  throw blockError(templateName, line, `closing marker "${name}" without its block`);
75
104
  }
76
105
  open.pop();
77
106
  }
107
+ function isBlockName(name) {
108
+ return (isPlatform(name) ||
109
+ isSurface(name) ||
110
+ name === THREAD ||
111
+ name === CONVERSATION ||
112
+ isCondition(name));
113
+ }
78
114
  function isPlatform(name) {
79
115
  return PLATFORMS.includes(name);
80
116
  }
117
+ export function isSurface(name) {
118
+ return SURFACES.includes(name);
119
+ }
81
120
  function isCondition(name) {
82
121
  return name === HAS_GUIDE || GUIDE_FILE_CONDITIONS.includes(name);
83
122
  }
@@ -1,3 +1,8 @@
1
- import type { Platform } from "../config.js";
2
- export declare const PLAYBOOK_DISPATCHER = "playbook";
3
- export declare const PLAYBOOK_TOPICS: Record<Platform, readonly string[]>;
1
+ import { type ActiveBlocks, type Surface } from "./render-template.js";
2
+ export declare const PLAYBOOK_DISPATCHER = "dispatcher";
3
+ export declare const PLAYBOOK = "playbook";
4
+ export declare const ENTRY_TOPICS: readonly string[];
5
+ export declare const PLAYBOOK_TOPICS: Record<GuideContext, readonly string[]>;
6
+ export type GuideContext = "thread" | "app" | "codingAgent";
7
+ export declare function guideContextOf(active: ActiveBlocks): GuideContext;
8
+ export declare function surfacesServing(topic: string): Surface[];