aligndev 0.22.1 → 0.23.1

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
@@ -68,17 +68,18 @@ Then ask your session to work with aligndev.
68
68
 
69
69
  ## Configuration
70
70
 
71
- `~/.alignfirst/aligndev.config.json` is optional. Without it, every key takes its default. For example, to launch Codex as the agent, whatever runs the assistant:
71
+ `~/.alignfirst/aligndev.settings.json` is optional. Without it, every key takes its default. For example, to launch Codex as the agent, whatever runs the assistant, with `sol` as the default model:
72
72
 
73
73
  ```json
74
74
  {
75
- "code": { "agent": "codex" }
75
+ "code": { "agent": "codex", "defaultModel": "sol" }
76
76
  }
77
77
  ```
78
78
 
79
79
  - `platform` — `codingAgent` (default) for a coding-agent assistant, `openclaw` for an OpenClaw bot.
80
80
  - `projectsRoot` — the projects directory of an OpenClaw host. Required by `openclaw`. `~/` expands to the home directory; a relative path resolves against `~/.alignfirst/`.
81
81
  - `code.agent` — the agent: `claude` or `codex`. Default: the coding agent that runs the assistant, detected from its environment. Set it to launch the other one, or when both are detected, as with Codex in a VS Code terminal where the Claude Code extension is installed.
82
+ - `code.defaultModel` — the model of a new session started without `--model`, one of `code.models`. Default: the agent's own default. A resumed session keeps its model.
82
83
  - `code.models` — the models the assistant may choose from. Default: Claude's `fable`, `opus`, `sonnet`, `haiku`, or Codex's `astra`, `sol`, `terra`, `luna`.
83
84
  - `code.skipPermissions` — `true` runs Claude Code with `--dangerously-skip-permissions` instead of `--permission-mode auto`, and Codex with `--dangerously-bypass-approvals-and-sandbox` instead of `--sandbox workspace-write`. Default: `false`.
84
85
  - `code.unset` — environment variables to hide from the agent, such as an API key meant for another tool on the host.
@@ -102,7 +103,7 @@ Install the setup skill where your agent will assemble the deployment's private
102
103
  npx -y skills add https://github.com/paleo/alignfirst --global --skill alignfirst-setup-guide
103
104
  ```
104
105
 
105
- Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code or Codex variant, and writes the installation, security, operation and recovery runbooks. Each managed project receives the full preparation contract: the AlignFirst bootstrap line, an optional work-files repository, docmap, isolated workspaces and a project-specific `DEVELOPERS.md`.
106
+ Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code or Codex 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`.
106
107
 
107
108
  ## Under the Hood
108
109
 
package/dist/cli.js CHANGED
@@ -56,7 +56,7 @@ ${usage}
56
56
 
57
57
  Run \`${aligndev} <command> --help\` for the usage of a command.
58
58
 
59
- Config (optional): ~/.alignfirst/aligndev.config.json. "platform" (${PLATFORMS.join(" or ")})
59
+ Config (optional): ~/.alignfirst/aligndev.settings.json. "platform" (${PLATFORMS.join(" or ")})
60
60
  defaults to codingAgent. "code.agent" (${CODING_AGENTS.join(" or ")}) defaults to the coding agent that
61
61
  runs aligndev, detected from its environment.
62
62
  `;
@@ -1,7 +1,11 @@
1
1
  import { isCompacted } from "./run-agent.js";
