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
@@ -1,17 +1,36 @@
1
- // The template rendered by `aligndev guide` without a topic.
2
- export const PLAYBOOK_DISPATCHER = "playbook";
3
- // The playbook topics each platform serves. Every topic is one file of `templates/guide/playbook/`,
4
- // shared by the platforms through platform blocks.
1
+ import { SURFACES } from "./render-template.js";
2
+ // `templates/guide/playbook/dispatcher.md`, printed by `aligndev guide` without a topic.
3
+ export const PLAYBOOK_DISPATCHER = "dispatcher";
4
+ // `templates/guide/playbook/playbook.md`, the operating instructions.
5
+ export const PLAYBOOK = "playbook";
6
+ // The topics printed after the playbook.
7
+ export const ENTRY_TOPICS = ["working-session", "channel-handling"];
8
+ // The playbook topics each context serves. Every topic is one file of `templates/guide/playbook/`,
9
+ // shared by the contexts through fact blocks.
5
10
  export const PLAYBOOK_TOPICS = {
6
- openclaw: [
11
+ thread: [
7
12
  "channel-handling",
8
13
  "working-session",
9
14
  "work-files-setup",
10
15
  "project-workspace-setup",
11
16
  "project-lifecycle",
12
17
  "consultation",
13
- "slack-message-tool",
14
- "discord-message-tool",
18
+ "message-tool",
19
+ ],
20
+ app: [
21
+ "working-session",
22
+ "work-files-setup",
23
+ "project-workspace-setup",
24
+ "project-lifecycle",
25
+ "consultation",
15
26
  ],
16
27
  codingAgent: ["working-session", "work-files-setup", "project-workspace-setup", "consultation"],
17
28
  };
29
+ export function guideContextOf(active) {
30
+ if (active.platform === "codingAgent")
31
+ return "codingAgent";
32
+ return active.surface === "app" ? "app" : "thread";
33
+ }
34
+ export function surfacesServing(topic) {
35
+ return SURFACES.filter((surface) => PLAYBOOK_TOPICS[guideContextOf({ platform: "openclaw", surface })].includes(topic));
36
+ }
@@ -26,7 +26,7 @@ export function validateEffectivePlans(ctx) {
26
26
  return value.plans.target;
27
27
  }
28
28
  catch (error) {
29
- throw new Error(`${errorMessage(error)}\nSee \`${ctx.forms.aligndev} guide work-files-setup\` for authorized preparation.`);
29
+ throw new Error(`${errorMessage(error)}\nSee the \`work-files-setup\` topic of \`${ctx.forms.aligndev} guide\` for authorized preparation.`);
30
30
  }
31
31
  }
