@friedbotstudio/create-baseline 0.5.0 → 0.6.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.
@@ -1,9 +1,12 @@
1
- // Domain — branded upgrade flow with interactive per-file conflict resolution.
1
+ // Domain — branded upgrade flow with three-tier merge orchestration.
2
2
  // Plan/apply split:
3
- // 1. dry-run threeWayMerge enumerate SKIP_CUSTOMIZED conflicts
4
- // 2. prompt the user once per conflict
5
- // 3. on cancel/abort: bail before any write
6
- // 4. on resolve: real threeWayMerge with onSkipCustomized backed by the Map
3
+ // 1. detect pending semantic-merge stage (idempotency short-circuit, AC-007)
4
+ // 2. dry-run threeWayMerge enumerate SKIP_CUSTOMIZED conflicts (tier-1 only)
5
+ // 3. prompt the user once per tier-1 conflict (with Show-diff loop, cap-at-2)
6
+ // 4. on cancel/abort: bail before any write
7
+ // 5. on resolve: real threeWayMerge with onSkipCustomized backed by the Map.
8
+ // Tier-2 MECHANICAL and tier-3 SEMANTIC files are NOT prompted — they're
9
+ // dispatched by the merge engine via upgrade-tiers.dispatchByTier.
7
10
 
8
11
  import * as clackModule from '@clack/prompts';
9
12
  import { existsSync } from 'node:fs';
@@ -12,19 +15,26 @@ import { join, relative, sep } from 'node:path';
12
15
  import { threeWayMerge, ACTION_KINDS } from '../merge.js';
13
16
  import { loadManifest, buildManifestFromDir } from '../manifest.js';
14
17
  import { COPY_EXCLUDE } from '../install.js';
18
+ import { findPendingStage } from '../upgrade-tiers.js';
19
+ import { renderUnifiedDiff } from '../diff-render.js';
15
20
  import { renderBrandStrip } from './splash.js';
16
21
 
17
22
  const SUCCESS = 0;
18
23
  const ERR_ABORT = 1;
19
24
  const ERR_NO_MANIFEST = 2;
20
25
  const ERR_DIVERGENCE = 3;
26
+ const ERR_MECHANICAL_CONFLICTED = 4;
27
+ const ERR_SEMANTIC_STAGED = 5;
21
28
 
22
29
  const CHOICE_OPTIONS = [
23
- { value: 'keep-mine', label: 'Keep mine', hint: 'preserve target file as-is' },
24
- { value: 'take-theirs', label: 'Take theirs', hint: 'overwrite with new baseline' },
30
+ { value: 'keep-mine', label: 'Keep your version', hint: 'preserve target file as-is' },
31
+ { value: 'take-theirs', label: 'Use new baseline', hint: 'overwrite with new template' },
32
+ { value: 'show-diff', label: 'Show diff', hint: 'render local vs incoming and re-prompt' },
25
33
  { value: 'abort', label: 'Abort', hint: 'exit without changes' },
26
34
  ];
27
35
 
