@sublang/spex 2.0.0 → 2.1.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
@@ -38,16 +38,38 @@ This creates:
38
38
  - `specs/decisions/` and `specs/intents/` hold decision records (DRs) and intent records (IRs); `specs/map.md` indexes the tree and `specs/meta.md` is the spec of specs.
39
39
  - Two starter packages (`git.md`, `licensing.md`) and a sample intent record seed the tree.
40
40
  - **`LICENSE`** — the verbatim Apache-2.0 text at the target root, written only when no `LICENSE` exists there.
41
- - **`CLAUDE.md` / `AGENTS.md`** — instructions that tell AI agents
42
- (Claude, Codex, etc.) to read relevant specs, resolve conflicts there
43
- first, and keep specs and code aligned.
41
+ - **Agent instruction files** — a managed section that tells coding
42
+ agents to read relevant specs, resolve conflicts there first, and keep
43
+ specs and code aligned: `CLAUDE.md` for Claude Code, `AGENTS.md` for
44
+ Codex, Kimi Code, and OpenCode, and `GEMINI.md` for Gemini CLI.
44
45
 
45
46
  See `specs/decisions/000-spec-structure-format.md` and `specs/meta.md` for the spec format and naming conventions.
46
47
 
47
- Idempotency: rerunning `scaffold` is safe — it only adds missing files.
48
- The one in-place edit it makes is to an existing `CLAUDE.md`/`AGENTS.md`, whose managed `## Specs (Source of Truth)` section is added or refreshed.
48
+ Idempotency: rerunning `scaffold` is safe — authored specs and content
49
+ outside Spex's managed `## Specs (Source of Truth)` sections stay
50
+ untouched. Agent instruction files are reconciled as described below.
49
51
  (`--update` edits more, mechanically; see below.)
50
52
 
53
+ ### Agent instructions
54
+
55
+ Interactive scaffold and update runs infer the current instruction
56
+ targets and ask for a quick default-yes confirmation. If you have
57
+ changed agents, decline and select the agents you use now. A fresh
58
+ project defaults to all supported targets.
59
+
60
+ For a non-interactive run, or to select directly, pass agent names:
61
+
62
+ ```sh
63
+ spex scaffold --agents=claude,codex
64
+ spex scaffold --update --agents=gemini,kimi
65
+ ```
66
+
67
+ Supported names are `claude`, `codex`, `gemini`, `kimi`, and
68
+ `opencode`; `all` selects all of them. The selection is the desired
69
+ state: Spex adds or refreshes selected managed sections and removes its
70
+ managed section from deselected targets, preserving all other content.
71
+ An otherwise empty deselected instruction file is removed.
72
+
51
73
  ### Linting
52
74
 
53
75
  Check the specs tree at any time:
@@ -58,7 +80,7 @@ spex lint
58
80
 
59
81
  The linter validates the layout, package file sections and their order, item IDs — lowercase `<pack>-<N>` matching the file's basename, unique across the tree — citations (enclosed inline links like `[[pack-3](pack.md#pack-3)]` whose files and anchors exist), Verification items citing the behaviors they check, reference markers, record sections, and the `map.md` index.
60
82
  Relationship-metadata lines like `Verifies:` are errors — the citations woven into an item's statement are the single source of its relationships.
