aligndev 0.26.0 → 0.28.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.
@@ -0,0 +1,24 @@
1
+ export interface GitContext {
2
+ cwd: string;
3
+ env: NodeJS.ProcessEnv;
4
+ }
5
+ export interface Repository {
6
+ mainWorktree: string;
7
+ commonDir: string;
8
+ worktrees: Worktree[];
9
+ }
10
+ export interface Worktree {
11
+ path: string;
12
+ branch: string | null;
13
+ main: boolean;
14
+ exists: boolean;
15
+ locked: boolean;
16
+ prunable: boolean;
17
+ }
18
+ export declare function readRepository(ctx: GitContext): Repository;
19
+ export declare function isProjectTrackedDirectory(ctx: GitContext, path: string, identity: string): boolean;
20
+ export declare function readWorktrees(ctx: GitContext, mainWorktree: string): Worktree[];
21
+ export declare function canonicalPath(path: string): string;
22
+ export declare function pathExists(path: string): boolean;
23
+ export declare function isInside(parent: string, path: string): boolean;
24
+ export declare function git(ctx: GitContext, ...args: string[]): string;
@@ -0,0 +1,103 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, lstatSync, realpathSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { errorMessage, isNodeError } from "../errors.js";
5
+ export function readRepository(ctx) {
6
+ const commonDir = repositoryIdentity(ctx);
7
+ if (git(ctx, "rev-parse", "--is-inside-work-tree").trim() !== "true" ||
8
+ basename(commonDir) !== ".git") {
9
+ throw new Error("A supported non-bare Git worktree with a main .git directory is required.");
10
+ }
11
+ const mainWorktree = realpathSync(dirname(commonDir));
12
+ const worktrees = readWorktrees(ctx, mainWorktree);
13
+ if (!worktrees.some((tree) => tree.main)) {
14
+ throw new Error("Cannot identify the main Git worktree.");
15
+ }
16
+ return { mainWorktree, commonDir, worktrees };
17
+ }
18
+ function repositoryIdentity(ctx) {
19
+ return realpathSync(git(ctx, "rev-parse", "--path-format=absolute", "--git-common-dir").trim());
20
+ }
21
+ export function isProjectTrackedDirectory(ctx, path, identity) {
22
+ const root = realpathSync(git(ctx, "rev-parse", "--show-toplevel").trim());
23
+ const logicalPath = join(realpathSync(dirname(path)), basename(path));
24
+ if (isInside(root, logicalPath) &&
25
+ hasTrackedFiles({ ...ctx, cwd: root }, relative(root, logicalPath)))
26
+ return true;
27
+ const resolved = realpathSync(path);
28
+ const source = { ...ctx, cwd: resolved };
29
+ if (optionalRepositoryIdentity(source) !== identity)
30
+ return false;
31
+ const sourceRoot = git(source, "rev-parse", "--show-toplevel").trim();
32
+ return hasTrackedFiles({ ...ctx, cwd: sourceRoot }, relative(sourceRoot, resolved));
33
+ }
34
+ function hasTrackedFiles(ctx, path) {
35
+ return (git(ctx, "--literal-pathspecs", "ls-files", "-z", "--", path === "" ? "." : path).length > 0);
36
+ }
37
+ function optionalRepositoryIdentity(ctx) {
38
+ try {
39
+ return repositoryIdentity(ctx);
40
+ }
41
+ catch (error) {
42
+ if (errorMessage(error).includes("not a git repository") ||
43
+ (isNodeError(error) && error.code === "ENOENT"))
44
+ return;
45
+ throw error;
46
+ }
47
+ }
48
+ export function readWorktrees(ctx, mainWorktree) {
49
+ return git(ctx, "worktree", "list", "--porcelain", "-z")
50
+ .split("\0\0")
51
+ .filter((record) => record.length > 0)
52
+ .map((record) => parseWorktree(record, mainWorktree));
53
+ }
54
+ function parseWorktree(record, mainWorktree) {
55
+ const fields = record.split("\0");
56
+ const pathField = fields.find((field) => field.startsWith("worktree "));
57
+ if (pathField === undefined)
58
+ throw new Error("Git returned a worktree record without a path.");
59
+ const path = canonicalPath(pathField.slice("worktree ".length));
60
+ const branchField = fields.find((field) => field.startsWith("branch "));
61
+ return {
62
+ path,
63
+ branch: branchField === undefined ? null : branchField.slice("branch refs/heads/".length),
64
+ main: path === mainWorktree,
65
+ exists: existsSync(path),
66
+ locked: fields.some((field) => field === "locked" || field.startsWith("locked ")),
67
+ prunable: fields.some((field) => field === "prunable" || field.startsWith("prunable ")),
68
+ };
69
+ }
70
+ export function canonicalPath(path) {
71
+ try {
72
+ return realpathSync(path);
73
+ }
74
+ catch (error) {
75
+ if (!isNodeError(error) || (error.code !== "ENOENT" && error.code !== "ENOTDIR"))
76
+ throw error;
77
+ const parent = dirname(path);
78
+ return parent === path ? resolve(path) : resolve(canonicalPath(parent), basename(path));
79
+ }
80
+ }
81
+ export function pathExists(path) {
82
+ try {
83
+ lstatSync(path);
84
+ return true;
85
+ }
86
+ catch (error) {
87
+ if (isNodeError(error) && error.code === "ENOENT")
88
+ return false;
89
+ throw error;
90
+ }
91
+ }
92
+ export function isInside(parent, path) {
93
+ const child = relative(parent, path);
94
+ return child === "" || (!isAbsolute(child) && child !== ".." && !child.startsWith(`..${sep}`));
95
+ }
96
+ export function git(ctx, ...args) {
97
+ return execFileSync("git", args, {
98
+ cwd: ctx.cwd,
99
+ env: ctx.env,
100
+ encoding: "utf8",
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ });
103
+ }
@@ -0,0 +1,8 @@
1
+ import { type Repository } from "./git.js";
2
+ import type { WorktreeContext } from "./worktree-cli.js";
3
+ export interface RemoveReport {
4
+ mainWorktree: string;
5
+ path: string;
6
+ removed: true;
7
+ }
8
+ export declare function removeWorktree(ctx: WorktreeContext, repo: Repository, input: string): RemoveReport;
@@ -0,0 +1,62 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { isNodeError } from "../errors.js";
4
+ import { readProjectReport } from "../project/layout.js";
5
+ import { canonicalPath, git, isInside, pathExists } from "./git.js";
6
+ export function removeWorktree(ctx, repo, input) {
7
+ const path = canonicalPath(resolve(ctx.cwd, input));
8
+ const target = repo.worktrees.find((tree) => tree.path === path);
9
+ if (target === undefined)
10
+ throw new Error(`Not an exact registered worktree root of this repository: ${path}`);
11
+ if (target.main)
12
+ throw new Error(`Cannot remove the main worktree: ${path}`);
13
+ if (target.locked)
14
+ throw new Error(`Cannot remove locked worktree: ${path}`);
15
+ if (!target.exists)
16
+ throw new Error(`Worktree is missing: ${path}. Inspect Git's registration manually.`);
17
+ const nested = repo.worktrees.find((tree) => tree.path !== path && isInside(path, tree.path));
18
+ if (nested !== undefined)
19
+ throw new Error(`Cannot remove ${path}: it contains another registered worktree root: ${nested.path}.`);
20
+ if (git({ ...ctx, cwd: path }, "status", "--porcelain", "-z", "--untracked-files=all").length > 0) {
21
+ throw new Error(`Cannot remove dirty worktree: ${path}. Preserve staged, modified and untracked files first.`);
22
+ }
23
+ protectSharedDirectories(ctx, repo, path);
24
+ git({ ...ctx, cwd: repo.mainWorktree }, "worktree", "remove", "--", path);
25
+ return { mainWorktree: repo.mainWorktree, path, removed: true };
26
+ }
27
+ function protectSharedDirectories(ctx, repo, target) {
28
+ for (const tree of repo.worktrees.filter((candidate) => candidate.exists)) {
29
+ const report = readProjectReport(ctx.alignfirstCommand, tree.path, ctx.env);
30
+ if ("error" in report)
31
+ throw new Error(`Cannot read shared-directory protection report for ${tree.path}: ${report.error}`);
32
+ const protectedPaths = [];
33
+ if (report.companion !== null)
34
+ protectedPaths.push(canonicalPath(report.companion.dir));
35
+ for (const name of [".plans", "_aligndev"]) {
36
+ const location = report.locations[name];
37
+ if (location.exists)
38
+ protectExistingTarget(protectedPaths, location.path);
39
+ }
40
+ if (tree.path !== target) {
41
+ for (const name of [".local", ".plans"]) {
42
+ const source = join(tree.path, name);
43
+ if (pathExists(source))
44
+ protectExistingTarget(protectedPaths, source);
45
+ }
46
+ }
47
+ for (const path of protectedPaths) {
48
+ if (isInside(target, path)) {
49
+ throw new Error(`Cannot remove ${target}: it contains protected shared directory ${path} referenced by ${tree.path}.`);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ function protectExistingTarget(paths, path) {
55
+ try {
56
+ paths.push(realpathSync(path));
57
+ }
58
+ catch (error) {
59
+ if (!isNodeError(error) || (error.code !== "ENOENT" && error.code !== "ENOTDIR"))
60
+ throw error;
61
+ }
62
+ }
@@ -0,0 +1,10 @@
1
+ import type { CommandForms } from "../command-form.js";
2
+ import type { Output } from "../output.js";
3
+ import { type GitContext } from "./git.js";
4
+ export interface WorktreeContext extends GitContext {
5
+ stdout: Output;
6
+ stderr: Output;
7
+ forms: CommandForms;
8
+ alignfirstCommand: string[];
9
+ }
10
+ export declare function runWorktree(tokens: string[], ctx: WorktreeContext): number;
@@ -0,0 +1,122 @@
1
+ import { parseArgs } from "node:util";
2
+ import { addWorktree } from "./add.js";
3
+ import { readRepository } from "./git.js";
4
+ import { removeWorktree } from "./remove.js";
5
+ export function runWorktree(tokens, ctx) {
6
+ const command = parseWorktreeArgs(tokens, ctx.forms.aligndev);
7
+ if (command.kind === "help") {
8
+ ctx.stdout.write(renderHelp(ctx.forms.aligndev));
9
+ return 0;
10
+ }
11
+ const repo = readRepository(ctx);
12
+ if (command.kind === "list") {
13
+ const report = { mainWorktree: repo.mainWorktree, worktrees: repo.worktrees };
14
+ ctx.stdout.write(command.json ? json(report) : renderList(repo.worktrees));
15
+ return 0;
16
+ }
17
+ if (command.kind === "remove") {
18
+ const report = removeWorktree(ctx, repo, command.path);
19
+ ctx.stdout.write(command.json ? json(report) : `Removed ${report.path}; branch preserved.\n`);
20
+ return 0;
21
+ }
22
+ const report = addWorktree(ctx, repo, command.options);
23
+ for (const warning of report.warnings)
24
+ ctx.stderr.write(`Warning: ${warning}\n`);
25
+ ctx.stdout.write(command.json ? json(report) : renderAdd(report));
26
+ return 0;
27
+ }
28
+ function parseWorktreeArgs(tokens, aligndev) {
29
+ const [command, ...rest] = tokens;
30
+ if (command === undefined || command === "--help" || command === "-h") {
31
+ if (tokens.length > 1)
32
+ throw new Error("Unexpected worktree help arguments.");
33
+ return { kind: "help" };
34
+ }
35
+ if (command !== "add" && command !== "list" && command !== "remove") {
36
+ throw new Error(`Unknown worktree command: ${command}`);
37
+ }
38
+ const { values, positionals } = parseArgs({
39
+ args: rest,
40
+ strict: true,
41
+ allowPositionals: true,
42
+ options: {
43
+ json: { type: "boolean", default: false },
44
+ help: { type: "boolean", short: "h", default: false },
45
+ ...(command === "add" ? { b: { type: "string" } } : {}),
46
+ },
47
+ });
48
+ if (values.help)
49
+ return { kind: "help" };
50
+ const newBranch = typeof values.b === "string" ? values.b : undefined;
51
+ const count = positionals.length;
52
+ const expected = command === "list" ? 0 : command === "remove" ? 1 : 2;
53
+ const validCount = command === "add" && newBranch !== undefined ? count === 1 || count === 2 : count === expected;
54
+ if (!validCount) {
55
+ throw new Error(`Invalid arguments. Run \`${aligndev} worktree ${command} --help\`.`);
56
+ }
57
+ if (command === "list")
58
+ return { kind: "list", json: values.json };
59
+ const path = positionals[0];
60
+ if (path === undefined)
61
+ throw new Error("A worktree path is required.");
62
+ if (command === "remove")
63
+ return { kind: "remove", path, json: values.json };
64
+ const branch = newBranch ?? positionals[1];
65
+ if (branch === undefined)
66
+ throw new Error("A branch is required.");
67
+ return {
68
+ kind: "add",
69
+ json: values.json,
70
+ options: {
71
+ path,
72
+ branch,
73
+ newBranch: newBranch !== undefined,
74
+ start: newBranch === undefined ? undefined : positionals[1],
75
+ },
76
+ };
77
+ }
78
+ function json(report) {
79
+ return `${JSON.stringify(report, undefined, 2)}\n`;
80
+ }
81
+ function renderList(worktrees) {
82
+ return worktrees
83
+ .map((tree) => `${tree.path} [${tree.branch ?? "detached"}]${tree.main ? " main" : ""}${tree.exists ? "" : " missing"}${tree.locked ? " locked" : ""}${tree.prunable ? " prunable" : ""}\n`)
84
+ .join("");
85
+ }
86
+ function renderAdd(report) {
87
+ return [
88
+ `Worktree ready: ${report.worktree.path} [${report.worktree.branch}]`,
89
+ ...Object.entries(report.directories).map(([name, directory]) => `${name}: ${directory.mode} ${directory.path}${directory.target === null ? "" : ` -> ${directory.target}`}`),
90
+ "Readiness covers Git and work files only; follow the project's install/build/test procedure.",
91
+ "",
92
+ ].join("\n");
93
+ }
94
+ function renderHelp(command) {
95
+ return `Usage:
96
+ ${command} worktree add <path> <branch> [--json]
97
+ ${command} worktree add <path> -b <branch> [<start-point>] [--json]
98
+ ${command} worktree list [--json]
99
+ ${command} worktree remove <path> [--json]
100
+ ${command} worktree <command> --help
101
+
102
+ Paths resolve from the caller, including linked worktrees and subdirectories.
103
+ Existing branches are reused; an unambiguous fetched remote branch may create its tracking branch.
104
+ -b creates a new branch from <start-point>, or the invoking worktree's HEAD. No fetch or base refresh.
105
+ The destination must be new and outside all registered worktrees. Occupied branches must be reused
106
+ at their listed path. Bare and nonstandard Git layouts are unsupported.
107
+
108
+ Add shares usable untracked main-worktree .plans and optional .local through symlinks, with local
109
+ 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.
114
+
115
+ List reads only Git's registry, including detached, missing, locked and prunable worktrees.
116
+ Remove accepts an exact linked root, refuses main/locked/dirty/protected shared targets, and uses
117
+ ordinary Git removal. It preserves branches, shared targets and companion registration; no force,
118
+ pruning, process teardown or recursive fallback. Stop project activity separately before removal.
119
+
120
+ --json prints one document on success; warnings and errors go to stderr. Failures exit 1.
121
+ `;
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aligndev",
3
- "version": "0.26.0",
3
+ "version": "0.28.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.",
@@ -9,7 +9,7 @@ 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 target project, so the agent works in the right repository. The project must have a `.plans/` directory, in the repository or in its companion directory.
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.
13
13
 
14
14
  {{ALIGNFIRST_SETUP}}
15
15
 
@@ -52,7 +52,7 @@ Any heartbeat received while an `{{ALIGNDEV}} code` run is **still pending** ent
52
52
 
53
53
  `Coding run {succeeded | failed} — the agent reports: {one-line summary of the Result block}. {What you verified.}`
54
54
 
55
- For a read-only question, answer it directly from the findings; include a failure or uncertainty when relevant. The coding-run template above is for change reports.
55
+ 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
56
 
57
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.
58
58
  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.
@@ -193,27 +193,13 @@ The current coding agent is `{{AGENT}}`, profile `{{PROFILE}}`. A nonempty profi
193
193
 
194
194
  Effective profile: `{{PROFILE}}`; agent: `{{AGENT}}`; native configuration: `{{NATIVE_CONFIG}}`. Environment values are omitted. Login must use the same effective environment as the child: apply profile `unset/env/configDir`, including HOME, PATH and credential routing, from the same working directory. A bare login in another shell may use a different account.
195
195
 
196
- New-session, help, guide and quota selection: explicit `--profile` → project's registry selection → global `code.profile` → automatic resolution. Resume inserts the latest run's recorded named profile before the global selection. A missing selected profile is an error; profiles never merge. Named choices bypass parent detection. Help, guide and quota use the actual cwd and require neither Git nor `.plans`.
197
-
198
- Automatic resolution uses a sole profile matching the detected agent, or that agent's unique `default: true` among several profiles. Omitted and false flags are equivalent; at most one true flag per agent is allowed. With no matching profile, use that agent's built-ins. A profile for another agent never overrides the detected parent. Without a detected parent, only a sole total profile is inferred; several detected kinds require a named choice. A per-agent flag never chooses the agent kind.
199
-
200
- Historical resumes with a null or missing profile use detected built-ins unless an explicit, project or global named choice replaces them. They ignore profile counts and flags, still require one detected parent and keep null in the new record. Original transcripts remain unchanged. A deleted recorded name requires an explicit or project replacement; global settings and inference cannot rescue it.
201
-
202
- Profiles select native configuration/authentication through `configDir` or the corresponding effective environment variable: `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, or `PI_CODING_AGENT_DIR`. `~/` uses the configured home; relative paths use the settings directory. Authenticate in this selected native configuration, not a different account. `env` values are literal non-secret configuration; `unset` removes inherited variables. Credentials remain in native stores or provisioned process environments. Parent identities are stripped after these overrides. Environment values are never recorded in session metadata.
203
-
204
- Select a user-facing model name, validate it against the accepted names, expand one `modelAliases` mapping, then apply native handling. Without a nonempty `models` override, Claude/Codex add alias names to their native default names; Pi accepts any nonblank selector. Pi exact provider-qualified IDs pin models; fuzzy selectors and thinking suffixes pass through to Pi. Use separate Pi profiles for Codex-backed and Anthropic-backed choices; AlignDev never guesses providers or accounts. Omitted quota uses a native Claude/Codex profile's environment; Pi needs explicit `quota.source: "codex"` or `"claude"`. `"none"` disables quota. Explicit quota starts from the caller environment, applies only quota `unset/env/configDir` and strips parent identities. It never copies coding-profile overrides or Pi credentials. Set quota `configDir` for the intended native account; omission deliberately keeps inherited/default storage. Quota paths follow profile expansion rules. Do not infer account pairing from model selection or retry against a different account after failure.
205
-
206
- Resume keeps the latest user-facing model unless `--model` replaces it; new-session defaults are ignored. A retained name disallowed by the selected profile requires an explicit accepted replacement. Null keeps the native conversation model. Retained aliases use current mappings, which can change their native targets. Resume requires the same agent and native identity; Pi also requires its recorded real directory. An unavailable conversation fails under the selected account with no fallback, copying or replacement conversation. Run metadata records the effective profile (or null), agent, model name, native ID and cwd. Historical records stay readable; status does not validate launch profiles.
207
-
208
- Unknown or obsolete settings keys are ignored with value-free warnings on stderr at each fixed settings/profile/quota shape; profile, environment and alias dictionaries remain maps. Recognized invalid values and duplicate defaults still fail. Settings are never rewritten.
209
-
210
- Direct launch keys and `code.defaultProfiles` are retired and ignored; they supply no legacy behavior. Move launch keys into `code.profiles.<name>`. Move needed per-agent preferences onto matching profiles as `default: true`, omitting singleton flags, and remove the map. Keep profile names unchanged; no automatic conversion occurs. Unique-profile inference can now select configured storage, model, environment and permission settings for new runs that previously used built-ins. Historical null-profile resumes retain their built-in fallback.
196
+ Profile selection, native configuration directories, quota sources and settings migration are configured outside this guide and documented in the `aligndev` README. A selection or settings error fails with the CLI's own diagnostic: report it, and never retry against another account.
211
197
 
212
198
  `contextTokens` is what the run left in the agent's context window, measured from its last model response. It describes the conversation, so resuming a session carries the figure forward and each run reports a larger one.
213
199
 
214
200
  {{ALIGNFIRST_USE}}
215
201
 
216
- {{PERMISSIONS}}.
202
+ {{PERMISSIONS}}. The agent needs read and write access to the work files under that policy. A worktree's `.plans` may be a symlink to the main worktree's, and a symlink grants no sandbox permission. Report missing access instead of enabling bypass permissions or granting the whole main repository.
217
203
 
218
204
  {{#openclaw}}
219
205
  For `new` runs, the `Session ID:` is printed to stdout and written with `agent: {{AGENT}}` in the session file frontmatter. Save it to resume the conversation later. Resume requires the same selected agent; agentless legacy sessions require a new session.
@@ -239,8 +225,9 @@ For large work, do not rush. Decompose it yourself only when the concerns are tr
239
225
 
240
226
  1. **Spec** — `{{ALIGNDEV}} code new --protocol spec --ticket AB-123 --message "Feature description"`. The agent investigates and asks questions; save the session id. Iterate until it writes the spec file.
241
227
  2. **Plan** — the spec run's context decides where planning happens. Read `contextTokens` from `{{ALIGNDEV}} code status`, then follow "Where the plan runs" below.
242
- 3. **Execute** — `{{ALIGNDEV}} code new --message "Execute the plan: \`.plans/AB-123/A2-plan.md\`"`. The agent implements and writes a summary file. Given a main plan, it spawns one subagent per sub-plan and writes a main summary; when the working tree is clean, append to the message: *"Feel free to commit between each plan."*
243
- 4. **Commit** — use the suggested commit message from the spec file.
228
+ 3. **Execute** — `{{ALIGNDEV}} code new --message "Execute the plan: \`.plans/AB-123/A2-plan.md\`"`. The agent implements and writes a summary file.
229
+ For a main plan, end the message with *"Commit at each step."*: the agent spawns one subagent per sub-plan, commits after each, and writes a main summary.
230
+ 4. **Commit** — use the suggested commit message from the spec file. After a main plan, the commits already exist; only commit what the subagents left uncommitted.
244
231
 
245
232
  Run the chain end to end. The plan is a step of the implementation, not a checkpoint for your user to clear: the moment it's written, launch the execution.
246
233
 
@@ -270,8 +257,6 @@ Then start the planning session, naming the spec so the agent does not have to g
270
257
 
271
258
  Either way the agent writes the plan file, or several sub-plans and a main plan for large work.
272
259
 
273
- Plan files are the agent's material: never read one, main plans included. When the user hands you a plan to execute, pass its path in the message as-is; for context, read the spec that shares the plan's leading letter in the same directory (`A1-spec.md` for `A2-plan.md`), when there is one.
274
-
275
260
  ## Light workflow (AAD)
276
261
 
277
262
  For one-shot changes or follow-up adjustments right after executing a plan. The agent investigates, discusses, then implements in one session.
@@ -298,7 +283,7 @@ Two fresh sessions: one reviews, one fixes.
298
283
 
299
284
  1. **Review** — `{{ALIGNDEV}} code new --protocol review --ticket AB-123`. The agent reviews the current branch against the base branch and writes a review file; its path is in the run's result. The base defaults to the repository's default branch; override it via `--message "Base branch: \`develop\`"`. Retain the session id.
300
285
  - **Follow up** (someone else's branch, its author pushed fixes) — `{{ALIGNDEV}} code resume <sessionId> --message "Fixes have been pushed, please check."`, in the review session, with the author's replies to the review appended when there are any. The agent checks its findings against the new commits and reports which are resolved and which remain. A new review session would start over.
301
- 2. **Fix** (optional, always in a fresh session — never in the review session) — `{{ALIGNDEV}} code new --protocol aad --ticket AB-123 --message "Here is a code review: \`.plans/AB-123/B1-review.md\`. What should we fix?"`. Point the message at wherever the review lives: the review file, or the PR/MR whose comments carry it. The agent proposes fixes; decide together what to fix, as in any AAD session. Keep it simple and avoid overengineering. When the agent asks about scope, welcome expansion that cleans things up and refuse expansion that adds complexity; simplicity wins. The agent then implements and writes a summary file.
286
+ 2. **Fix** (optional, always in a fresh session — never in the review session) — `{{ALIGNDEV}} code new --protocol aad --ticket AB-123 --message "Here is a code review: \`.plans/AB-123/B1-review.md\`. What should we fix?"`. Send this message as it is, pointed at wherever the review lives: the review file, or the PR/MR whose comments carry it. The agent challenges the findings and proposes fixes; decide together what to fix, as in any AAD session. The goal is the project's code quality, and a finding is not an order: welcome a fix or an expansion that cleans things up, refuse one that adds complexity; simplicity wins. The agent then implements and writes a summary file.
302
287
 
303
288
  Skip the fix step when the review is informational.
304
289
 
@@ -48,7 +48,7 @@ From the user's message and the retained inventory result:
48
48
  - **TICKET_ID** — the ticket the user gave.
49
49
  - **TASK** — a one-line restatement, in your own words, of what the user wants. Preserve every
50
50
  resource URL verbatim in this line so the working session can inspect it.
51
- - **REQUEST** — for a detailed explanation (several requirements, constraints, or itemized points), the complete user message, unchanged, its opening sentence included even when the task line restates it. The working session files this text verbatim; a condensed task line is not a substitute. Omit it for a short request.
51
+ - **REQUEST** — the complete original user message, unchanged, even for a short request. Include its opening sentence and every itemized point or constraint; the task line is only a summary.
52
52
 
53
53
  A value the user did not supply and the lookup did not resolve stays missing. Step 3 turns it into a question. Run no project inspection or work command.
54
54
 
@@ -70,7 +70,7 @@ Pass no `message`: content on `thread-create` would post ahead of the starter. T
70
70
 
71
71
  A fresh thread session inherits nothing from this channel: not the transcript, the project listing, or the message that named the project. The starter is the visible record the thread session reads after the service activates it.
72
72
 
73
- Template. One labelled line per value. Start with the task line. Add one adjacent project / project-path pair for each resolved project, omitting the path when it is unresolved. Add the ticket line only when known. Add the request block only for a detailed explanation. Bold project values with your surface's markers rather than literal `**`. Write the starter in the user's language, labels included; keep the line structure, and copy each canonical path, ticket id, and URL exactly.
73
+ Template. One labelled line per value. Start with the task line. Add one adjacent project / project-path pair for each resolved project, omitting the path when it is unresolved. Add the ticket line only when known. Always include the original request block. Bold project values with your surface's markers rather than literal `**`. Write the starter in the user's language, labels included; keep the line structure, and copy each canonical path, ticket id, and URL exactly.
74
74
 
75
75
  ```text
76
76
  Task: {TASK}
@@ -86,7 +86,7 @@ Request:
86
86
 
87
87
  Omit unknown project, path, and ticket fields instead of filling them with placeholder text. Write the task value as "to be defined" in the user's language when the user gave no scope. The request block preserves the original language and every detail; do not condense or translate it.
88
88
 
89
- Earlier channel context that the thread session would otherwise lose belongs in the task line, condensed and rephrased. A detailed request also carries the original message in the request block. Do not narrate in third person ("the user is asking…").
89
+ Earlier channel context that the thread session would otherwise lose belongs in the task line, condensed and rephrased. Do not narrate in third person ("the user is asking…").
90
90
 
91
91
  The `{ask}` is one sentence, and it reflects the first unresolved requirement:
92
92
 
@@ -94,7 +94,7 @@ The `{ask}` is one sentence, and it reflects the first unresolved requirement:
94
94
  - No PROJECT_PATH for project removal → ask which listed canonical path to remove.
95
95
  - A clearly single-project task with no PROJECT → ask which project it belongs to, restating the ticket id when present.
96
96
  - An unresolved PROJECT for ordinary single-project work → state that the name is not in the project inventory, then ask for the path of a listed project.
97
- - No TICKET_ID for single-project work → ask for the ticket id, unless the request is a read-only question, advice or a brainstorming without a code review or requested protocol, contains a resource URL that can provide it, carries a detailed request, explicitly says there is no ticket or asks for a side ticket, or is operational work handled without an AlignFirst protocol. The working session handles ticket creation or collection for a detailed request.
97
+ - No TICKET_ID for a brief single-project change, code review, or named protocol → ask for the ticket id, unless a resource URL can provide it or the request explicitly says there is no ticket or asks for a side ticket. A detailed request, a consultation (question, advice, brainstorming), and operational work leave the ticket to the working session.
98
98
  - No TASK → ask what needs to be done.
99
99
  - A resource URL that may provide the project or ticket → ask for neither; state that the working session will inspect the URL.
100
100
  - A request explicitly spanning several projects, or work independent of any project → ask for no main project; state `Ready for the work session.` in the user's language.
@@ -104,6 +104,8 @@ Whichever case applies, the `{ask}` never says that this channel session handles
104
104
 
105
105
  For project creation or repository onboarding, a proposed PROJECT with no PROJECT_PATH is complete enough for handoff. The lifecycle procedure establishes its path.
106
106
 
107
+ Before sending the starter, compare it with the original message. You lack the project context to judge which details matter. The Request block must be complete.
108
+
107
109
  Once the starter's delivery is confirmed, call `thread_handoff` with `action: "start"` and the bare THREAD_ID. A tool result `Skipped due to queued user message.` means OpenClaw skipped the call because a new message was steered into this turn; call `start` again for the same thread. On `queued` or `alreadyStarted`, end the turn on exactly `NO_REPLY`: the starter is this turn's reply, and the thread shows under the user's message. Do no project work and send no second starter. On a partial or ambiguous delivery, do not call `start`. If delivery or handoff fails, end the turn on the concise actionable error. Retry against the original confirmed thread; never create a replacement merely because activation failed. Missing plugin/tool access is a deployment failure, not a reason to ask for a mechanical follow-up.
108
110
 
109
111
  In a DM or group DM, `start` is unsupported. Explain that project work must be requested from a supported channel; do not promise automatic thread activation there.
@@ -21,10 +21,10 @@ Run `{{ALIGNFIRST}} context` from PROJECT_PATH.
21
21
  {{/codingAgent}}
22
22
 
23
23
  {{#openclaw}}
24
- Use the main worktree on the configured default branch. When the question explicitly concerns a branch or a PR, or follows ongoing branch work in this thread, use that branch's existing registered workspace instead: resolve it through the project's workspace guide, and report the limitation rather than inspecting a different branch when no workspace exists. In main-worktree mode (`{{ALIGNDEV}} guide project-workspace-setup`), that workspace is the main worktree while it holds the branch.
24
+ Use the main worktree on the configured default branch. When the question explicitly concerns a branch or a PR, or follows ongoing branch work in this thread, use that branch's existing registered workspace instead: resolve it through the project's documented workspace list, or `{{ALIGNDEV}} worktree list --json` when no tooling exists. Report the limitation rather than inspecting a different branch when no worktree exists. Do not create a worktree merely to answer a question.
25
25
  {{/openclaw}}
26
26
  {{#codingAgent}}
27
- Use the session's worktree and its branch as they are. When the question explicitly concerns another branch or a PR, use that branch's existing registered workspace instead: resolve it through the project's workspace guide, and report the limitation rather than inspecting a different branch when no workspace exists.
27
+ Use the session's worktree and its branch as they are. When the question explicitly concerns another branch or a PR, use that branch's existing registered workspace instead: resolve it through the project's documented workspace list, or `{{ALIGNDEV}} worktree list --json` when no tooling exists. Report the limitation rather than inspecting a different branch when no worktree exists. Do not create a worktree merely to answer a question.
28
28
  {{/codingAgent}}
29
29
 
30
30
  {{#openclaw}}
@@ -48,6 +48,8 @@ Retain `git rev-parse --short HEAD`, the revision the answer comes from. Report
48
48
 
49
49
  ## Step 3 — Delegate
50
50
 
51
+ Delegation creates session files under the work files, so complete `{{ALIGNDEV}} guide work-files-setup` from PROJECT_PATH first.
52
+
51
53
  {{#openclaw}}
52
54
  Apply the takeover-turn checkpoint in the playbook (`{{ALIGNDEV}} guide`), then run `{{ALIGNDEV}} code new --message` from the selected worktree, without `--protocol`, `--ticket`, or `--no-ticket`.
53
55
  {{/openclaw}}
@@ -92,7 +94,7 @@ A single question answered in one turn ends at Step 4. Nothing is written.
92
94
  Record the exchange when it produced something worth keeping: the user asked for ideas, an opinion, or a decision, or the topic continued past your first answer. Then:
93
95
 
94
96
  1. **Ask about the ticket, without waiting for it.** Add one sentence to the answer you are already sending, in the user's language: *"Is there a ticket to attach this discussion to, or do we continue without one?"* Ask it once in the session, then carry on regardless of the reply.
95
- 2. **Establish TICKET_ID** on the turn that states a decision, or when the user asks to wrap up or changes topic. Use the ticket the user named, or run `{{ALIGNFIRST}} ticket --side` from PROJECT_PATH and take the `side-N` it reports.
97
+ 2. **Establish TICKET_ID** on the turn that states a decision, or when the user asks to wrap up or changes topic. Use the ticket the user named, or run `{{ALIGNFIRST}} sync`, then `{{ALIGNFIRST}} ticket --side` from PROJECT_PATH and take the `side-N` it reports.
96
98
  3. **Name the file.** Run `{{ALIGNFIRST}} sync`, then `{{ALIGNFIRST}} ticket {TICKET_ID} --next consultation.md --new-cycle`, both from PROJECT_PATH, and append FILE_NAME to TICKET_DIR exactly as printed. Syncing first brings down the ticket's existing work files, so the new file is numbered after them. A consultation opens its own cycle, and the flag is harmless on a ticket with no work files yet.
97
99
  4. **Have the agent write it.** Resume the consultation's session with no protocol, naming that exact path. Ask for the discussion's summary, the ideas considered, the decisions reached, and the open questions named as open. The agent syncs its own writes.
98
100
  5. **Report where it landed.** Your closing message states TICKET_ID and the file path. The file names the revision retained at Step 2.
@@ -17,17 +17,10 @@ You are the AlignFirst assistant in a coding-agent session, and the user talks t
17
17
  {{/codingAgent}}
18
18
 
19
19
  {{#openclaw}}
20
- **The agent** — the coding agent (Claude Code or Codex) you launch in a project with `{{ALIGNDEV}} code`. It reads and changes the codebase; you guide it.
20
+ You run inside OpenClaw, but you are the assistant, never an agent. **The agent** is the coding agent you launch in a project with `{{ALIGNDEV}} code`: it reads and changes the codebase; you guide it.
21
21
  {{/openclaw}}
22
22
  {{#codingAgent}}
23
- **The agent** — the selected child (Claude Code, Codex or Pi) you launch in a project with `{{ALIGNDEV}} code`. It reads and changes the codebase; you guide it.
24
- {{/codingAgent}}
25
-
26
- {{#openclaw}}
27
- You run inside OpenClaw, but you are the assistant, never an agent. "The agent" always means the coding agent you launch.
28
- {{/openclaw}}
29
- {{#codingAgent}}
30
- You run inside Claude Code, Codex or Pi as the parent assistant. "The agent" always means the selected child, independently of your host.
23
+ You run inside Claude Code, Codex or Pi as the parent assistant. **The agent** is the selected child (Claude Code, Codex or Pi) you launch in a project with `{{ALIGNDEV}} code`, independently of your host: it reads and changes the codebase; you guide it.
31
24
 
32
25
  Your own tools could edit the code, but you delegate: you never implement, investigate, or modify the codebase yourself.
33
26
  {{/codingAgent}}
@@ -79,20 +72,13 @@ Creating, onboarding, or removing a project is not handled in this mode. When th
79
72
 
80
73
  ## Tickets and AlignFirst protocols
81
74
 
82
- {{#openclaw}}
83
- Code reviews and explicitly requested AlignFirst protocols follow their protocol workflow, including its ticket and workspace requirements. Other read-only questions, advice and brainstormings need no ticket or AlignFirst protocol to start. They use the refreshed main worktree unless they explicitly concern another branch; follow the working session's consultation runbook, which also records a discussion worth keeping.
84
- {{/openclaw}}
85
- {{#codingAgent}}
86
- Code reviews and explicitly requested AlignFirst protocols follow their protocol workflow, including its ticket and workspace requirements. Other read-only questions, advice and brainstormings need no ticket or AlignFirst protocol to start. They use the session's worktree as it is; follow the working session's consultation runbook, which also records a discussion worth keeping.
87
- {{/codingAgent}}
88
-
89
75
  A development task that changes one project needs a TICKET_ID. A project's or deployment's instructions define whether you can create or update tickets. When they provide no ticket-system access, skip those external operations and ask the user for an ID. When the user explicitly says there is no ticket, the working session reserves a side ticket `side-N` before workspace setup. Operational maintenance on existing branches and workspaces does not create a new ticket context.
90
76
 
91
77
  {{#openclaw}}
92
- Use AlignFirst protocols only for work owned by one project. Delegate project bootstrap (creation and repository onboarding), a multi-project request with no main project, workspace cleanup, base-branch refresh, and other operational work to the agent without a protocol. A ticket ID may still identify the project workspaces involved.
78
+ Use AlignFirst protocols only for work owned by one project. Project bootstrap (creation and repository onboarding), a multi-project request with no main project, workspace cleanup, base-branch refresh, and other operational work use no protocol. A ticket ID may still identify the project workspaces involved.
93
79
  {{/openclaw}}
94
80
  {{#codingAgent}}
95
- Delegate workspace cleanup, base-branch refresh, and other operational work to the agent without a protocol. A ticket ID may still identify the project workspaces involved.
81
+ Workspace cleanup, base-branch refresh, and other operational work use no protocol. A ticket ID may still identify the project workspaces involved.
96
82
  {{/codingAgent}}
97
83
 
98
84
  Users may name a protocol by its skill alias. Translate it to the `{{ALIGNDEV}} code --protocol` value: `alspec` → `spec`, `alplan` → `plan`, `al` or AAD → `aad`, `almerge` → `merge`, `alreview` → `review`, `aldescription` → `description`. `alcatchup` means `--catchup`; `alcatchupaad` and `alcatchupspec` mean `--catchup` with `aad` or `spec`.
@@ -140,7 +126,7 @@ Coding runs are long. Run `{{ALIGNDEV}} code` in the background, as the delegati
140
126
 
141
127
  {{#openclaw}}
142
128
  - Put screenshots, downloads, OCR/PDF scratch, temporary conversions, and other non-project artifacts under `~/.openclaw/workspace/scratch/`. This static media root works with both bare `MEDIA:` delivery and structured `message` attachments. Files persist across reboots until an administrator prunes them.
143
- - A gitignored `.local/` directory in a project can be use as a scratch space too.
129
+ - A gitignored `.local/` directory in a project can be used as a scratch space too.
144
130
  - `/tmp/` is fine only for files you don't care about losing.
145
131
  {{/openclaw}}
146
132
  {{#codingAgent}}
@@ -152,12 +138,7 @@ Keep scratch artifacts out of tracked git directories.
152
138
 
153
139
  ## Vocabulary
154
140
 
155
- {{#openclaw}}
156
- - **the agent** — the coding agent (Claude Code or Codex) you launch in a project with `{{ALIGNDEV}} code`. It reads and changes the codebase; you guide it. Call it _the agent_ with the user too.
157
- {{/openclaw}}
158
- {{#codingAgent}}
159
- - **the agent** — the selected child (Claude Code, Codex or Pi) launched with `{{ALIGNDEV}} code`. Call it _the agent_ with the user too.
160
- {{/codingAgent}}
141
+ - **the agent** — the coding agent you launch with `{{ALIGNDEV}} code`. Call it _the agent_ with the user too.
161
142
  - **ticket** — an issue or card.
162
- - **project workspace** — in a project, it means branch + worktree + isolated dev server. The user might refer to it as _workspace_, _work env_, _local environment_, _worktree_, _branch_.
143
+ - **project workspace** — a branch in its own worktree, with an isolated dev server when the project runs one. The user might refer to it as _workspace_, _work env_, _local environment_, _worktree_, _branch_.
163
144
  - **dev server** (or *your server*) — the local instance of the project running in the worktree, with hot reload, etc. The user might refer to it as _server_, _local server_, or even the _env URL_.