32
32
  function isRecord(value) {
@@ -1,4 +1,5 @@
1
- import { type Repository, type Worktree } from "./git.js";
1
+ import { type Repository } from "./git.js";
2
+ import { type WorktreeReport } from "./setup.js";
2
3
  import type { WorktreeContext } from "./worktree-cli.js";
3
4
  export interface AddOptions {
4
5
  path: string;
@@ -6,15 +7,4 @@ export interface AddOptions {
6
7
  newBranch: boolean;
7
8
  start?: string;
8
9
  }
9
- export interface AddReport {
10
- mainWorktree: string;
11
- worktree: Worktree;
12
- directories: Record<".local" | ".plans", DirectoryReport>;
13
- warnings: string[];
14
- }
15
- export interface DirectoryReport {
16
- path: string;
17
- mode: "symlink" | "tracked" | "companion" | "absent";
18
- target: string | null;
19
- }
20
- export declare function addWorktree(ctx: WorktreeContext, repo: Repository, options: AddOptions): AddReport;
10
+ export declare function addWorktree(ctx: WorktreeContext, repo: Repository, options: AddOptions): WorktreeReport;
@@ -1,22 +1,18 @@
1
- import { appendFileSync, mkdirSync, readFileSync, realpathSync, statSync, symlinkSync, } from "node:fs";
2
- import { dirname, join, resolve } from "node:path";
1
+ import { statSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
3
  import { errorMessage } from "../errors.js";
4
- import { readReport, validateEffectivePlans } from "../project/plans.js";
5
- import { canonicalPath, git, isInside, isProjectTrackedDirectory, pathExists, readRepository, } from "./git.js";
4
+ import { canonicalPath, git, isInside, pathExists } from "./git.js";
5
+ import { finishSetup, prepareDirectories, } from "./setup.js";
6
6
  export function addWorktree(ctx, repo, options) {
7
7
  const prepared = prepareAdd(ctx, repo, options);
8
8
  createGitWorktree(ctx, options, prepared);
9
- return finishSetup(ctx, repo, options, prepared);
9
+ return finishSetup(ctx, repo, prepared.destination, { directories: prepared.directories, warnings: prepared.warnings }, options.branch);
10
10
  }
11
11
  function prepareAdd(ctx, repo, options) {
12
12
  const destination = validateDestination(ctx, repo, options.path);
13
13
  const branch = prepareBranch(ctx, repo, options);
14
- const sourceCtx = { ...ctx, cwd: repo.mainWorktree };
15
- const sourceReport = readReport(sourceCtx);
16
- const plansTarget = validateEffectivePlans(sourceCtx);
17
- const warnings = [];
18
- const directories = planDirectories(sourceCtx, repo, destination, branch.commit, sourceReport, plansTarget, warnings);
19
- return { destination, branch, directories, warnings };
14
+ const prepared = prepareDirectories(ctx, repo, destination, branch.commit);
15
+ return { destination, branch, ...prepared };
20
16
  }
21
17
  function validateDestination(ctx, repo, input) {
22
18
  const literal = resolve(ctx.cwd, input);
@@ -71,42 +67,6 @@ function prepareBranch(ctx, repo, options) {
71
67
  const commit = git(ctx, "rev-parse", "--verify", "--end-of-options", `${start}^{commit}`).trim();
72
68
  return { create, start: !create ? options.branch : start, commit, track };
73
69
  }
74
- function planDirectories(ctx, repo, destination, commit, report, plansTarget, warnings) {
75
- const local = planLocal(ctx, repo, destination, commit, warnings);
76
- const plans = report.locations[".plans"];
77
- if (plans.in === "companion") {
78
- return { ".local": local, ".plans": { path: plans.path, mode: "companion", target: null } };
79
- }
80
- if (targetTracks(ctx, commit, ".plans")) {
81
- throw new Error(`Target commit tracks .plans. See \`${ctx.forms.aligndev} guide work-files-setup\` for authorized preparation.`);
82
- }
83
- return {
84
- ".local": local,
85
- ".plans": { path: join(destination, ".plans"), mode: "symlink", target: plansTarget },
86
- };
87
- }
88
- function planLocal(ctx, repo, destination, commit, warnings) {
89
- const path = join(destination, ".local");
90
- if (targetTracks(ctx, commit, ".local")) {
91
- warnings.push("Target branch tracks .local; it remains branch-local and is not shared.");
92
- return { path, mode: "tracked", target: null };
93
- }
94
- const source = join(repo.mainWorktree, ".local");
95
- if (!pathExists(source))
96
- return { path, mode: "absent", target: null };
97
- if (!statSync(source).isDirectory())
98
- throw new Error(`Source is not a usable directory: ${source}`);
99
- const target = realpathSync(source);
100
- if (isProjectTrackedDirectory(ctx, source, repo.commonDir)) {
101
- warnings.push("Main-worktree .local belongs to tracked content on another branch; leaving .local absent.");
102
- return { path, mode: "absent", target: null };
103
- }
104
- return { path, mode: "symlink", target };
105
- }
106
- function targetTracks(ctx, commit, path) {
107
- return (git(ctx, "--literal-pathspecs", "ls-tree", "-r", "--name-only", "-z", commit, "--", path)
108
- .length > 0);
109
- }
110
70
  function createGitWorktree(ctx, options, prepared) {
111
71
  const { branch, destination } = prepared;
112
72
  const createArgs = branch.create
@@ -119,57 +79,3 @@ function createGitWorktree(ctx, options, prepared) {
119
79
  throw new Error(`Git worktree creation failed: ${errorMessage(error)}\nInspect ${destination} and branch ${options.branch} for partial effects before retrying. No rollback was attempted.`);
120
80
  }
121
81
  }
122
- function finishSetup(ctx, repo, options, prepared) {
123
- const { destination, directories, warnings } = prepared;
124
- let step = "directory links and local Git exclusions";
125
- try {
126
- const targetCtx = { ...ctx, cwd: destination };
127
- createLinks(targetCtx, repo, directories);
128
- step = "effective work-files verification";
129
- validateEffectivePlans(targetCtx);
130
- const worktree = readRepository(targetCtx).worktrees.find((tree) => tree.path === destination);
131
- if (worktree === undefined || worktree.branch !== options.branch) {
132
- throw new Error("Created worktree does not have the requested branch in Git's registry.");
133
- }
134
- return { mainWorktree: repo.mainWorktree, worktree, directories, warnings };
135
- }
136
- catch (error) {
137
- throw new Error(`Worktree setup failed during ${step}: ${errorMessage(error)}\n` +
138
- `Retained worktree ${destination} and branch ${options.branch}. Inspect and repair the failed step manually, ` +
139
- `or remove it with \`${ctx.forms.aligndev} worktree remove ${quotePath(destination)}\` after preserving any work. No rollback was attempted.`);
140
- }
141
- }
142
- function quotePath(path) {
143
- return `'${path.replaceAll("'", "'\\''")}'`;
144
- }
145
- function createLinks(ctx, repo, directories) {
146
- const links = Object.entries(directories).filter(([, directory]) => directory.mode === "symlink");
147
- if (links.length === 0)
148
- return;
149
- for (const [name, directory] of links) {
150
- if (directory.target === null)
151
- throw new Error("Missing symlink target.");
152
- symlinkSync(join(repo.mainWorktree, name), directory.path, "dir");
153
- }
154
- const exclude = git({ ...ctx, cwd: repo.mainWorktree }, "rev-parse", "--path-format=absolute", "--git-path", "info/exclude").trim();
155
- let content = pathExists(exclude) ? readFileSync(exclude, "utf8") : "";
156
- for (const [name] of links) {
157
- const pattern = `/${name}`;
158
- if (!content.split(/\r?\n/u).includes(pattern)) {
159
- mkdirSync(dirname(exclude), { recursive: true });
160
- const addition = `${content.endsWith("\n") || content === "" ? "" : "\n"}${pattern}\n`;
161
- appendFileSync(exclude, addition);
162
- content += addition;
163
- }
164
- }
165
- for (const [name, directory] of links) {
166
- try {
167
- git(ctx, "check-ignore", "-q", "--", name);
168
- }
169
- catch {
170
- throw new Error(`Generated link ${directory.path} is not ignored. Inspect conflicting tracked ignore rules; they were not edited.`);
171
- }
172
- if (realpathSync(directory.path) !== directory.target)
173
- throw new Error(`Link target changed: ${directory.path}`);
174
- }
175
- }
@@ -0,0 +1,18 @@
1
+ import { type Repository, type Worktree } from "./git.js";
2
+ import type { WorktreeContext } from "./worktree-cli.js";
3
+ export interface DirectoryPreparation {
4
+ directories: Record<".local" | ".plans", DirectoryReport>;
5
+ warnings: string[];
6
+ }
7
+ export interface DirectoryReport {
8
+ path: string;
9
+ mode: "directory" | "symlink" | "tracked" | "companion" | "absent";
10
+ target: string | null;
11
+ }
12
+ export interface WorktreeReport extends DirectoryPreparation {
13
+ mainWorktree: string;
14
+ worktree: Worktree;
15
+ }
16
+ export declare function setupWorktree(ctx: WorktreeContext, repo: Repository, input?: string): WorktreeReport;
17
+ export declare function prepareDirectories(ctx: WorktreeContext, repo: Repository, destination: string, commit: string, includeIndex?: boolean): DirectoryPreparation;
18
+ export declare function finishSetup(ctx: WorktreeContext, repo: Repository, destination: string, prepared: DirectoryPreparation, expectedBranch?: string): WorktreeReport;
@@ -0,0 +1,192 @@
1
+ import { appendFileSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, symlinkSync, } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { errorMessage } from "../errors.js";
4
+ import { readReport, validateEffectivePlans } from "../project/plans.js";
5
+ import { canonicalPath, git, isProjectTrackedDirectory, pathExists, readRepository, } from "./git.js";
6
+ export function setupWorktree(ctx, repo, input) {
7
+ const worktree = selectWorktree(ctx, repo, input);
8
+ let prepared;
9
+ try {
10
+ if (worktree.main)
11
+ return reportMain(ctx, repo, worktree);
12
+ prepared = prepareDirectories(ctx, repo, worktree.path, "HEAD", true);
13
+ }
14
+ catch (error) {
15
+ throw setupFailure(ctx, worktree.path, "directory preparation", error);
16
+ }
17
+ return finishSetup(ctx, repo, worktree.path, prepared);
18
+ }
19
+ function selectWorktree(ctx, repo, input) {
20
+ const path = canonicalPath(input === undefined ? git(ctx, "rev-parse", "--show-toplevel").trim() : resolve(ctx.cwd, input));
21
+ const worktree = repo.worktrees.find((tree) => tree.path === path);
22
+ if (worktree === undefined || !worktree.exists || !pathExists(path)) {
23
+ throw new Error(`Setup requires an existing registered worktree root of this repository: ${path}`);
24
+ }
25
+ const targetCtx = { ...ctx, cwd: path };
26
+ const targetRepo = readRepository(targetCtx);
27
+ if (targetRepo.commonDir !== repo.commonDir ||
28
+ canonicalPath(git(targetCtx, "rev-parse", "--show-toplevel").trim()) !== path) {
29
+ throw new Error(`Setup requires an exact registered worktree root: ${path}`);
30
+ }
31
+ return worktree;
32
+ }
33
+ function reportMain(ctx, repo, worktree) {
34
+ const sourceCtx = { ...ctx, cwd: repo.mainWorktree };
35
+ const report = readReport(sourceCtx);
36
+ validateEffectivePlans(sourceCtx);
37
+ const plans = report.locations[".plans"];
38
+ return {
39
+ mainWorktree: repo.mainWorktree,
40
+ worktree,
41
+ directories: {
42
+ ".local": describeDirectory(join(repo.mainWorktree, ".local")),
43
+ ".plans": plans.in === "companion"
44
+ ? { path: plans.path, mode: "companion", target: null }
45
+ : describeDirectory(plans.path),
46
+ },
47
+ warnings: [],
48
+ };
49
+ }
50
+ function describeDirectory(path) {
51
+ if (!pathExists(path))
52
+ return { path, mode: "absent", target: null };
53
+ if (!statSync(path).isDirectory())
54
+ throw new Error(`Source is not a usable directory: ${path}`);
55
+ return lstatSync(path).isSymbolicLink()
56
+ ? { path, mode: "symlink", target: realpathSync(path) }
57
+ : { path, mode: "directory", target: null };
58
+ }
59
+ export function prepareDirectories(ctx, repo, destination, commit, includeIndex = false) {
60
+ const sourceCtx = { ...ctx, cwd: repo.mainWorktree };
61
+ const report = readReport(sourceCtx);
62
+ const plansTarget = validateEffectivePlans(sourceCtx);
63
+ const targetCtx = includeIndex ? { ...ctx, cwd: destination } : sourceCtx;
64
+ const warnings = [];
65
+ const local = planLocal(sourceCtx, targetCtx, repo, destination, commit, includeIndex, warnings);
66
+ const plans = report.locations[".plans"];
67
+ if (plans.in === "companion") {
68
+ return {
69
+ directories: {
70
+ ".local": local,
71
+ ".plans": { path: plans.path, mode: "companion", target: null },
72
+ },
73
+ warnings,
74
+ };
75
+ }
76
+ if (targetTracks(targetCtx, commit, ".plans", includeIndex)) {
77
+ throw new Error(`Target commit${includeIndex ? " or index" : ""} tracks .plans. See the \`work-files-setup\` topic of \`${ctx.forms.aligndev} guide\` for authorized preparation.`);
78
+ }
79
+ return {
80
+ directories: {
81
+ ".local": local,
82
+ ".plans": { path: join(destination, ".plans"), mode: "symlink", target: plansTarget },
83
+ },
84
+ warnings,
85
+ };
86
+ }
87
+ function planLocal(sourceCtx, targetCtx, repo, destination, commit, includeIndex, warnings) {
88
+ const path = join(destination, ".local");
89
+ if (targetTracks(targetCtx, commit, ".local", includeIndex)) {
90
+ warnings.push("Target branch tracks .local; it remains branch-local and is not shared.");
91
+ return { path, mode: "tracked", target: null };
92
+ }
93
+ const source = join(repo.mainWorktree, ".local");
94
+ if (!pathExists(source))
95
+ return { path, mode: "absent", target: null };
96
+ if (!statSync(source).isDirectory())
97
+ throw new Error(`Source is not a usable directory: ${source}`);
98
+ const target = realpathSync(source);
99
+ if (isProjectTrackedDirectory(sourceCtx, source, repo.commonDir)) {
100
+ warnings.push("Main-worktree .local belongs to tracked content on another branch; leaving .local absent.");
101
+ return { path, mode: "absent", target: null };
102
+ }
103
+ return { path, mode: "symlink", target };
104
+ }
105
+ function targetTracks(ctx, commit, path, includeIndex) {
106
+ return (git(ctx, "--literal-pathspecs", "ls-tree", "-r", "--name-only", "-z", commit, "--", path)
107
+ .length > 0 ||
108
+ (includeIndex && git(ctx, "--literal-pathspecs", "ls-files", "-z", "--", path).length > 0));
109
+ }
110
+ export function finishSetup(ctx, repo, destination, prepared, expectedBranch) {
111
+ let step = "directory conflict checks";
112
+ try {
113
+ const targetCtx = { ...ctx, cwd: destination };
114
+ checkDestinations(prepared.directories);
115
+ step = "directory links and local Git exclusions";
116
+ applyDirectories(targetCtx, repo, prepared.directories);
117
+ step = "effective work-files verification";
118
+ validateEffectivePlans(targetCtx);
119
+ const worktree = readRepository(targetCtx).worktrees.find((tree) => tree.path === destination);
120
+ if (worktree === undefined ||
121
+ (expectedBranch !== undefined && worktree.branch !== expectedBranch)) {
122
+ throw new Error("Worktree does not have the requested branch in Git's registry.");
123
+ }
124
+ return { mainWorktree: repo.mainWorktree, worktree, ...prepared };
125
+ }
126
+ catch (error) {
127
+ throw setupFailure(ctx, destination, step, error, expectedBranch);
128
+ }
129
+ }
130
+ function checkDestinations(directories) {
131
+ for (const directory of Object.values(directories)) {
132
+ if (directory.mode !== "symlink")
133
+ continue;
134
+ if (directory.target === null)
135
+ throw new Error("Missing symlink target.");
136
+ if (!pathExists(directory.path))
137
+ continue;
138
+ if (lstatSync(directory.path).isSymbolicLink()) {
139
+ try {
140
+ if (realpathSync(directory.path) === directory.target)
141
+ continue;
142
+ }
143
+ catch {
144
+ // Broken and cyclic links are conflicts, not missing destinations.
145
+ }
146
+ }
147
+ throw new Error(`Conflicting shared directory destination: ${directory.path}. Existing content was preserved.`);
148
+ }
149
+ }
150
+ function applyDirectories(ctx, repo, directories) {
151
+ const links = Object.entries(directories).filter(([, directory]) => directory.mode === "symlink");
152
+ if (links.length === 0)
153
+ return;
154
+ for (const [name, directory] of links) {
155
+ if (!pathExists(directory.path))
156
+ symlinkSync(join(repo.mainWorktree, name), directory.path, "dir");
157
+ }
158
+ ensureExclusions(ctx, repo, links.map(([name]) => name));
159
+ for (const [name, directory] of links) {
160
+ try {
161
+ git(ctx, "check-ignore", "-q", "--", name);
162
+ }
163
+ catch {
164
+ throw new Error(`Generated link ${directory.path} is not ignored. Inspect conflicting tracked ignore rules; they were not edited.`);
165
+ }
166
+ if (realpathSync(directory.path) !== directory.target)
167
+ throw new Error(`Link target changed: ${directory.path}`);
168
+ }
169
+ }
170
+ function ensureExclusions(ctx, repo, names) {
171
+ const exclude = git({ ...ctx, cwd: repo.mainWorktree }, "rev-parse", "--path-format=absolute", "--git-path", "info/exclude").trim();
172
+ let content = pathExists(exclude) ? readFileSync(exclude, "utf8") : "";
173
+ for (const name of names) {
174
+ const pattern = `/${name}`;
175
+ if (content.split(/\r?\n/u).includes(pattern))
176
+ continue;
177
+ mkdirSync(dirname(exclude), { recursive: true });
178
+ const addition = `${content.endsWith("\n") || content === "" ? "" : "\n"}${pattern}\n`;
179
+ appendFileSync(exclude, addition);
180
+ content += addition;
181
+ }
182
+ }
183
+ function setupFailure(ctx, destination, step, error, branch) {
184
+ const quoted = `'${destination.replaceAll("'", "'\\''")}'`;
185
+ return new Error(`Worktree setup failed during ${step}: ${errorMessage(error)}\n` +
186
+ `Retained worktree ${destination}${branch === undefined ? " and its Git state" : ` and branch ${branch}`}. ` +
187
+ `Inspect and repair the failed step manually, then retry with \`${ctx.forms.aligndev} worktree setup ${quoted}\`.` +
188
+ (branch === undefined
189
+ ? ""
190
+ : ` Or remove it with \`${ctx.forms.aligndev} worktree remove ${quoted}\` after preserving any work.`) +
191
+ " No rollback was attempted.");
192
+ }
@@ -2,6 +2,7 @@ import { parseArgs } from "node:util";
2
2
  import { addWorktree } from "./add.js";
3
3
  import { readRepository } from "./git.js";
4
4
  import { removeWorktree } from "./remove.js";
5
+ import { setupWorktree } from "./setup.js";
5
6
  export function runWorktree(tokens, ctx) {
6
7
  const command = parseWorktreeArgs(tokens, ctx.forms.aligndev);
7
8
  if (command.kind === "help") {
@@ -19,10 +20,12 @@ export function runWorktree(tokens, ctx) {
19
20
  ctx.stdout.write(command.json ? json(report) : `Removed ${report.path}; branch preserved.\n`);
20
21
  return 0;
21
22
  }
22
- const report = addWorktree(ctx, repo, command.options);
23
+ const report = command.kind === "setup"
24
+ ? setupWorktree(ctx, repo, command.path)
25
+ : addWorktree(ctx, repo, command.options);
23
26
  for (const warning of report.warnings)
24
27
  ctx.stderr.write(`Warning: ${warning}\n`);
25
- ctx.stdout.write(command.json ? json(report) : renderAdd(report));
28
+ ctx.stdout.write(command.json ? json(report) : renderReady(report));
26
29
  return 0;
27
30
  }
28
31
  function parseWorktreeArgs(tokens, aligndev) {
@@ -32,7 +35,7 @@ function parseWorktreeArgs(tokens, aligndev) {
32
35
  throw new Error("Unexpected worktree help arguments.");
33
36
  return { kind: "help" };
34
37
  }
35
- if (command !== "add" && command !== "list" && command !== "remove") {
38
+ if (command !== "add" && command !== "setup" && command !== "list" && command !== "remove") {
36
39
  throw new Error(`Unknown worktree command: ${command}`);
37
40
  }
38
41
  const { values, positionals } = parseArgs({
@@ -50,12 +53,18 @@ function parseWorktreeArgs(tokens, aligndev) {
50
53
  const newBranch = typeof values.b === "string" ? values.b : undefined;
51
54
  const count = positionals.length;
52
55
  const expected = command === "list" ? 0 : command === "remove" ? 1 : 2;
53
- const validCount = command === "add" && newBranch !== undefined ? count === 1 || count === 2 : count === expected;
56
+ const validCount = command === "setup"
57
+ ? count <= 1
58
+ : command === "add" && newBranch !== undefined
59
+ ? count === 1 || count === 2
60
+ : count === expected;
54
61
  if (!validCount) {
55
62
  throw new Error(`Invalid arguments. Run \`${aligndev} worktree ${command} --help\`.`);
56
63
  }
57
64
  if (command === "list")
58
65
  return { kind: "list", json: values.json };
66
+ if (command === "setup")
67
+ return { kind: "setup", path: positionals[0], json: values.json };
59
68
  const path = positionals[0];
60
69
  if (path === undefined)
61
70
  throw new Error("A worktree path is required.");
@@ -83,9 +92,9 @@ function renderList(worktrees) {
83
92
  .map((tree) => `${tree.path} [${tree.branch ?? "detached"}]${tree.main ? " main" : ""}${tree.exists ? "" : " missing"}${tree.locked ? " locked" : ""}${tree.prunable ? " prunable" : ""}\n`)
84
93
  .join("");
85
94
  }
86
- function renderAdd(report) {
95
+ function renderReady(report) {
87
96
  return [
88
- `Worktree ready: ${report.worktree.path} [${report.worktree.branch}]`,
97
+ `Worktree ready: ${report.worktree.path} [${report.worktree.branch ?? "detached"}]`,
89
98
  ...Object.entries(report.directories).map(([name, directory]) => `${name}: ${directory.mode} ${directory.path}${directory.target === null ? "" : ` -> ${directory.target}`}`),
90
99
  "Readiness covers Git and work files only; follow the project's install/build/test procedure.",
91
100
  "",
@@ -95,6 +104,7 @@ function renderHelp(command) {
95
104
  return `Usage:
96
105
  ${command} worktree add <path> <branch> [--json]
97
106
  ${command} worktree add <path> -b <branch> [<start-point>] [--json]
107
+ ${command} worktree setup [<path>] [--json]
98
108
  ${command} worktree list [--json]
99
109
  ${command} worktree remove <path> [--json]
100
110
  ${command} worktree <command> --help
@@ -105,12 +115,20 @@ Existing branches are reused; an unambiguous fetched remote branch may create it
105
115
  The destination must be new and outside all registered worktrees. Occupied branches must be reused
106
116
  at their listed path. Bare and nonstandard Git layouts are unsupported.
107
117
 
108
- Add shares usable untracked main-worktree .plans and optional .local through symlinks, with local
118
+ Add and setup share usable untracked main-worktree .plans and optional .local through symlinks, with local
109
119
  Git exclusions. Companion plans are used directly. Tracked .local stays branch-local with a warning.
110
- Missing or project-tracked effective plans require separately authorized preparation:
111
- ${command} guide work-files-setup
112
- Add never registers a companion, migrates files, installs, builds or starts application processes.
113
- Late setup failures retain the worktree and branch and report manual recovery.
120
+ Missing or project-tracked effective plans require separately authorized preparation: see the
121
+ work-files-setup topic of ${command} guide.
122
+ Neither command registers a companion, migrates files, installs, builds or starts application processes.
123
+ Readiness covers Git and work files only; follow repository preparation and shutdown separately.
124
+ Setup without a path discovers the current Git worktree root, including from a nested directory.
125
+ An explicit path must be an exact existing registered root of this repository; main and detached
126
+ worktrees are supported. Setup preserves branches, the index, unrelated files and Git registration.
127
+ Equivalent shared links are reused. Conflicts are preserved; repair them and retry idempotent setup.
128
+ Late failures retain partial preparation and report a quoted setup retry command.
129
+ External tools may use this post-creation hook inside their worktree:
130
+ ${command} worktree setup
131
+ There is no lightweight teardown hook; the external owner manages deletion and project shutdown.
114
132
 
115
133
  List reads only Git's registry, including detached, missing, locked and prunable worktrees.
116
134
  Remove accepts an exact linked root, refuses main/locked/dirty/protected shared targets, and uses
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aligndev",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "license": "CC0-1.0",
5
5
  "author": "Thomas MUR",
6
6
  "description": "The AlignDev CLI: the assistant's playbook, coding-agent delegation, and project inventory.",
@@ -37,6 +37,9 @@
37
37
  "publishConfig": {
38
38
  "access": "public"
39
39
  },
40
+ "dependencies": {
41
+ "@alignfirst/docmap": "~0.12.0"
42
+ },
40
43
  "devDependencies": {
41
44
  "@types/node": "~26.6.5",
42
45
  "rimraf": "~6.1.3",
@@ -9,11 +9,11 @@ Run a coding agent through AlignFirst protocols with `{{ALIGNDEV}} code`. It wra
9
9
 
10
10
  **Never implement, investigate, or modify the codebase yourself. Your role is to delegate and guide the agent.**
11
11
 
12
- Run `{{ALIGNDEV}} code` from the root of the selected worktree, so the agent works in the right repository. The project must have usable `.plans/`, in the repository or in its companion directory: `{{ALIGNFIRST}} plans check` verifies it, and `{{ALIGNDEV}} guide work-files-setup` prepares it.
12
+ Run `{{ALIGNDEV}} code` from the root of the selected worktree, so the agent works in the right repository. The project must have usable `.plans/`, in the repository or in its companion directory: `{{ALIGNFIRST}} plans check` verifies it, and `{{GUIDE}} work-files-setup` prepares it.
13
13
 
14
14
  {{ALIGNFIRST_SETUP}}
15
15
 
16
- Each ticketed run writes `.plans/<ticket>/_aligndev/<stamp>.md`. This file is the durable record of the run. It may live in the project's companion directory; the `sessionFile:` line of `{{ALIGNDEV}} code status` gives the actual path. Its frontmatter carries `status` (`running` → `succeeded`/`failed`) and the `sessionId`, and the `---- Result ----` block holds the outcome. A run that answers more than once lists each response oldest first, separated by `---- Later result ----`. A substantive report may precede a short later acknowledgement; report the substantive outcome.
16
+ Each ticketed run writes `.plans/<ticket>/_aligndev/<stamp>.running.md`, renamed to `<stamp>.md` when the run ends; `{{ALIGNDEV}} code status` accepts either name. This file is the durable record of the run. It may live in the project's companion directory; the `sessionFile:` line of `{{ALIGNDEV}} code status` gives the actual path. Its frontmatter carries `status` (`running` → `succeeded`/`failed`) and the `sessionId`, and the `---- Result ----` block holds the outcome. A run that answers more than once lists each response oldest first, separated by `---- Later result ----`. A substantive report may precede a short later acknowledgement; report the substantive outcome.
17
17
 
18
18
  {{#openclaw}}
19
19
  ## How it runs
@@ -29,7 +29,12 @@ Under OpenClaw, background it through the `exec` tool:
29
29
 
30
30
  `{{ALIGNDEV}} code <command> <options> ; openclaw system event --text "aligndev code run finished — read its session file and report to the user" --mode now --session-key <KEY>`
31
31
 
32
+ {{#thread}}
32
33
  Chain with `;` (never `&&`) so a failed run wakes you too, and keep the `;` on the same line as the `{{ALIGNDEV}} code` command: a line that starts with `;` is a shell syntax error, the wake command never runs, and the run's completion is lost. The wake may reach you as a bare heartbeat with the text dropped, and OpenClaw's own `Exec completed` notice may lag behind it. Never wait for either text.
34
+ {{/thread}}
35
+ {{#app}}
36
+ Chain with `;` (never `&&`) so a failed run wakes you too, and keep the `;` on the same line as the `{{ALIGNDEV}} code` command: a line that starts with `;` is a shell syntax error, the wake command never runs, and the run's completion is lost. The wake may reach you as a bare heartbeat with the text dropped. Never wait for its text.
37
+ {{/app}}
33
38
  - Pass `background: true` and `timeoutSeconds: 0` (no kill timer). Never rely on the auto-yield or a finite timeout.
34
39
  - For a run launched without `--ticket` or `--no-ticket`, pass `--meta <KEY>` with this session's key. `{{ALIGNDEV}} code status --meta <KEY>` then finds its result among concurrent runs in the shared main worktree.
35
40
  - Set the exec `workdir` to the project root as an **absolute** path (`~` is not expanded there), or `cd` into the project inside the command itself.
@@ -42,6 +47,10 @@ As soon as the run is backgrounded, tell the user — in the user's language —
42
47
  ## After a background run completes
43
48
 
44
49
  The chained wake fires when the backgrounded `{{ALIGNDEV}} code` exits. This session receives a heartbeat, often as a plain heartbeat poll with no message text. A run counts as pending while it is running **and until its outcome is reported**.
50
+ {{#app}}
51
+
52
+ In this conversation, the run's exit brings two turns, about ten seconds apart: OpenClaw's `Exec completed` notice, then the chained wake as a heartbeat. Both are completion wakes. The first finds the run pending and reports it; the second finds it reported.
53
+ {{/app}}
45
54
 
46
55
  **First, decide whether this heartbeat needs a report.** A heartbeat is a completion wake only while a run is pending. Once you have reported the outcome, later heartbeats for that run need nothing. End them with exactly `HEARTBEAT_OK`, alone.
47
56
 
@@ -54,7 +63,7 @@ Any heartbeat received while an `{{ALIGNDEV}} code` run is **still pending** ent
54
63
 
55
64
  For a consultation, answer it directly from the findings; include a failure or uncertainty when relevant. The coding-run template above is for change reports.
56
65
 
57
- The report is the plain text that ends the turn, on Slack and Discord alike. It must be the turn's **final message**: text written between tool calls may never post. Never follow it with `NO_REPLY`, `HEARTBEAT_OK`, a duplicate message-tool post, or another tool call.
66
+ The report is the plain text that ends the turn. It must be the turn's **final message**: text written between tool calls may never post. Never follow it with `NO_REPLY`, `HEARTBEAT_OK`, a duplicate message-tool post, or another tool call.
58
67
  3. **Don't reconstruct what happened.** Verifying the result is what your operating instructions prescribe; re-deriving the run's story is not: no re-running the agent, no fetch/merge, no `git` archaeology to double-check its account — the session file is authoritative for that.
59
68
 
60
69
  Reporting the run is not calling the work done: the report relays the agent's claim plus what you verified. When your verification finds a failing check, the report says so, and the fix is new work — a fresh run with its own completion wake; the wake you were answering is discharged by your report.
@@ -89,7 +98,7 @@ Retain these distinct values for each run:
89
98
  Prepare the literal delegated prompt in a UTF-8 file, then launch the ordinary quoted shell command through `background` with `action: "start"` and `cwd`. Supply `--quiet --meta <unique-run-key>` yourself; the extension never parses or appends CLI options. This example assumes `/tmp/aligndev-request.txt` already contains the request. Generate a fresh key for every actual launch; the UUID below illustrates one run:
90
99
 
91
100
  ```json
92
- {"action":"start","command":"{{ALIGNDEV}} code new --message-file '/tmp/aligndev-request.txt' --quiet --meta 'a20bc7c1-c056-4d07-8cc2-90fe491a6df6'","cwd":"/srv/projects/example","label":"coding run"}
101
+ {"action":"start","command":{{BACKGROUND_COMMAND_JSON}},"cwd":"/srv/projects/example","label":"coding run"}
93
102
  ```
94
103
 
95
104
  For resume, use `{{ALIGNDEV}} code resume <sessionId> --message-file <path> --quiet --meta <fresh-run-key>` from the original worktree. A Pi child must resume from its recorded directory. Use safe shell quoting for paths and options; never interpolate raw user text into a command. A quoted heredoc with `--message-file -` is another literal-input route.
@@ -181,12 +190,12 @@ Don't reconstruct what happened: no re-running the agent, no `git` archaeology t
181
190
  {{#openclaw}}
182
191
  The current coding agent is `{{AGENT}}`, profile `{{PROFILE}}`. The profile's nonempty `models` replaces its displayed allowlist. Codex aliases `astra`, `sol`, `terra`, and `luna` resolve to the newest bundled matching slug only when selected; a configured full slug passes through unchanged.
183
192
 
184
- `{{ALIGNDEV}} code status` checks that a `running` process still owns its recorded pid. A dead run is sealed as `status: failed`, `exitReason: terminated` before the command reports it. `{{ALIGNDEV}} code quota` works without a `.plans` directory and does not start a coding session. Its output belongs to the selected native quota CLI's account; account pairing with the coding child is not verified.
193
+ `{{ALIGNDEV}} code status` seals a `running` record only when its `machineId` matches this installation and its pid is conclusively gone or reused. Foreign, legacy and uncertain records stay `running`; a sealed run reports `status: failed`, `exitReason: terminated`. `{{ALIGNDEV}} code quota` works without a `.plans` directory and does not start a coding session. Its output belongs to the selected native quota CLI's account; account pairing with the coding child is not verified.
185
194
  {{/openclaw}}
186
195
  {{#codingAgent}}
187
196
  The current coding agent is `{{AGENT}}`, profile `{{PROFILE}}`. A nonempty profile `models` list replaces its accepted model list. Pi has no finite allowlist by default: native selectors pass through unchanged, preferably `provider/model`, with optional thinking suffix. For a Pi child without `--model`, a new run uses profile `defaultModel`, else Pi's own default; a resume retains and validates its recorded model. Codex aliases `astra`, `sol`, `terra`, and `luna` resolve to the newest bundled matching slug only when selected; a configured full slug passes through unchanged.
188
197
 
189
- `{{ALIGNDEV}} code status` checks that a `running` process still owns its recorded pid. A dead run is sealed as `status: failed`, `exitReason: terminated` before the command reports it. `{{ALIGNDEV}} code quota` needs no `.plans` and starts no session. Its output belongs to the selected native quota CLI's account; account pairing with the coding child is not verified.
198
+ `{{ALIGNDEV}} code status` seals a `running` record only when its `machineId` matches this installation and its pid is conclusively gone or reused. Foreign, legacy and uncertain records stay `running`; a sealed run reports `status: failed`, `exitReason: terminated`. `{{ALIGNDEV}} code quota` needs no `.plans` and starts no session. Its output belongs to the selected native quota CLI's account; account pairing with the coding child is not verified.
190
199
  {{/codingAgent}}
191
200
 
192
201
  ### Profiles and resume