aligndev 0.27.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
 
@@ -177,7 +181,7 @@ npx -y skills add https://github.com/paleo/alignfirst --global --skill alignfirs
177
181
 
178
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.
179
183
 
180
- 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`.
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.
181
185
 
182
186
  ## Under the Hood
183
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 ??
@@ -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
+ }
@@ -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;