@llman-sdd/core 0.10.0 → 0.11.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 (40) hide show
  1. package/package.json +7 -6
  2. package/src/archive/freeze.ts +73 -11
  3. package/src/archive/frozenCard.ts +62 -5
  4. package/src/archive/ignoreChain.ts +167 -0
  5. package/src/archive/sevenzip.ts +17 -8
  6. package/src/change/lifecycle.ts +55 -59
  7. package/src/config/schema.ts +0 -13
  8. package/src/config/surface.ts +2 -12
  9. package/src/context/sddState.ts +23 -18
  10. package/src/index.ts +15 -36
  11. package/src/init/defaultConfig.ts +2 -13
  12. package/src/init/init.ts +50 -19
  13. package/src/init/skillCheck.ts +60 -0
  14. package/src/project/migrations.ts +81 -9
  15. package/src/spec/authoring.ts +5 -1
  16. package/src/templates/skills.ts +15 -12
  17. package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +5 -5
  18. package/templates/zh-Hans/skills/llman-sdd-apply.md +8 -9
  19. package/templates/zh-Hans/skills/llman-sdd-arch-review.md +1 -1
  20. package/templates/zh-Hans/skills/llman-sdd-archive.md +13 -14
  21. package/templates/zh-Hans/skills/llman-sdd-continue.md +3 -3
  22. package/templates/zh-Hans/skills/llman-sdd-draft.md +3 -3
  23. package/templates/zh-Hans/skills/llman-sdd-explore.md +2 -3
  24. package/templates/zh-Hans/skills/llman-sdd-ff.md +3 -2
  25. package/templates/zh-Hans/skills/llman-sdd-graph.md +1 -1
  26. package/templates/zh-Hans/skills/llman-sdd-propose.md +8 -9
  27. package/templates/zh-Hans/skills/llman-sdd-quick.md +4 -5
  28. package/templates/zh-Hans/skills/llman-sdd-research.md +1 -1
  29. package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +4 -3
  30. package/templates/zh-Hans/skills/llman-sdd-validate.md +2 -2
  31. package/templates/zh-Hans/skills/llman-sdd-verify.md +3 -3
  32. package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +2 -2
  33. package/templates/zh-Hans/units/skills/git-native-flow.md +8 -8
  34. package/templates/zh-Hans/units/skills/stage-guard.md +3 -3
  35. package/templates/zh-Hans/units/skills/structured-protocol.md +1 -1
  36. package/templates/zh-Hans/units/skills/validation-hints.md +3 -3
  37. package/src/context/indexStore.ts +0 -171
  38. package/src/context/retrieve.ts +0 -332
  39. package/src/context/tree.ts +0 -112
  40. package/templates/zh-Hans/units/skills/index-fallback.md +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llman-sdd/core",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Pure domain logic for llman-sdd (config, gherkin specs, validation, templates)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,14 +25,15 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "7z-wasm": "^1.2.0",
28
- "@cucumber/gherkin": "^42.0.1",
29
- "@cucumber/messages": "^34.2.1",
28
+ "@cucumber/gherkin": "^43.0.0",
29
+ "@cucumber/messages": "^35.0.0",
30
30
  "@statelyai/graph": "^2.6.0",
31
- "@toon-format/toon": "^4.1.1",
31
+ "@toon-format/toon": "^4.4.0",
32
+ "ignore": "^7.0.16",
32
33
  "nunjucks": "^3.2.4",
33
- "xstate": "^5.33.2",
34
+ "xstate": "^5.33.4",
34
35
  "yaml": "^2.9.1",
35
- "zod": "^4.6.5"
36
+ "zod": "^4.6.7"
36
37
  },
