aligndev 0.23.3 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +74 -19
  2. package/dist/alignfirst-cli.d.ts +1 -0
  3. package/dist/alignfirst-cli.js +43 -1
  4. package/dist/cli.js +7 -14
  5. package/dist/code/claude-agent.d.ts +1 -1
  6. package/dist/code/claude-agent.js +25 -11
  7. package/dist/code/code-cli.d.ts +9 -4
  8. package/dist/code/code-cli.js +216 -84
  9. package/dist/code/codex-agent.d.ts +2 -2
  10. package/dist/code/codex-agent.js +24 -8
  11. package/dist/code/codex-rollout.d.ts +1 -1
  12. package/dist/code/codex-rollout.js +9 -5
  13. package/dist/code/coding-agent.d.ts +1 -1
  14. package/dist/code/coding-agent.js +13 -4
  15. package/dist/code/models.d.ts +2 -2
  16. package/dist/code/models.js +27 -15
  17. package/dist/code/native-context.d.ts +2 -0
  18. package/dist/code/native-context.js +21 -0
  19. package/dist/code/pi-agent.d.ts +2 -0
  20. package/dist/code/pi-agent.js +240 -0
  21. package/dist/code/quota-process.d.ts +9 -0
  22. package/dist/code/quota-process.js +165 -0
  23. package/dist/code/quota.d.ts +2 -3
  24. package/dist/code/quota.js +92 -98
  25. package/dist/code/run-agent.d.ts +12 -3
  26. package/dist/code/run-agent.js +48 -19
  27. package/dist/code/session-file.d.ts +3 -0
  28. package/dist/code/session-file.js +33 -10
  29. package/dist/config.d.ts +44 -7
  30. package/dist/config.js +163 -36
  31. package/dist/guide/code-guide.d.ts +2 -2
  32. package/dist/guide/code-guide.js +17 -6
  33. package/dist/guide/guide-cli.js +16 -7
  34. package/dist/json-shape.d.ts +3 -0
  35. package/dist/json-shape.js +23 -0
  36. package/dist/package-version.d.ts +1 -0
  37. package/dist/package-version.js +7 -0
  38. package/dist/project/layout.d.ts +4 -0
  39. package/dist/project/layout.js +28 -10
  40. package/dist/project/render.js +3 -1
  41. package/dist/project/status.d.ts +2 -1
  42. package/dist/project/status.js +1 -0
  43. package/package.json +1 -1
  44. package/templates/guide/code.md +102 -21
  45. package/templates/guide/playbook/consultation.md +5 -0
  46. package/templates/guide/playbook/playbook.md +12 -2
  47. package/templates/guide/playbook/project-workspace-setup.md +1 -1
  48. package/templates/guide/playbook/working-session.md +10 -0
@@ -1,25 +1,47 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  export const RESULT_MARKER = "\n---- Result ----\n";
4
+ const LATER_RESULT_SEPARATOR = "\n\n---- Later result ----\n\n";
5
+ export function createSessionFile(sessionsDir, ticket, now, frontmatter) {
6
+ const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
7
+ mkdirSync(dir, { recursive: true });
8
+ const stamp = formatStamp(now);
9
+ for (let suffix = 1;; ++suffix) {
10
+ const path = sessionFileCandidate(dir, stamp, suffix);
11
+ try {
12
+ claimSessionFile(path, frontmatter);
13
+ return path;
14
+ }
15
+ catch (error) {
16
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
17
+ throw error;
18
+ }
19
+ }
20
+ }
21
+ function sessionFileCandidate(dir, stamp, suffix) {
22
+ return join(dir, `${stamp}${suffix === 1 ? "" : `-${suffix}`}.md`);
23
+ }
24
+ function claimSessionFile(path, frontmatter) {
25
+ writeFileSync(path, `${serializeFrontmatter(frontmatter)}\n`, { flag: "wx" });
26
+ }
4
27
  // `sessionsDir` is the `.plans`-shaped directory holding the session directories: the resolved
5
28
  // `_aligndev` location, which is the resolved `.plans` unless the companion holds a separate tree.
6
29
  export function resolveSessionFilePath(sessionsDir, ticket, now, fileExists = existsSync) {
7
30
  const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
8
31
  const stamp = formatStamp(now);
9
- let candidate = join(dir, `${stamp}.md`);
10
- let suffix = 2;
11
- while (fileExists(candidate)) {
12
- candidate = join(dir, `${stamp}-${suffix}.md`);
32
+ let suffix = 1;
33
+ while (fileExists(sessionFileCandidate(dir, stamp, suffix)))
13
34
  ++suffix;
14
- }
15
- return candidate;
35
+ return sessionFileCandidate(dir, stamp, suffix);
16
36
  }
