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.
package/README.md CHANGED
@@ -34,9 +34,13 @@ For a coding-agent assistant, parent host and delegated child are independent: a
34
34
 
35
35
  ## Start in Claude Code, Codex or Pi
36
36
 
37
- The project needs an AlignFirst `.plans` directory, in its repository or in a [companion directory](https://github.com/paleo/alignfirst/tree/main/packages/alignfirst#companion-directories). The [setup guide](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/coding-agent-assistant.md) prepares it.
37
+ The project needs usable AlignFirst work files, untracked by the project's own repository or in a [companion directory](https://github.com/paleo/alignfirst/tree/main/packages/alignfirst#companion-directories). A separate work-files repository may track them. The [setup guide](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/coding-agent-assistant.md) prepares it. `alignfirst plans check --json` verifies them, from the main worktree or a linked one. AlignFirst refuses effective plans tracked by the project's own repository. Missing or project-tracked effective plans require authorized companion preparation through `aligndev guide work-files-setup`; existing project content stays untouched and is not copied.
38
38
 
39
- The child needs network access and writes outside the repository. Claude Code/Codex parents request their established sandbox bypass or elevation; approve that request when it comes. Pi uses ordinary OS permissions and saved project trust. It has no implied sandbox or per-command approval boundary, and A profile's `skipPermissions` has no effect on Pi.
39
+ Full workspace tooling is optional. The assistant follows the project's documented tooling when present; otherwise `aligndev worktree` creates or reuses an isolated Git worktree without installation or tracked configuration changes. It shares usable untracked project plans and optional `.local` through locally excluded symlinks, or uses companion plans directly. Readiness covers Git and work files only; dependency installation, builds, tests and application lifecycle follow the repository's commands separately. Removal refuses dirty worktrees, preserves branches and shared targets, and does not stop processes or tear down infrastructure. See `aligndev worktree --help` for the command reference.
40
+
41
+ The child needs network access and access to its selected work files. Parent-host elevation and the child's permission policy are separate. A shared symlink grants no sandbox permission. In native Codex 0.162.1 host probes, normal `workspace-write` denied writes through shared project `.plans` and `.local` links (`Errno 30`). Prepared companion plans passed through the existing `--add-dir <companion>` route; shared `.local` and outside-root writes remained denied. Report denied real paths. For companion plans, obtain approval through `aligndev guide work-files-setup`, preserving existing project files. Do not silently bypass the sandbox or grant the whole main repository write access.
42
+
43
+ Pi uses ordinary OS permissions and saved project trust; a profile's `skipPermissions` has no effect. Native Pi 1.3.0 host probes passed for shared plans, a separate work-files repository, companion plans and `.local`. These results establish OS access, not sandbox confinement. Neither agent's host-user probes establish production service-account or deployment support.
40
44
 
41
45
  ### With the Skill
42
46
 
@@ -85,7 +89,7 @@ Then ask your session to work with aligndev.
85
89
  ```json
86
90
  {
87
91
  "code": {
88
- "profiles": { "work": { "agent": "claude", "configDir": "~/.claude-work" } }
92
+ "profiles": { "work": { "agent": "claude" } }
89
93
  }
90
94
  }
91
95
  ```
@@ -99,9 +103,9 @@ For multiple accounts and independent quota sources:
99
103
  "code": {
100
104
  "profile": "codex-personal",
101
105
  "profiles": {
102
- "codex-personal": { "agent": "codex", "configDir": "~/.codex", "defaultModel": "sol" },
106
+ "codex-personal": { "agent": "codex", "defaultModel": "sol" },
103
107
  "claude-personal": {
104
- "agent": "claude", "default": true, "configDir": "~/.claude", "defaultModel": "opus",
108
+ "agent": "claude", "default": true, "defaultModel": "opus",
105
109
  "unset": ["ANTHROPIC_API_KEY"]
106
110
  },
107
111
  "claude-work": {
@@ -109,14 +113,14 @@ For multiple accounts and independent quota sources:
109
113
  "unset": ["ANTHROPIC_API_KEY"]
110
114
  },
111
115
  "pi-codex": {
112
- "agent": "pi", "default": true, "configDir": "~/.pi/agent", "defaultModel": "sol",
116
+ "agent": "pi", "default": true, "defaultModel": "sol",
113
117
  "modelAliases": { "sol": "openai/sol" },
114
- "quota": { "source": "codex", "configDir": "~/.codex" }
118
+ "quota": { "source": "codex" }
115
119
  },
116
120
  "pi-anthropic": {
117
121
  "agent": "pi", "configDir": "~/.pi/anthropic", "defaultModel": "opus",
118
122
  "modelAliases": { "opus": "anthropic/opus" },
119
- "quota": { "source": "claude", "configDir": "~/.claude" }
123
+ "quota": { "source": "claude" }
120
124
  }
121
125
  }
122
126
  }
@@ -135,9 +139,9 @@ Remove `code.profile` above to use automatic per-agent selection: the sole Codex
135
139
  Each profile accepts:
136
140
 
137
141
  - `default` — optional boolean preference for this profile's agent. With several matching profiles, exactly one true flag selects the preference. Omitted and false are equivalent; a sole matching profile needs no flag. At most one true flag per agent is allowed, even with a named choice. Independent defaults for different agents are valid. The flag never selects an agent kind.
138
- - `configDir` — native configuration and authentication storage: `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, or `PI_CODING_AGENT_DIR`. `~/` uses the configured home; relative paths resolve against the settings directory. Omission keeps native inherited/default storage.
142
+ - `configDir` — native directory selection through `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, or `PI_CODING_AGENT_DIR`. Omit it for ordinary setup: the caller's variable is inherited unless `env` or `unset` changes it; without a variable, native defaults apply. `null` deliberately removes that variable to force native-default directory behavior. A string resolves and sets it, including when naming the default path. `~/` uses the configured home; relative paths resolve against the settings directory.
139
143
  - `env` — literal environment values for non-secret configuration. No interpolation or shell expansion. Keep credentials in native stores or separately provisioned process environments.
140
- - `unset` — inherited variables to remove, including API keys that select an unintended authentication route. A variable cannot occur in both `env` and `unset`. An explicit `configDir` cannot coexist with its native directory variable in either field.
144
+ - `unset` — inherited variables to remove, including API keys that select an unintended authentication route. A variable cannot occur in both `env` and `unset`. A string or null `configDir` cannot coexist with its native directory variable in either field.
141
145
  - `defaultModel` — new-session default, validated against accepted names. Omission uses the native default.
142
146
  - `models` — a nonempty list replaces accepted names. Otherwise Claude accepts `fable`, `opus`, `sonnet`, `haiku`, Codex accepts `astra`, `sol`, `terra`, `luna`, and both add configured alias names. Pi accepts every nonblank selector. An empty list adds no override.
143
147
  - `modelAliases` — one-step user-facing name → native selector mappings. Validate the chosen name first, expand once, then apply native handling. A Codex alias target such as `sol` still resolves through its bundled catalog.
@@ -146,9 +150,11 @@ Each profile accepts:
146
150
 
147
151
  Selection for new sessions, help, `guide code`, and quota: `--profile` → project registry selection → `code.profile` → automatic resolution. Resume inserts its latest recorded named profile before the global selection. Named choices bypass parent detection; a missing name fails rather than falling through. Automatic resolution selects a sole matching profile or the unique true flag among several matches; without either, several matches are ambiguous. No matching profile uses the detected agent's built-ins. Without a parent, zero or several profiles require a named choice, regardless of flags. Several detected kinds always require a named choice. Project selections use the actual working directory, matching linked worktrees through AlignFirst; help/guide/quota need no `.plans` or Git repository. `--profile` is rejected on status and unrelated guide topics.
148
152
 
149
- `aligndev code quota [--profile <name>]` needs neither a ticket nor `.plans` and starts no coding session. Explicit quota settings start from the original caller environment, apply only their own `unset`, `env` and source-specific `configDir`, then strip parent-session identities. Coding-profile overrides and Pi credentials are not copied into the quota environment. The same path and validation rules apply. For multiple accounts, set quota `configDir` explicitly; omission deliberately keeps the native CLI's inherited/default configuration. Pair each Pi profile with the intended Codex or Claude account, as in the examples above. Reports name the profile and native source; the limits belong to that CLI's account. AlignDev does not verify that it matches Pi's account or infer it from a model. Native requests time out after 30 seconds and await bounded process cleanup.
153
+ `aligndev code quota [--profile <name>]` needs neither a ticket nor `.plans` and starts no coding session. Explicit quota settings start from the original caller environment, apply only their own `unset`, `env` and source-specific `configDir`, then strip parent-session identities. Coding-profile overrides and Pi credentials are not copied into the quota environment. The same path and validation rules apply. Select quota storage only when needed: omission inherits independently from the original caller, null removes the source's native directory variable, and a string selects explicit storage. Pair each Pi profile with the intended Codex or Claude account, using a custom quota directory when account separation is intended. Reports name the profile and native source; the limits belong to that CLI's account. AlignDev does not verify that it matches Pi's account or infer it from a model. Native requests time out after 30 seconds and await bounded process cleanup.
150
154
 
151
- The child inherits the caller environment, removes `unset`, then applies `env` and `configDir`. Parent-session identities are stripped afterward, and required adapter values win. The same finalized environment reaches discovery, execution and native context lookup. Help, guides and failures identify native storage selected through `configDir`, profile environment overrides, inherited variables or profile removal. They show environment-variable names and origins, never their values. Login must reproduce that effective environment and cwd. No environment values are printed or saved in run metadata.
155
+ For example, `"configDir": null` forces native-default mode despite an inherited directory variable; `"configDir": "~/.claude-work"` deliberately selects custom Claude storage. On macOS, explicitly setting `CLAUDE_CONFIG_DIR` to the default path can select different Keychain credentials from leaving it unset. Such a string remains valid and is distinct from omission or null. Confirm the intended mode before changing an existing selection; AlignDev performs no settings rewrite, credential transfer or automatic login. A null reset changes only directory routing, not HOME, PATH or API-key precedence.
156
+
157
+ The child inherits the caller environment, removes `unset`, then applies `env` and the directory selection (setting a string or removing the native variable for null). Parent-session identities are stripped afterward, and required adapter values win. The same finalized environment reaches discovery, execution and native context lookup. Help, guides and failures identify native storage selected through a string `configDir`, a null reset, profile environment overrides, inherited variables or profile removal. They show environment-variable names and origins, never their values. Login must reproduce that effective environment and cwd. No environment values are printed or saved in run metadata.
152
158
 
153
159
  Resume requires the same native agent and, for Pi, the same real directory. A selected account must contain the native conversation; failure never falls back to an old profile or accepts a new conversation. `--model` overrides the recorded user-facing model; otherwise that name is retained and validated under the current profile. A disallowed retained name requires an explicit replacement; a recorded null keeps the native conversation's model. Profile defaults apply only to new sessions. Retained aliases use the selected profile's current mappings, so changing a mapping can change the native target. Session metadata records profile, agent, chosen name, native ID and cwd; historical records with blank or missing profiles read as null. Unless an explicit, project or global named choice replaces null, resume uses detected built-ins, ignoring configured profile counts and flags, and records null in the new run. No or several detected parents still fail. Original records remain unchanged. A deleted recorded name needs an explicit or project replacement; global selection and inference cannot rescue it. Status reads durable metadata even when launch settings are invalid or a profile has been deleted.
154
160
 
@@ -173,7 +179,9 @@ Install the setup skill where your agent will assemble the deployment's private
173
179
  npx -y skills add https://github.com/paleo/alignfirst --global --skill alignfirst-setup-guide
174
180
  ```
175
181
 
176
- Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code, Codex or Pi variant, and writes the installation, security, operation and recovery runbooks. Each managed project receives the full preparation contract: the `alignfirst context` section in its `AGENTS.md`, an optional work-files repository, docmap, isolated workspaces and a project-specific `DEVELOPERS.md`.
182
+ Deployments require null or a string for every coding profile and enabled explicit quota source; omission is invalid there. Generated service defaults use null. Inventory still records absolute filesystem paths, while native commands unset the directory variable for null or set its resolved value for a string.
183
+
184
+ Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code, Codex or Pi variant, and writes the installation, security, operation and recovery runbooks. Each managed project receives the preparation contract: project context, usable work files, docmap, runtime procedures and a project-specific `DEVELOPERS.md`, in the repository or its companion. Full workspace tooling is optional; lightweight worktrees provide isolation when it is absent.
177
185
 
178
186
  ## Under the Hood
179
187
 
package/dist/cli.js CHANGED
@@ -8,6 +8,7 @@ import { errorMessage } from "./errors.js";
8
8
  import { runGuide } from "./guide/guide-cli.js";
9
9
  import { readPackageVersion } from "./package-version.js";
10
10
  import { runProject } from "./project/project-cli.js";
11
+ import { runWorktree } from "./worktree/worktree-cli.js";
11
12
  export async function main(options) {
12
13
  const ctx = resolveContext(options);
13
14
  const [command, ...tokens] = (options?.argv ?? process.argv).slice(2);
@@ -19,12 +20,17 @@ export async function main(options) {
19
20
  ctx.stdout.write(`${readPackageVersion()}\n`);
20
21
  return 0;
21
22
  }
22
- if (command !== "code" && command !== "project" && command !== "guide") {
23
+ if (command !== "code" &&
24
+ command !== "project" &&
25
+ command !== "guide" &&
26
+ command !== "worktree") {
23
27
  const error = command === undefined ? "Error: no command given." : `Error: unknown command "${command}".`;
24
28
  ctx.stderr.write(`${error}\n\n${renderHelp(ctx.forms.aligndev)}`);
25
29
  return 1;
26
30
  }
27
31
  try {
32
+ if (command === "worktree")
33
+ return runWorktree(tokens, ctx);
28
34
  if (command === "code")
29
35
  return await runCode(tokens, () => loadConfig(ctx.home), ctx);
30
36
  const config = loadConfig(ctx.home);
@@ -44,6 +50,10 @@ function renderHelp(aligndev) {
44
50
  `${aligndev} project <command> [<options>]`,
45
51
  "List projects, check their inventory, claim port ranges.",
46
52
  ],
53
+ [
54
+ `${aligndev} worktree <command> [<options>]`,
55
+ "Create, list and safely remove lightweight Git worktrees.",
56
+ ],
47
57
  [`${aligndev} guide [<topic>]`, "Print the assistant's playbook and guides."],
48
58
  [`${aligndev} -h, --help`],
49
59
  [`${aligndev} -v, --version`],
@@ -5,6 +5,7 @@ import { loadCatchup, loadContext, openTicket, reserveSideTicket } from "../alig
5
5
  import { resolveCodeConfig, resolveQuotaConfig, } from "../config.js";
6
6
  import { errorMessage } from "../errors.js";
7
7
  import { companionInUse, readProjectReport, } from "../project/layout.js";
8
+ import { validateEffectivePlans } from "../project/plans.js";
8
9
  import { createAgentAdapter } from "./coding-agent.js";
9
10
  import { expandModelAlias, resolveModels } from "./models.js";
10
11
  import { describeNativeStorage } from "./native-context.js";
@@ -46,6 +47,8 @@ export async function runCode(tokens, loadSettings, ctx) {
46
47
  }
47
48
  const config = loadSettings();
48
49
  const report = readReport(ctx);
50
+ if (command.kind === "session")
51
+ validateEffectivePlans(ctx);
49
52
  const records = command.kind === "session" ? listSessionRecords(report.locations._aligndev.path) : [];
50
53
  const args = command.kind === "session" ? command.args : undefined;
51
54
  const previous = args?.resume === undefined
@@ -380,12 +383,6 @@ async function runSession(args, code, ctx, report, records, previous) {
380
383
  const { cwd, env, stdout, stderr, forms, alignfirstCommand, modelResolver } = ctx;
381
384
  const { agent } = code;
382
385
  const tree = sessionTreeOf(report, cwd);
383
- const plans = report.locations[".plans"];
384
- if (!plans.exists) {
385
- stderr.write(`Error: no .plans/ directory at ${displayPath(tree.cwd, plans.path)}. ` +
386
- `Create it, or run \`${forms.alignfirst} plans setup <clone>\`.\n`);
387
- return 1;
388
- }
389
386
  const resolvedTicket = args.noTicket