36
+ const SHOW_DIFF_CONSECUTIVE_CAP = 2;
37
+
28
38
  export async function run({ target, opts = {}, prompts = clackModule } = {}) {
29
39
  if (!target || typeof target !== 'string') {
30
40
  throw new Error('tui.upgrade.run requires a non-empty string target');
@@ -43,26 +53,27 @@ export async function run({ target, opts = {}, prompts = clackModule } = {}) {
43
53
  process.stdout.write(renderBrandStrip({ version, subtitle: 'upgrade' }));
44
54
  prompts.intro('create-baseline upgrade');
45
55
 
56
+ const pending = await findPendingStage(target);
57
+ if (pending) return reportPendingStage(prompts, pending);
58
+
46
59
  const { oldManifest, newManifest } = await loadManifests(opts.templateDir, manifestPath);
60
+ if (isLegacyManifest(oldManifest)) {
61
+ prompts.log.warn('legacy manifest_version: 1 detected; BASE-content recovery unavailable. Tier-2 / tier-3 files will fall back to the binary prompt.');
62
+ }
63
+
47
64
  const dryReport = await threeWayMerge(opts.templateDir, target, oldManifest, newManifest, { dryRun: true });
48
65
  const conflicts = dryReport.actions.filter((a) => a.kind === ACTION_KINDS.SKIP_CUSTOMIZED);
49
66
 
50
67
  const choices = new Map();
51
- for (const conflict of conflicts) {
52
- const choice = await prompts.select({
53
- message: `${conflict.path} has been customized — choose:`,
54
- options: CHOICE_OPTIONS,
55
- });
56
- if (prompts.isCancel(choice) || choice === 'abort') {
57
- prompts.cancel('Upgrade aborted; tree unchanged.');
58
- return ERR_ABORT;
59
- }
60
- choices.set(conflict.path, choice);
68
+ const aborted = await collectUserChoices(prompts, conflicts, opts.templateDir, target, choices);
69
+ if (aborted) {
70
+ prompts.cancel('Upgrade aborted; tree unchanged.');
71
+ return ERR_ABORT;
61
72
  }
62
73
 
63
74
  if (opts.dryRun) {
64
75
  for (const action of dryReport.actions) {
65
- prompts.log.info(`${action.kind.padEnd(24)} ${action.path}`);
76
+ prompts.log.info(`${action.kind.padEnd(28)} ${action.path}`);
66
77
  }
67
78
  prompts.outro('Dry run complete; no changes written.');
68
79
  return SUCCESS;
@@ -71,10 +82,79 @@ export async function run({ target, opts = {}, prompts = clackModule } = {}) {
71
82
  const onSkipCustomized = (rel) => choices.get(rel) ?? 'keep-mine';
72
83
  const finalReport = await threeWayMerge(opts.templateDir, target, oldManifest, newManifest, { onSkipCustomized });
73
84
 
85
+ for (const action of finalReport.actions) {
86
+ if (isReportableAction(action.kind)) {
87
+ prompts.log.info(`${action.kind.padEnd(28)} ${action.path}`);
88
+ }
89
+ if (action.kind === ACTION_KINDS.MECHANICAL_MERGE_CONFLICTED) {
90
+ prompts.log.warn(`Merged with conflicts — resolve in ${action.path}`);
91
+ }
92
+ }
93
+
94
+ const stagedCount = finalReport.actions.filter((a) => a.kind === ACTION_KINDS.SEMANTIC_MERGE_STAGED).length;
95
+ if (stagedCount > 0) {
96
+ prompts.log.info(`${stagedCount} file(s) need semantic merge. Open Claude Code and run /upgrade-project to reconcile.`);
97
+ }
98
+
74
99
  const applied = finalReport.actions.filter((a) => isApplied(a.kind)).length;
75
100
  const skipped = finalReport.actions.filter((a) => a.kind === ACTION_KINDS.SKIP_CUSTOMIZED).length;
76
101
  prompts.outro(`Applied ${applied}; ${skipped} skipped.`);
77
- return finalReport.exitCode === 3 ? ERR_DIVERGENCE : SUCCESS;
102
+ return mapExitCode(finalReport.exitCode);
103
+ }
104
+
105
+ function reportPendingStage(prompts, pending) {
106
+ const fileLines = pending.files.map((f) => ` - ${f}`).join('\n');
107
+ prompts.log.warn(`Pending semantic-merge stage at ${pending.stage_ts}.\n${pending.files.length} file(s) awaiting reconciliation:\n${fileLines}\nOpen Claude Code and run /upgrade-project to reconcile.`);
108
+ prompts.outro('No new work; existing stage pending.');
109
+ return ERR_SEMANTIC_STAGED;
110
+ }
111
+
112
+ function isLegacyManifest(m) {
113
+ if (!m) return false;
114
+ if (m.manifest_version === 1) return true;
115
+ return typeof m.baseline_version !== 'string';
116
+ }
117
+
118
+ async function collectUserChoices(prompts, conflicts, templateDir, target, choices) {
119
+ for (const conflict of conflicts) {
120
+ const choice = await pickForFile(prompts, conflict.path, templateDir, target);
121
+ if (choice === 'abort') return true;
122
+ if (choice !== null) choices.set(conflict.path, choice);
123
+ }
124
+ return false;
125
+ }
126
+
127
+ async function pickForFile(prompts, rel, templateDir, target) {
128
+ let consecutiveShowDiff = 0;
129
+ while (true) {
130
+ const choice = await prompts.select({
131
+ message: `${rel} has been customized — choose:`,
132
+ options: CHOICE_OPTIONS,
133
+ });
134
+ if (prompts.isCancel(choice)) return 'abort';
135
+ if (choice !== 'show-diff') return choice;
136
+ await renderConflictDiff(prompts, rel, templateDir, target);
137
+ consecutiveShowDiff++;
138
+ if (consecutiveShowDiff >= SHOW_DIFF_CONSECUTIVE_CAP) {
139
+ prompts.log.info(`Show-diff picked ${SHOW_DIFF_CONSECUTIVE_CAP} times for ${rel}; falling through (keeping your version). Re-run if you want to choose differently.`);
140
+ return null;
141
+ }
142
+ }
143
+ }
144
+
145
+ async function renderConflictDiff(prompts, rel, templateDir, target) {
146
+ const localBytes = await readFile(join(target, rel), 'utf8');
147
+ const incomingBytes = await readFile(join(templateDir, rel), 'utf8');
148
+ const diff = renderUnifiedDiff(localBytes, incomingBytes, { colorize: process.stdout.isTTY === true });
149
+ prompts.log.info(`Diff for ${rel} (local → incoming):\n${diff}`);
150
+ }
151
+
152
+ function isReportableAction(kind) {
153
+ return (
154
+ kind === ACTION_KINDS.MECHANICAL_MERGE_CLEAN ||
155
+ kind === ACTION_KINDS.MECHANICAL_MERGE_CONFLICTED ||
156
+ kind === ACTION_KINDS.SEMANTIC_MERGE_STAGED
157
+ );
78
158
  }
79
159
 
80
160
  function isApplied(kind) {
@@ -83,17 +163,39 @@ function isApplied(kind) {
83
163
  kind === ACTION_KINDS.OVERWRITE ||
84
164
  kind === ACTION_KINDS.PRUNE ||
85
165
  kind === ACTION_KINDS.SPECIAL_MERGE ||
86
- kind === ACTION_KINDS.NEVER_TOUCH_ADD
166
+ kind === ACTION_KINDS.NEVER_TOUCH_ADD ||
167
+ kind === ACTION_KINDS.MECHANICAL_MERGE_CLEAN
87
168
  );
88
169
  }
89
170
 
171
+ function mapExitCode(mergeExit) {
172
+ if (mergeExit === 5) return ERR_SEMANTIC_STAGED;
173
+ if (mergeExit === 4) return ERR_MECHANICAL_CONFLICTED;
174
+ if (mergeExit === 3) return ERR_DIVERGENCE;
175
+ return SUCCESS;
176
+ }
177
+
90
178
  async function loadManifests(templateDir, manifestPath) {
91
179
  const oldManifest = await loadManifest(manifestPath);
92
180
  const tplFiles = await listShippedFiles(templateDir);
93
181
  const newManifest = await buildManifestFromDir(templateDir, tplFiles);
182
+ await overlayShippedTiers(templateDir, newManifest);
94
183
  return { oldManifest, newManifest };
95
184
  }
96
185
 
186
+ async function overlayShippedTiers(templateDir, newManifest) {
187
+ const shippedPath = join(templateDir, '.claude/manifest.json');
188
+ if (!existsSync(shippedPath)) return;
189
+ const shipped = JSON.parse(await readFile(shippedPath, 'utf8'));
190
+ if (!shipped?.files) return;
191
+ for (const rel of Object.keys(newManifest.files)) {
192
+ const shippedEntry = shipped.files[rel];
193
+ if (shippedEntry && typeof shippedEntry === 'object' && typeof shippedEntry.tier === 'string') {
194
+ newManifest.files[rel] = { sha256: newManifest.files[rel], tier: shippedEntry.tier };
195
+ }
196
+ }
197
+ }
198
+
97
199
  async function readPackageVersion() {
98
200
  try {
99
201
  const url = new URL('../../../package.json', import.meta.url);
@@ -110,10 +212,5 @@ async function listShippedFiles(root, base = root, acc = []) {
110
212
  if (entry.isDirectory()) await listShippedFiles(full, base, acc);
111
213
  else if (entry.isFile()) acc.push(relative(base, full).split(sep).join('/'));
112
214
  }
113
- // COPY_EXCLUDE (single source of truth in install.js) now lists no paths —
114
- // the shipped manifest moved into `.claude/manifest.json` so the recursive
115
- // walk picks it up at the same path the consumer expects. The filter stays
116
- // for forward-compat; if a future path needs to be kept out of the merge,
117
- // add it to install.js → COPY_EXCLUDE in one place.
118
215
  return acc.filter((p) => !COPY_EXCLUDE.includes(p));
119
216
  }
@@ -0,0 +1,234 @@
1
+ // Domain — tier dispatch + BASE-content recovery + semantic-merge staging.
2
+ // Consumed by src/cli/merge.js's customized-file branch. See
3
+ // docs/specs/upgrade-flow-rework.md §Behavior #2/#3/#4/#5/#6.
4
+
5
+ import { mkdir, mkdtemp, readFile, readdir, unlink, writeFile } from 'node:fs/promises';
6
+ import { existsSync } from 'node:fs';
7
+ import { dirname, join, resolve, sep } from 'node:path';
8
+ import { tmpdir } from 'node:os';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { createHash, randomUUID } from 'node:crypto';
11
+
12
+ export class NoBaseError extends Error {
13
+ constructor(message, opts = {}) {
14
+ super(message);
15
+ this.name = 'NoBaseError';
16
+ this.kind = opts.kind ?? 'unknown';
17
+ this.rel = opts.rel ?? null;
18
+ if (opts.cause) this.cause = opts.cause;
19
+ }
20
+ }
21
+
22
+ export async function resolveBase(rel, baseline_version, target, opts = {}) {
23
+ const { oldManifest = null, pack = null } = opts;
24
+ const expectedSha = readExpectedSha(oldManifest, rel);
25
+ const cached = await readCacheIfPresent(target, rel);
26
+ if (cached) {
27
+ if (expectedSha && sha256(cached) === expectedSha) return cached;
28
+ if (expectedSha) {
29
+ throw new NoBaseError(`cache sha mismatch for ${rel}`, { kind: 'cache_sha_mismatch', rel });
30
+ }
31
+ return cached;
32
+ }
33
+ if (!baseline_version) {
34
+ throw new NoBaseError(`legacy manifest; cannot recover BASE for ${rel}`, { kind: 'legacy_manifest', rel });
35
+ }
36
+ const fetched = await fetchFromNpm(rel, baseline_version, pack);
37
+ if (expectedSha && sha256(fetched) !== expectedSha) {
38
+ throw new NoBaseError(`npm tarball sha mismatch for ${rel}`, { kind: 'npm_sha_mismatch', rel });
39
+ }
40
+ await writeCacheThrough(target, rel, fetched);
41
+ return fetched;
42
+ }
43
+
44
+ export async function findPendingStage(target) {
45
+ const stageRoot = join(target, '.claude/state/upgrade');
46
+ if (!existsSync(stageRoot)) return null;
47
+ const stages = await listSubdirs(stageRoot);
48
+ for (const ts of stages) {
49
+ const manifestPath = join(stageRoot, ts, 'manifest.json');
50
+ if (!existsSync(manifestPath)) continue;
51
+ const pending = await readPendingFiles(manifestPath);
52
+ if (pending.length > 0) return { stage_ts: ts, files: pending };
53
+ }
54
+ return null;
55
+ }
56
+
57
+ export async function dispatchByTier(rel, tier, ctx) {
58
+ if (tier === 'BINARY_PROMPT') {
59
+ return { kind: 'SKIP_CUSTOMIZED', path: rel, reason: 'tier BINARY_PROMPT: user prompt deferred' };
60
+ }
61
+ if (tier === 'MECHANICAL') return runMechanicalMerge(rel, ctx);
62
+ if (tier === 'SEMANTIC') return runSemanticStage(rel, ctx);
63
+ throw new Error(`unknown tier: ${tier}`);
64
+ }
65
+
66
+ export async function writeStage(ctx, rel, baseBuf, incomingBuf, localBuf) {
67
+ if (!ctx.stageRunTs) ctx.stageRunTs = stageTimestamp();
68
+ const stageDir = join(ctx.target, '.claude/state/upgrade', ctx.stageRunTs);
69
+ await mkdir(stageDir, { recursive: true });
70
+ await writeStageArtifact(stageDir, `${rel}.baseline-base`, baseBuf);
71
+ await writeStageArtifact(stageDir, `${rel}.baseline-incoming`, incomingBuf);
72
+ await appendToStageManifest(stageDir, ctx, rel, baseBuf, incomingBuf, localBuf);
73
+ }
74
+
75
+ // --- foundation helpers ---
76
+
77
+ function sha256(buf) {
78
+ return createHash('sha256').update(buf).digest('hex');
79
+ }
80
+
81
+ function readExpectedSha(oldManifest, rel) {
82
+ const entry = oldManifest?.files?.[rel];
83
+ if (typeof entry === 'string') return entry;
84
+ if (entry && typeof entry === 'object' && typeof entry.sha256 === 'string') return entry.sha256;
85
+ return null;
86
+ }
87
+
88
+ async function readCacheIfPresent(target, rel) {
89
+ const cachePath = join(target, '.claude/.baseline-prior', rel);
90
+ if (!existsSync(cachePath)) return null;
91
+ return await readFile(cachePath);
92
+ }
93
+
94
+ async function writeCacheThrough(target, rel, bytes) {
95
+ const cachePath = join(target, '.claude/.baseline-prior', rel);
96
+ await mkdir(dirname(cachePath), { recursive: true });
97
+ await writeFile(cachePath, bytes);
98
+ }
99
+
100
+ async function fetchFromNpm(rel, baseline_version, packOverride) {
101
+ const packFn = packOverride ?? defaultPack;
102
+ const spec = `@friedbotstudio/create-baseline@${baseline_version}`;
103
+ let result;
104
+ try {
105
+ result = await packFn(spec);
106
+ } catch (err) {
107
+ throw new NoBaseError(`npm fetch failed for ${rel}: ${err.message}`, {
108
+ kind: 'npm_fetch_failed', rel, cause: err,
109
+ });
110
+ }
111
+ const bytes = await extractFromPackResult(result, rel);
112
+ if (!bytes) {
113
+ throw new NoBaseError(`npm tarball missing ${rel}`, { kind: 'npm_missing_file', rel });
114
+ }
115
+ return bytes;
116
+ }
117
+
118
+ async function defaultPack(spec) {
119
+ const mod = await import('libnpmpack');
120
+ const fn = mod.default ?? mod.pack ?? mod;
121
+ return fn(spec);
122
+ }
123
+
124
+ async function extractFromPackResult(result, rel) {
125
+ if (result instanceof Map) return result.get(rel) ?? null;
126
+ if (Buffer.isBuffer(result) || result instanceof Uint8Array) {
127
+ return extractFromTarball(Buffer.from(result), rel);
128
+ }
129
+ throw new Error(`unsupported pack result type: ${typeof result}`);
130
+ }
131
+
132
+ async function extractFromTarball(tarballBytes, rel) {
133
+ const tmp = await mkdtemp(join(tmpdir(), 'baseline-prior-extract-'));
134
+ const tmpRoot = resolve(tmp) + sep;
135
+ const result = spawnSync('tar', ['-xz', '-C', tmp, '-f', '-'], { input: tarballBytes });
136
+ if (result.status !== 0) {
137
+ throw new Error(`tar extract failed: ${(result.stderr || '').toString()}`);
138
+ }
139
+ const candidate = join(tmp, 'package', rel);
140
+ // Defense in depth: although bsdtar (macOS default) and GNU tar both refuse
141
+ // absolute paths and `..` components by default when extracting, validate
142
+ // the candidate resolves under tmp before reading. Refuses to follow a
143
+ // malicious tarball that somehow planted bytes outside the extraction root.
144
+ const resolved = resolve(candidate);
145
+ if (!resolved.startsWith(tmpRoot)) {
146
+ throw new NoBaseError(`tarball entry escapes extraction root: ${rel}`, { kind: 'tarball_path_traversal', rel });
147
+ }
148
+ if (!existsSync(resolved)) return null;
149
+ return await readFile(resolved);
150
+ }
151
+
152
+ async function listSubdirs(root) {
153
+ const entries = await readdir(root, { withFileTypes: true });
154
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
155
+ }
156
+
157
+ async function readPendingFiles(manifestPath) {
158
+ try {
159
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
160
+ return (manifest.files || []).filter((f) => f.status === 'PENDING').map((f) => f.rel);
161
+ } catch {
162
+ return [];
163
+ }
164
+ }
165
+
166
+ // --- domain helpers ---
167
+
168
+ async function runMechanicalMerge(rel, ctx) {
169
+ const base = await resolveBase(rel, ctx.baseline_version, ctx.target, {
170
+ oldManifest: ctx.oldManifest, pack: ctx.pack,
171
+ });
172
+ const remote = await readFile(join(ctx.templateDir, rel));
173
+ const localPath = join(ctx.target, rel);
174
+ const tmpBase = join(tmpdir(), `merge-base-${randomUUID()}`);
175
+ const tmpRemote = join(tmpdir(), `merge-remote-${randomUUID()}`);
176
+ await writeFile(tmpBase, base);
177
+ await writeFile(tmpRemote, remote);
178
+ const result = spawnSync('git', ['merge-file', '--diff3', localPath, tmpBase, tmpRemote], { encoding: 'utf8' });
179
+ await unlink(tmpBase).catch(() => {});
180
+ await unlink(tmpRemote).catch(() => {});
181
+ if (result.status === 0) {
182
+ return { kind: 'MECHANICAL_MERGE_CLEAN', path: rel, reason: 'git merge-file clean' };
183
+ }
184
+ if (typeof result.status === 'number' && result.status > 0 && result.status < 128) {
185
+ return { kind: 'MECHANICAL_MERGE_CONFLICTED', path: rel, hunks: result.status, reason: `${result.status} conflict hunk(s)` };
186
+ }
187
+ throw new Error(`git merge-file failed for ${rel}: status=${result.status} stderr=${(result.stderr || '').toString()}`);
188
+ }
189
+
190
+ async function runSemanticStage(rel, ctx) {
191
+ const base = await resolveBase(rel, ctx.baseline_version, ctx.target, {
192
+ oldManifest: ctx.oldManifest, pack: ctx.pack,
193
+ });
194
+ const remote = await readFile(join(ctx.templateDir, rel));
195
+ const local = await readFile(join(ctx.target, rel));
196
+ await writeStage(ctx, rel, base, remote, local);
197
+ return { kind: 'SEMANTIC_MERGE_STAGED', path: rel, reason: 'staged for /upgrade-project' };
198
+ }
199
+
200
+ async function writeStageArtifact(stageDir, rel, bytes) {
201
+ const dst = join(stageDir, rel);
202
+ await mkdir(dirname(dst), { recursive: true });
203
+ await writeFile(dst, bytes);
204
+ }
205
+
206
+ async function appendToStageManifest(stageDir, ctx, rel, baseBuf, incomingBuf, localBuf) {
207
+ const manifestPath = join(stageDir, 'manifest.json');
208
+ const manifest = existsSync(manifestPath)
209
+ ? JSON.parse(await readFile(manifestPath, 'utf8'))
210
+ : newStageManifest(ctx);
211
+ manifest.files.push({
212
+ rel,
213
+ base_sha256: sha256(baseBuf),
214
+ incoming_sha256: sha256(incomingBuf),
215
+ local_sha256: sha256(localBuf),
216
+ status: 'PENDING',
217
+ });
218
+ await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
219
+ }
220
+
221
+ function newStageManifest(ctx) {
222
+ return {
223
+ stage_version: 1,
224
+ slug: ctx.slug ?? 'upgrade',
225
+ created_at: new Date().toISOString(),
226
+ baseline_version_from: ctx.oldManifest?.baseline_version ?? 'unknown',
227
+ baseline_version_to: ctx.baseline_version ?? 'unknown',
228
+ files: [],
229
+ };
230
+ }
231
+
232
+ function stageTimestamp() {
233
+ return new Date().toISOString().replace(/[:.]/g, '-');
234
+ }
@@ -11,7 +11,7 @@
11
11
 
12
12
  **Mandatory binding language.** Each numbered section (§) below specifies a binding requirement for the baseline. Implementations SHALL conform; `CLAUDE.md` Articles SHALL reference the corresponding §; project amendments (per `CLAUDE.md` Art. X) SHALL NOT contradict any § here.
13
13
 
14
- The baseline turns soft engineering rules (no unauthorized commits, no stubs, no mocks of internal code, no self-approved specs) into structural guarantees enforced by write-boundary hooks. Eleven workflow phases plus one stripped-down chore track (skips TDD; runs verify + archive mandatorily, simplify/integrate/document conditionally), seventeen write/run-boundary guards plus four lifecycle hooks plus one input-boundary hook (twenty-two hook scripts total — twenty `.sh` + two `.mjs` after the JS-port pilot), thirty-seven skills, one subagent, and four consent gates. Decisions live in main context; the lone subagent (`swarm-worker`) executes pre-decided recipes in parallel worktrees during `/swarm-dispatch`. Every artifact is archived; every third-party API is looked up against live docs. Project memory accumulates across sessions in `.claude/memory/` — auto-extracted by a Stop hook, curated in main context via `/memory-flush`, self-healing via re-verification.
14
+ The baseline turns soft engineering rules (no unauthorized commits, no stubs, no mocks of internal code, no self-approved specs) into structural guarantees enforced by write-boundary hooks. Eleven workflow phases plus one stripped-down chore track (skips TDD; runs verify + archive mandatorily, simplify/integrate/document conditionally), seventeen write/run-boundary guards plus four lifecycle hooks plus one input-boundary hook (twenty-two hook scripts total — twenty `.sh` + two `.mjs` after the JS-port pilot), thirty-eight skills, one subagent, and four consent gates. Decisions live in main context; the lone subagent (`swarm-worker`) executes pre-decided recipes in parallel worktrees during `/swarm-dispatch`. Every artifact is archived; every third-party API is looked up against live docs. Project memory accumulates across sessions in `.claude/memory/` — auto-extracted by a Stop hook, curated in main context via `/memory-flush`, self-healing via re-verification.
15
15
 
16
16
  ---
17
17
 
@@ -110,7 +110,7 @@ Applies to every language. Mappings for TSX, Node, Python, Go, Rust ship inside
110
110
  │ │ └── lib/common.sh # shared helpers
111
111
  │ ├── agents/ # 1 subagent: swarm-worker (rendered from src/agents/swarm-worker.template.md)
112
112
  │ ├── commands/ # 5 consent/bootstrap gates (user-only — structurally)
113
- │ ├── skills/ # 37 skills: artifact (4) + phases (11) + workers (5) + spec helpers (4) + orchestration (3) + memory (1) + shared globals (7) + audit (1) + alt tracks (1)
113
+ │ ├── skills/ # 38 skills: artifact (4) + phases (11) + workers (5) + spec helpers (4) + orchestration (3) + memory (1) + shared globals (7) + audit (1) + alt tracks (1) + maintenance (1)
114
114
  │ ├── memory/ # project memory: 7 canonical files + _pending.md (gitignored body) + README.md
115
115
  │ └── state/ # runtime: workflow.json, approvals, swarm plans, verdicts, logs
116
116
  ├── src/ # pristine ship-time templates (overlay source for `npx @friedbotstudio/create-baseline`)
@@ -181,7 +181,7 @@ The baseline ships exactly one subagent. The architectural reason: subagents los
181
181
 
182
182
  **Automated re-rendering by `/init-project`.** Step 6.4 re-renders `swarm-worker.md` from the template, driven by the recommender's `additions.swarm_worker_skills`. The recommender does **not** propose new subagent types — only stack-skill additions for the existing worker. Specialization happens via skills loaded into the worker's context, not via parallel agent personas; new decision-making roles belong in skills, which run in main context.
183
183
 
184
- ### §4.3 Skills (37)
184
+ ### §4.3 Skills (38)
185
185
 
186
186
  Each at `.claude/skills/<name>/SKILL.md`, frontmatter `name` + `description`, plus optional `template.md` (artifact skills) or helper scripts.
187
187
 
@@ -516,7 +516,7 @@ Seed-level requirement: no stale workflow artifacts in the working tree after co
516
516
 
517
517
  **Step 4:** Write `src/agents/swarm-worker.template.md` (canonical-body store, per §4.2) — the only subagent template. Then render `.claude/agents/swarm-worker.md` from it with default tokens. The template carries four tokens — `{{NAME}}`, `{{DESCRIPTION}}`, `{{SKILLS}}`, `{{ROLE_LINE}}`. Default `SKILLS` is the YAML list block ` - scenario\n - implement` (the worker's two mandatory sub-skills). Render-parity holds at this stage. `/init-project` later re-renders the worker with stack-aware tokens when the recommender flags stack-specific skills to preload via `additions.swarm_worker_skills`.
518
518
 
519
- **Step 5:** Write `.claude/skills/` for the 37 skills (§4.3) — 29 workflow/worker/orchestration/memory/alt-track skills you author (the +1 over 28 is the `changelog` Phase 11.5 skill) plus 7 shared globals plus 1 audit skill. The breakdown: artifact drafting (4) + workflow phases (10) + phase workers (5: `scenario`, `implement`, `verify`, `prose`, `design-ui`) + spec helpers (4: `spec-lint`, `spec-render`, `spec-diagram-review`, `spec-traceability-review`) + orchestration (3: `harness`, `swarm-plan`, `swarm-dispatch`) + memory (1: `memory-flush`) + shared globals (7: `claude-automation-recommender`, `code-structure`, `humanizer`, `documentation`, `technical-tutorials`, `copywriting`, `impeccable`) + drift defender (1: `audit-baseline`) + alternate tracks (1: `chore`). The vendored `claude-automation-recommender` (Apache 2.0, from `claude-code-setup`), the writing/quality globals, and the design global ship unchanged with their licenses intact. Artifact skills (intake, brd, spec, rca) each ship a `template.md`. Helper scripts: swarm-plan gets `validate.sh`, swarm-dispatch gets `swarm_merge.sh`, spec-render gets `render.sh`, spec-lint gets `lint.sh`, archive gets `archive.sh`, audit-baseline gets `audit.sh`. All helper scripts `chmod +x`.
519
+ **Step 5:** Write `.claude/skills/` for the 38 skills (§4.3) — 29 workflow/worker/orchestration/memory/alt-track skills you author (the +1 over 28 is the `changelog` Phase 11.5 skill) plus 7 shared globals plus 1 audit skill plus 1 maintenance skill. The breakdown: artifact drafting (4) + workflow phases (10) + phase workers (5: `scenario`, `implement`, `verify`, `prose`, `design-ui`) + spec helpers (4: `spec-lint`, `spec-render`, `spec-diagram-review`, `spec-traceability-review`) + orchestration (3: `harness`, `swarm-plan`, `swarm-dispatch`) + memory (1: `memory-flush`) + shared globals (7: `claude-automation-recommender`, `code-structure`, `humanizer`, `documentation`, `technical-tutorials`, `copywriting`, `impeccable`) + drift defender (1: `audit-baseline`) + alternate tracks (1: `chore`) + maintenance (1: `upgrade-project`). The vendored `claude-automation-recommender` (Apache 2.0, from `claude-code-setup`), the writing/quality globals, and the design global ship unchanged with their licenses intact. Artifact skills (intake, brd, spec, rca) each ship a `template.md`. Helper scripts: swarm-plan gets `validate.sh`, swarm-dispatch gets `swarm_merge.sh`, spec-render gets `render.sh`, spec-lint gets `lint.sh`, archive gets `archive.sh`, audit-baseline gets `audit.sh`. All helper scripts `chmod +x`.
520
520
 
521
521
  **Step 6:** Write `.claude/commands/*.md` for the 4 gates (§4.4). All carry `disable-model-invocation: true` as belt-and-braces; structural user-only is enforced by their directory.
522
522