17
37
  // Writes the initial `running` header. Present before the run starts so an interrupted run still
18
38
  // leaves an auditable record; the terminal frontmatter rewrite happens on completion.
19
39
  export function writeInitialSessionFile(sessionFilePath, frontmatter) {
20
- const header = `${serializeFrontmatter(frontmatter)}\n`;
21
40
  mkdirSync(dirname(sessionFilePath), { recursive: true });
22
- writeFileSync(sessionFilePath, header);
41
+ claimSessionFile(sessionFilePath, frontmatter);
42
+ }
43
+ export function formatResults(earlier, last) {
44
+ return [...earlier, last].join(LATER_RESULT_SEPARATOR);
23
45
  }
24
46
  // Appends the result block, then rewrites the frontmatter in place. Append-first keeps the tailed
25
47
  // transcript intact until the single terminal rewrite.
@@ -188,7 +210,7 @@ function serializeValue(value) {
188
210
  return needsQuote(value) ? JSON.stringify(value) : value;
189
211
  }
190
212
  function needsQuote(value) {
191
- return value === "" || /[:"#]/.test(value) || value !== value.trim();
213
+ return value === "" || /[:"#\p{Cc}\p{Zl}\p{Zp}]/u.test(value) || value !== value.trim();
192
214
  }
193
215
  function splitSessionFile(content) {
194
216
  const match = content.match(/^---\n([\s\S]*?)\n---\n/);
@@ -208,6 +230,7 @@ export function parseFrontmatter(block) {
208
230
  return {
209
231
  status: map.status ?? "running",
210
232
  agent: parseAgent(map.agent),
233
+ profile: map.profile ?? null,
211
234
  protocol: map.protocol ?? null,
212
235
  ticket: map.ticket ?? null,
213
236
  model: map.model ?? null,
@@ -226,7 +249,7 @@ export function parseFrontmatter(block) {
226
249
  };
227
250
  }
228
251
  function parseAgent(raw) {
229
- return raw === "claude" || raw === "codex" ? raw : null;
252
+ return raw === "claude" || raw === "codex" || raw === "pi" ? raw : null;
230
253
  }
231
254
  function parsePid(raw) {
232
255
  if (raw === null || raw === undefined)
package/dist/config.d.ts CHANGED
@@ -1,26 +1,63 @@
1
1
  import { type CodingAgent } from "./code/coding-agent.js";
2
+ import type { AligndevProjectSettings } from "./project/layout.js";
2
3
  export declare const PLATFORMS: readonly ["openclaw", "codingAgent"];
4
+ export declare const CONFIG_DIRECTORY_VARIABLES: {
5
+ readonly claude: "CLAUDE_CONFIG_DIR";
6
+ readonly codex: "CODEX_HOME";
7
+ readonly pi: "PI_CODING_AGENT_DIR";
8
+ };
3
9
  export type Platform = (typeof PLATFORMS)[number];
4
10
  export interface LoadedConfig {
5
11
  path: string;
6
12
  platform: Platform;
7
13
  projectsRoot?: ProjectsRoot;
8
- code: LoadedCodeConfig;
14
+ code: CodeSettings;
9
15
  }
10
16
  export interface ProjectsRoot {
11
17
  path: string;
12
18
  written: string;
13
19
  }
14
- export interface LoadedCodeConfig {
15
- agent?: CodingAgent;
20
+ export interface CodeSettings {
21
+ profile?: string;
22
+ defaultProfiles?: Partial<Record<CodingAgent, string>>;
23
+ profiles?: Record<string, CodingProfile>;
24
+ }
25
+ export interface CodingProfile {
26
+ agent: CodingAgent;
27
+ configDir?: string;
16
28
  defaultModel?: string;
17
29
  models?: string[];
30
+ modelAliases?: Record<string, string>;
31
+ skipPermissions?: boolean;
32
+ env?: Record<string, string>;
33
+ unset?: string[];
34
+ quota?: QuotaSettings;
35
+ }
36
+ export interface QuotaSettings {
37
+ source: "claude" | "codex" | "none";
38
+ configDir?: string;
39
+ env?: Record<string, string>;
40
+ unset?: string[];
41
+ }
42
+ export interface CodeConfig extends CodingProfile {
43
+ profile: string | null;
18
44
  skipPermissions: boolean;
19
45
  unset: string[];
20
- }
21
- export interface CodeConfig extends LoadedCodeConfig {
22
- agent: CodingAgent;
46
+ childEnv: NodeJS.ProcessEnv;
23
47
  }
24
48
  export declare function loadConfig(home: string): LoadedConfig;
25
- export declare function resolveCodeConfig(config: LoadedConfig, env: NodeJS.ProcessEnv): CodeConfig;
49
+ export type QuotaSource = "claude" | "codex";
50
+ export type ResolvedQuota = {
51
+ source: "none";
52
+ } | {
53
+ source: QuotaSource;
54
+ env: NodeJS.ProcessEnv;
55
+ };
56
+ export declare function resolveQuotaConfig(code: CodeConfig, callerEnv: NodeJS.ProcessEnv): ResolvedQuota;
57
+ export interface ProfileSelection {
58
+ project?: AligndevProjectSettings | null;
59
+ explicit?: string;
60
+ recorded?: string | null;
61
+ }
62
+ export declare function resolveCodeConfig(config: LoadedConfig, env: NodeJS.ProcessEnv, selection?: ProfileSelection): CodeConfig;
26
63
  export declare function requireProjectsRoot(config: LoadedConfig): ProjectsRoot;
package/dist/config.js CHANGED
@@ -1,41 +1,85 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
- import { CODING_AGENTS, detectCodingAgents } from "./code/coding-agent.js";
3
+ import { CODING_AGENTS, createAgentAdapter, detectCodingAgents, } from "./code/coding-agent.js";
4
4
  import { resolveModels } from "./code/models.js";
5
+ import { buildAgentEnv } from "./code/run-agent.js";
5
6
  import { errorMessage } from "./errors.js";
6
- import { arrayOf, boolean, literal, nonEmptyString, object, optional, parseShape, string, } from "./json-shape.js";
7
+ import { arrayOf, boolean, literal, matching, nonblankString, nonEmptyString, nulFreeString, object, optional, parseShape, record, } from "./json-shape.js";
7
8
  export const PLATFORMS = ["openclaw", "codingAgent"];
8
- const codeShape = object({
9
- agent: optional(literal(...CODING_AGENTS)),
10
- defaultModel: optional(nonEmptyString),
11
- models: optional(arrayOf(string)),
9
+ export const CONFIG_DIRECTORY_VARIABLES = {
10
+ claude: "CLAUDE_CONFIG_DIR",
11
+ codex: "CODEX_HOME",
12
+ pi: "PI_CODING_AGENT_DIR",
13
+ };
14
+ const environmentName = matching(/^[A-Za-z_][A-Za-z0-9_]*$/);
15
+ const environmentShape = record(nulFreeString, environmentName);
16
+ const quotaShape = object({
17
+ source: literal("claude", "codex", "none"),
18
+ configDir: optional(directoryValue),
19
+ env: optional(environmentShape),
20
+ unset: optional(arrayOf(environmentName)),
21
+ });
22
+ const profileShape = object({
23
+ agent: literal(...CODING_AGENTS),
24
+ configDir: optional(directoryValue),
25
+ defaultModel: optional(nonblankString),
26
+ models: optional(arrayOf(nonblankString)),
27
+ modelAliases: optional(record(nonblankString, nonblankString)),
12
28
  skipPermissions: optional(boolean),
13
- unset: optional(arrayOf(string)),
29
+ env: optional(environmentShape),
30
+ unset: optional(arrayOf(environmentName)),
31
+ quota: optional(quotaShape),
32
+ });
33
+ const codeShape = object({
34
+ profile: optional(nonblankString),
35
+ defaultProfiles: optional(object({
36
+ claude: optional(nonblankString),
37
+ codex: optional(nonblankString),
38
+ pi: optional(nonblankString),
39
+ })),
40
+ profiles: optional(record(profileShape, nonblankString)),
14
41
  });
15
42
  const configShape = object({
16
43
  platform: optional(literal(...PLATFORMS)),
17
44
  projectsRoot: optional(nonEmptyString),
18
45
  code: optional(codeShape),
19
46
  });
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.
47
+ const RETIRED_CODE_KEYS = ["agent", "defaultModel", "models", "skipPermissions", "unset"];
22
48
  export function loadConfig(home) {
23
49
  const path = join(home, ".alignfirst", "aligndev.settings.json");
24
50
  const value = existsSync(path) ? parseConfigFile(path) : absentConfig(home);
25
51
  const code = value.code ?? {};
52
+ for (const [name, profile] of Object.entries(code.profiles ?? {})) {
53
+ const field = `code.profiles[${JSON.stringify(name)}]`;
54
+ validateEnvironment(profile, profile.agent, field, path);
55
+ if (profile.configDir !== undefined)
56
+ profile.configDir = resolvePath(profile.configDir, home, path);
57
+ if (profile.quota !== undefined) {
58
+ const quota = profile.quota;
59
+ if (quota.source === "none") {
60
+ if (Object.keys(quota).some((key) => key !== "source")) {
61
+ throw invalidConfig(path, `${field}.quota with source none accepts no other options`);
62
+ }
63
+ }
64
+ else {
65
+ validateEnvironment(quota, quota.source, `${field}.quota`, path);
66
+ }
67
+ if (quota.configDir !== undefined)
68
+ quota.configDir = resolvePath(quota.configDir, home, path);
69
+ }
70
+ }
26
71
  return {
27
72
  path,
28
73
  platform: value.platform ?? "codingAgent",
29
74
  ...(value.projectsRoot === undefined
30
75
  ? {}
31
- : { projectsRoot: resolveProjectsRoot(value.projectsRoot, home, path) }),
32
- code: {
33
- ...(code.agent === undefined ? {} : { agent: code.agent }),
34
- ...(code.defaultModel === undefined ? {} : { defaultModel: code.defaultModel }),
35
- ...(code.models === undefined ? {} : { models: code.models }),
36
- skipPermissions: code.skipPermissions ?? false,
37
- unset: code.unset ?? [],
38
- },
76
+ : {
77
+ projectsRoot: {
78
+ path: resolvePath(value.projectsRoot, home, path),
79
+ written: value.projectsRoot,
80
+ },
81
+ }),
82
+ code,
39
83
  };
40
84
  }
41
85
  function absentConfig(home) {
@@ -53,41 +97,124 @@ function parseConfigFile(path) {
53
97
  catch (error) {
54
98
  throw invalidConfig(path, errorMessage(error));
55
99
  }
100
+ if (typeof value === "object" &&
101
+ value !== null &&
102
+ "code" in value &&
103
+ typeof value.code === "object" &&
104
+ value.code !== null) {
105
+ const retired = RETIRED_CODE_KEYS.find((key) => Object.hasOwn(value.code ?? {}, key));
106
+ if (retired !== undefined) {
107
+ throw invalidConfig(path, `code.${retired} is retired: move launch settings into ` +
108
+ "code.profiles and select one with code.profile (manual conversion required)");
109
+ }
110
+ }
56
111
  return parseShape(configShape, value, (detail) => invalidConfig(path, detail));
57
112
  }
58
113
  function invalidConfig(path, detail) {
59
114
  return new Error(`Error: invalid aligndev config ${path}: ${detail}`);
60
115
  }
61
- function resolveProjectsRoot(written, home, path) {
116
+ function directoryValue(value, path) {
117
+ nonblankString(value, path);
118
+ return nulFreeString(value, path);
119
+ }
120
+ function validateEnvironment(settings, agent, field, path) {
121
+ for (const name of settings.unset ?? []) {
122
+ if (Object.hasOwn(settings.env ?? {}, name)) {
123
+ throw invalidConfig(path, `${field}.unset overlaps ${field}.env for ${name}`);
124
+ }
125
+ }
126
+ const variable = CONFIG_DIRECTORY_VARIABLES[agent];
127
+ if (settings.configDir !== undefined &&
128
+ (Object.hasOwn(settings.env ?? {}, variable) || settings.unset?.includes(variable))) {
129
+ throw invalidConfig(path, `${field}.configDir conflicts with env/unset for ${variable}`);
130
+ }
131
+ }
132
+ function resolvePath(written, home, path) {
62
133
  if (written.startsWith("~/"))
63
- return { path: join(home, written.slice(2)), written };
64
- return { path: isAbsolute(written) ? written : resolve(dirname(path), written), written };
134
+ return join(home, written.slice(2));
135
+ return isAbsolute(written) ? written : resolve(dirname(path), written);
136
+ }
137
+ export function resolveQuotaConfig(code, callerEnv) {
138
+ const quota = code.quota;
139
+ if (quota?.source === "none")
140
+ return { source: "none" };
141
+ if (quota === undefined) {
142
+ if (code.agent === "pi") {
143
+ throw new Error("Pi account quota is unsupported without explicit configuration: " +
144
+ "set quota.source to claude or codex with its native configDir, or none to disable it.");
145
+ }
146
+ return { source: code.agent, env: code.childEnv };
147
+ }
148
+ const overrides = { ...quota.env };
149
+ if (quota.configDir !== undefined)
150
+ overrides[CONFIG_DIRECTORY_VARIABLES[quota.source]] = quota.configDir;
151
+ return {
152
+ source: quota.source,
153
+ env: buildAgentEnv(callerEnv, quota.unset ?? [], overrides),
154
+ };
65
155
  }
66
- export function resolveCodeConfig(config, env) {
67
- const code = { ...config.code, agent: resolveAgent(config, env) };
68
- checkDefaultModel(code, config.path);
69
- return code;
156
+ export function resolveCodeConfig(config, env, selection = {}) {
157
+ validateReferences(config);
158
+ const name = selection.explicit ?? selection.project?.profile ?? selection.recorded ?? config.code.profile;
159
+ let profile;
160
+ let effectiveName = name;
161
+ if (name !== undefined) {
162
+ profile = referencedProfile(config, name, "selected profile");
163
+ }
164
+ else {
165
+ const agent = detectAgent(config, env);
166
+ effectiveName = config.code.defaultProfiles?.[agent];
167
+ profile =
168
+ effectiveName === undefined
169
+ ? { agent }
170
+ : referencedProfile(config, effectiveName, "defaultProfiles");
171
+ }
172
+ checkDefaultModel(profile, config.path, effectiveName);
173
+ const overrides = { ...profile.env };
174
+ if (profile.configDir !== undefined)
175
+ overrides[CONFIG_DIRECTORY_VARIABLES[profile.agent]] = profile.configDir;
176
+ return {
177
+ ...profile,
178
+ profile: effectiveName ?? null,
179
+ skipPermissions: profile.skipPermissions ?? false,
180
+ unset: profile.unset ?? [],
181
+ childEnv: buildAgentEnv(env, profile.unset ?? [], overrides, createAgentAdapter(profile.agent).env),
182
+ };
183
+ }
184
+ function validateReferences(config) {
185
+ if (config.code.profile !== undefined)
186
+ referencedProfile(config, config.code.profile, "code.profile");
187
+ for (const [agent, name] of Object.entries(config.code.defaultProfiles ?? {})) {
188
+ const profile = referencedProfile(config, name, `code.defaultProfiles.${agent}`);
189
+ if (profile.agent !== agent)
190
+ throw invalidConfig(config.path, `code.defaultProfiles.${agent} references a ${profile.agent} profile`);
191
+ }
192
+ }
193
+ function referencedProfile(config, name, field) {
194
+ const profile = Object.hasOwn(config.code.profiles ?? {}, name)
195
+ ? config.code.profiles?.[name]
196
+ : undefined;
197
+ if (name.trim() === "" || profile === undefined) {
198
+ throw invalidConfig(config.path, `${field} references missing profile ${JSON.stringify(name)}; define it in code.profiles or select another --profile`);
199
+ }
200
+ return profile;
70
201
  }
71
- // The configured `code.agent` wins; otherwise, the coding agent that runs aligndev.
72
- function resolveAgent(config, env) {
73
- const { agent } = config.code;
74
- if (agent !== undefined)
75
- return agent;
202
+ function detectAgent(config, env) {
76
203
  const detected = detectCodingAgents(env);
77
204
  if (detected.length === 1)
78
205
  return detected[0];
79
206
  const problem = detected.length === 0
80
- ? "no coding agent detected: run aligndev from Claude Code or Codex, or set"
81
- : "both Claude Code and Codex detected: set";
82
- throw new Error(`Error: ${problem} "code.agent" (${CODING_AGENTS.join(" or ")}) in ${config.path}.`);
207
+ ? `no coding agent detected (${CODING_AGENTS.join(", ")})`
208
+ : `multiple coding agents detected (${detected.join(", ")})`;
209
+ throw new Error(`Error: ${problem}: select --profile or set "code.profile" in ${config.path}.`);
83
210
  }
84
- function checkDefaultModel(code, path) {
211
+ function checkDefaultModel(code, path, profile) {
85
212
  if (code.defaultModel === undefined)
86
213
  return;
87
- const models = resolveModels(code.agent, code.models);
88
- if (models.includes(code.defaultModel))
214
+ const models = resolveModels(code.agent, code.models, code.modelAliases);
215
+ if (models === undefined || models.includes(code.defaultModel))
89
216
  return;
90
- throw new Error(`Error: code.defaultModel must be one of: ${models.join(", ")}, in ${path}.`);
217
+ throw invalidConfig(path, `code.profiles[${JSON.stringify(profile)}].defaultModel must be one of: ${models.join(", ")}`);
91
218
  }
92
219
  export function requireProjectsRoot(config) {
93
220
  if (config.projectsRoot !== undefined)
@@ -1,4 +1,4 @@
1
1
  import type { CodingAgent } from "../code/coding-agent.js";
2
2
  import type { CommandForms } from "../command-form.js";
3
- import type { Platform } from "../config.js";
4
- export declare function renderCodeGuide(platform: Platform, agent: CodingAgent, models: readonly string[], defaultModel: string | undefined, forms: CommandForms): string;
3
+ import { type Platform } from "../config.js";
4
+ export declare function renderCodeGuide(platform: Platform, agent: CodingAgent, models: readonly string[] | undefined, defaultModel: string | undefined, forms: CommandForms, profile?: string | null, nativeStorage?: string): string;
@@ -1,12 +1,23 @@
1
+ import { CONFIG_DIRECTORY_VARIABLES } from "../config.js";
1
2
  import { renderGuideTemplate } from "./render-template.js";
2
- export function renderCodeGuide(platform, agent, models, defaultModel, forms) {
3
+ export function renderCodeGuide(platform, agent, models, defaultModel, forms, profile = null, nativeStorage = `${CONFIG_DIRECTORY_VARIABLES[agent]}: inherited/default native storage`) {
3
4
  return renderGuideTemplate("code.md", { platform }, forms, {
4
5
  AGENT: agent,
5
- AUTH_COMMAND: agent === "claude" ? "`claude`, then `/login`" : "`codex login`",
6
- PERMISSIONS: agent === "claude"
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
- MODELS: models.map((model) => `\`${model}\``).join(", "),
6
+ PROFILE: profile ?? "(built-in)",
7
+ NATIVE_CONFIG: nativeStorage,
8
+ AUTH_COMMAND: agent === "pi"
9
+ ? "`pi`, then `/login <provider>`, or configure provider credentials in the selected native configuration"
10
+ : agent === "claude"
11
+ ? "`claude`, then `/login` in the selected native configuration"
12
+ : "`codex login` in the selected native configuration",
13
+ PERMISSIONS: agent === "pi"
14
+ ? "Pi uses ordinary OS permissions, including companion access. `profile.skipPermissions` has no effect. Saved project trust is honored; no forced approval is passed"
15
+ : agent === "claude"
16
+ ? "Normal runs use `--permission-mode auto`, plus `--add-dir <companion>` for a project with a companion directory. `profile.skipPermissions: true` in the aligndev settings selects `--dangerously-skip-permissions`"
17
+ : "Normal runs use `--sandbox workspace-write`, plus `--add-dir <companion>` for a project with a companion directory. `profile.skipPermissions: true` in the aligndev settings selects `--dangerously-bypass-approvals-and-sandbox`",
18
+ MODEL_POLICY: models === undefined
19
+ ? "Any nonblank pi-native selector, preferably `provider/model` (thinking suffixes supported)"
20
+ : `One of ${models.map((model) => `\`${model}\``).join(", ")}`,
10
21
  DEFAULT_MODEL: defaultModel === undefined ? "the coding agent's default" : `\`${defaultModel}\``,
11
22
  ALIGNFIRST_SETUP: forms.viaNpx
12
23
  ? "The project must be prepared for AlignFirst. `npx -y aligndev` runs the `alignfirst` CLI through `npx`."
@@ -1,7 +1,9 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { resolveModels } from "../code/models.js";
3
+ import { describeNativeStorage } from "../code/native-context.js";
3
4
  import { PLATFORMS, requireProjectsRoot, resolveCodeConfig, } from "../config.js";
4
5
  import { errorMessage } from "../errors.js";
6
+ import { readProjectReport } from "../project/layout.js";
5
7
  import { renderProjectsGuideForRoot } from "../project/project-cli.js";
6
8
  import { renderCodeGuide } from "./code-guide.js";
7
9
  import { resolveGuideFile } from "./guide-file.js";
@@ -23,6 +25,7 @@ function parseGuideArgs(tokens) {
23
25
  args: tokens,
24
26
  options: {
25
27
  root: { type: "string" },
28
+ profile: { type: "string" },
26
29
  help: { type: "boolean", short: "h", default: false },
27
30
  },
28
31
  strict: true,
@@ -34,12 +37,15 @@ function parseGuideArgs(tokens) {
34
37
  if (values.root !== undefined && topic !== "project") {
35
38
  throw new Error("Error: --root is valid only with `aligndev guide project`.");
36
39
  }
37
- return { topic, root: values.root, help: values.help };
40
+ if (values.profile !== undefined && topic !== "code") {
41
+ throw new Error("Error: --profile is valid only with `aligndev guide code`.");
42
+ }
43
+ return { topic, root: values.root, profile: values.profile, help: values.help };
38
44
  }
39
45
  function renderUsage(forms) {
40
46
  const playbookTopics = PLATFORMS.map((platform) => ` ${platform}: ${PLAYBOOK_TOPICS[platform].join(", ")}`);
41
47
  return `Usage:
42
- ${forms.aligndev} guide [<topic>] [--root <path>]
48
+ ${forms.aligndev} guide [<topic>] [--root <path>] [--profile <name>]
43
49
  ${forms.aligndev} guide --help
44
50
 
45
51
  Without a topic, prints the playbook of the platform set in the aligndev settings.
@@ -54,16 +60,19 @@ ${playbookTopics.join("\n")}
54
60
  }
55
61
  function renderTopic(args, config, ctx) {
56
62
  if (args.topic === "code")
57
- return renderCodeTopic(config, ctx);
63
+ return renderCodeTopic(config, ctx, args.profile);
58
64
  if (args.topic === "project" && config.platform === "openclaw") {
59
65
  return renderProjectsGuideForRoot({ ...ctx, projectsRoot: config.projectsRoot }, args.root);
60
66
  }
61
67
  return renderPlaybookTopic(args.topic, config, ctx);
62
68
  }
63
- function renderCodeTopic(config, ctx) {
64
- const code = resolveCodeConfig(config, ctx.env);
65
- const models = resolveModels(code.agent, code.models);
66
- return renderCodeGuide(config.platform, code.agent, models, code.defaultModel, ctx.forms);
69
+ function renderCodeTopic(config, ctx, profile) {
70
+ const report = readProjectReport(ctx.alignfirstCommand, ctx.cwd, ctx.env);
71
+ if ("error" in report)
72
+ throw new Error(report.error);
73
+ const code = resolveCodeConfig(config, ctx.env, { project: report.aligndev, explicit: profile });
74
+ const models = resolveModels(code.agent, code.models, code.modelAliases);
75
+ return renderCodeGuide(config.platform, code.agent, models, code.defaultModel, ctx.forms, code.profile, describeNativeStorage(code));
67
76
  }
68
77
  function renderPlaybookTopic(topic, config, ctx) {
69
78
  if (topic !== undefined)
@@ -9,6 +9,9 @@ type Fields<T> = {
9
9
  export declare function parseShape<T>(check: Check<T>, value: unknown, toError: (detail: string) => Error): T;
10
10
  /** Rejects the first unknown key, then checks each field in declaration order. */
11
11
  export declare function object<T extends object>(fields: Fields<T>): Check<T>;
12
+ export declare function record<T>(check: Check<T>, keyCheck?: Check<string>): Check<Record<string, T>>;
13
+ export declare function nonblankString(value: unknown, path: string): string;
14
+ export declare function nulFreeString(value: unknown, path: string): string;
12
15
  export declare function optional<T>(check: Check<T>): OptionalField<T>;
13
16
  export declare function literal<const T extends readonly (string | number)[]>(...values: T): Check<T[number]>;
14
17
  export declare function integerBetween(min: number, max: number): Check<number>;
@@ -33,6 +33,29 @@ export function object(fields) {
33
33
  return result;
34
34
  };
35
35
  }
36
+ export function record(check, keyCheck = string) {
37
+ return (value, path) => {
38
+ if (!isPlainObject(value))
39
+ throw shapeError(path, "be an object");
40
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => {
41
+ const fieldPath = childPath(path, key);
42
+ keyCheck(key, fieldPath);
43
+ return [key, check(item, fieldPath)];
44
+ }));
45
+ };
46
+ }
47
+ export function nonblankString(value, path) {
48
+ const text = string(value, path);
49
+ if (text.trim() === "")
50
+ throw shapeError(path, "be nonblank");
51
+ return text;
52
+ }
53
+ export function nulFreeString(value, path) {
54
+ const text = string(value, path);
55
+ if (text.includes("\u0000"))
56
+ throw shapeError(path, "contain no NUL characters");
57
+ return text;
58
+ }
36
59
  function isPlainObject(value) {
37
60
  if (typeof value !== "object" || value === null)
38
61
  return false;
@@ -0,0 +1 @@
1
+ export declare function readPackageVersion(): string;
@@ -0,0 +1,7 @@
1
+ import { readFileSync } from "node:fs";
2
+ export function readPackageVersion() {
3
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
4
+ if (pkg.version === undefined)
5
+ throw new Error("aligndev: package.json is missing 'version'");
6
+ return pkg.version;
7
+ }
@@ -5,8 +5,12 @@ export interface ProjectReport {
5
5
  cli: ProjectCliReport | null;
6
6
  config: ProjectConfigView | null;
7
7
  companion: CompanionReport | null;
8
+ aligndev: AligndevProjectSettings | null;
8
9
  locations: Record<ItemName, ItemLocation>;
9
10
  }
11
+ export interface AligndevProjectSettings {
12
+ profile: string;
13
+ }
10
14
  export type ConfigSource = "project" | "companion";
11
15
  export interface ProjectCliReport {
12
16
  installed: string;
@@ -1,6 +1,5 @@
1
- import { runAlignfirst } from "../alignfirst-cli.js";
1
+ import { describeAlignfirst, runAlignfirst } from "../alignfirst-cli.js";
2
2
  import { errorMessage } from "../errors.js";
3
- const MIN_ALIGNFIRST_VERSION = "0.9.0";
4
3
  export function readProjectReport(command, cwd, env) {
5
4
  const result = runAlignfirst(command, ["config", "--json"], cwd, env);
6
5
  if (result.status !== 0) {
@@ -12,22 +11,30 @@ export function readProjectReport(command, cwd, env) {
12
11
  value = JSON.parse(result.stdout);
13
12
  }
14
13
  catch (error) {
15
- throw new Error(`Invalid alignfirst config report for ${cwd}: ${errorMessage(error)}`);
14
+ throw new Error(`Invalid alignfirst config report for ${cwd}: ${errorMessage(error)} ${describeAlignfirst(command, cwd, env)}`);
15
+ }
16
+ if (isOutdatedReport(value)) {
17
+ return { error: `${outdatedAlignfirst(cwd)} ${describeAlignfirst(command, cwd, env)}` };
18
+ }
19
+ try {
20
+ return parseProjectReport(value, cwd);
21
+ }
22
+ catch (error) {
23
+ throw new Error(`${errorMessage(error)} ${describeAlignfirst(command, cwd, env)}`);
16
24
  }
17
- if (isOutdatedReport(value))
18
- return { error: outdatedAlignfirst(cwd) };
19
- return parseProjectReport(value, cwd);
20
25
  }
21
26
  function firstLine(value) {
22
27
  return value.trim().split("\n", 1)[0] ?? "";
23
28
  }
24
- // Before alignfirst 0.9.0, the report had no `.alignfirst-instructions` location.
29
+ // Detect the contract rather than the package version, including unreleased checkout builds.
25
30
  function isOutdatedReport(value) {
26
- return (isRecord(value) && !(isRecord(value.locations) && ".alignfirst-instructions" in value.locations));
31
+ return (isRecord(value) &&
32
+ (!Object.hasOwn(value, "aligndev") ||
33
+ !(isRecord(value.locations) && ".alignfirst-instructions" in value.locations)));
27
34
  }
28
35
  function outdatedAlignfirst(path) {
29
- return (`The alignfirst CLI used in ${path} is too old: aligndev requires alignfirst ` +
30
- `${MIN_ALIGNFIRST_VERSION} or later.`);
36
+ return (`The alignfirst CLI used in ${path} is too old: aligndev requires the profile-aware ` +
37
+ 'alignfirst config --json contract (top-level "aligndev"). Upgrade alignfirst.');
31
38
  }
32
39
  function parseProjectReport(value, path) {
33
40
  if (!isRecord(value))
@@ -37,9 +44,20 @@ function parseProjectReport(value, path) {
37
44
  cli: parseCli(value.cli, path),
38
45
  config: parseConfig(value.config, path),
39
46
  companion: parseCompanion(value.companion, path),
47
+ aligndev: parseAligndev(value.aligndev, path),
40
48
  locations: parseLocations(value.locations, path),
41
49
  };
42
50
  }
51
+ function parseAligndev(value, path) {
52
+ if (value === null)
53
+ return null;
54
+ if (!isRecord(value) ||
55
+ typeof value.profile !== "string" ||
56
+ value.profile.trim().length === 0 ||
57
+ Object.keys(value).some((key) => key !== "profile"))
58
+ throw invalidReport(path);
59
+ return { profile: value.profile };
60
+ }
43
61
  function parseSource(value, path) {
44
62
  if (value === "project" || value === "companion" || value === null)
45
63
  return value;