37
38
  "engines": {
38
39
  "bun": ">=1.4.0",
@@ -18,7 +18,9 @@ import {
18
18
  frozenCardIdOf,
19
19
  frozenCardName,
20
20
  isFrozenCard,
21
+ unfenceFrozenCard,
21
22
  } from './frozenCard.ts';
23
+ import { collectFilteredEntries } from './ignoreChain.ts';
22
24
  import type { SevenZipPort } from './sevenzip.ts';
23
25
 
24
26
  export const FREEZE_ARCHIVE_NAME = 'freezed_changes.7z.archived';
@@ -65,6 +67,9 @@ export interface FreezeOpts {
65
67
  before?: string;
66
68
  keepRecent?: number;
67
69
  dryRun?: boolean;
70
+ /** r120: absolute paths of extra gitignore-format files (highest
71
+ * precedence in the layered evaluation; nonexistent file is an error). */
72
+ ignoreFiles?: string[];
68
73
  }
69
74
 
70
75
  export interface FreezeRunResult {
@@ -96,6 +101,24 @@ export async function runFreeze(
96
101
  // Card = authoritative record that bodies are in the cold backup. Write
97
102
  // cards first; on `7z add` failure roll them back and keep the original dirs.
98
103
  const archiveAbs = join(rootAbs, ARCHIVE_DIR_REL, FREEZE_ARCHIVE_NAME);
104
+ const archiveBase = join(rootAbs, ARCHIVE_DIR_REL);
105
+
106
+ // r120: layered gitignore filtering runs before any mutation — user-file
107
+ // existence errors and the zero-files guard must leave the tree untouched.
108
+ const packed: string[] = [];
109
+ let excludedTotal = 0;
110
+ for (const c of candidates) {
111
+ const { files, excluded } = collectFilteredEntries(io, {
112
+ rootAbs,
113
+ candidateAbs: join(archiveBase, c),
114
+ userIgnoreFiles: opts.ignoreFiles ?? [],
115
+ });
116
+ if (files.length === 0) {
117
+ throw new Error(`candidate has no packable files after ignore filtering: ${c}`);
118
+ }
119
+ excludedTotal += excluded;
120
+ packed.push(...files.map((f) => `${c}/${f}`));
121
+ }
99
122
 
100
123
  const cards: Array<{ datedId: string; source: string }> = [];
101
124
  for (const c of candidates) {
@@ -116,7 +139,7 @@ export async function runFreeze(
116
139
  io.writeText(`${ARCHIVE_DIR_REL}/${frozenCardName(card.datedId)}`, card.source);
117
140
  }
118
141
  try {
119
- await sz.add(archiveAbs, join(rootAbs, ARCHIVE_DIR_REL), candidates);
142
+ await sz.add(archiveAbs, archiveBase, packed);
120
143
  } catch (error) {
121
144
  for (const card of cards) io.remove(`${ARCHIVE_DIR_REL}/${frozenCardName(card.datedId)}`);
122
145
  throw error;
@@ -124,12 +147,13 @@ export async function runFreeze(
124
147
  for (const c of candidates) {
125
148
  io.removeDir(`${ARCHIVE_DIR_REL}/${c}`);
126
149
  }
127
- return {
128
- candidates,
129
- lines: [
130
- `Froze ${candidates.length} archived changes into ./${ARCHIVE_DIR_REL}/${FREEZE_ARCHIVE_NAME}`,
131
- ],
132
- };
150
+ const lines = [
151
+ `Froze ${candidates.length} archived changes into ./${ARCHIVE_DIR_REL}/${FREEZE_ARCHIVE_NAME}`,
152
+ ];
153
+ if (excludedTotal > 0) {
154
+ lines.push(`Excluded ${excludedTotal} ignored file(s) via gitignore chain`);
155
+ }
156
+ return { candidates, lines };
133
157
  }
134
158
 
135
159
  /**
@@ -175,6 +199,42 @@ export interface ThawResult {
175
199
  restored: string[];
176
200
  }
177
201
 
202
+ /**
203
+ * r121: rewrite every fenced card under `archiveDirRel` into the fence-free
204
+ * single-document form. Shared by the thaw pass and the migrate action so both
205
+ * obey one definition of "legacy card". Returns how many cards changed.
206
+ * Cards that are not fenced (or not plainly fenced) are left untouched.
207
+ */
208
+ export function unfenceLegacyCards(io: FreezeIo, archiveDirRel: string): number {
209
+ let changed = 0;
210
+ for (const rel of planUnfenceLegacyCards(io, archiveDirRel)) {
211
+ const unfenced = unfenceFrozenCard(io.readText(rel));
212
+ if (unfenced === null) continue;
213
+ io.writeText(rel, unfenced);
214
+ changed++;
215
+ }
216
+ return changed;
217
+ }
218
+
219
+ /**
220
+ * r121: dry-run half of {@link unfenceLegacyCards} — the exact same scan and
221
+ * predicates, returning the card paths that WOULD change without writing.
222
+ * Sharing the predicate is what keeps `--dry-run` from drifting from the write
223
+ * path.
224
+ */
225
+ export function planUnfenceLegacyCards(io: FreezeIo, archiveDirRel: string): string[] {
226
+ if (!io.exists(archiveDirRel)) return [];
227
+ const hits: string[] = [];
228
+ for (const name of io.listDir(archiveDirRel).toSorted()) {
229
+ if (!isFrozenCard(name) || frozenCardIdOf(name) === null) continue;
230
+ const rel = `${archiveDirRel}/${name}`;
231
+ if (io.isDirectory(rel)) continue;
232
+ if (unfenceFrozenCard(io.readText(rel)) === null) continue;
233
+ hits.push(rel);
234
+ }
235
+ return hits;
236
+ }
237
+
178
238
  export async function runThaw(
179
239
  io: FreezeIo,
180
240
  sz: SevenZipPort,
@@ -219,10 +279,12 @@ export async function runThaw(
219
279
  if (io.exists(cardRel)) io.remove(cardRel);
220
280
  restored.push(name);
221
281
  }
222
- return {
223
- restored,
224
- lines: [`Thawed ${restored.length} selected archived changes to ${destRel}`],
225
- };
282
+ // r121: thaw already rewrites the archive area, so normalize any remaining
283
+ // fenced cards in the same pass. Failing here must never block the restore.
284
+ const unfenced = unfenceLegacyCards(io, ARCHIVE_DIR_REL);
285
+ const lines = [`Thawed ${restored.length} selected archived changes to ${destRel}`];
286
+ if (unfenced > 0) lines.push(`Unfenced ${unfenced} legacy card(s)`);
287
+ return { restored, lines };
226
288
  } finally {
227
289
  io.removeDir(tmpRel);
228
290
  }
@@ -13,15 +13,18 @@
13
13
  * Title source: frontmatter `title` wins when non-empty, else the proposal H1
14
14
  * (legacy archive dirs).
15
15
  *
16
- * Depends_on extraction is deliberately dependency-free (no `yaml` package):
17
- * it recognizes single-line flow `[a, b]`, block `- item` lists and multi-line
18
- * flow blocks, then normalizes to a single-line flow array so `parseDeps`
19
- * reads it unchanged. Anything unparseable degrades to `depends_on: []` (never
20
- * blocks the freeze).
16
+ * Depends_on *extraction* stays dependency-free: it recognizes single-line
17
+ * flow `[a, b]`, block `- item` lists and multi-line flow blocks, then
18
+ * normalizes to a single-line flow array so `parseDeps` reads it unchanged.
19
+ * Anything unparseable degrades to `depends_on: []` (never blocks the freeze).
20
+ * The r121 normalizer is the one place that consults the `yaml` package — it
21
+ * must prove the stripped body is a genuine single document before rewriting.
21
22
  *
22
23
  * Pure string logic — all filesystem effects live in freeze.ts (FreezeIo).
23
24
  */
24
25
 
26
+ import { parseDocument } from 'yaml';
27
+
25
28
  import { datedCardIdOf } from '../util/datedId.ts';
26
29
 
27
30
  export const FROZEN_CARD_EXT = '.yaml';
@@ -106,3 +109,57 @@ export function composeFrozenCard(title: string, frontmatter: string): string {
106
109
  const dependsOn = extractDependsOn(frontmatter);
107
110
  return [`title: "${escapeYamlScalar(title)}"`, dependsOn].join('\n') + '\n';
108
111
  }
112
+
113
+ /**
114
+ * r121: fence-stripping normalizer for legacy cards. Predecessor-era cards
115
+ * open and close with a standalone `---` line, which makes them a *multi*-
116
+ * document YAML stream — generic single-document validators (pre-commit's
117
+ * `check-yaml` by default) reject them. Returns the fence-free text, or null
118
+ * when the input is not a plain fenced card.
119
+ *
120
+ * Conservative by construction — a miss is fine, a false rewrite is not:
121
+ * - first and last non-empty lines must each be exactly `---` (a stray `---`
122
+ * inside a scalar value must never trigger a rewrite);
123
+ * - the stripped body must parse as exactly one YAML document;
124
+ * - that document's keys must be a subset of `title` / `depends_on`.
125
+ * A card already in the fence-free form returns null (idempotent by contract).
126
+ */
127
+ export function unfenceFrozenCard(source: string): string | null {
128
+ const lines = source.split('\n');
129
+ // Trailing newline yields a final '' element; strip it so line indexes point
130
+ // at real content.
131
+ while (lines.length > 0 && (lines[lines.length - 1] ?? '').trim() === '') lines.pop();
132
+ if (lines.length < 3) return null;
133
+ const isFence = (line: string | undefined): boolean =>
134
+ (line ?? '').replace(/\s+$/u, '') === '---';
135
+ if (!isFence(lines[0]) || !isFence(lines[lines.length - 1])) return null;
136
+ // Normalize to LF while stripping: a lone trailing \r is not a YAML line
137
+ // break, so a CRLF card would otherwise fail the single-document parse.
138
+ const body = lines
139
+ .slice(1, -1)
140
+ .map((line) => line.replace(/\r$/u, ''))
141
+ .join('\n');
142
+ if (body.trim() === '') return null;
143
+ let parsed: unknown;
144
+ try {
145
+ const doc = parseDocument(body);
146
+ if (doc.errors.length > 0) return null;
147
+ parsed = doc.toJS({ json: true });
148
+ } catch {
149
+ return null;
150
+ }
151
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
152
+ const record = parsed as Record<string, unknown>;
153
+ const keys = Object.keys(record);
154
+ if (keys.length === 0) return null;
155
+ const allowed = new Set(['title', 'depends_on']);
156
+ if (keys.some((k) => !allowed.has(k))) return null;
157
+ // Shape check, not just key names: r121 keeps `depends_on` participating in
158
+ // dependency-edge parsing, so a scalar/object here is a card we do not
159
+ // understand — leave it for a human rather than normalizing a broken one.
160
+ const title = record['title'];
161
+ if (title !== undefined && typeof title !== 'string') return null;
162
+ const deps = record['depends_on'];
163
+ if (deps !== undefined && deps !== null && !Array.isArray(deps)) return null;
164
+ return `${body}\n`;
165
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * r120 freeze content filter: git-style layered .gitignore evaluation for
3
+ * `archive freeze` (review-freeze capability). For each candidate directory
4
+ * the packer walks the tree and keeps only files no ignore layer decides
5
+ * against: user-supplied `--ignore-file` layers first (highest precedence),
6
+ * then `.gitignore` files found while descending (deeper wins), then the
7
+ * ancestor chain from the candidate dir up to the discovered project root
8
+ * (nearest ancestor holding `.git`; the instance root when absent).
9
+ *
10
+ * Purity: filesystem access flows through the injected IgnoreChainIo; the
11
+ * `ignore` package is a pure pattern engine. All paths are absolute here;
12
+ * POSIX relativization happens per layer (anchoring base = the layer's own
13
+ * directory, exactly like git).
14
+ */
15
+ import { dirname, join, relative, sep } from 'node:path';
16
+
17
+ import * as ignoreModule from 'ignore';
18
+
19
+ import type { FsPort } from '../util/fsPort.ts';
20
+
21
+ type Ignore = ignoreModule.Ignore;
22
+
23
+ /**
24
+ * CJS `export =` interop: both Bun and Node surface the factory on
25
+ * `.default` while the ESM namespace itself is not callable — and under
26
+ * verbatimModuleSyntax tsc types the namespace import as a pure namespace,
27
+ * so the callable is recovered through a structural cast against the
28
+ * package's own `Ignore` interface.
29
+ */
30
+ const createIgnore = (ignoreModule as unknown as { default: () => Ignore }).default;
31
+
32
+ export type IgnoreChainIo = Pick<FsPort, 'exists' | 'listDir' | 'readText' | 'isDirectory'>;
33
+
34
+ export class IgnoreChainError extends Error {}
35
+
36
+ /** One `.gitignore`-style rule set; `base` is the anchoring directory. */
37
+ interface Layer {
38
+ base: string;
39
+ ig: Ignore;
40
+ }
41
+
42
+ export interface FilteredCandidate {
43
+ /** POSIX file paths relative to the candidate dir (7z entry base). */
44
+ files: string[];
45
+ /** Files excluded by ignore rules (pruned directories count recursively). */
46
+ excluded: number;
47
+ }
48
+
49
+ function toPosix(p: string): string {
50
+ return sep === '/' ? p : p.split(sep).join('/');
51
+ }
52
+
53
+ function relPosix(from: string, to: string): string {
54
+ return toPosix(relative(from, to));
55
+ }
56
+
57
+ /**
58
+ * Outermost ignore root: the nearest ancestor of `start` (inclusive) holding
59
+ * `.git` (a directory, or the file git uses for worktrees); when the tree is
60
+ * not inside a git repository the instance root `start` itself is the
61
+ * outermost layer (r120 fallback semantics).
62
+ */
63
+ export function discoverIgnoreRoot(io: IgnoreChainIo, start: string): string {
64
+ let cur = start;
65
+ for (;;) {
66
+ if (io.exists(join(cur, '.git'))) return cur;
67
+ const parent = dirname(cur);
68
+ if (parent === cur) return start;
69
+ cur = parent;
70
+ }
71
+ }
72
+
73
+ function loadLayer(io: IgnoreChainIo, base: string): Layer | null {
74
+ const path = join(base, '.gitignore');
75
+ if (!io.exists(path)) return null;
76
+ return { base, ig: createIgnore().add(io.readText(path)) };
77
+ }
78
+
79
+ /** First decisive layer wins: user files → deepest walk layer → ancestors. */
80
+ function decide(
81
+ user: readonly Layer[],
82
+ walk: readonly Layer[],
83
+ ancestors: readonly Layer[],
84
+ pathAbs: string,
85
+ isDir: boolean,
86
+ ): boolean {
87
+ const layers: Layer[] = [...user];
88
+ for (let i = walk.length - 1; i >= 0; i--) layers.push(walk[i]!);
89
+ layers.push(...ancestors);
90
+ for (const layer of layers) {
91
+ let rel = relPosix(layer.base, pathAbs);
92
+ // A .gitignore governs only its own subtree (git semantics); layers the
93
+ // path lies outside of cannot decide and must not be consulted.
94
+ if (rel === '' || rel === '..' || rel.startsWith('../')) continue;
95
+ if (isDir) rel = `${rel}/`;
96
+ const verdict = layer.ig.test(rel);
97
+ if (verdict.ignored || verdict.unignored) return verdict.ignored;
98
+ }
99
+ return false;
100
+ }
101
+
102
+ function countFiles(io: IgnoreChainIo, dirAbs: string): number {
103
+ let n = 0;
104
+ for (const name of io.listDir(dirAbs)) {
105
+ if (name === '.git') continue;
106
+ const abs = join(dirAbs, name);
107
+ n += io.isDirectory(abs) ? countFiles(io, abs) : 1;
108
+ }
109
+ return n;
110
+ }
111
+
112
+ export interface CollectFilteredOpts {
113
+ /** Instance root (absolute) — ignore-root discovery starts here. */
114
+ rootAbs: string;
115
+ /** Candidate change directory (absolute, under the instance root). */
116
+ candidateAbs: string;
117
+ /** Absolute paths of extra gitignore-format files (highest precedence,
118
+ * anchored at the candidate dir — extras describe per-change junk). */
119
+ userIgnoreFiles: string[];
120
+ }
121
+
122
+ export function collectFilteredEntries(
123
+ io: IgnoreChainIo,
124
+ opts: CollectFilteredOpts,
125
+ ): FilteredCandidate {
126
+ const user: Layer[] = [];
127
+ for (const file of opts.userIgnoreFiles) {
128
+ if (!io.exists(file)) {
129
+ throw new IgnoreChainError(`ignore file not found: ${file}`);
130
+ }
131
+ user.push({ base: opts.candidateAbs, ig: createIgnore().add(io.readText(file)) });
132
+ }
133
+
134
+ // Ancestor chain: candidate dir first (highest of the fixed layers), then
135
+ // each parent up to the discovered ignore root (outermost, last).
136
+ const outer = discoverIgnoreRoot(io, opts.rootAbs);
137
+ const ancestors: Layer[] = [];
138
+ for (let cur = opts.candidateAbs; ; cur = dirname(cur)) {
139
+ const layer = loadLayer(io, cur);
140
+ if (layer) ancestors.push(layer);
141
+ if (cur === outer) break;
142
+ const parent = dirname(cur);
143
+ if (parent === cur) break; // defensive: ignore root not an ancestor
144
+ }
145
+
146
+ const walk: Layer[] = [];
147
+ const files: string[] = [];
148
+ let excluded = 0;
149
+ const visit = (dirAbs: string): void => {
150
+ const layer = loadLayer(io, dirAbs);
151
+ if (layer) walk.push(layer);
152
+ for (const name of io.listDir(dirAbs).toSorted()) {
153
+ if (name === '.git') continue; // git never packs .git metadata (r120)
154
+ const abs = join(dirAbs, name);
155
+ const isDir = io.isDirectory(abs);
156
+ if (decide(user, walk, ancestors, abs, isDir)) {
157
+ excluded += isDir ? countFiles(io, abs) : 1;
158
+ continue;
159
+ }
160
+ if (isDir) visit(abs);
161
+ else files.push(relPosix(opts.candidateAbs, abs));
162
+ }
163
+ if (layer) walk.pop();
164
+ };
165
+ visit(opts.candidateAbs);
166
+ return { files, excluded };
167
+ }
@@ -82,10 +82,15 @@ function mount(mod: EmscriptenModule, seq: number, hostDir: string): string {
82
82
  return mountpoint;
83
83
  }
84
84
 
85
- /** 7z `l` listing: header/footer dashed rules around fixed-ish columns; our
86
- * entry names are space-free, so the name is column 6+. */
85
+ /** 7z `l` listing: header/footer dashed rules around fixed-ish columns.
86
+ * Column offsets come from the header row, NOT whitespace splitting — solid
87
+ * blocks leave the Compressed cell empty for every file after the block
88
+ * head, which collapses the column count and silently dropped those rows
89
+ * (surfaced by r120's explicit file lists; our entry names are space-free). */
87
90
  function parseListNames(lines: string[]): string[] {
88
91
  const names: string[] = [];
92
+ let nameCol = -1;
93
+ let attrCol = -1;
89
94
  let inTable = false;
90
95
  let rulesSeen = 0;
91
96
  for (const line of lines) {
@@ -95,14 +100,18 @@ function parseListNames(lines: string[]): string[] {
95
100
  if (rulesSeen === 3) break;
96
101
  continue;
97
102
  }
98
- if (inTable) {
99
- const parts = line.trim().split(/\s+/u);
100
- if (parts.length >= 6) {
101
- const attr = parts[2] ?? '';
102
- const name = parts.slice(5).join(' ');
103
- if (name !== '' && !attr.includes('D')) names.push(name);
103
+ if (!inTable) {
104
+ if (/\bDate\s+Time\s+Attr\b/u.test(line)) {
105
+ nameCol = line.lastIndexOf('Name');
106
+ attrCol = line.lastIndexOf('Attr');
104
107
  }
108
+ continue;
105
109
  }
110
+ if (nameCol < 0 || attrCol < 0 || line.trim() === '') continue;
111
+ // Attr cells are fixed-width 5 chars (e.g. `....A`, `D....`).
112
+ const attr = line.slice(attrCol, attrCol + 5);
113
+ const name = line.slice(nameCol).trim();
114
+ if (name !== '' && !attr.includes('D')) names.push(name);
106
115
  }
107
116
  return names;
108
117
  }
@@ -73,10 +73,10 @@ export function newChange(
73
73
  export interface StartResult {
74
74
  branch: string;
75
75
  baseBranch: string;
76
- /** Where the recorded base_branch came from (r95 deviation warning input). */
77
- baseSource: 'flag' | 'worktree' | 'default';
76
+ /** Where the recorded base_branch came from. */
77
+ baseSource: AttachBaseSource | 'worktree';
78
78
  baseSha: string;
79
- /** Absolute worktree path when started with --worktree (r68); undefined on the classic path. */
79
+ /** Absolute worktree path when started with --worktree; undefined when binding the current branch. */
80
80
  worktreePath?: string;
81
81
  }
82
82
 
@@ -177,13 +177,29 @@ export function startChange(
177
177
  worktreeNaming?: 'id' | 'hash';
178
178
  /** r119: instance dir relative to the git toplevel ('' at the repo root). */
179
179
  instanceDirRel?: string;
180
+ /** Rebind when the change is already attached to a branch. */
181
+ force?: boolean;
180
182
  } = {},
181
183
  ): StartResult {
182
184
  const path = proposalPath(id);
183
185
  if (!io.exists(path)) throw new LifecycleError(`proposal not found: ${path}`);
186
+ const here = currentBranch(git);
187
+ if (
188
+ !opts.worktree &&
189
+ here !== null &&
190
+ here !== '' &&
191
+ here !== defaultBranch(git) &&
192
+ !opts.force
193
+ ) {
194
+ const existing = readBinding(io.readText(path));
195
+ if (existing !== null) {
196
+ throw new LifecycleError(
197
+ `change \`${id}\` already attached to branch \`${existing.branch}\` (base ${existing.baseSha}); pass --force to rebind`,
198
+ );
199
+ }
200
+ }
184
201
  const dirty = dirtyCount(git);
185
202
  if (dirty > 0) throw new LifecycleError(dirtyTree('change start'));
186
- const here = currentBranch(git);
187
203
  if (here === null) throw new LifecycleError(detachedHead('change start'));
188
204
  const branchPrefix = opts.branchPrefix ?? 'sdd/';
189
205
  const branch = `${branchPrefix}${id}`;
@@ -192,9 +208,20 @@ export function startChange(
192
208
  assertLocalBase(git, opts.base, branch, 'new');
193
209
  }
194
210
 
211
+ // A non-default checkout binds the current branch. The default branch
212
+ // still creates sdd/<id>. --worktree always creates a branch elsewhere.
213
+ if (!opts.worktree && here !== defaultBranch(git)) {
214
+ const bound = attachChange(git, io, id, { force: opts.force, base: opts.base });
215
+ return {
216
+ branch: bound.branch,
217
+ baseBranch: bound.baseBranch,
218
+ baseSource: bound.baseSource,
219
+ baseSha: bound.baseSha,
220
+ };
221
+ }
222
+
195
223
  // r68 fork-source resolution: --base explicit > current branch (worktree
196
- // mode records the actual source, which may be a non-default branch) >
197
- // default branch. The classic path keeps the r14 default-branch gate.
224
+ // mode records the actual source) > default branch.
198
225
  let baseBranch: string;
199
226
  let baseSource: StartResult['baseSource'];
200
227
  if (opts.base !== undefined) {
@@ -206,11 +233,6 @@ export function startChange(
206
233
  } else {
207
234
  baseBranch = defaultBranch(git);
208
235
  baseSource = 'default';
209
- if (here !== baseBranch) {
210
- throw new LifecycleError(
211
- `already on non-default branch \`${here}\`; use \`change attach\` to bind it, or switch to the default branch before \`change start\``,
212
- );
213
- }
214
236
  }
215
237
 
216
238
  let worktreePath: string | undefined;
@@ -269,7 +291,7 @@ export function attachChange(
269
291
  }
270
292
  const branch = currentBranch(git);
271
293
  if (branch === null || branch === '') {
272
- throw new LifecycleError(detachedHead('change attach'));
294
+ throw new LifecycleError(detachedHead('change start'));
273
295
  }
274
296
  if (opts.base !== undefined) {
275
297
  assertLocalBase(git, opts.base, branch, 'bound');
@@ -286,7 +308,7 @@ export function attachChange(
286
308
  });
287
309
  if (branch === fork.branch) {
288
310
  throw new LifecycleError(
289
- `${onDefaultBranch('change attach', branch)}; create or switch to a feature branch, or use \`change start\``,
311
+ `${onDefaultBranch('change start', branch)}; create or switch to a feature branch before binding the current checkout`,
290
312
  );
291
313
  }
292
314
  const baseSha = mergeBase(git, branch, fork.branch);
@@ -388,7 +410,7 @@ export function finalizeChange(
388
410
  const path = proposalPath(id);
389
411
  const binding = readBinding(io.readText(path));
390
412
  if (binding === null) {
391
- throw new LifecycleError(`change \`${id}\` has no branch binding — run start/attach first`);
413
+ throw new LifecycleError(`change \`${id}\` has no branch binding — run \`change start\` first`);
392
414
  }
393
415
  // T34 close-out gate before any write: specs-landed verdict + task gate.
394
416
  const closeOut = closeOutGate({ git, io, id, binding, specsPrefix: opts.specsPrefix });
@@ -416,7 +438,7 @@ export function finalizeChange(
416
438
  // fail before any write (no switch, no merge, no rename).
417
439
  const current = currentBranch(git);
418
440
  if (current !== binding.branch) {
419
- throw new LifecycleError(notOnBoundBranch('change finalize', binding.branch, current));
441
+ throw new LifecycleError(notOnBoundBranch('change archive', binding.branch, current));
420
442
  }
421
443
  const method = opts.method ?? 'squash';
422
444
  const target = opts.into ?? binding.baseBranch ?? defaultBranch(git);
@@ -540,7 +562,7 @@ function mergeRenameCommit(
540
562
  return { target, archiveDir, warnings, commitSubject, executedIn };
541
563
  }
542
564
 
543
- /** `change archive`: independent seal-off with task + strict git gates (r39/r40). */
565
+ /** `change archive`: task gates, clean tree, merge, rename, optional close-out commit. */
544
566
  export function archiveChange(
545
567
  git: GitLike,
546
568
  io: FsIo,
@@ -548,68 +570,42 @@ export function archiveChange(
548
570
  opts: {
549
571
  into?: string;
550
572
  method?: 'squash' | 'ff';
551
- force?: boolean;
552
573
  /** CLI already enforced a clean tree before the acceptance command ran. */
553
574
  skipCleanTree?: boolean;
554
575
  today: string;
576
+ noCommit?: boolean;
555
577
  /** r119: instance-relative specs prefix of the change's own root. */
556
578
  specsPrefix?: string;
557
579
  },
558
580
  ): FinalizeResult {
559
581
  const path = proposalPath(id);
560
582
  const binding = readBinding(io.readText(path));
561
- if (!opts.force && binding === null) {
562
- throw new LifecycleError(`change \`${id}\` has no branch binding — run start/attach first`);
583
+ if (binding === null) {
584
+ throw new LifecycleError(`change \`${id}\` has no branch binding — run \`change start\` first`);
563
585
  }
564
- if (!opts.force) {
565
- // T34: shared close-out verdict before any write (archive honors --force).
566
- const closeOut = closeOutGate({ git, io, id, binding, specsPrefix: opts.specsPrefix });
567
- if (!closeOut.ok) throw new LifecycleError(closeOut.reason as string);
568
- const tasksPath = `${CHANGES_DIR}/${id}/tasks.md`;
569
- const gate = archiveTaskGate(io.exists(tasksPath) ? io.readText(tasksPath) : null);
570
- if (gate.blocked) {
571
- // D9: when a pending unchecked task starts with a close-out verb, append
572
- // the same remediation hint as the validate WARNING (single constant).
573
- const closeOut = closeOutTaskLines(gate.pendingLines);
574
- throw new LifecycleError(
575
- [
576
- `archive blocked by unchecked tasks (${gate.pendingLines.length} pending)`,
577
- ...gate.pendingLines,
578
- ...(closeOut.length > 0
579
- ? [
580
- `task "${closeOut[0]?.replace(/^-\s+\[ \]\s*/u, '').trim() ?? ''}" looks like a close-out step; ${CLOSE_OUT_TASK_HINT}`,
581
- ]
582
- : []),
583
- ].join('\n'),
584
- );
585
- }
586
- const current = currentBranch(git);
587
- if (current === null || current === '')
588
- throw new LifecycleError(detachedHead('change archive'));
589
- if (current !== binding?.branch) {
590
- throw new LifecycleError(
591
- notOnBoundBranch('change archive', (binding?.branch ?? '') as string, current),
592
- );
593
- }
594
- if (current === defaultBranch(git)) {
595
- throw new LifecycleError(onDefaultBranch('change archive', current));
596
- }
597
- if (!opts.skipCleanTree && !isCleanTree(git))
598
- throw new LifecycleError(dirtyTree('change archive'));
599
- } else if (binding === null) {
600
- throw new LifecycleError(`change \`${id}\` has no branch binding — cannot merge`);
586
+ const closeOut = closeOutGate({ git, io, id, binding, specsPrefix: opts.specsPrefix });
587
+ if (!closeOut.ok) throw new LifecycleError(closeOut.reason as string);
588
+ const current = currentBranch(git);
589
+ if (current === null || current === '') throw new LifecycleError(detachedHead('change archive'));
590
+ if (current !== binding.branch) {
591
+ throw new LifecycleError(notOnBoundBranch('change archive', binding.branch, current));
601
592
  }
593
+ if (current === defaultBranch(git)) {
594
+ throw new LifecycleError(onDefaultBranch('change archive', current));
595
+ }
596
+ if (!opts.skipCleanTree && !isCleanTree(git))
597
+ throw new LifecycleError(dirtyTree('change archive'));
602
598
  const method = opts.method ?? 'squash';
603
- const target = opts.into ?? binding?.baseBranch ?? defaultBranch(git);
599
+ const target = opts.into ?? binding.baseBranch ?? defaultBranch(git);
604
600
  return mergeRenameCommit(
605
601
  git,
606
602
  io,
607
603
  id,
608
- binding?.branch as string,
604
+ binding.branch,
609
605
  target,
610
606
  method,
611
607
  opts.today,
612
- undefined,
608
+ opts.noCommit,
613
609
  instanceDirRelOf(opts.specsPrefix ?? DEFAULT_SPECS_PREFIX),
614
610
  );
615
611
  }