390
387
  ? undefined
391
388
  : (args.ticket ??
@@ -765,6 +762,18 @@ Config (~/.alignfirst/aligndev.settings.json):
765
762
  code.profile Global named profile. Effective profile: ${profile ?? "(built-in)"} (selected: ${agent}).
766
763
  code.profiles Complete named profiles: agent, default, configDir, env, unset,
767
764
  defaultModel, models, modelAliases, skipPermissions, quota. No inheritance.
765
+ profile.configDir Omit for ordinary setup: inherit the native directory variable unless
766
+ env/unset changes it; otherwise use native defaults. null deliberately
767
+ removes it for native-default mode. A string resolves and sets it,
768
+ even when naming the default path. ~/ uses the configured home;
769
+ relative paths use the settings directory. String/null conflicts with
770
+ the matching native variable in env/unset: CLAUDE_CONFIG_DIR (claude),
771
+ CODEX_HOME (codex), PI_CODING_AGENT_DIR (pi).
772
+ profile.quota source: claude, codex or none. Enabled sources use the same omitted/null/
773
+ string directory rules, starting from the original caller env without
774
+ coding-profile overrides. Omitted Claude/Codex quota uses the coding
775
+ environment; pi requires an explicit source or none. none accepts no
776
+ other recognized fields, including configDir: null.
768
777
  profile.default Optional boolean preference for that agent; at most one true per agent.
769
778
  A sole matching profile is inferred without a flag. No matching profile
770
779
  uses detected built-ins. Without a parent, only a sole total profile is
@@ -780,7 +789,11 @@ Native configuration: ${describeNativeStorage(code)}.
780
789
  Login must use the same effective environment as the child: apply profile unset/env/configDir,
781
790
  including HOME, PATH and credential routing, from the same working directory. Then use
782
791
  ${authenticationInstruction(agent)}. A bare login in another shell may use a different account.
783
- Environment values are omitted.
792
+ Environment values are omitted. A null reset changes directory routing only, not HOME, PATH
793
+ or API-key precedence. On macOS, setting Claude's default path can select different Keychain
794
+ credentials from an unset CLAUDE_CONFIG_DIR. Confirm the intended mode before changing existing
795
+ strings; no automatic settings rewrite, login or credential transfer occurs. OpenClaw deployments
796
+ require null/string selections for every coding profile and enabled explicit quota source.
784
797
 
785
798
  Selected-agent permissions: ${permissionMode}
786
799
  The project's companion directory is prepared before launch; pi uses ordinary OS access.
@@ -1,9 +1,11 @@
1
1
  import { CONFIG_DIRECTORY_VARIABLES } from "../config.js";
2
2
  export function describeNativeStorage(code) {
3
3
  const variable = CONFIG_DIRECTORY_VARIABLES[code.agent];
4
- const directory = code.configDir === undefined
5
- ? describeVariable(code, variable)
6
- : `${variable}: configDir ${JSON.stringify(code.configDir)}`;
4
+ const directory = code.configDir === null
5
+ ? `${variable}: unset by configDir: null; native defaults apply`
6
+ : code.configDir === undefined
7
+ ? describeVariable(code, variable)
8
+ : `${variable}: configDir ${JSON.stringify(code.configDir)}`;
7
9
  const home = ["HOME", "USERPROFILE"]
8
10
  .filter((name) => code.childEnv[name] !== undefined || code.unset?.includes(name))
9
11
  .map((name) => describeVariable(code, name));
package/dist/config.d.ts CHANGED
@@ -24,7 +24,7 @@ export interface CodeSettings {
24
24
  export interface CodingProfile {
25
25
  agent: CodingAgent;
26
26
  default?: boolean;
27
- configDir?: string;
27
+ configDir?: string | null;
28
28
  defaultModel?: string;
29
29
  models?: string[];
30
30
  modelAliases?: Record<string, string>;
@@ -35,7 +35,7 @@ export interface CodingProfile {
35
35
  }
36
36
  export interface QuotaSettings {
37
37
  source: "claude" | "codex" | "none";
38
- configDir?: string;
38
+ configDir?: string | null;
39
39
  env?: Record<string, string>;
40
40
  unset?: string[];
41
41
  }
package/dist/config.js CHANGED
@@ -48,7 +48,7 @@ export function loadConfig(home) {
48
48
  for (const [name, profile] of Object.entries(code.profiles ?? {})) {
49
49
  const field = `code.profiles[${JSON.stringify(name)}]`;
50
50
  validateEnvironment(profile, profile.agent, field, path);
51
- if (profile.configDir !== undefined)
51
+ if (typeof profile.configDir === "string")
52
52
  profile.configDir = resolvePath(profile.configDir, home, path);
53
53
  if (profile.quota !== undefined) {
54
54
  const quota = profile.quota;
@@ -60,7 +60,7 @@ export function loadConfig(home) {
60
60
  else {
61
61
  validateEnvironment(quota, quota.source, `${field}.quota`, path);
62
62
  }
63
- if (quota.configDir !== undefined)
63
+ if (typeof quota.configDir === "string")
64
64
  quota.configDir = resolvePath(quota.configDir, home, path);
65
65
  }
66
66
  }
@@ -130,6 +130,8 @@ function invalidConfig(path, detail) {
130
130
  return new Error(`Error: invalid aligndev config ${path}: ${detail}`);
131
131
  }
132
132
  function directoryValue(value, path) {
133
+ if (value === null)
134
+ return null;
133
135
  nonblankString(value, path);
134
136
  return nulFreeString(value, path);
135
137
  }
@@ -157,18 +159,24 @@ export function resolveQuotaConfig(code, callerEnv) {
157
159
  if (quota === undefined) {
158
160
  if (code.agent === "pi") {
159
161
  throw new Error("Pi account quota is unsupported without explicit configuration: " +
160
- "set quota.source to claude or codex with its native configDir, or none to disable it.");
162
+ "set quota.source to claude or codex, or none to disable it.");
161
163
  }
162
164
  return { source: code.agent, env: code.childEnv };
163
165
  }
164
- const overrides = { ...quota.env };
165
- if (quota.configDir !== undefined)
166
- overrides[CONFIG_DIRECTORY_VARIABLES[quota.source]] = quota.configDir;
167
166
  return {
168
167
  source: quota.source,
169
- env: buildAgentEnv(callerEnv, quota.unset ?? [], overrides),
168
+ env: buildNativeEnv(callerEnv, quota, quota.source),
170
169
  };
171
170
  }
171
+ function buildNativeEnv(callerEnv, settings, agent, required = {}) {
172
+ const variable = CONFIG_DIRECTORY_VARIABLES[agent];
173
+ const overrides = { ...settings.env };
174
+ if (typeof settings.configDir === "string")
175
+ overrides[variable] = settings.configDir;
176
+ const unset = settings.unset ?? [];
177
+ const removals = settings.configDir === null ? [...unset, variable] : unset;
178
+ return buildAgentEnv(callerEnv, removals, overrides, required);
179
+ }
172
180
  export function resolveCodeConfig(config, env, selection = {}) {
173
181
  validateReferences(config);
174
182
  const name = selection.explicit ?? selection.project?.profile ?? selection.recorded ?? config.code.profile;
@@ -186,15 +194,12 @@ export function resolveCodeConfig(config, env, selection = {}) {
186
194
  effectiveName = automatic.name;
187
195
  }
188
196
  checkDefaultModel(profile, config.path, effectiveName);
189
- const overrides = { ...profile.env };
190
- if (profile.configDir !== undefined)
191
- overrides[CONFIG_DIRECTORY_VARIABLES[profile.agent]] = profile.configDir;
192
197
  return {
193
198
  ...profile,
194
199
  profile: effectiveName ?? null,
195
200
  skipPermissions: profile.skipPermissions ?? false,
196
201
  unset: profile.unset ?? [],
197
- childEnv: buildAgentEnv(env, profile.unset ?? [], overrides, createAgentAdapter(profile.agent).env),
202
+ childEnv: buildNativeEnv(env, profile, profile.agent, createAgentAdapter(profile.agent).env),
198
203
  };
199
204
  }
200
205
  function validateReferences(config) {
@@ -6,11 +6,12 @@ export const PLAYBOOK_TOPICS = {
6
6
  openclaw: [
7
7
  "channel-handling",
8
8
  "working-session",
9
+ "work-files-setup",
9
10
  "project-workspace-setup",
10
11
  "project-lifecycle",
11
12
  "consultation",
12
13
  "slack-message-tool",
13
14
  "discord-message-tool",
14
15
  ],
15
- codingAgent: ["working-session", "project-workspace-setup", "consultation"],
16
+ codingAgent: ["working-session", "work-files-setup", "project-workspace-setup", "consultation"],
16
17
  };
@@ -0,0 +1,9 @@
1
+ import type { CommandForms } from "../command-form.js";
2
+ import type { GitContext } from "../worktree/git.js";
3
+ import { type ProjectReport } from "./layout.js";
4
+ export interface PlansContext extends GitContext {
5
+ alignfirstCommand: string[];
6
+ forms: CommandForms;
7
+ }
8
+ export declare function validateEffectivePlans(ctx: PlansContext): string;
9
+ export declare function readReport(ctx: PlansContext): ProjectReport;
@@ -0,0 +1,40 @@
1
+ import { isAbsolute } from "node:path";
2
+ import { runAlignfirst } from "../alignfirst-cli.js";
3
+ import { errorMessage } from "../errors.js";
4
+ import { readProjectReport } from "./layout.js";
5
+ export function validateEffectivePlans(ctx) {
6
+ try {
7
+ const result = runAlignfirst(ctx.alignfirstCommand, ["plans", "check", "--json"], ctx.cwd, ctx.env);
8
+ if (result.status !== 0) {
9
+ const diagnostic = result.stderr.trimEnd();
10
+ throw new Error(diagnostic === "" ? "alignfirst plans check failed" : diagnostic);
11
+ }
12
+ let value;
13
+ try {
14
+ value = JSON.parse(result.stdout);
15
+ }
16
+ catch {
17
+ throw new Error(`Invalid alignfirst plans check JSON report for ${ctx.cwd}`);
18
+ }
19
+ if (!isRecord(value) ||
20
+ !isRecord(value.plans) ||
21
+ typeof value.plans.target !== "string" ||
22
+ value.plans.target.trim().length === 0 ||
23
+ !isAbsolute(value.plans.target)) {
24
+ throw new Error(`Invalid alignfirst plans check report for ${ctx.cwd}`);
25
+ }
26
+ return value.plans.target;
27
+ }
28
+ catch (error) {
29
+ throw new Error(`${errorMessage(error)}\nSee \`${ctx.forms.aligndev} guide work-files-setup\` for authorized preparation.`);
30
+ }
31
+ }
32
+ function isRecord(value) {
33
+ return typeof value === "object" && value !== null;
34
+ }
35
+ export function readReport(ctx) {
36
+ const report = readProjectReport(ctx.alignfirstCommand, ctx.cwd, ctx.env);
37
+ if ("error" in report)
38
+ throw new Error(report.error);
39
+ return report;
40
+ }
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { realpathSync } from "node:fs";
3
3
  import { basename } from "node:path";
4
+ import { readWorktrees } from "../worktree/git.js";
4
5
  import { errorMessage, isNodeError } from "../errors.js";
5
6
  const URL_WITH_AUTHORITY = /^[A-Za-z][A-Za-z\d+.-]*:\/\//u;
6
7
  export function getProjectStatus(inventory, projectPath) {
@@ -37,7 +38,11 @@ function buildProjectDetails(project) {
37
38
  aligndev: project.description.aligndev,
38
39
  locations: project.description.locations,
39
40
  workspaces: project.workspaces,
40
- worktrees: readWorktrees(project.path),
41
+ worktrees: readWorktrees({ cwd: project.path, env: process.env }, project.path).map((tree) => ({
42
+ branch: tree.branch,
43
+ name: basename(tree.path),
44
+ path: tree.path,
45
+ })),
41
46
  };
42
47
  }
43
48
  function readRemoteHost(projectPath) {
@@ -74,29 +79,6 @@ function scpRemoteHost(remoteUrl) {
74
79
  const match = /^(?:[^@/:\s]+@)?(\[[^\]]+\]|[^/:\s]+):/u.exec(remoteUrl);
75
80
  return match?.[1] ?? null;
76
81
  }
77
- function readWorktrees(projectPath) {
78
- return runGit(projectPath, "worktree", "list", "--porcelain", "-z")
79
- .split("\0\0")
80
- .filter((record) => record.length > 0)
81
- .map(parseWorktree);
82
- }
83
- function parseWorktree(record) {
84
- const fields = record.split("\0");
85
- const pathField = fields.find((field) => field.startsWith("worktree "));
86
- if (pathField === undefined)
87
- throw new Error("Git returned a worktree record without a path");
88
- const path = realpathSync(pathField.slice("worktree ".length));
89
- const branchField = fields.find((field) => field.startsWith("branch "));
90
- return {
91
- branch: branchField === undefined ? null : shortBranch(branchField.slice("branch ".length)),
92
- name: basename(path),
93
- path,
94
- };
95
- }
96
- function shortBranch(branch) {
97
- const prefix = "refs/heads/";
98
- return branch.startsWith(prefix) ? branch.slice(prefix.length) : branch;
99
- }
100
82
  function runGit(projectPath, ...args) {
101
83
  try {
102
84
  return execFileSync("git", ["-C", projectPath, ...args], {
@@ -0,0 +1,20 @@
1
+ import { type Repository, type Worktree } from "./git.js";
2
+ import type { WorktreeContext } from "./worktree-cli.js";
3
+ export interface AddOptions {
4
+ path: string;
5
+ branch: string;
6
+ newBranch: boolean;
7
+ start?: string;
8
+ }
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;
@@ -0,0 +1,175 @@
1
+ import { appendFileSync, 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, isInside, isProjectTrackedDirectory, pathExists, readRepository, } from "./git.js";
6
+ export function addWorktree(ctx, repo, options) {
7
+ const prepared = prepareAdd(ctx, repo, options);
8
+ createGitWorktree(ctx, options, prepared);
9
+ return finishSetup(ctx, repo, options, prepared);
10
+ }
11
+ function prepareAdd(ctx, repo, options) {
12
+ const destination = validateDestination(ctx, repo, options.path);
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 };
20
+ }
21
+ function validateDestination(ctx, repo, input) {
22
+ const literal = resolve(ctx.cwd, input);
23
+ if (pathExists(literal))
24
+ throw new Error(`Destination already exists: ${literal}`);
25
+ const destination = canonicalPath(literal);
26
+ let ancestor = dirname(destination);
27
+ while (!pathExists(ancestor))
28
+ ancestor = dirname(ancestor);
29
+ if (!statSync(ancestor).isDirectory())
30
+ throw new Error(`Destination parent is not a directory: ${ancestor}`);
31
+ for (const tree of repo.worktrees) {
32
+ if (isInside(tree.path, destination) || isInside(destination, tree.path)) {
33
+ throw new Error(`Destination overlaps registered worktree ${tree.path}. Choose a new sibling directory.`);
34
+ }
35
+ }
36
+ return destination;
37
+ }
38
+ function prepareBranch(ctx, repo, options) {
39
+ git(ctx, "check-ref-format", `refs/heads/${options.branch}`);
40
+ if (options.branch.startsWith("-") || options.branch === "HEAD")
41
+ throw new Error("Invalid branch name.");
42
+ const occupied = repo.worktrees.find((tree) => tree.branch === options.branch);
43
+ if (occupied !== undefined)
44
+ throw new Error(`Branch ${options.branch} is already checked out at ${occupied.path}; reuse that worktree.`);
45
+ const localRef = `refs/heads/${options.branch}`;
46
+ const locals = git(ctx, "for-each-ref", "--format=%(refname)", "refs/heads").trim().split("\n");
47
+ const exists = locals.includes(localRef);
48
+ if (options.newBranch && exists)
49
+ throw new Error(`Branch already exists: ${options.branch}`);
50
+ let start = options.start ?? "HEAD";
51
+ let create = options.newBranch;
52
+ let track = false;
53
+ if (!options.newBranch) {
54
+ if (exists)
55
+ start = localRef;
56
+ else {
57
+ const remotes = git(ctx, "for-each-ref", "--format=%(refname)", "refs/remotes")
58
+ .trim()
59
+ .split("\n")
60
+ .filter((ref) => ref.slice("refs/remotes/".length).split("/").slice(1).join("/") === options.branch);
61
+ if (remotes.length !== 1 || remotes[0] === undefined) {
62
+ throw new Error(remotes.length === 0
63
+ ? `No local or fetched remote branch: ${options.branch}`
64
+ : `Ambiguous remote branch ${options.branch}: ${remotes.join(", ")}. Choose explicitly with -b <branch> <remote/ref>.`);
65
+ }
66
+ start = remotes[0];
67
+ create = true;
68
+ track = true;
69
+ }
70
+ }
71
+ const commit = git(ctx, "rev-parse", "--verify", "--end-of-options", `${start}^{commit}`).trim();
72
+ return { create, start: !create ? options.branch : start, commit, track };
73
+ }
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
+ function createGitWorktree(ctx, options, prepared) {
111
+ const { branch, destination } = prepared;
112
+ const createArgs = branch.create
113
+ ? ["-b", options.branch, ...(branch.track ? ["--track"] : [])]
114
+ : [];
115
+ try {
116
+ git(ctx, "worktree", "add", ...createArgs, "--", destination, branch.start);
117
+ }
118
+ catch (error) {
119
+ 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
+ }
121
+ }
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
+ }