2
+ // After the agent's turn, `claude -p` waits for its background work, but stops it after 10 minutes
3
+ // of idle waiting by default. `0` waits until the work ends.
4
+ const CLAUDE_ENV = { CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" };
2
5
  export function createClaudeAdapter() {
3
6
  return {
4
7
  executable: "claude",
8
+ env: CLAUDE_ENV,
5
9
  buildArgs: buildClaudeArgs,
6
10
  createState: createClaudeState,
7
11
  interpretLine: interpretClaudeLine,
@@ -52,9 +56,7 @@ export function interpretClaudeLine(line, state) {
52
56
  case "result":
53
57
  state.protocolComplete = true;
54
58
  state.protocolFailed = event.is_error === true;
55
- state.result = asString(event.result);
56
- if (state.protocolFailed)
57
- state.failure = state.result;
59
+ captureResult(asString(event.result), state);
58
60
  return;
59
61
  case "unparsed":
60
62
  return asString(event.raw);
@@ -73,6 +75,15 @@ export function assessClaudeState(state) {
73
75
  contextCompacted: isCompacted(state),
74
76
  };
75
77
  }
78
+ // Background work wakes the agent for more turns, each closed by its own `result` event. A turn
79
+ // with nothing to report closes with an empty one, which must not erase the previous result.
80
+ function captureResult(result, state) {
81
+ if (state.protocolFailed)
82
+ state.failure = result;
83
+ if (result === "" && state.result !== undefined)
84
+ return;
85
+ state.result = result;
86
+ }
76
87
  // What the newest assistant response holds in the context window. Claude reports cache reads and
77
88
  // writes beside `input_tokens`, so the occupancy is their sum plus the response itself. A subagent
78
89
  // message carries `parent_tool_use_id` and measures its own context, not the main conversation's.
@@ -54,7 +54,7 @@ export interface SessionArgs {
54
54
  export declare function runCode(tokens: string[], config: LoadedConfig, ctx: CodeContext): Promise<number>;
55
55
  export declare function parseCodeArgs(tokens: string[], aligndev: string): CodeCommand;
56
56
  export declare function validateSessionArgs(args: SessionArgs, models: readonly string[]): string | undefined;
57
- export declare function checkLaunchGuards(args: SessionArgs, agent: CodingAgent, realCwd: string, records: SessionRecord[]): string | undefined;
57
+ export declare function checkLaunchGuards(args: SessionArgs, agent: CodingAgent, realCwd: string, ticket: string | undefined, records: SessionRecord[]): string | undefined;
58
58
  export declare function resolveTicket(args: SessionArgs, records: SessionRecord[]): string | undefined;
59
59
  export interface RunInput {
60
60
  args: SessionArgs;
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync, realpathSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { loadCatchup, loadContext, openTicket, reserveSideTicket } from "../alignfirst-cli.js";
@@ -23,14 +23,6 @@ const SESSION_OPTIONS = {
23
23
  meta: { type: "string" },
24
24
  help: { type: "boolean", short: "h", default: false },
25
25
  };
26
- // Items whose companion copy the agent may edit: the companion becomes a writable directory.
27
- const WRITABLE_COMPANION_ITEMS = [
28
- ".alignfirst.json",
29
- ".alignfirst-instructions",
30
- "DEVELOPERS.md",
31
- "docs",
32
- ".plans",
33
- ];
34
26
  // Items the agent would not find in the repository: a new session gets `alignfirst context`.
35
27
  const CONTEXT_COMPANION_ITEMS = [
36
28
  ".alignfirst.json",
@@ -340,15 +332,14 @@ async function runSession(args, code, ctx) {
340
332
  return 1;
341
333
  }
342
334
  const records = listSessionRecords(tree.sessionsDir);
343
- const guardError = checkLaunchGuards(args, agent, tree.cwd, records);
335
+ const resolvedTicket = args.noTicket ? undefined : resolveTicket(args, records);
336
+ const guardError = checkLaunchGuards(args, agent, tree.cwd, resolvedTicket, records);
344
337
  if (guardError) {
345
338
  stderr.write(`${guardError}\n`);
346
339
  return 1;
347
340
  }
348
341
  const now = new Date();
349
- const ticket = args.noTicket
350
- ? reserveSideTicket(alignfirstCommand, cwd, env)
351
- : resolveTicket(args, records);
342
+ const ticket = args.noTicket ? reserveSideTicket(alignfirstCommand, cwd, env) : resolvedTicket;
352
343
  if (ticket !== undefined && !args.noTicket && args.resume === undefined) {
353
344
  openTicket(alignfirstCommand, cwd, ticket, env);
354
345
  }
@@ -362,12 +353,13 @@ async function runSession(args, code, ctx) {
362
353
  const contextContent = args.resume === undefined && companionInUse(report, CONTEXT_COMPANION_ITEMS)
363
354
  ? loadContext(alignfirstCommand, cwd, env)
364
355
  : undefined;
356
+ const model = selectModel(args, code, records);
365
357
  const sessionFilePath = resolveSessionFilePath(tree.sessionsDir, ticket, now);
366
- writeInitialSessionFile(sessionFilePath, buildFrontmatter(args, agent, now, tree.cwd, ticket));
358
+ writeInitialSessionFile(sessionFilePath, buildFrontmatter({ args, agent, model, now, realCwd: tree.cwd, ticket }));
367
359
  stdout.write(`Session file: ${displayPath(tree.cwd, sessionFilePath)}\n\n`);
368
360
  let executableModel;
369
361
  try {
370
- executableModel = await modelResolver(agent, args.model, {
362
+ executableModel = await modelResolver(agent, model, {
371
363
  cwd,
372
364
  env: buildAgentEnv(env, code.unset),
373
365
  });
@@ -384,7 +376,7 @@ async function runSession(args, code, ctx) {
384
376
  stderr.write(`${message}\n`);
385
377
  return 1;
386
378
  }
387
- const result = await runAgent(buildRunConfig({
379
+ const runConfig = buildRunConfig({
388
380
  args,
389
381
  code,
390
382
  report,
@@ -396,7 +388,9 @@ async function runSession(args, code, ctx) {
396
388
  catchupContent,
397
389
  contextContent,
398
390
  alignfirst: forms.alignfirst,
399
- }), createAgentAdapter(agent), stdout);
391
+ });
392
+ createMissingCompanion(report, runConfig.additionalDirectories);
393
+ const result = await runAgent(runConfig, createAgentAdapter(agent), stdout);
400
394
  if (args.resume === undefined && result.sessionId) {
401
395
  stdout.write(`\nSession ID: ${result.sessionId}\n`);
402
396
  }
@@ -409,7 +403,7 @@ async function runSession(args, code, ctx) {
409
403
  }
410
404
  // Fail-fast launch guards, run against the (healed) session records before anything is written.
411
405
  // Returns the error to print, or `undefined` when the launch may proceed.
412
- export function checkLaunchGuards(args, agent, realCwd, records) {
406
+ export function checkLaunchGuards(args, agent, realCwd, ticket, records) {
413
407
  if (args.resume !== undefined) {
414
408
  // A resumed run writes a new session file carrying the same sessionId as the original, so one
415
409
  // id can match several records — a running status on any of them blocks.
@@ -421,7 +415,7 @@ export function checkLaunchGuards(args, agent, realCwd, records) {
421
415
  return (`Error: session ${args.resume} is still running (pid ${running.frontmatter.pid}); ` +
422
416
  "wait for it to finish or kill it.");
423
417
  }
424
- const latest = [...matches].sort((a, b) => b.frontmatter.startedAt.localeCompare(a.frontmatter.startedAt))[0];
418
+ const latest = latestRecord(matches);
425
419
  if (latest.frontmatter.agent === null) {
426
420
  return (`Error: session ${args.resume} predates agent-aware sessions and cannot be resumed; ` +
427
421
  "start a new session.");
@@ -431,16 +425,28 @@ export function checkLaunchGuards(args, agent, realCwd, records) {
431
425
  `selected agent is ${agent}.`);
432
426
  }
433
427
  }
434
- // Protocol runs only: plain messages (answers, questions, plan executions) may run at any time.
428
+ // Protocol runs only, against other protocol runs: they share the working tree, and
429
+ // `alignfirst ticket --next` reserves no work-file prefix within a ticket.
435
430
  if (args.protocol !== undefined) {
436
- const busy = records.find((r) => r.frontmatter.status === "running" && r.frontmatter.cwd === realCwd);
437
- if (busy) {
438
- return (`Error: a protocol run is already active in this worktree (${busy.path}, ` +
439
- `pid ${busy.frontmatter.pid}); one protocol run at a time per worktree.`);
440
- }
431
+ const active = records.filter((r) => r.frontmatter.status === "running" && r.frontmatter.protocol !== null);
432
+ const sameWorktree = active.find((r) => r.frontmatter.cwd === realCwd);
433
+ if (sameWorktree)
434
+ return busyProtocolError(sameWorktree, "in this worktree");
435
+ const sameTicket = ticket === undefined ? undefined : active.find((r) => r.frontmatter.ticket === ticket);
436
+ if (sameTicket)
437
+ return busyProtocolError(sameTicket, `on ticket ${ticket}`);
441
438
  }
442
439
  return;
443
440
  }
441
+ function busyProtocolError(record, scope) {
442
+ return (`Error: a ${record.frontmatter.protocol} protocol run is already active ${scope} ` +
443
+ `(${record.path}, pid ${record.frontmatter.pid}); one protocol run at a time per worktree ` +
444
+ "and per ticket.");
445
+ }
446
+ // The newest record of a non-empty list: a resumed session has one record per run.
447
+ function latestRecord(records) {
448
+ return [...records].sort((a, b) => b.frontmatter.startedAt.localeCompare(a.frontmatter.startedAt))[0];
449
+ }
444
450
  function unknownResumeError(resume, records) {
445
451
  if (records.length === 0) {
446
452
  return `Error: unknown session id ${resume}; no session records exist.`;
@@ -485,19 +491,31 @@ function inferTicketFromMessage(message) {
485
491
  return;
486
492
  return [...candidates][0];
487
493
  }
488
- function buildFrontmatter(args, agent, now, realCwd, ticket) {
494
+ // `--model` wins. Otherwise a new session takes `code.defaultModel`, and a resume keeps the model
495
+ // of its latest run, unchecked against the current allowlist. `undefined` leaves the agent's
496
+ // default.
497
+ function selectModel(args, code, records) {
498
+ if (args.model !== undefined)
499
+ return args.model;
500
+ if (args.resume === undefined)
501
+ return code.defaultModel;
502
+ const runs = records.filter((r) => r.frontmatter.sessionId === args.resume);
503
+ return latestRecord(runs).frontmatter.model ?? undefined;
504
+ }
505
+ function buildFrontmatter(input) {
506
+ const { args, now, ticket } = input;
489
507
  return {
490
508
  status: "running",
491
- agent,
509
+ agent: input.agent,
492
510
  protocol: args.protocol ?? null,
493
511
  ticket: ticket ?? null,
494
- model: args.model ?? null,
512
+ model: input.model ?? null,
495
513
  sessionId: null,
496
514
  command: formatCommand(args),
497
515
  meta: args.meta ?? null,
498
516
  pid: process.pid,
499
517
  pidStartTime: readPidStartTime(process.pid),
500
- cwd: realCwd,
518
+ cwd: input.realCwd,
501
519
  startedAt: now.toISOString(),
502
520
  endedAt: null,
503
521
  exitReason: null,
@@ -539,6 +557,7 @@ export function buildRunConfig(input) {
539
557
  protocol: args.protocol,
540
558
  ticket: input.ticket,
541
559
  message: args.message,
560
+ newSession: args.resume === undefined,
542
561
  catchupContent: input.catchupContent,
543
562
  contextContent: input.contextContent,
544
563
  alignfirst: input.alignfirst,
@@ -548,15 +567,19 @@ export function buildRunConfig(input) {
548
567
  resume: args.resume,
549
568
  executableModel: input.executableModel,
550
569
  skipPermissions: code.skipPermissions,
551
- additionalDirectories: !code.skipPermissions &&
552
- report.companion !== null &&
553
- companionInUse(report, WRITABLE_COMPANION_ITEMS)
554
- ? [report.companion.dir]
555
- : [],
570
+ additionalDirectories: !code.skipPermissions && report.companion !== null ? [report.companion.dir] : [],
556
571
  unset: code.unset,
557
572
  env: input.env,
558
573
  };
559
574
  }
575
+ // A registered companion becomes writable before its directory exists: create it for the agent.
576
+ function createMissingCompanion(report, additionalDirectories) {
577
+ const { companion } = report;
578
+ if (companion === null || companion.exists || !additionalDirectories.includes(companion.dir)) {
579
+ return;
580
+ }
581
+ mkdirSync(companion.dir, { recursive: true });
582
+ }
560
583
  function renderHelp(agent, models, forms) {
561
584
  const { aligndev, alignfirst } = forms;
562
585
  const permissionMode = agent === "claude"
@@ -603,23 +626,25 @@ Options (new, resume):
603
626
  --catchup Load the ticket history before the message. new only.
604
627
  -m, --message "..." Message to send. Required for spec/aad, or without protocol/catchup.
605
628
  --message-file <path> Read the message from a UTF-8 file, or stdin with -. Exclusive with -m.
606
- --model <model> Model for a new session: one of ${models.join(", ")}. Omit to use the
607
- default model.
629
+ --model <model> One of ${models.join(", ")}. A new session defaults to
630
+ code.defaultModel, else to the coding agent's default. A resume keeps the
631
+ session's model.
608
632
  --meta "..." Opaque handoff string, stored verbatim in the session file frontmatter
609
633
  (\`meta:\`). aligndev never interprets it; a later reader of the session file
610
634
  (e.g. the caller reporting the run's outcome) can use it.
611
635
 
612
636
  ${requires}
613
637
 
614
- Config (~/.alignfirst/aligndev.config.json):
638
+ Config (~/.alignfirst/aligndev.settings.json):
615
639
  code.agent Coding agent: claude or codex (selected: ${agent}). Defaults to the coding
616
640
  agent that runs aligndev.
641
+ code.defaultModel Default model of a new session, one of the models accepted by --model.
617
642
  code.models List replacing the models accepted by --model.
618
643
  code.skipPermissions true to run the coding agent with permission prompts disabled.
619
644
  code.unset Env vars to strip from the coding agent child.
620
645
 
621
646
  Selected-agent permissions: ${permissionMode}
622
- The normal mode also makes the project's companion directory writable when it is in use.
647
+ The normal mode also makes the project's companion directory writable.
623
648
  ${modelBehavior}
624
649
 
625
650
  ${aligndev} code runs a coding agent in the foreground and blocks until it finishes, streaming the
@@ -81,7 +81,7 @@ function runCodexModelCatalog(context) {
81
81
  function codexAliasError(alias, error) {
82
82
  const detail = error instanceof Error ? error.message : String(error);
83
83
  return (`Unable to resolve Codex model alias ${JSON.stringify(alias)}: ${detail}. ` +
84
- "Update the Codex CLI, or set `code.models` in the aligndev config to an explicit full model " +
84
+ "Update the Codex CLI, or set `code.models` in the aligndev settings to an explicit full model " +
85
85
  "slug and select that value.");
86
86
  }
87
87
  function isRecord(value) {
@@ -1,9 +1,11 @@
1
1
  export declare const PROTOCOLS: readonly ["spec", "plan", "aad", "description", "review", "merge"];
2
+ export declare const RUN_CONTEXT: string;
2
3
  export type Protocol = (typeof PROTOCOLS)[number];
3
4
  export interface PromptInput {
4
5
  protocol?: string;
5
6
  ticket?: string;
6
7
  message?: string;
8
+ newSession: boolean;
7
9
  catchupContent?: string;
8
10
  contextContent?: string;
9
11
  alignfirst: string;
@@ -1,14 +1,20 @@
1
1
  export const PROTOCOLS = ["spec", "plan", "aad", "description", "review", "merge"];
2
+ // Opens every new session. Codex kills its subagents when its turn ends; Claude waits for them.
3
+ export const RUN_CONTEXT = "You run non-interactively. When your turn ends, the process exits and kills every subagent " +
4
+ "and background command still running. Before ending your turn, wait for each one you started " +
5
+ "and check its result.";
2
6
  export function buildPrompt(input) {
3
- const { protocol, ticket, message, catchupContent, contextContent, alignfirst } = input;
7
+ const { protocol, ticket, message, newSession, catchupContent, contextContent, alignfirst } = input;
4
8
  const instruction = protocol === undefined ? message : buildProtocolPrompt(alignfirst, protocol, ticket, message);
5
- if (catchupContent === undefined && contextContent === undefined)
6
- return instruction ?? "";
7
9
  const sections = [];
10
+ if (newSession)
11
+ sections.push("## Run context", RUN_CONTEXT);
8
12
  if (contextContent !== undefined)
9
13
  sections.push("## Project context", contextContent.trimEnd());
10
14
  if (catchupContent !== undefined)
11
15
  sections.push("## Ticket history", catchupContent);
16
+ if (sections.length === 0)
17
+ return instruction ?? "";
12
18
  sections.push("## Current instruction", currentInstruction(instruction, catchupContent));
13
19
  return sections.join("\n\n");
14
20
  }
@@ -41,6 +41,7 @@ export interface AgentAssessment {
41
41
  }
42
42
  export interface AgentAdapter {
43
43
  executable: string;
44
+ env?: Readonly<Record<string, string>>;
44
45
  buildArgs(config: RunConfig): string[];
45
46
  createState(): AgentProtocolState;
46
47
  interpretLine(line: string, state: AgentProtocolState): string | undefined;
@@ -63,7 +63,7 @@ function selectResult(adapter, state, assessment, outcome, authRequired) {
63
63
  function spawnAgent(config, adapter, state, out, spawnProcess) {
64
64
  const child = spawnProcess(adapter.executable, adapter.buildArgs(config), {
65
65
  cwd: config.cwd,
66
- env: buildAgentEnv(config.env, config.unset),
66
+ env: { ...buildAgentEnv(config.env, config.unset), ...adapter.env },
67
67
  stdio: ["pipe", "pipe", "pipe"],
68
68
  });
69
69
  const detachChildGuards = guardChildLifecycle(child, config.sessionFilePath, state);
package/dist/config.d.ts CHANGED
@@ -13,6 +13,7 @@ export interface ProjectsRoot {
13
13
  }
14
14
  export interface LoadedCodeConfig {
15
15
  agent?: CodingAgent;
16
+ defaultModel?: string;
16
17
  models?: string[];
17
18
  skipPermissions: boolean;
18
19
  unset: string[];
package/dist/config.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
3
  import { CODING_AGENTS, detectCodingAgents } from "./code/coding-agent.js";
4
+ import { resolveModels } from "./code/models.js";
4
5
  import { errorMessage } from "./errors.js";
5
6
  import { arrayOf, boolean, literal, nonEmptyString, object, optional, parseShape, string, } from "./json-shape.js";
6
7
  export const PLATFORMS = ["openclaw", "codingAgent"];
7
8
  const codeShape = object({
8
9
  agent: optional(literal(...CODING_AGENTS)),
10
+ defaultModel: optional(nonEmptyString),
9
11
  models: optional(arrayOf(string)),
10
12
  skipPermissions: optional(boolean),
11
13
  unset: optional(arrayOf(string)),
@@ -15,10 +17,11 @@ const configShape = object({
15
17
  projectsRoot: optional(nonEmptyString),
16
18
  code: optional(codeShape),
17
19
  });
18
- // An absent file is a normal state: every key takes its default.
20
+ // An absent file is a normal state: every key takes its default. A leftover file under the old
21
+ // name is an error, so a missed rename never silently drops the user's settings.
19
22
  export function loadConfig(home) {
20
- const path = join(home, ".alignfirst", "aligndev.config.json");
21
- const value = existsSync(path) ? parseConfigFile(path) : {};
23
+ const path = join(home, ".alignfirst", "aligndev.settings.json");
24
+ const value = existsSync(path) ? parseConfigFile(path) : absentConfig(home);
22
25
  const code = value.code ?? {};
23
26
  return {
24
27
  path,
@@ -28,12 +31,20 @@ export function loadConfig(home) {
28
31
  : { projectsRoot: resolveProjectsRoot(value.projectsRoot, home, path) }),
29
32
  code: {
30
33
  ...(code.agent === undefined ? {} : { agent: code.agent }),
34
+ ...(code.defaultModel === undefined ? {} : { defaultModel: code.defaultModel }),
31
35
  ...(code.models === undefined ? {} : { models: code.models }),
32
36
  skipPermissions: code.skipPermissions ?? false,
33
37
  unset: code.unset ?? [],
34
38
  },
35
39
  };
36
40
  }
41
+ function absentConfig(home) {
42
+ if (existsSync(join(home, ".alignfirst", "aligndev.config.json"))) {
43
+ throw new Error("Error: ~/.alignfirst/aligndev.config.json was renamed: " +
44
+ "move it to ~/.alignfirst/aligndev.settings.json");
45
+ }
46
+ return {};
47
+ }
37
48
  function parseConfigFile(path) {
38
49
  let value;
39
50
  try {
@@ -52,19 +63,32 @@ function resolveProjectsRoot(written, home, path) {
52
63
  return { path: join(home, written.slice(2)), written };
53
64
  return { path: isAbsolute(written) ? written : resolve(dirname(path), written), written };
54
65
  }
55
- // The configured `code.agent` wins; otherwise, the coding agent that runs aligndev.
56
66
  export function resolveCodeConfig(config, env) {
67
+ const code = { ...config.code, agent: resolveAgent(config, env) };
68
+ checkDefaultModel(code, config.path);
69
+ return code;
70
+ }
71
+ // The configured `code.agent` wins; otherwise, the coding agent that runs aligndev.
72
+ function resolveAgent(config, env) {
57
73
  const { agent } = config.code;
58
74
  if (agent !== undefined)
59
- return { ...config.code, agent };
75
+ return agent;
60
76
  const detected = detectCodingAgents(env);
61
77
  if (detected.length === 1)
62
- return { ...config.code, agent: detected[0] };
78
+ return detected[0];
63
79
  const problem = detected.length === 0
64
80
  ? "no coding agent detected: run aligndev from Claude Code or Codex, or set"
65
81
  : "both Claude Code and Codex detected: set";
66
82
  throw new Error(`Error: ${problem} "code.agent" (${CODING_AGENTS.join(" or ")}) in ${config.path}.`);
67
83
  }
84
+ function checkDefaultModel(code, path) {
85
+ if (code.defaultModel === undefined)
86
+ return;
87
+ const models = resolveModels(code.agent, code.models);
88
+ if (models.includes(code.defaultModel))
89
+ return;
90
+ throw new Error(`Error: code.defaultModel must be one of: ${models.join(", ")}, in ${path}.`);
91
+ }
68
92
  export function requireProjectsRoot(config) {
69
93
  if (config.projectsRoot !== undefined)
70
94
  return config.projectsRoot;
@@ -1,4 +1,4 @@
1
1
  import type { CodingAgent } from "../code/coding-agent.js";
2
2
  import type { CommandForms } from "../command-form.js";
3
3
  import type { Platform } from "../config.js";
4
- export declare function renderCodeGuide(platform: Platform, agent: CodingAgent, models: readonly string[], forms: CommandForms): string;
4
+ export declare function renderCodeGuide(platform: Platform, agent: CodingAgent, models: readonly string[], defaultModel: string | undefined, forms: CommandForms): string;
@@ -1,12 +1,13 @@
1
1
  import { renderGuideTemplate } from "./render-template.js";
2
- export function renderCodeGuide(platform, agent, models, forms) {
2
+ export function renderCodeGuide(platform, agent, models, defaultModel, forms) {
3
3
  return renderGuideTemplate("code.md", { platform }, forms, {
4
4
  AGENT: agent,
5
5
  AUTH_COMMAND: agent === "claude" ? "`claude`, then `/login`" : "`codex login`",
6
6
  PERMISSIONS: agent === "claude"
7
- ? "Normal runs use `--permission-mode auto`, plus `--add-dir <companion>` when the project's AlignFirst files live in its companion directory. `code.skipPermissions: true` in the aligndev config selects `--dangerously-skip-permissions`"
8
- : "Normal runs use `--sandbox workspace-write`, plus `--add-dir <companion>` when the project's AlignFirst files live in its companion directory. `code.skipPermissions: true` in the aligndev config selects `--dangerously-bypass-approvals-and-sandbox`",
7
+ ? "Normal runs use `--permission-mode auto`, plus `--add-dir <companion>` for a project with a companion directory. `code.skipPermissions: true` in the aligndev settings selects `--dangerously-skip-permissions`"
8
+ : "Normal runs use `--sandbox workspace-write`, plus `--add-dir <companion>` for a project with a companion directory. `code.skipPermissions: true` in the aligndev settings selects `--dangerously-bypass-approvals-and-sandbox`",
9
9
  MODELS: models.map((model) => `\`${model}\``).join(", "),
10
+ DEFAULT_MODEL: defaultModel === undefined ? "the coding agent's default" : `\`${defaultModel}\``,
10
11
  ALIGNFIRST_SETUP: forms.viaNpx
11
12
  ? "The project must be prepared for AlignFirst. `npx -y aligndev` runs the `alignfirst` CLI through `npx`."
12
13
  : "The project must be prepared for AlignFirst, with the `alignfirst` CLI installed (`npm install -g alignfirst`).",
@@ -42,11 +42,11 @@ function renderUsage(forms) {
42
42
  ${forms.aligndev} guide [<topic>] [--root <path>]
43
43
  ${forms.aligndev} guide --help
44
44
 
45
- Without a topic, prints the playbook of the platform set in the aligndev config.
45
+ Without a topic, prints the playbook of the platform set in the aligndev settings.
46
46
 
47
47
  Topics:
48
48
  code The delegation guide for \`${forms.aligndev} code\`.
49
- project The projects guide, openclaw only. --root overrides projectsRoot in the aligndev config.
49
+ project The projects guide, openclaw only. --root overrides projectsRoot in the aligndev settings.
50
50
 
51
51
  Playbook topics, by platform:
52
52
  ${playbookTopics.join("\n")}
@@ -63,7 +63,7 @@ function renderTopic(args, config, ctx) {
63
63
  function renderCodeTopic(config, ctx) {
64
64
  const code = resolveCodeConfig(config, ctx.env);
65
65
  const models = resolveModels(code.agent, code.models);
66
- return renderCodeGuide(config.platform, code.agent, models, ctx.forms);
66
+ return renderCodeGuide(config.platform, code.agent, models, code.defaultModel, ctx.forms);
67
67
  }
68
68
  function renderPlaybookTopic(topic, config, ctx) {
69
69
  if (topic !== undefined)
@@ -228,7 +228,7 @@ function findEnclosingRange(ranges, claim) {
228
228
  return;
229
229
  return ranges?.find((range) => containsRange(range, claim));
230
230
  }
231
- // Two projects can share a companion only through a `_` in a directory name.
231
+ // Two projects share a companion only when their registry `dir` values resolve to the same path.
232
232
  function reportSharedCompanions(projects, issues) {
233
233
  const projectsByCompanion = new Map();
234
234
  for (const project of projects) {
@@ -83,7 +83,7 @@ function parsePlans(value, path) {
83
83
  throw invalidReport(path);
84
84
  return value.folder === undefined ? {} : { folder: value.folder };
85
85
  }
86
- // The report's other companion fields (`key`, `flags`) are alignfirst's concern.
86
+ // The report's other companion fields (`key`, `items`) are alignfirst's concern.
87
87
  function parseCompanion(value, path) {
88
88
  if (value === null)
89
89
  return null;
@@ -56,7 +56,7 @@ function renderUsage(aligndev) {
56
56
  ${aligndev} project free-ports --size <n> [--range <code>] [--json] [--root <path>]
57
57
  ${aligndev} project --help
58
58
 
59
- --root defaults to projectsRoot in the aligndev config, then to the working directory.
59
+ --root defaults to projectsRoot in the aligndev settings, then to the working directory.
60
60
  A relative status <path> starts from the working directory.
61
61
  `;
62
62
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aligndev",
3
- "version": "0.22.1",
3
+ "version": "0.23.1",
4
4
  "license": "CC0-1.0",
5
5
  "author": "Thomas MUR",
6
6
  "description": "The AlignDev CLI: the assistant's playbook, coding-agent delegation, and project inventory.",
@@ -37,7 +37,7 @@ As soon as the run is backgrounded, tell the user — in the user's language —
37
37
 
38
38
  Each ticketed run writes `.plans/<ticket>/_aligndev/<stamp>.md`. This file is the durable record of the run. It may live in the project's companion directory; the `sessionFile:` line of `{{ALIGNDEV}} code status` gives the actual path. Its frontmatter carries `status` (`running` → `succeeded`/`failed`) and the `sessionId`, and the `---- Result ----` block holds the outcome.
39
39
 
40
- **One protocol run at a time per workspace** — protocol runs share the working tree. Finish (or kill) the current protocol run before launching or resuming another. Plain messages (answers, questions) can be sent at any time.
40
+ **One protocol run at a time per workspace and per ticket** — protocol runs share the working tree, and the ticket's work files. Finish (or kill) the current protocol run before launching or resuming another. Plain messages (answers, questions) can be sent at any time.
41
41
 
42
42
  ## After a background run completes
43
43
 
@@ -74,7 +74,7 @@ Coding runs can be long (several hours is fine), and a foreground command is sub
74
74
 
75
75
  Run `{{ALIGNDEV}} code` outside your sandbox: the agent needs network access, and it writes outside the project, to its own session storage and possibly to the companion directory. In Codex, request escalated permissions for the command. In Claude Code with sandboxing enabled, run it with the sandbox disabled.
76
76
 
77
- **One protocol run at a time per worktree** — protocol runs share the working tree. Finish (or kill) the current protocol run before launching or resuming another. Plain messages (answers, questions) can be sent at any time.
77
+ **One protocol run at a time per worktree and per ticket** — protocol runs share the working tree, and the ticket's work files. Finish (or kill) the current protocol run before launching or resuming another. Plain messages (answers, questions) can be sent at any time.
78
78
 
79
79
  ## Background runs and reporting
80
80
 
@@ -120,10 +120,10 @@ Keep session files in place; they are the durable audit trail.
120
120
  | `--message "..."` | Message to send, written in English. `-m` is the short form. Required for `spec`, `aad`, and when neither `--protocol` nor `--catchup` is given. A message file also satisfies this requirement. |
121
121
  | `--message-file <path>` | Read a UTF-8 message file; `-` reads stdin. Mutually exclusive with `--message`. |
122
122
  | `--catchup` | Load the ticket history before the protocol and message. `new` only, requires a ticket. Alone, it returns a short synthesis. |
123
- | `--model <model>` | One of {{MODELS}}. Prefer the default model (omit the flag). |
123
+ | `--model <model>` | One of {{MODELS}}. A new session defaults to {{DEFAULT_MODEL}}; a resume keeps the session's model. Prefer the default (omit the flag). |
124
124
  | `--meta "..."` | Opaque handoff string stored verbatim in the session file's `meta:` frontmatter. `{{ALIGNDEV}} code` never reads it — it's for you to stash context the run's later reader needs (e.g. where to report the outcome). |
125
125
 
126
- The current coding agent is `{{AGENT}}`. `code.models` in the aligndev config replaces its displayed allowlist. Codex aliases `astra`, `sol`, `terra`, and `luna` resolve to the newest bundled matching slug only when selected; a configured full slug passes through unchanged.
126
+ The current coding agent is `{{AGENT}}`. `code.models` in the aligndev settings replaces its displayed allowlist. Codex aliases `astra`, `sol`, `terra`, and `luna` resolve to the newest bundled matching slug only when selected; a configured full slug passes through unchanged.
127
127
 
128
128
  `{{ALIGNDEV}} code status` checks that a `running` process still owns its recorded pid. A dead run is sealed as `status: failed`, `exitReason: terminated` before the command reports it. `{{ALIGNDEV}} code quota` works without a `.plans` directory and does not start a coding session. Its output follows the selected agent's available account limits.
129
129
 
@@ -20,7 +20,7 @@ Creation has a hard user-input gate. Before any filesystem, Git, port-allocation
20
20
 
21
21
  1. Settle the stack, allowed parent directory, project name, and port requirements with the user. Use the `{{ALIGNDEV}} guide project` output to constrain the choices.
22
22
  2. Create the main-worktree directory under the selected allowed parent. Initialize its Git repository on `main`.
23
- 3. Once the directory contains its `.git` directory, retain the canonical path as PROJECT_PATH. When the project declares ports, run `{{ALIGNDEV}} project free-ports --root <selected parent directory> --size <perWorkspace × maxWorkspaces> [--range <code>]` and retain the block; preparation through the setup guide writes it into `.alignfirst.json`. The selected parent's marker owns its port range. Report that `.alignfirst.json` was written and name the block.
23
+ 3. Once the directory contains its `.git` directory, retain the canonical path as PROJECT_PATH. When the project declares ports, run `{{ALIGNDEV}} project free-ports --root <selected parent directory> --size <port names × concurrent workspaces> [--range <code>]` and retain the block; preparation through the setup guide writes it into `.alignfirst.json`. The selected parent's marker owns its port range. Report that `.alignfirst.json` was written and name the block.
24
24
  4. Create `.plans/`, then run `{{ALIGNFIRST}} sync`. With an external ticket, run `{{ALIGNFIRST}} ticket {TICKET_ID} --next request.md` and append FILE_NAME to TICKET_DIR, exactly as printed, to get the path. Otherwise run `{{ALIGNFIRST}} ticket --side`; TICKET_ID is the reported `side-N`, and the path is `{TICKET_DIR}A1-request.md`. Write the complete creation request there from the starter and every later human message that supplied the gate's values. Record the project name, selected parent, stack, port requirements, and requested stopping point; never copy only the starter's task line. Then run `{{ALIGNFIRST}} sync`. The bot chooses the identifier and writes the request; the agent does neither. A later plans setup migrates this content when it replaces the directory with a symlink.
25
25
  5. Before delegating the bootstrap, run `{{ALIGNDEV}} guide code`. On a takeover turn, apply the pre-delegation race checkpoint in the playbook (`{{ALIGNDEV}} guide`) immediately before `{{ALIGNDEV}} code new`. Then bootstrap directly from PROJECT_PATH through `{{ALIGNDEV}} code new --message`, with no protocol. Explicitly instruct it to use `alignfirst-setup-guide` and prepare the repository for an assistant. It must run `{{ALIGNDEV}} project doctor` after writing `.alignfirst.json` and before workspace setup, stopping on an unhealthy inventory. Include `.local/` as a gitignored shared directory in the workspace mechanism. Follow the selected stack and the host-specific guide.
26
26
  6. Verify the project through the setup guide, run `{{ALIGNFIRST}} sync`, and make its initial commit on `main` in PROJECT_PATH. Do not ask for confirmation before committing.
@@ -39,12 +39,12 @@ Before any discussion:
39
39
 
40
40
  1. Select a parent directory allowed by `{{ALIGNDEV}} guide project`. Ask the user when several qualify.
41
41
  2. Clone the repository into that parent. PROJECT is the clone's directory name; PROJECT_PATH is its canonical path.
42
- 3. Retain the canonical path as PROJECT_PATH. Run `{{ALIGNDEV}} project status <PROJECT_PATH>` and retain its `DEVELOPERS.md` path as DEVELOPERS_PATH. When the project's workspace wrapper declares ports, run `{{ALIGNDEV}} project free-ports --root <selected parent directory> --size <perWorkspace × maxWorkspaces> [--range <code>]` and retain the block; preparation through the setup guide writes it into `.alignfirst.json`.
42
+ 3. Retain the canonical path as PROJECT_PATH. Run `{{ALIGNDEV}} project status <PROJECT_PATH>` and retain its `DEVELOPERS.md` path as DEVELOPERS_PATH. When the project's workspace wrapper declares ports, run `{{ALIGNDEV}} project free-ports --root <selected parent directory> --size <port names × concurrent workspaces> [--range <code>]` and retain the block; preparation through the setup guide writes it into `.alignfirst.json`.
43
43
  4. Install dependencies and build, following the repository's own README.
44
44
 
45
45
  ### Step 2 — Check the AlignDev contract
46
46
 
47
- The contract is the one the `alignfirst-setup-guide` lists under "Prepare a Project for an Assistant": AlignFirst skills configuration, docmap, the workspace system, and a `DEVELOPERS.md` with a workspaces section. The workspace system and its section belong to the contract only for a project that installs them; a project without them runs in main-worktree mode. When DEVELOPERS_PATH exists, the project is prepared: continue with the normal working-session flow for the user's request. Otherwise, continue to Step 3.
47
+ The contract is the one the `alignfirst-setup-guide` lists under "Prepare a Project for an Assistant": the `alignfirst context` bootstrap section, docmap, the workspace system, and a `DEVELOPERS.md` with a workspaces section. The workspace system and its section belong to the contract only for a project that installs them; a project without them runs in main-worktree mode. When DEVELOPERS_PATH exists, the project is prepared: continue with the normal working-session flow for the user's request. Otherwise, continue to Step 3.
48
48
 
49
49
  ### Step 3 — Warn and ask
50
50
 
@@ -72,7 +72,7 @@ When the user reports the merge, or you observe it while checking the PR:
72
72
  2. Install dependencies and build.
73
73
  3. When the user chose the work-files repository, clone it under `{{PROJECTS_ROOT}}` when no clone exists there (the projects guide names the repository), then run `{{ALIGNFIRST}} plans setup {{PROJECTS_ROOT}}/<clone>` from PROJECT_PATH. Otherwise, run `mkdir .plans`.
74
74
  4. Run `{{ALIGNDEV}} project doctor`. Stop when the inventory is unhealthy.
75
- 5. Run the project's `workspace setup` on the main worktree. Add `--profile remote` when the deployment sets `REMOTE_DEV_DOMAIN`.
75
+ 5. Run the project's `workspace setup` on the main worktree.
76
76
  6. Continue with the normal working-session flow for the original request through `{{ALIGNDEV}} guide project-workspace-setup`.
77
77
 
78
78
  ### Prepare through the companion
@@ -4,7 +4,7 @@ A projects directory groups projects and optional nested projects directories. I
4
4
 
5
5
  A project is a git main worktree, direct child of a projects directory. Its linked worktrees are listed as its workspaces. Other child directories, those that are not git repositories, appear under `others`.
6
6
 
7
- A project's AlignFirst files may live in its companion directory, declared in the companion registry `~/.alignfirst/companions/registry.json`. `{{ALIGNDEV}} project status <path>` gives each location.
7
+ A project's AlignFirst files may live in its companion directory, the `dir` of its entry in the companion registry `~/.alignfirst/companions/registry.json`. `{{ALIGNDEV}} project status <path>` gives each location.
8
8
 
9
9
  ## Commands
10
10
 
@@ -17,17 +17,17 @@ A project's AlignFirst files may live in its companion directory, declared in th
17
17
  {{ALIGNDEV}} guide project [--root <path>]
18
18
  ```
19
19
 
20
- `--root` selects the projects directory. It defaults to `projectsRoot` in the aligndev config, then to the working directory.
20
+ `--root` selects the projects directory. It defaults to `projectsRoot` in the aligndev settings, then to the working directory.
21
21
 
22
22
  `doctor` is a read-only health gate. It exits successfully only when discovery completes with no
23
23
  inventory issues.
24
24
 
25
25
  ## Port claims
26
26
 
27
- Run `{{ALIGNDEV}} project free-ports --size <n>` with the block size required by the project's workspace scheme: `perWorkspace × maxWorkspaces`. The directory section identifies the range for each project kind. Pass `--range <code>` for a coded range; the default needs no flag. The setup guide writes the returned block as `portRange` in the project's `.alignfirst.json`.
27
+ Run `{{ALIGNDEV}} project free-ports --size <n>` with the size of the project's port range: port names × expected concurrent workspaces. The directory section identifies the range for each project kind. Pass `--range <code>` for a coded range; the default needs no flag. The setup guide writes the returned block as `portRange` in the project's `.alignfirst.json`.
28
28
 
29
- The project config is its registration. Deleting the project removes it from the listing. The workspace kernel refuses a `workspace` command when the project's `portRange` disagrees with its port scheme.
29
+ The project config is its registration. Deleting the project removes it from the listing. The workspace dev-server refuses a command when the project's `portRange` disagrees with the `ports` range of its config.
30
30
 
31
31
  ## Reported issues
32
32
 
33
- The listing reports invalid project configs, non-main root projects, a `.alignfirst.json` outside a git main worktree, project or nested-directory ranges outside their enclosing range, overlapping project ranges, and projects sharing one companion directory.
33
+ The listing reports invalid project configs, non-main root projects, a `.alignfirst.json` outside a git main worktree, project or nested-directory ranges outside their enclosing range, overlapping project ranges, and projects whose registry entries resolve to the same companion directory.