61
- Directories of previous spec generations (`specs/compositions/`, `specs/user/`, …) are errors pointing at the migration skill (see [Upgrading](#upgrading-from-an-earlier-release)).
83
+ Directories of previous spec generations (`specs/compositions/`, `specs/user/`, …) are errors pointing to `spex scaffold --update` for the migration prompt (see [Upgrading](#upgrading-from-an-earlier-release)).
62
84
  Errors exit non-zero; warnings do not.
63
85
 
64
86
  **Try it:** review the sample intent record `specs/intents/000-spdx-headers.md`, update the copyright text, then prompt your AI coding agent:
@@ -77,6 +99,14 @@ spex scaffold --lang zh
77
99
 
78
100
  Chinese (`zh`) is currently bundled. Any file without a localized template falls back to English, so the tree is always complete. The chosen language is recorded in `specs/meta.md` and reused automatically on `spex scaffold --update`.
79
101
 
102
+ To switch an existing tree to another language:
103
+
104
+ ```bash
105
+ spex scaffold --update --lang zh
106
+ ```
107
+
108
+ This rewrites the bundled specs in the target language and prints a prompt you can hand an AI agent to translate the project's own specs; passing the language the tree already uses is just an ordinary update.
109
+
80
110
  ### Updating templates
81
111
 
82
112
  When a new release ships updated templates, refresh them with:
@@ -89,10 +119,14 @@ It runs from within a git repository and requires a clean `specs/` working tree,
89
119
 
90
120
  - Spex-authoritative *framework* files (`specs/meta.md` and the spec-format decision record) are refreshed unconditionally, including when they are absent. If you had modified one of these, `--update` warns and names it so you can reapply your changes from git history.
91
121
  - Starter *seed* files (`map.md`, the sample intent record, the starter packages) are refreshed when you have not customized them, and written from the bundled template when they are absent. Customized starter files are kept as-is. Remove a starter file *after* `--update` if you do not want it.
92
- - The managed specs section of an existing `CLAUDE.md`/`AGENTS.md` is refreshed; absent agent files are not created.
93
- - Files you authored are never edited.
94
-
95
- Review the changes with `git diff -- specs CLAUDE.md AGENTS.md` and run `spex lint`.
122
+ - Agent instruction files are reconciled with the confirmed or explicit
123
+ selection; a non-interactive run infers existing managed targets and
124
+ defaults to all targets when none exist.
125
+ - Files outside the framework and seed sets and the supported agent
126
+ instruction targets are never edited.
127
+
128
+ Review the changes with
129
+ `git diff -- specs CLAUDE.md AGENTS.md GEMINI.md` and run `spex lint`.
96
130
  The command prints a per-file indicator for every framework and seed path, plus a copy-paste-ready prompt for your AI agent to reconcile citations and local extensions with the refreshed law.
97
131
 
98
132
  ## Upgrading from an earlier release
@@ -100,7 +134,7 @@ The command prints a per-file indicator for every framework and seed path, plus
100
134
  ### From 1.x
101
135
 
102
136
  Spex 2.0 tightens the packages-only law introduced in 1.0. Run
103
- `spex scaffold --update`, review the refreshed law and merge guidance,
137
+ `spex scaffold --update`, review the refreshed law and printed merge prompt,
104
138
  then reconcile your packages until `spex lint` passes. In particular,
105
139
  every package now requires Verification of its own behavior, behavior
106
140
  citations from Verification stay inside that package, record citations
@@ -121,12 +155,12 @@ generation of the law. Spex 2.0 uses the following structure:
121
155
 
122
156
  The CLI detects but does not restructure a legacy tree:
123
157
 
124
- - `spex scaffold --update` still refreshes the spex-owned law files, leaves all legacy content untouched, and prints migration guidance when it recognizes a legacy generation.
158
+ - `spex scaffold --update` still refreshes the spex-owned law files, leaves all legacy content untouched, and prints a self-contained migration prompt instead of the ordinary update prompt when it recognizes a legacy generation.
125
159
  - Plain `spex scaffold` refuses a tree with a legacy directory — it writes nothing and points at `--update` — so two generations never entangle.
126
160
  - `spex lint` reports legacy directories as errors pointing the same way.
127
161
 
128
- The structural migration itself — items reclassify, compositions fold into packages, intents get rewritten — is judgment work done by an AI agent following the **spec-structure-migration** skill shipped in the spex repo, not by a script (the scripted migration of earlier releases is retired).
129
- Follow the walkthrough in [docs/spec-migration.md](https://github.com/sublang-ai/spex/blob/main/docs/spec-migration.md), install the skill per [its README](https://github.com/sublang-ai/spex/blob/main/skills/spec-structure-migration/README.md), and let the agent loop until its checker and `spex lint` — the mechanical gate — pass clean.
162
+ The structural migration itself — items reclassify, compositions fold into packages, intents get rewritten — is judgment work, not a script.
163
+ Give the printed prompt to any capable AI agent, let it loop until `spex lint` passes, and review the resulting diff.
130
164
 
131
165
  ## Workflow
132
166
 
@@ -1,17 +1,28 @@
1
+ export declare const AGENT_TARGETS: readonly [{
2
+ readonly file: "CLAUDE.md";
3
+ readonly agents: readonly ["claude"];
4
+ readonly label: "Claude Code";
5
+ }, {
6
+ readonly file: "AGENTS.md";
7
+ readonly agents: readonly ["codex", "kimi", "opencode"];
8
+ readonly label: "Codex / Kimi Code / OpenCode";
9
+ }, {
10
+ readonly file: "GEMINI.md";
11
+ readonly agents: readonly ["gemini"];
12
+ readonly label: "Gemini CLI";
13
+ }];
14
+ export type AgentName = (typeof AGENT_TARGETS)[number]["agents"][number];
15
+ export type AgentTargetFile = (typeof AGENT_TARGETS)[number]["file"];
16
+ export interface AgentInteraction {
17
+ interactive: boolean;
18
+ ask(prompt: string): string | null;
19
+ }
20
+ export declare function parseAgentNames(value: string): AgentName[];
21
+ /** Resolve the desired instruction targets without writing the project. */
22
+ export declare function resolveAgentTargets(basePath: string, explicitAgents?: readonly AgentName[], interaction?: AgentInteraction): AgentTargetFile[];
1
23
  /**
2
- * Read scaffold/agent-specs.txt and process CLAUDE.md and AGENTS.md
3
- * at basePath.
4
- *
5
- * SCAF-10: when neither exists, both are created; when only one
6
- * exists, only that file is updated. Section replacement parses
7
- * Markdown and matches the H2 heading "Specs (Source of Truth)"
8
- * case-sensitively, immune to lookalikes inside code fences.
9
- * SCAF-5: replace in place or skip when identical.
10
- *
11
- * With `createMissing: false` (the --update flow), absent files stay
12
- * absent; only existing agent files get their managed section
13
- * refreshed.
24
+ * Reconcile the selected native agent files with the managed section
25
+ * from scaffold/agent-specs.txt. Unselected files lose only that
26
+ * section; unrelated content is never removed.
14
27
  */
15
- export declare function appendAgentSpecs(basePath: string, options?: {
16
- createMissing?: boolean;
17
- }): void;
28
+ export declare function reconcileAgentSpecs(basePath: string, selectedTargets: readonly AgentTargetFile[]): void;
@@ -1,11 +1,40 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { existsSync, readFileSync, readSync, unlinkSync, writeFileSync, } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { getScaffoldDir } from "./bundled-scaffold.js";
6
6
  import { headingText, parseMarkdown, startOffset } from "./markdown.js";
7
7
  const SECTION_TITLE = "Specs (Source of Truth)";
8
- const AGENT_FILES = ["CLAUDE.md", "AGENTS.md"];
8
+ export const AGENT_TARGETS = [
9
+ {
10
+ file: "CLAUDE.md",
11
+ agents: ["claude"],
12
+ label: "Claude Code",
13
+ },
14
+ {
15
+ file: "AGENTS.md",
16
+ agents: ["codex", "kimi", "opencode"],
17
+ label: "Codex / Kimi Code / OpenCode",
18
+ },
19
+ {
20
+ file: "GEMINI.md",
21
+ agents: ["gemini"],
22
+ label: "Gemini CLI",
23
+ },
24
+ ];
25
+ const AGENT_NAMES = AGENT_TARGETS.flatMap((target) => target.agents);
26
+ const AGENT_FILES = AGENT_TARGETS.map((target) => target.file);
27
+ const terminalInteraction = {
28
+ interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
29
+ ask(prompt) {
30
+ process.stderr.write(prompt);
31
+ const buffer = Buffer.alloc(1024);
32
+ const bytes = readSync(0, buffer, 0, buffer.length, null);
33
+ if (bytes === 0)
34
+ return null;
35
+ return buffer.toString("utf-8", 0, bytes).trim();
36
+ },
37
+ };
9
38
  /**
10
39
  * Extract the specs section from content: from the managed heading to
11
40
  * the next h2 heading or end of file. The content is parsed as
@@ -28,6 +57,85 @@ function findSection(content) {
28
57
  end -= content[end - 2] === "\r" ? 2 : 1;
29
58
  return [startOffset(managed), end];
30
59
  }
60
+ function hasManagedSection(filePath) {
61
+ return (existsSync(filePath) &&
62
+ findSection(readFileSync(filePath, "utf-8")) !== null);
63
+ }
64
+ function targetsForAgents(agents) {
65
+ const selected = new Set(agents);
66
+ return AGENT_TARGETS.filter((target) => target.agents.some((agent) => selected.has(agent))).map((target) => target.file);
67
+ }
68
+ export function parseAgentNames(value) {
69
+ const tokens = value
70
+ .split(",")
71
+ .map((token) => token.trim().toLowerCase())
72
+ .filter(Boolean);
73
+ if (tokens.length === 0) {
74
+ throw new Error("--agents requires a comma-separated agent list");
75
+ }
76
+ if (tokens.includes("all")) {
77
+ if (tokens.length !== 1) {
78
+ throw new Error("--agents=all cannot be combined with other agents");
79
+ }
80
+ return [...AGENT_NAMES];
81
+ }
82
+ const unknown = tokens.filter((token) => !AGENT_NAMES.includes(token));
83
+ if (unknown.length > 0) {
84
+ throw new Error(`Unknown agent${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}. Supported agents: ${AGENT_NAMES.join(", ")}, all`);
85
+ }
86
+ return [...new Set(tokens)];
87
+ }
88
+ function detectCurrentTargets(basePath) {
89
+ const managed = AGENT_FILES.filter((file) => hasManagedSection(join(basePath, file)));
90
+ if (managed.length > 0)
91
+ return managed;
92
+ return AGENT_FILES.filter((file) => existsSync(join(basePath, file)));
93
+ }
94
+ function targetSummary(files) {
95
+ const selected = new Set(files);
96
+ return AGENT_TARGETS.filter((target) => selected.has(target.file))
97
+ .map((target) => ` ${AGENT_TARGETS.indexOf(target) + 1}. ${target.label} (${target.file})`)
98
+ .join("\n");
99
+ }
100
+ function promptForTargets(interaction) {
101
+ const response = interaction.ask("Select the coding agents that should receive Spex instructions:\n" +
102
+ targetSummary(AGENT_FILES) +
103
+ "\nEnter numbers separated by commas [all]: ");
104
+ if (response === null)
105
+ throw new Error("agent selection canceled");
106
+ if (response === "" || response.toLowerCase() === "all") {
107
+ return [...AGENT_FILES];
108
+ }
109
+ const numbers = response.split(",").map((token) => token.trim());
110
+ if (numbers.some((token) => !/^[1-3]$/.test(token)) ||
111
+ numbers.length === 0) {
112
+ throw new Error("agent selection must be all or comma-separated numbers 1-3");
113
+ }
114
+ return [
115
+ ...new Set(numbers.map((number) => AGENT_FILES[Number(number) - 1])),
116
+ ];
117
+ }
118
+ /** Resolve the desired instruction targets without writing the project. */
119
+ export function resolveAgentTargets(basePath, explicitAgents, interaction = terminalInteraction) {
120
+ if (explicitAgents !== undefined)
121
+ return targetsForAgents(explicitAgents);
122
+ const current = detectCurrentTargets(basePath);
123
+ if (!interaction.interactive) {
124
+ return current.length > 0 ? current : [...AGENT_FILES];
125
+ }
126
+ if (current.length === 0)
127
+ return promptForTargets(interaction);
128
+ const response = interaction.ask("Spex agent instructions currently target:\n" +
129
+ targetSummary(current) +
130
+ "\nKeep this selection? [Y/n] ");
131
+ if (response === null)
132
+ throw new Error("agent selection canceled");
133
+ if (response === "" || /^y(?:es)?$/i.test(response))
134
+ return current;
135
+ if (/^n(?:o)?$/i.test(response))
136
+ return promptForTargets(interaction);
137
+ throw new Error("answer y or n when confirming agent instructions");
138
+ }
31
139
  /**
32
140
  * Process a single agent file: replace section in place, append,
33
141
  * or create.
@@ -60,32 +168,52 @@ function processFile(filePath, specsContent, fileExists, shouldCreate) {
60
168
  writeFileSync(filePath, existing + separator + specsContent);
61
169
  return "updated";
62
170
  }
171
+ function removeManagedSection(filePath) {
172
+ if (!existsSync(filePath))
173
+ return null;
174
+ const existing = readFileSync(filePath, "utf-8");
175
+ const section = findSection(existing);
176
+ if (section === null)
177
+ return null;
178
+ const [start, end] = section;
179
+ const before = existing.slice(0, start).trimEnd();
180
+ const after = existing.slice(end).trimStart();
181
+ if (before === "" && after === "") {
182
+ unlinkSync(filePath);
183
+ return "removed";
184
+ }
185
+ // Infer the seam from the content that survives, never from the
186
+ // whole file: the managed section carries the bundle's line endings
187
+ // (CRLF where git checked agent-specs.txt out on Windows), and a
188
+ // section being deleted must not impose them on what remains.
189
+ const surviving = before !== "" ? before : after;
190
+ const lineEnding = surviving.includes("\r\n") ? "\r\n" : "\n";
191
+ const updated = before !== "" && after !== ""
192
+ ? `${before}${lineEnding}${lineEnding}${after}`
193
+ : before !== ""
194
+ ? `${before}${lineEnding}`
195
+ : after;
196
+ writeFileSync(filePath, updated);
197
+ return "removed";
198
+ }
63
199
  /**
64
- * Read scaffold/agent-specs.txt and process CLAUDE.md and AGENTS.md
65
- * at basePath.
66
- *
67
- * SCAF-10: when neither exists, both are created; when only one
68
- * exists, only that file is updated. Section replacement parses
69
- * Markdown and matches the H2 heading "Specs (Source of Truth)"
70
- * case-sensitively, immune to lookalikes inside code fences.
71
- * SCAF-5: replace in place or skip when identical.
72
- *
73
- * With `createMissing: false` (the --update flow), absent files stay
74
- * absent; only existing agent files get their managed section
75
- * refreshed.
200
+ * Reconcile the selected native agent files with the managed section
201
+ * from scaffold/agent-specs.txt. Unselected files lose only that
202
+ * section; unrelated content is never removed.
76
203
  */
77
- export function appendAgentSpecs(basePath, options = {}) {
78
- const createMissing = options.createMissing ?? true;
204
+ export function reconcileAgentSpecs(basePath, selectedTargets) {
205
+ if (selectedTargets.length === 0) {
206
+ throw new Error("at least one agent instruction target must be selected");
207
+ }
79
208
  const scaffoldDir = getScaffoldDir();
80
209
  const specsContent = readFileSync(join(scaffoldDir, "agent-specs.txt"), "utf-8");
81
- const presence = AGENT_FILES.map((f) => existsSync(join(basePath, f)));
82
- const neitherExists = presence.every((p) => !p);
83
- for (let i = 0; i < AGENT_FILES.length; i++) {
84
- const fileName = AGENT_FILES[i];
210
+ const selected = new Set(selectedTargets);
211
+ for (const fileName of AGENT_FILES) {
85
212
  const filePath = join(basePath, fileName);
86
- const fileExists = presence[i];
87
- const shouldCreate = createMissing && neitherExists;
88
- const result = processFile(filePath, specsContent, fileExists, shouldCreate);
213
+ const fileExists = existsSync(filePath);
214
+ const result = selected.has(fileName)
215
+ ? processFile(filePath, specsContent, fileExists, true)
216
+ : removeManagedSection(filePath);
89
217
  switch (result) {
90
218
  case "created":
91
219
  console.log(` ${fileName} (created)`);
@@ -96,8 +224,11 @@ export function appendAgentSpecs(basePath, options = {}) {
96
224
  case "skipped":
97
225
  console.log(` ${fileName} (skipped)`);
98
226
  break;
227
+ case "removed":
228
+ console.log(` ${fileName} (removed)`);
229
+ break;
99
230
  case null:
100
- // File absent and not creating — no output
231
+ // Unselected and unmanaged — no output.
101
232
  break;
102
233
  }
103
234
  }
package/dist/cli.js CHANGED
@@ -6,10 +6,14 @@ import { scaffold } from "./scaffold.js";
6
6
  const USAGE = `Usage: spex <command> [options]
7
7
 
8
8
  Commands:
9
- scaffold [--lang <code>] [<path>] Create specs directory structure
10
- scaffold --update Refresh scaffold-provided specs templates
9
+ scaffold [--lang <code>] [--agents <names>] [<path>]
10
+ Create specs directory structure
11
+ scaffold --update [--lang <code>] [--agents <names>]
12
+ Refresh scaffold-provided specs templates
11
13
  lint [<path>] Check the specs tree structure, item IDs,
12
- and citations`;
14
+ and citations
15
+
16
+ Agent names: claude, codex, gemini, kimi, opencode, or all`;
13
17
  function main() {
14
18
  const args = process.argv.slice(2);
15
19
  const command = args[0];
@@ -9,6 +9,13 @@ export type LegacyItemLayoutResult = {
9
9
  type RefreshPristineSeedsOptions = {
10
10
  migratedFrom?: ReadonlyMap<string, string>;
11
11
  language?: ScaffoldLanguage;
12
+ /**
13
+ * A second language whose bundled versions also count as pristine.
14
+ * A language switch reads the tree in its old language and writes
15
+ * the new one, so a seed pristine in the old language is a
16
+ * convertible bundled file, not a user customization.
17
+ */
18
+ alsoRecognize?: readonly ScaffoldLanguage[];
12
19
  /**
13
20
  * Replacement indicator text for user-modified seeds that this run
14
21
  * transformed in place (e.g. a restructured map.md), so one line
@@ -44,7 +51,7 @@ export declare function getLegacyFileHistory(relPath: string): string[];
44
51
  /** isPristine over the legacy manifest (removed bundled paths). */
45
52
  export declare function isLegacyPristine(basePath: string, relPath: string): PristineState;
46
53
  export declare function canonicalContentHash(data: Buffer): string;
47
- export declare function isPristine(basePath: string, relPath: string, language?: ScaffoldLanguage): PristineState;
48
- export declare function overwriteFrameworkSpecFiles(basePath: string, language?: ScaffoldLanguage): string[];
54
+ export declare function isPristine(basePath: string, relPath: string, language?: ScaffoldLanguage, alsoRecognize?: readonly ScaffoldLanguage[]): PristineState;
55
+ export declare function overwriteFrameworkSpecFiles(basePath: string, language?: ScaffoldLanguage, alsoRecognize?: readonly ScaffoldLanguage[]): string[];
49
56
  export declare function refreshPristineSeeds(basePath: string, options?: RefreshPristineSeedsOptions): void;
50
57
  export {};
@@ -239,10 +239,12 @@ export function isLegacyPristine(basePath, relPath) {
239
239
  ? "pristine"
240
240
  : "modified";
241
241
  }
242
- function getRecognizedFileHistory(relPath, language) {
242
+ function getRecognizedFileHistory(relPath, language, alsoRecognize = []) {
243
243
  const history = new Set(getFileHistory(relPath));
244
- if (language !== "en") {
245
- for (const hash of getFileHistory(getOverlayRelPath(language, relPath))) {
244
+ for (const lang of [language, ...alsoRecognize]) {
245
+ if (lang === "en")
246
+ continue;
247
+ for (const hash of getFileHistory(getOverlayRelPath(lang, relPath))) {
246
248
  history.add(hash);
247
249
  }
248
250
  }
@@ -262,21 +264,21 @@ function canonicalHashInput(data) {
262
264
  return data.toString("utf-8").replace(/\r\n?/g, "\n");
263
265
  }
264
266
  // SCAF-22.
265
- export function isPristine(basePath, relPath, language = "en") {
267
+ export function isPristine(basePath, relPath, language = "en", alsoRecognize = []) {
266
268
  const target = join(basePath, relPath);
267
269
  if (!existsSync(target))
268
270
  return "missing";
269
- return getRecognizedFileHistory(relPath, language).includes(hashFile(target))
271
+ return getRecognizedFileHistory(relPath, language, alsoRecognize).includes(hashFile(target))
270
272
  ? "pristine"
271
273
  : "modified";
272
274
  }
273
275
  // SCAF-14. Returns the framework paths that were overwritten while
274
276
  // carrying unrecognized (user-modified) content, so the caller can warn
275
277
  // before the run completes (SCAF-18).
276
- export function overwriteFrameworkSpecFiles(basePath, language = "en") {
278
+ export function overwriteFrameworkSpecFiles(basePath, language = "en", alsoRecognize = []) {
277
279
  const replacedUserModified = [];
278
280
  for (const relPath of FRAMEWORK_FILES) {
279
- const state = isPristine(basePath, relPath, language);
281
+ const state = isPristine(basePath, relPath, language, alsoRecognize);
280
282
  const target = join(basePath, relPath);
281
283
  const source = getBundledSpecFilePath(relPath, language);
282
284
  if (state !== "missing" && hashFile(target) === hashFile(source)) {
@@ -307,7 +309,7 @@ function formatSeedIndicator(relPath, indicator, migratedFrom) {
307
309
  export function refreshPristineSeeds(basePath, options = {}) {
308
310
  const language = options.language ?? "en";
309
311
  for (const relPath of SEED_FILES) {
310
- const state = isPristine(basePath, relPath, language);
312
+ const state = isPristine(basePath, relPath, language, options.alsoRecognize);
311
313
  if (state === "modified") {
312
314
  const indicator = formatSeedIndicator(relPath, options.indicatorOverrides?.get(relPath) ?? "kept — user-modified", options.migratedFrom);
313
315
  console.log(` ${relPath} (${indicator})`);
package/dist/lint.js CHANGED
@@ -58,7 +58,7 @@ const HAS_CITATION_RE = /\[[^\]]*\]\([^)]*\)/;
58
58
  const CITATION_SCAN_RE = /\[[^\]]*\]\([^)]*\)/g;
59
59
  const DETACHED_VERIFIES_RE = /^Verifies\b(?:[\s,.;]|and\b)*$/;
60
60
  // Legacy directories of retired spec generations (lint-4); their
61
- // structural migration is agent-skill work, not CLI code (DR-021).
61
+ // structural migration is agent judgment, not CLI code (DR-022).
62
62
  const LEGACY_DIRS = [
63
63
  "user",
64
64
  "dev",
@@ -228,7 +228,7 @@ function lintStructure(ctx) {
228
228
  const specsDir = join(ctx.basePath, "specs");
229
229
  for (const dir of LEGACY_DIRS) {
230
230
  if (existsSync(join(specsDir, dir))) {
231
- report(ctx, `specs/${dir}`, 1, "error", "structure/legacy-layout", `legacy directory specs/${dir}/ found; run the spec-structure-migration skill to migrate to the current layout (DR-021)`);
231
+ report(ctx, `specs/${dir}`, 1, "error", "structure/legacy-layout", `legacy directory specs/${dir}/ found; run \`spex scaffold --update\` to refresh the spec law and get the migration prompt`);
232
232
  }
233
233
  }
234
234
  for (const entry of readdirSync(specsDir).sort()) {
package/dist/scaffold.js CHANGED
@@ -3,16 +3,15 @@
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { existsSync, readFileSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
- import { appendAgentSpecs } from "./append-agent-specs.js";
6
+ import { parseAgentNames, reconcileAgentSpecs, resolveAgentTargets, } from "./append-agent-specs.js";
7
7
  import { getScaffoldDir, readBundledMarkdown } from "./bundled-scaffold.js";
8
- import { copyRootLicense, copyTemplates, formatSupportedLanguages, isLegacyPristine, isPristine, isSupportedLanguage, overwriteFrameworkSpecFiles, refreshPristineSeeds, } from "./copy-templates.js";
8
+ import { canonicalContentHash, copyRootLicense, copyTemplates, formatSupportedLanguages, getFileHistory, SUPPORTED_LANGUAGES, isLegacyPristine, isPristine, isSupportedLanguage, overwriteFrameworkSpecFiles, refreshPristineSeeds, } from "./copy-templates.js";
9
9
  import { createSpecsStructure } from "./create-specs-structure.js";
10
10
  import { resolveBase } from "./resolve-base.js";
11
11
  const AUTHORING_LANGUAGE_RE = /^Authoring language:\s*([A-Za-z0-9-]+)\s*$/m;
12
12
  // SCAF-26 / SCAF-52: directories that mark a legacy spec generation.
13
- // Structural migration of a legacy generation is agent-skill work, not
14
- // CLI code (DR-021), so the CLI only detects these and points at the
15
- // spec-structure-migration skill.
13
+ // Structural migration is agent judgment, not CLI code (DR-022), so
14
+ // the CLI detects these and prints the bundled migration prompt.
16
15
  const LEGACY_GENERATION_DIRS = [
17
16
  "user",
18
17
  "dev",
@@ -30,6 +29,7 @@ function parseLanguage(code) {
30
29
  function parseArgs(args) {
31
30
  let update = false;
32
31
  let language;
32
+ let agents;
33
33
  const pathArgs = [];
34
34
  for (let i = 0; i < args.length; i += 1) {
35
35
  const arg = args[i];
@@ -56,24 +56,40 @@ function parseArgs(args) {
56
56
  language = parseLanguage(arg.slice("--lang=".length));
57
57
  continue;
58
58
  }
59
+ if (arg === "--agents") {
60
+ const value = args[i + 1];
61
+ if (value === undefined) {
62
+ throw new Error("--agents requires a comma-separated agent list");
63
+ }
64
+ if (agents !== undefined) {
65
+ throw new Error("--agents may only be specified once");
66
+ }
67
+ agents = parseAgentNames(value);
68
+ i += 1;
69
+ continue;
70
+ }
71
+ if (arg.startsWith("--agents=")) {
72
+ if (agents !== undefined) {
73
+ throw new Error("--agents may only be specified once");
74
+ }
75
+ agents = parseAgentNames(arg.slice("--agents=".length));
76
+ continue;
77
+ }
59
78
  if (arg.startsWith("-")) {
60
79
  throw new Error(`Unknown option: ${arg}`);
61
80
  }
62
81
  pathArgs.push(arg);
63
82
  }
64
83
  if (update) {
65
- if (language !== undefined) {
66
- throw new Error("--update does not accept --lang");
67
- }
68
84
  if (pathArgs.length !== 0) {
69
85
  throw new Error("--update does not accept a <path> argument");
70
86
  }
71
- return { mode: "update" };
87
+ return { mode: "update", language, agents };
72
88
  }
73
89
  if (pathArgs.length > 1) {
74
90
  throw new Error(`Unexpected arguments: ${pathArgs.slice(1).join(" ")}`);
75
91
  }
76
- return { mode: "create", pathArg: pathArgs[0], language };
92
+ return { mode: "create", pathArg: pathArgs[0], language, agents };
77
93
  }
78
94
  function getGitRoot() {
79
95
  try {
@@ -97,13 +113,35 @@ function assertCleanSpecsTree(basePath) {
97
113
  }
98
114
  }
99
115
  function readActiveLanguage(basePath) {
116
+ const resolved = resolveActiveLanguage(basePath);
117
+ return resolved.kind === "undeterminable" ? "en" : resolved.language;
118
+ }
119
+ /**
120
+ * Resolve the tree's authoring language and how confidently.
121
+ *
122
+ * A declaration is definitive. Absent one, `specs/meta.md` matching a
123
+ * version this CLI shipped is still definitive — every bundled base
124
+ * `meta.md` is English — which keeps pre-marker trees updating
125
+ * silently. What remains is genuinely undeterminable: a file we never
126
+ * shipped that declares nothing (a localized tree whose marker line
127
+ * was lost reads exactly like this), or no file at all. Guessing `en`
128
+ * there replaces a localized tree's framework files with English, so
129
+ * the caller stops instead.
130
+ */
131
+ function resolveActiveLanguage(basePath) {
100
132
  const metaPath = join(basePath, "specs", "meta.md");
101
- if (!existsSync(metaPath))
102
- return "en";
103
- const match = readFileSync(metaPath, "utf-8").match(AUTHORING_LANGUAGE_RE);
104
- if (match === null)
105
- return "en";
106
- return parseLanguage(match[1]);
133
+ if (!existsSync(metaPath)) {
134
+ return { kind: "undeterminable", reason: "absent" };
135
+ }
136
+ const content = readFileSync(metaPath);
137
+ const match = content.toString("utf-8").match(AUTHORING_LANGUAGE_RE);
138
+ if (match !== null) {
139
+ return { kind: "declared", language: parseLanguage(match[1]) };
140
+ }
141
+ if (getFileHistory("specs/meta.md").includes(canonicalContentHash(content))) {
142
+ return { kind: "bundled-english", language: "en" };
143
+ }
144
+ return { kind: "undeterminable", reason: "unrecognized" };
107
145
  }
108
146
  function resolveCreateLanguage(basePath, requestedLanguage) {
109
147
  const metaPath = join(basePath, "specs", "meta.md");
@@ -161,52 +199,99 @@ function detectLegacyGeneration(basePath, language) {
161
199
  isOldGenerationMeta(basePath, language) ||
162
200
  matchesRetiredBundledSeed(basePath));
163
201
  }
164
- // SCAF-26: the guidance names the migration skill, its guide, and the
165
- // lint gate. No path-level summary lines here — the per-file indicators
166
- // above are the run's only path summary (SCAF-11).
167
- function printMigrationGuidance() {
168
- console.log("");
169
- console.log("This specs tree carries a legacy spec generation (spex 0.x). The template refresh");
170
- console.log("above left all legacy content untouched: structural migration is");
171
- console.log("agent-skill work, not CLI code.");
172
- console.log("To migrate, run the spec-structure-migration skill bundled with spex");
173
- console.log("(skills/spec-structure-migration/ in the spex repo); its guide is");
174
- console.log("docs/spec-migration.md.");
175
- console.log("The migrated tree must pass `spex lint` — the mechanical gate.");
176
- }
177
202
  // SCAF-18: the four-step --update pipeline — framework overwrite, seed
178
203
  // refresh, agent-file refresh, then the completion output.
179
- function updateScaffoldTemplates() {
204
+ function updateScaffoldTemplates(agents, requested) {
180
205
  const basePath = getGitRoot();
181
206
  assertCleanSpecsTree(basePath);
182
- const language = readActiveLanguage(basePath);
207
+ const active = resolveActiveLanguage(basePath);
208
+ // An explicit --lang settles the language outright, so neither the
209
+ // undeterminable stop nor its warning applies.
210
+ if (active.kind === "undeterminable" && requested === undefined) {
211
+ if (active.reason === "unrecognized") {
212
+ throw new Error("specs/meta.md declares no authoring language and matches no bundled " +
213
+ "version, so the language cannot be determined and updating would " +
214
+ "replace the framework files with English. Restore its " +
215
+ "`Authoring language: <code>` line (`en` or `zh`), commit the " +
216
+ "specs/ change, and run again — --update needs a clean specs/ tree.");
217
+ }
218
+ // Absent: an older tree being repaired, since --update creates
219
+ // missing framework files. English is the only available answer,
220
+ // but a localized tree lands mixed, so it is never silent.
221
+ console.warn(" warning: no specs/meta.md, so the authoring language is unknown; " +
222
+ "creating framework files as en. On a localized tree, set the new " +
223
+ "`Authoring language:` line to that language, commit the specs/ " +
224
+ "changes, and run `spex scaffold --update` again to refresh them " +
225
+ "from its overlay.");
226
+ }
227
+ // The declaration, not the fallback: an undeclared tree must not
228
+ // look like an English one, or --lang en reads as "same language"
229
+ // and the switch never runs.
230
+ const declared = active.kind === "undeterminable" ? undefined : active.language;
231
+ const language = requested ?? declared ?? "en";
232
+ // A switch reads a tree written in one language and writes another,
233
+ // so both languages' bundled versions count as pristine: without
234
+ // that, the old language's files read as user customizations and
235
+ // seeds would be kept rather than converted.
236
+ // A switch reads a tree written in one language and writes another.
237
+ // When the tree still declares its language, that one language is
238
+ // enough; when it declares none, any bundled language could be in
239
+ // the tree, so all of them count — otherwise the undeclared tree's
240
+ // seeds read as customizations and are kept in the old language.
241
+ const switchingFrom = requested === undefined
242
+ ? undefined
243
+ : declared === undefined
244
+ ? "unknown"
245
+ : requested === declared
246
+ ? undefined
247
+ : declared;
248
+ const alsoRecognize = switchingFrom === undefined
249
+ ? []
250
+ : switchingFrom === "unknown"
251
+ ? SUPPORTED_LANGUAGES
252
+ : [switchingFrom];
183
253
  // Sample legacy-generation markers before the framework overwrite
184
254
  // replaces specs/meta.md (SCAF-26).
185
255
  const legacyGeneration = detectLegacyGeneration(basePath, language);
186
- const replacedFramework = overwriteFrameworkSpecFiles(basePath, language);
187
- refreshPristineSeeds(basePath, { language });
188
- appendAgentSpecs(basePath, { createMissing: false });
256
+ const agentTargets = resolveAgentTargets(basePath, agents);
257
+ const replacedFramework = overwriteFrameworkSpecFiles(basePath, language, alsoRecognize);
258
+ refreshPristineSeeds(basePath, { language, alsoRecognize });
259
+ reconcileAgentSpecs(basePath, agentTargets);
189
260
  warnReplacedFrameworkFiles(replacedFramework);
190
261
  console.log("");
191
262
  console.log("spex scaffold --update completed.");
192
263
  console.log("Review the file indicators above and inspect changes (e.g., `git diff -- specs`),");
193
264
  console.log("then run `spex lint` to check the specs tree.");
194
- console.log("Optionally, share this prompt with your AI agent to reconcile citations and local extensions:");
265
+ console.log(legacyGeneration
266
+ ? "Share this prompt with your AI agent to migrate the untouched legacy content:"
267
+ : "Optionally, share this prompt with your AI agent to reconcile citations and local extensions:");
195
268
  console.log("");
196
269
  console.log("```");
197
- console.log(readBundledMarkdown("update-merge-prompt.md"));
270
+ console.log(readBundledMarkdown(legacyGeneration
271
+ ? "spec-migration-prompt.md"
272
+ : "update-merge-prompt.md"));
198
273
  console.log("```");
199
- if (legacyGeneration)
200
- printMigrationGuidance();
274
+ if (switchingFrom !== undefined) {
275
+ console.log("");
276
+ console.log(switchingFrom === "unknown"
277
+ ? `Authoring language set to ${language}: bundled specs are now ${language}.`
278
+ : `Authoring language switched from ${switchingFrom} to ${language}: bundled specs are now ${language}.`);
279
+ console.log("Existing project specs stay in their original language — translating them is agent work.");
280
+ console.log("Share this prompt with your AI agent to translate them:");
281
+ console.log("");
282
+ console.log("```");
283
+ console.log(readBundledMarkdown("language-switch-prompt.md"));
284
+ console.log("```");
285
+ }
201
286
  }
202
- // SCAF-52: a legacy tree gets guidance, not a re-scaffold — creating
203
- // current seed targets beside legacy files would entangle two spec
204
- // generations before the migration skill has run.
287
+ // SCAF-52: a legacy tree gets the migration prompt, not a re-scaffold —
288
+ // creating current seed targets beside legacy files would entangle two
289
+ // spec generations before migration.
205
290
  function assertNoLegacyLayout(basePath) {
206
291
  for (const dir of LEGACY_GENERATION_DIRS) {
207
292
  const abs = join(basePath, "specs", dir);
208
293
  if (existsSync(abs) && statSync(abs).isDirectory()) {
209
- throw new Error(`specs/${dir}/ marks a legacy spec generation (spex 0.x); run \`spex scaffold --update\` to refresh templates and get migration guidance before scaffolding`);
294
+ throw new Error(`specs/${dir}/ marks a legacy spec generation (spex 0.x); run \`spex scaffold --update\` to refresh templates and get the migration prompt before scaffolding`);
210
295
  }
211
296
  }
212
297
  }
@@ -218,16 +303,17 @@ export function scaffold(args = []) {
218
303
  try {
219
304
  const options = parseArgs(args);
220
305
  if (options.mode === "update") {
221
- updateScaffoldTemplates();
306
+ updateScaffoldTemplates(options.agents, options.language);
222
307
  return;
223
308
  }
224
309
  const basePath = resolveBase(options.pathArg);
225
310
  const language = resolveCreateLanguage(basePath, options.language);
226
311
  assertNoLegacyLayout(basePath);
312
+ const agentTargets = resolveAgentTargets(basePath, options.agents);
227
313
  createSpecsStructure(basePath);
228
314
  copyTemplates(basePath, language);
229
315
  copyRootLicense(basePath);
230
- appendAgentSpecs(basePath);
316
+ reconcileAgentSpecs(basePath, agentTargets);
231
317
  }
232
318
  catch (err) {
233
319
  const msg = err instanceof Error ? err.message : String(err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sublang/spex",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "The essential spec layer AI agents need to build software reliably",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -0,0 +1,12 @@
1
+ <!-- SPDX-License-Identifier: Apache-2.0 -->
2
+ <!-- SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai> -->
3
+
4
+ Translate this project's own specs into the authoring language now declared by @specs/meta.md:
5
+
6
+ - Translate the prose of every spec file the project owns under @specs/ — package Intents, behavior and test statements, decision records, intent records, and @specs/map.md entries. The bundled framework files are already in the new language.
7
+ - Preserve every item ID, heading anchor, and citation target exactly: `[[pack-3](pack.md#pack-3)]` keeps its ID text and link, and `pack-3` stays `pack-3` in the heading it names.
8
+ - Use the section names the active @specs/meta.md defines for package files and records; do not invent alternatives.
9
+ - Leave untranslated what is not prose: file paths, identifiers, code, commands, `Authoring language:` and other machine-readable marker lines, and external reference URLs.
10
+ - Preserve meaning over style. Where a term is a defined concept in @specs/meta.md, translate it the way meta.md translates it, and keep one rendering per term throughout.
11
+ - Translate only. Do not add, drop, split, merge, or restructure any requirement while translating.
12
+ - Finish by running `spex lint` and resolving any error.
@@ -0,0 +1,28 @@
1
+ <!-- SPDX-License-Identifier: Apache-2.0 -->
2
+ <!-- SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai> -->
3
+
4
+ Migrate every legacy Spex specs tree in this repository to the current spec generation:
5
+
6
+ - Read current `@specs/meta.md` and `@specs/decisions/000-spec-structure-format.md` fully before editing; they are the target law, and `spex scaffold --update` refreshed them while leaving legacy content untouched.
7
+ Synchronize each additional spec tree's framework law to that target while preserving tree-specific context; do not revise the target law itself without explicit human approval.
8
+ - Preserve every stated behavior, local extension, record state, checkbox, and item's concern; invent or drop nothing.
9
+ If an item ID appeared in a public release, obtain owner approval for the generation-wide spelling change before editing.
10
+ - Inventory the whole tree and build a complete rename map before moving content.
11
+ Each old short-form ID becomes `<destination-file-basename>-<N>`, lowercase, with `<N>` unchanged; resolve basename clashes first, then retarget headings, prose names, links, paths, anchors, and inbound citations tree-wide.
12
+ - Retarget old `META-*` citations by concern, never by number alone.
13
+ Non-identity mappings are `META-3` and `META-28` to `meta-30`, `META-32` to `meta-31`, `META-37` to `meta-28`, `META-38` to `meta-33`, `META-42` to `meta-29`, and `META-43` to `meta-22`; `META-17`, `META-26`, `META-31`, `META-33` through `META-36`, `META-39` through `META-41`, and `META-44` have no direct successor.
14
+ For removed law, keep still-true prose and drop the link; rewrite or remove a dead claim.
15
+ - Merge old `user/`, `dev/`, `test/`, and `items/` sources for one subject into one package; those directories are classification hints only.
16
+ Fold `interactions/` and `compositions/` into ordinary packages, and move `iterations/` records to `intents/`.
17
+ When the update created a current seed at a destination, reconcile legacy local content into it rather than overwriting or duplicating it.
18
+ - Make each package self-contained with `# <basename>: <Title>` and the current section order.
19
+ Classify guarantees its human or component users rely on as External Behavior and hidden behavior as Internal Behavior; behavior cited by a peer must be External.
20
+ - Restate each item as one GEARS requirement and place its cases or steps after the statement's final colon.
21
+ Use current item and record citation forms, put every peer binding citation at the behavior phrase it makes specific, confine Verification citations to the containing package, and remove relationship-metadata lines or detached `Verifies` sentences.
22
+ - Give every DR and IR the current sections and truthful status.
23
+ For a legacy IR missing commit-sized Tasks, recover minimal truthful tasks from history or flag the gap rather than inventing them; no DR or spec item may cite or name an IR.
24
+ - Update `map.md` and any project guidance describing the old layout.
25
+ Preserve SPDX headers byte-for-byte, keep one sentence per line, and remove legacy files or directories only after their content and citations survive in the new tree.
26
+ - Loop on `spex lint` until clean.
27
+ Manually review for residue it may not catch — old uppercase item IDs, single-bracket item citations, legacy paths, relationship-metadata lines, and dangling links — and re-read heavily restructured files for semantic fidelity.
28
+ - Hand over the rename map, every classification, dependency, status, and split judgment, and every unresolved question for human diff review; do not merge it yourself.
@@ -6,7 +6,6 @@ Review Git diffs under @specs/ and perform a spec update merge:
6
6
  - If @specs/decisions/000-spec-structure-format.md or @specs/meta.md changed, update existing @specs/ files to conform while preserving local content that still applies.
7
7
  - Preserve every item ID and normative concern that appeared in a prior release; provisional IDs may be compacted before publication.
8
8
  - Classify behavior relative to each package: outcomes and guarantees the package's users may rely on belong in `## External Behavior`; behavior hidden from them belongs in `## Internal Behavior`.
9
- - Scope this merge to reconciling the template diff: do not restructure a legacy tree (a `user/`, `dev/`, `test/`, `items/`, `interactions/`, `compositions/`, or `iterations/` directory) into @specs/packages/ yourself — structural migration of a legacy generation belongs to the `spec-structure-migration` skill (`skills/spec-structure-migration/` in the spex repo; guide: `docs/spec-migration.md`).
10
9
  - Convert every item citation to the enclosed ID-text form, e.g. `[[pack-3](pack.md#pack-3)]`, and every record citation to a plain ID-text link, e.g. `[DR-000](decisions/000-example.md)`; place a behavior binding citation at the phrase it makes specific and confine test behavior citations to the containing package.
11
10
  - Place every attachment after the final colon of its governing GEARS statement.
12
11
  - Remove relationship-metadata lines (`Verifies:`, `Binds:`, `Composes:`, `Clients:`, `Suppliers:`, `Scope:`) and detached `Verifies ...` sentences: move each binding citation to the behavior phrase it makes specific and each test citation to the assertion it verifies, then delete the line.