@su-sws/synthetic-web-team 0.1.1 → 0.2.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,27 +1,63 @@
1
1
  // File emission.
2
2
  //
3
- // Two rules that shape everything here:
3
+ // Four rules that shape everything here:
4
4
  //
5
5
  // 1. Per-editor files are THIN POINTERS, never content copies. There is then no
6
6
  // place for content to diverge, and no reason to regenerate anything later.
7
7
  // 2. Every emitted file is self-sufficient about being a pointer, because
8
8
  // precedence and merge order are not uniform across editors and layering
9
9
  // cannot be relied on.
10
-
11
- import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, rmSync, rmdirSync } from 'node:fs';
10
+ // 3. AGENTS.md, CLAUDE.md and GEMINI.md are SHARED files. Next.js writes the
11
+ // same ones, and a project has its own rules in them. So the contract is a
12
+ // marked block merged into AGENTS.md, and CLAUDE.md only has to import it.
13
+ // Replacing the whole file dropped a project's Next.js block and its own
14
+ // rules, and reported that as `updated`.
15
+ // 4. Everything else this tool writes in a project lives under .sws/. The root
16
+ // of a repository belongs to the team, and a `standards/` folder they did
17
+ // not ask for, next to their own source, is clutter. Nothing is written into
18
+ // .claude/ either: many teams git-ignore it, so a committed file that points
19
+ // there works on one machine and breaks for everyone else.
20
+
21
+ import {
22
+ existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync,
23
+ lstatSync, realpathSync, readlinkSync, renameSync, rmSync, rmdirSync,
24
+ } from 'node:fs';
12
25
  import { createHash } from 'node:crypto';
13
- import { join, dirname, sep } from 'node:path';
14
-
15
- const POINTER = (target) => `<!--
26
+ import { join, dirname, resolve, sep } from 'node:path';
27
+
28
+ // Where a project's vendored standards live.
29
+ export const STANDARDS_DIR = '.sws/standards';
30
+
31
+ // Layouts an earlier version wrote, and where those files live now. A re-run
32
+ // moves every file the install record lists; see migrate().
33
+ const MOVED = [['standards/', `${STANDARDS_DIR}/`]];
34
+
35
+ // The markers around the contract in AGENTS.md, in the shape Next.js uses for
36
+ // its own block, so the two sit in one file without either touching the other.
37
+ export const CONTRACT_BEGIN = '<!-- BEGIN:sws-agent-contract -->';
38
+ export const CONTRACT_END = '<!-- END:sws-agent-contract -->';
39
+
40
+ // The heading every version of the contract before the markers opened with.
41
+ // Finding it with no markers means an old copy sits in the file next to the
42
+ // project's own content, and nothing says where ours ends.
43
+ const LEGACY_CONTRACT_HEADING = '# Stanford Web Services: agent contract';
44
+
45
+ // CLAUDE.md and GEMINI.md: byte for byte what create-next-app writes, so the
46
+ // two tools stop rewriting each other's file.
47
+ export const IMPORT = '@AGENTS.md\n';
48
+
49
+ // The comment earlier versions wrote above the import, kept verbatim so a
50
+ // re-run can recognise it and take it out. It named .claude/skills/, which is a
51
+ // path in a directory many teams git-ignore, and the skills are not in the
52
+ // project any more anyway.
53
+ const LEGACY_POINTER_COMMENT = `<!--
16
54
  Stanford Web Services agent team.
17
55
 
18
- This file is a POINTER, not content. The behavioral contract is ${target},
56
+ This file is a POINTER, not content. The behavioral contract is AGENTS.md,
19
57
  and the team is in .agents/skills/ and .claude/skills/.
20
58
 
21
- Editing this file will not change how the agent behaves. Edit ${target}.
59
+ Editing this file will not change how the agent behaves. Edit AGENTS.md.
22
60
  -->
23
-
24
- @${target}
25
61
  `;
26
62
 
27
63
  // The two paths skills are read from. Neither is read by every editor, so two
@@ -59,8 +95,11 @@ export function plan({ root, source, editors, answers, tier, scope = 'project' }
59
95
  // they are byte-identical in every repository and referencing them in place is
60
96
  // not available: most editors that read .agents/skills offer no configurable
61
97
  // path to redirect. See docs/skill-paths.md and docs/two-part-install.md.
62
- add('AGENTS.md', readFileSync(join(source, 'AGENTS.md'), 'utf8'),
63
- 'behavioral contract, read by every tool');
98
+ add('AGENTS.md', contract(source),
99
+ 'behavioral contract, between markers; the rest of the file is yours', {
100
+ merge: 'block', markers: [CONTRACT_BEGIN, CONTRACT_END], legacyHeading: LEGACY_CONTRACT_HEADING,
101
+ adds: 'the contract, between sws-agent-contract markers',
102
+ });
64
103
 
65
104
  const skills = skillNames(source);
66
105
 
@@ -72,7 +111,7 @@ export function plan({ root, source, editors, answers, tier, scope = 'project' }
72
111
  else add(`${base}/${n}`, readFileSync(p, 'utf8'), null);
73
112
  }
74
113
  };
75
- walk(join(source, 'standards'), 'standards');
114
+ walk(join(source, 'standards'), STANDARDS_DIR);
76
115
 
77
116
  // PROJECT STATE, NOT CONTENT. These two accumulate real answers, resolved
78
117
  // versions, recorded divergences, and accepted risks with review dates. They
@@ -89,9 +128,22 @@ export function plan({ root, source, editors, answers, tier, scope = 'project' }
89
128
  'accepted risks, with reasons and review dates', { preserve: true });
90
129
 
91
130
  // ---- per editor, thin pointers only -------------------------------------
131
+ //
132
+ // A pointer names AGENTS.md and .sws/ and nothing else. Skills are installed
133
+ // per machine, so a committed file has nothing true to say about where they
134
+ // live, and the place it used to name was .claude/.
135
+ //
136
+ // Most of these are files a project may already have for its own reasons,
137
+ // so they are ADDED TO, never written: see SHARED. Only the rules files under
138
+ // our own name (.cursor/rules/sws.mdc, .devin/rules/sws.md) are whole files.
92
139
  for (const e of editors) {
93
140
  for (const f of e.emits) {
94
141
  if (files.some((x) => x.path === f)) continue;
142
+ if (SHARED[f]) {
143
+ const { contents, ...opts } = SHARED[f];
144
+ add(f, contents, `for ${e.label}`, opts);
145
+ continue;
146
+ }
95
147
  const c = pointerFor(f);
96
148
  if (c !== null) add(f, c, `for ${e.label}`);
97
149
  }
@@ -100,11 +152,29 @@ export function plan({ root, source, editors, answers, tier, scope = 'project' }
100
152
  return files;
101
153
  }
102
154
 
103
- function pointerFor(path) {
104
- if (path === 'CLAUDE.md' || path === 'GEMINI.md') return POINTER('AGENTS.md');
155
+ // --- shared files, and what we add to each ---------------------------------
156
+
157
+ // The MCP server, wired up and nothing else.
158
+ //
159
+ // This used to emit an empty shell, on the reasoning that the wizard cannot
160
+ // know which servers a person is entitled to use. That still holds for third
161
+ // parties -- a wrong entry produces confusing tool failures -- but it does not
162
+ // hold for @su-sws/synthetic-web-team-mcp, which is ours, optional, and read-only apart from
163
+ // sws_scaffold (which itself defaults to a dry run).
164
+ //
165
+ // The server is a SECOND entry point, never a requirement: everything it
166
+ // exposes is also a file in .sws/standards/ that the agent can read directly.
167
+ // If the client cannot start it, nothing else stops working.
168
+ const SERVER_NAME = 'sws';
169
+ const SERVER = { command: 'npx', args: ['-y', '@su-sws/synthetic-web-team-mcp'] };
170
+
171
+ const MD_POINTER = ['<!-- BEGIN:sws-pointer -->', '<!-- END:sws-pointer -->'];
172
+ const TOML_POINTER = ['# BEGIN:sws-pointer', '# END:sws-pointer'];
105
173
 
106
- if (path === '.github/copilot-instructions.md') {
107
- return `<!-- Pointer. The contract is AGENTS.md; skills are in .claude/skills/. -->
174
+ // What every release before the markers wrote as the whole file, verbatim, so
175
+ // a re-run can find it inside a file that has grown around it and replace
176
+ // exactly that.
177
+ const OLD_COPILOT = `<!-- Pointer. The contract is AGENTS.md; skills are in .claude/skills/. -->
108
178
 
109
179
  Follow the Stanford Web Services agent contract in \`AGENTS.md\` at the repository
110
180
  root, and the standards in \`standards/\`.
@@ -112,8 +182,69 @@ root, and the standards in \`standards/\`.
112
182
  Non-negotiables: WCAG 2.1 AA, the Global Footer is immutable
113
183
  (\`standards/fragments/global-footer.yml\`), never commit credentials.
114
184
  `;
115
- }
185
+ const OLD_CODEX = `# Stanford Web Services. AGENTS.md and .agents/skills/ are read automatically.
186
+ #
187
+ # Optional: the SWS MCP server, a second entry point to the same standards.
188
+ # [mcp_servers.sws]
189
+ # command = "npx"
190
+ # args = ["-y", "@su-sws/synthetic-web-team-mcp"]
191
+ `;
192
+
193
+ function pointerBlock([begin, end], body, legacyText, { fences = true } = {}) {
194
+ return {
195
+ contents: `${begin}\n${body}\n${end}`, merge: 'block', markers: [begin, end], legacyText, fences,
196
+ adds: 'a pointer to AGENTS.md, between sws-pointer markers',
197
+ };
198
+ }
116
199
 
200
+ function mcpServer(key, entry, extra = {}) {
201
+ return {
202
+ contents: `${JSON.stringify({ [key]: { [SERVER_NAME]: entry } }, null, 2)}\n`,
203
+ part: canonical(entry), merge: 'mcp', key, entry, ...extra,
204
+ adds: 'the sws MCP server, next to yours',
205
+ };
206
+ }
207
+
208
+ const SHARED = {
209
+ // Only for the tools that do not read AGENTS.md themselves, and only the import.
210
+ 'CLAUDE.md': { contents: IMPORT, merge: 'import', adds: 'the line @AGENTS.md' },
211
+ 'GEMINI.md': { contents: IMPORT, merge: 'import', adds: 'the line @AGENTS.md' },
212
+
213
+ // Also what Copilot code review reads on a pull request.
214
+ '.github/copilot-instructions.md': pointerBlock(MD_POINTER, `Follow the Stanford Web Services agent contract in \`AGENTS.md\` at the repository
215
+ root, and the standards in \`.sws/standards/\`.
216
+
217
+ Non-negotiables: WCAG 2.1 AA, the Global Footer is immutable
218
+ (\`.sws/standards/fragments/global-footer.yml\`), never commit credentials.`, [OLD_COPILOT]),
219
+
220
+ '.codex/config.toml': pointerBlock(TOML_POINTER, `# Stanford Web Services. Codex reads AGENTS.md automatically.
221
+ #
222
+ # Optional: the SWS MCP server, a second entry point to the same standards.
223
+ # [mcp_servers.sws]
224
+ # command = "npx"
225
+ # args = ["-y", "@su-sws/synthetic-web-team-mcp"]`, [OLD_CODEX], { fences: false }),
226
+
227
+ '.mcp.json': mcpServer('mcpServers', SERVER),
228
+ '.cursor/mcp.json': mcpServer('mcpServers', SERVER),
229
+ '.agents/mcp_config.json': mcpServer('mcpServers', SERVER),
230
+ // VS Code's key is `servers`. Earlier versions wrote `mcpServers` here, which
231
+ // VS Code does not read, so that entry is moved across when it is ours.
232
+ '.vscode/mcp.json': mcpServer('servers', { type: 'stdio', ...SERVER }, { legacyKey: 'mcpServers', legacyEntry: SERVER }),
233
+ };
234
+
235
+ // The contract as it ships: the marked block from this package's own AGENTS.md,
236
+ // markers included. Anything outside the markers there is about this repository
237
+ // and stays behind. Line endings are normalised so the hash is the same on
238
+ // every platform.
239
+ export function contract(source) {
240
+ const text = lf(readFileSync(join(source, 'AGENTS.md'), 'utf8'));
241
+ const found = findBlock(text);
242
+ return found
243
+ ? text.slice(found.start, found.end)
244
+ : `${CONTRACT_BEGIN}\n${text.trimEnd()}\n${CONTRACT_END}`;
245
+ }
246
+
247
+ function pointerFor(path) {
117
248
  if (path === '.cursor/rules/sws.mdc') {
118
249
  // .mdc is mandatory here; a .md file is silently ignored by Cursor.
119
250
  return `---
@@ -121,11 +252,11 @@ description: Stanford Web Services standards
121
252
  alwaysApply: true
122
253
  ---
123
254
 
124
- Follow the agent contract in \`AGENTS.md\` at the repository root. Skills are in
125
- \`.agents/skills/\`. Standards are in \`standards/\`.
255
+ Follow the agent contract in \`AGENTS.md\` at the repository root. Standards are
256
+ in \`.sws/standards/\`.
126
257
 
127
258
  Non-negotiables: WCAG 2.1 AA, the Global Footer is immutable
128
- (\`standards/fragments/global-footer.yml\`), never commit credentials.
259
+ (\`.sws/standards/fragments/global-footer.yml\`), never commit credentials.
129
260
  `;
130
261
  }
131
262
 
@@ -135,39 +266,9 @@ trigger: always_on
135
266
  description: Stanford Web Services standards
136
267
  ---
137
268
 
138
- Follow the agent contract in \`AGENTS.md\`. Skills are in \`.agents/skills/\`.
269
+ Follow the agent contract in \`AGENTS.md\`. Standards are in \`.sws/standards/\`.
139
270
  `;
140
271
  }
141
-
142
- // MCP config: wire up OUR server and nothing else.
143
- //
144
- // This used to emit an empty shell, on the reasoning that the wizard cannot
145
- // know which servers a person is entitled to use. That still holds for third
146
- // parties -- a wrong entry produces confusing tool failures -- but it does not
147
- // hold for @su-sws/synthetic-web-team-mcp, which is ours, optional, and read-only apart from
148
- // sws_scaffold (which itself defaults to a dry run).
149
- //
150
- // The server is a SECOND entry point, never a requirement: everything it
151
- // exposes is also a file in standards/ that the agent can read directly. If
152
- // the client cannot start it, nothing else stops working.
153
- if (path.endsWith('mcp.json') || path.endsWith('mcp_config.json')) {
154
- return JSON.stringify({
155
- mcpServers: {
156
- sws: {
157
- command: 'npx',
158
- args: ['-y', '@su-sws/synthetic-web-team-mcp'],
159
- },
160
- },
161
- }, null, 2) + '\n';
162
- }
163
- if (path === '.codex/config.toml') {
164
- return '# Stanford Web Services. AGENTS.md and .agents/skills/ are read automatically.\n' +
165
- '#\n' +
166
- '# Optional: the SWS MCP server, a second entry point to the same standards.\n' +
167
- '# [mcp_servers.sws]\n' +
168
- '# command = "npx"\n' +
169
- '# args = ["-y", "@su-sws/synthetic-web-team-mcp"]\n';
170
- }
171
272
  return null;
172
273
  }
173
274
 
@@ -205,7 +306,7 @@ owners:
205
306
  # WHERE THIS SITE IS SERVED. SWS runs BOTH Netlify and Vercel, one per family,
206
307
  # so neither is a divergence -- pick whichever the unit already administers.
207
308
  # Profiles, with what each host does and does not cover:
208
- # standards/hosting/. Leave provider null until the choice is made.
309
+ # .sws/standards/hosting/. Leave provider null until the choice is made.
209
310
  #
210
311
  # Recording this matters more than it looks. Until 2026-09-03 this project
211
312
  # believed Netlify was the only SWS host, because hosting was inferred from
@@ -245,7 +346,7 @@ resolved:
245
346
  node: ${q(process.versions.node)}
246
347
 
247
348
  # Where content comes from. This package is scoped to static content authored in
248
- # the repo: no CMS, not Storyblok, not decoupled Drupal. See standards/scope.md.
349
+ # the repo: no CMS, not Storyblok, not decoupled Drupal. See .sws/standards/scope.md.
249
350
  # A CMS is not a divergence you can record here -- it is out of scope, which is
250
351
  # a different thing. If a project needs one, raise it rather than recording it.
251
352
  content:
@@ -307,28 +408,100 @@ const ACKNOWLEDGED_TEMPLATE = `# Accepted risks.
307
408
  * repository on the strength of a version bump is not a risk worth
308
409
  * taking for tidiness.
309
410
  *
411
+ * Two more for shared files, which hold the project's content as well as ours:
412
+ *
413
+ * merged Our part was added to a file that already had other content:
414
+ * the contract block appended to the project's own AGENTS.md, or
415
+ * the import added to its CLAUDE.md. Their content is untouched.
416
+ * For these files the record holds the hash of OUR part only.
417
+ *
418
+ * moved A file an earlier version wrote somewhere else, `standards/` at
419
+ * the root, now under .sws/. Listed separately in the result.
420
+ *
310
421
  * Comparison is by content, never mtime: re-running the same version must be
311
422
  * `unchanged` even though the source files have newer timestamps.
423
+ *
424
+ * Never through a symbolic link. `CLAUDE.md -> AGENTS.md` is a common setup,
425
+ * and writing the import through it would replace the contract with a line that
426
+ * imports itself.
312
427
  */
313
428
  export function write(root, files, { force = false, version = null, scope = 'project' } = {}) {
314
429
  const prev = readInstalled(root);
315
- const planned = new Set(files.map((f) => f.path));
430
+ let planned = new Set(files.map((f) => f.path));
431
+
432
+ // Moves first, so the loop below finds each file where it lives now, with the
433
+ // hash that tells an edit from an old version carried across with it.
434
+ const { moved, carried, deferred } = scope === 'project'
435
+ ? migrate(root, prev, planned, { force })
436
+ : { moved: [], carried: {}, deferred: null };
437
+
438
+ // A move that has to wait: this run updates the standards where they are.
439
+ if (deferred) {
440
+ files = files.map((f) => (f.path.startsWith(deferred.to)
441
+ ? { ...f, path: deferred.from + f.path.slice(deferred.to.length) } : f));
442
+ planned = new Set(files.map((f) => f.path));
443
+ }
444
+ const record = { ...carried, ...(prev?.files ?? {}) };
445
+
316
446
  const results = [];
317
447
  const nextHashes = {};
448
+ const agents = join(root, 'AGENTS.md');
318
449
 
319
450
  for (const f of files) {
320
451
  const p = join(root, f.path);
321
- const newHash = hash(f.contents);
452
+ // For a shared file this is the hash of OUR part, which is what the record
453
+ // keeps for it: the rest of the file is the project's.
454
+ const newHash = hash(f.part ?? f.contents);
455
+ const recorded = record[f.path];
456
+ const st = lstatSync(p, { throwIfNoEntry: false });
322
457
  let status;
323
-
324
- if (!existsSync(p)) {
458
+ let reason;
459
+ let contents = f.contents;
460
+ let target = p;
461
+
462
+ if (scope === 'project' && !resolvesInside(root, p)) {
463
+ // A parent directory that is a link out of the project. The checks below
464
+ // look at the file itself; this one stops a write landing somewhere else
465
+ // entirely, through `.sws/` or `.github/` linked to a shared folder.
466
+ //
467
+ // Project scope only. At user scope the root is a home directory, and a
468
+ // `~/.claude` that links into a dotfiles repository or another volume is
469
+ // the person's own setup: following it is what they want, and refusing
470
+ // it left Claude Code with no skills at all.
471
+ status = 'conflict';
472
+ reason = 'outside';
473
+ } else if (f.merge && f.path !== 'AGENTS.md' && sameFile(p, agents)) {
474
+ // This file and AGENTS.md are one file, linked either way round, as with
475
+ // CLAUDE.md or .github/copilot-instructions.md -> AGENTS.md. It already
476
+ // holds the contract, and adding our part would put an import, or a
477
+ // pointer to AGENTS.md, inside AGENTS.md itself.
478
+ status = 'unchanged';
479
+ } else if (st?.isSymbolicLink()) {
480
+ // Never written through, with one exception: the contract, into a file
481
+ // inside the project, as when AGENTS.md links to CLAUDE.md. A merge only
482
+ // adds our part, so it lands in the file the tools read. Pointer blocks
483
+ // and MCP configs never follow a link.
484
+ const real = f.path === 'AGENTS.md' ? fileInside(root, p) : null;
485
+ if (real) {
486
+ const m = MERGE.block(readFileSync(real, 'utf8'), f, { recorded, force });
487
+ ({ status, reason } = m);
488
+ if (m.text !== undefined) contents = m.text;
489
+ target = real;
490
+ } else {
491
+ status = 'conflict';
492
+ reason = 'symlink';
493
+ }
494
+ } else if (f.merge) {
495
+ const m = MERGE[f.merge](st ? readFileSync(p, 'utf8') : null, f, { recorded, force });
496
+ ({ status, reason } = m);
497
+ if (m.text !== undefined) contents = m.text;
498
+ } else if (!st) {
325
499
  status = 'created';
326
500
  } else {
327
501
  const local = readFileSync(p, 'utf8');
328
502
  if (f.preserve) status = 'preserved';
329
503
  else if (local === f.contents) status = 'unchanged';
330
504
  else {
331
- const recorded = prev?.files?.[f.path];
332
505
  // No record means we cannot tell an edit from an old version, so the
333
506
  // safe default is to update. Conflict detection needs evidence.
334
507
  const edited = recorded !== undefined && hash(local) !== recorded;
@@ -336,9 +509,12 @@ export function write(root, files, { force = false, version = null, scope = 'pro
336
509
  }
337
510
  }
338
511
 
339
- if (status === 'created' || status === 'updated') {
512
+ if (status === 'created' || status === 'updated' || status === 'merged') {
340
513
  mkdirSync(dirname(p), { recursive: true });
341
- writeFileSync(p, f.contents);
514
+ writeFileSync(target, contents);
515
+ nextHashes[f.path] = newHash;
516
+ } else if (f.merge && status === 'unchanged') {
517
+ // Our part, not the whole file: the rest belongs to the project.
342
518
  nextHashes[f.path] = newHash;
343
519
  } else if (status === 'conflict') {
344
520
  // Keep the hash of what we LAST WROTE, never what is on disk now.
@@ -355,13 +531,21 @@ export function write(root, files, { force = false, version = null, scope = 'pro
355
531
  // reason: a one-shot warning is easy to miss, and an agent discards the
356
532
  // output entirely. It is also what makes `remove()` safe, since the record
357
533
  // stays a description of OUR content rather than drifting onto theirs.
358
- nextHashes[f.path] = prev?.files?.[f.path] ?? newHash;
534
+ //
535
+ // A conflict with no record behind it records nothing. A shared file can
536
+ // conflict on its very first run (an MCP config with comments), and
537
+ // recording what we WOULD have written read, on the next run, as proof
538
+ // that we had written it and someone removed it, so the server was never
539
+ // added once the comments were gone.
540
+ if (recorded !== undefined) nextHashes[f.path] = recorded;
359
541
  } else {
360
542
  nextHashes[f.path] = existsSync(p) ? hash(readFileSync(p, 'utf8')) : newHash;
361
543
  }
362
- results.push({ path: f.path, status });
544
+ results.push({ path: f.path, status, ...(reason ? { reason } : {}) });
363
545
  }
364
546
 
547
+ // A moved file's old path no longer exists, so it drops out of the record
548
+ // here rather than reporting as an orphan.
365
549
  const orphans = Object.keys(prev?.files ?? {}).filter((x) => !planned.has(x) && existsSync(join(root, x)));
366
550
 
367
551
  // Keep orphans in the record while the file still exists, so they are reported
@@ -378,15 +562,439 @@ export function write(root, files, { force = false, version = null, scope = 'pro
378
562
  return {
379
563
  results,
380
564
  orphans,
565
+ moved,
566
+ deferred,
381
567
  previousVersion: prev?.version ?? null,
382
568
  created: count('created'),
383
569
  updated: count('updated'),
384
570
  unchanged: count('unchanged'),
385
571
  preserved: count('preserved'),
572
+ merged: count('merged'),
386
573
  conflicts: results.filter((r) => r.status === 'conflict').map((r) => r.path),
387
574
  };
388
575
  }
389
576
 
577
+ // What a re-run would move, or why it would wait, for a dry run, which writes
578
+ // nothing.
579
+ export function plannedMigration(root, files, { force = false } = {}) {
580
+ const { moved, deferred } = migrate(root, readInstalled(root), new Set(files.map((f) => f.path)), { dryRun: true, force });
581
+ return { moved, deferred };
582
+ }
583
+
584
+ /**
585
+ * Move what an earlier version wrote to where this one writes it.
586
+ *
587
+ * Driven by the install record only, the same rule `remove()` follows: a
588
+ * `standards/` folder with no record behind it may be the team's own, so it is
589
+ * never touched. For each file the record lists under an old prefix:
590
+ *
591
+ * - the record entry is carried to the new path, so an edit made before the
592
+ * move is still told apart from an old version after it
593
+ * - the file is RENAMED, never rewritten, so a local edit travels with it and
594
+ * reports as a conflict at its new path, as it would have at the old one
595
+ * - if the new path already exists (a move by hand, as in the first pilot),
596
+ * the old copy is deleted only when its hash proves it is ours and
597
+ * unedited; otherwise it stays and reports as an orphan
598
+ * - a file this version no longer ships is left where it is, an orphan like
599
+ * any other
600
+ *
601
+ * Emptied directories are pruned afterwards, so a `standards/` that held only
602
+ * our files disappears and one that also holds the team's own survives.
603
+ *
604
+ * NOT WHILE THE PROJECT'S OWN CODE READS THE OLD PATH. The recipe tells a site
605
+ * to generate its Global Footer from `standards/fragments/global-footer.yml`,
606
+ * so moving the file out from under it fails that site's next build, and the
607
+ * push after that deploys nothing. The sites this would break are exactly the
608
+ * ones that followed the rule. So references are looked for first, and if any
609
+ * turn up the whole move waits: this run keeps the standards current where they
610
+ * are, and reports each reference so it can be pointed at .sws/standards/.
611
+ * `force` moves them regardless.
612
+ */
613
+ function migrate(root, prev, planned, { dryRun = false, force = false } = {}) {
614
+ const pending = [];
615
+ const carried = {};
616
+ for (const [rel, recorded] of Object.entries(prev?.files ?? {})) {
617
+ const rule = MOVED.find(([from]) => rel.startsWith(from));
618
+ if (!rule) continue;
619
+ const to = rule[1] + rel.slice(rule[0].length);
620
+ if (!planned.has(to)) continue;
621
+ carried[to] = recorded;
622
+ if (existsSync(join(root, rel))) pending.push({ from: rel, to, recorded });
623
+ }
624
+
625
+ if (pending.length && !force) {
626
+ // Files the record lists are ours, not the project's code: an orphaned
627
+ // 0.1.2 pointer that still says `standards/` must not hold the move.
628
+ const references = findReferences(root, pending, new Set([...planned, ...Object.keys(prev?.files ?? {})]));
629
+ if (references.length) {
630
+ return { moved: [], carried: {}, deferred: { files: pending.length, from: MOVED[0][0], to: MOVED[0][1], references } };
631
+ }
632
+ }
633
+
634
+ const moved = [];
635
+ for (const { from, to, recorded } of pending) {
636
+ const src = join(root, from);
637
+ const dest = join(root, to);
638
+ // Both ends must resolve inside the project, parents included. A
639
+ // `standards/` replaced by a link to a shared folder would otherwise have
640
+ // its files renamed out of that folder. Such a file is left where it is,
641
+ // and reports as an orphan.
642
+ if (!resolvesInside(root, src) || !resolvesInside(root, dest)) continue;
643
+ if (existsSync(dest)) {
644
+ if (hash(readFileSync(src, 'utf8')) !== recorded) continue;
645
+ if (!dryRun) rmSync(src);
646
+ } else if (!dryRun) {
647
+ mkdirSync(dirname(dest), { recursive: true });
648
+ renameSync(src, dest);
649
+ }
650
+ moved.push({ from, to });
651
+ }
652
+ if (!dryRun) pruneEmpty(root, moved.map((m) => m.from));
653
+ return { moved, carried, deferred: null };
654
+ }
655
+
656
+ // Everything that could break when the files move, which is every text file
657
+ // except prose: a build can read the footer from a Python or shell step, a Ruby
658
+ // plugin or a Makefile as easily as from JavaScript, and the Jekyll and Quarto
659
+ // stubs describe exactly those routes. A README that still says `standards/` is
660
+ // out of date, which is worth fixing, but it fails no build. Binaries are
661
+ // skipped by extension, and by a NUL byte for anything the list misses.
662
+ const PROSE_FILES = /\.(md|markdown|txt|rst|adoc)$/i;
663
+ const BINARY_FILES = /\.(png|jpe?g|gif|webp|avif|ico|svgz|woff2?|ttf|otf|eot|pdf|zip|gz|tgz|mp3|mp4|webm|mov|wasm)$/i;
664
+ const SKIP_ANYWHERE = new Set(['node_modules', '.git', 'dist', 'build', 'out', '_site', '.next', '.astro',
665
+ '.netlify', '.vercel', '.turbo', '.cache', 'coverage']);
666
+ const SKIP_AT_ROOT = new Set(['.sws', 'standards']);
667
+
668
+ function findReferences(root, pending, ours) {
669
+ const re = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
670
+ // The entries actually being moved, `fragments`, `policy`, `scope.md`...,
671
+ // so an unrelated `standards/` path of the team's own does not count.
672
+ const entries = [...new Set(pending.map((m) => m.from.split('/')[1]))].map(re).join('|');
673
+ // Matched against the WHOLE file, so a call formatted across lines still
674
+ // counts: `\s*` spans newlines. Each match is mapped back to the line it
675
+ // starts on.
676
+ const patterns = [
677
+ // standards/fragments/..., ../standards/..., `${root}/standards/...`
678
+ new RegExp(`(?<!\\.sws[\\\\/])(?<![\\w.-])standards[\\\\/](?:${entries})(?![\\w-])`, 'g'),
679
+ // join('standards', 'fragments', ...), the way this package's own site does it
680
+ new RegExp(`(?<!['"]\\.sws['"]\\s*,\\s*)['"]standards['"]\\s*,\\s*['"](?:${entries})['"\\\\/]`, 'g'),
681
+ // sws check --standards standards
682
+ /--standards[= ](?:\.\/)?standards(?![\w./-])/g,
683
+ ];
684
+
685
+ // A link into the files being moved, such as Jekyll's
686
+ // `_data/global-footer.yml -> ../standards/fragments/global-footer.yml`, is
687
+ // left dangling by the move. Read as text, so a link that is already dangling
688
+ // still counts, and through realpath for one that goes via another link.
689
+ const oldDir = pending[0].from.split('/')[0];
690
+ const intoOld = (p) => {
691
+ // The folder itself counts too, as in `_data/sws -> ../standards`.
692
+ const under = (base, x) => x === join(base, oldDir) || x.startsWith(join(base, oldDir) + sep);
693
+ try { if (under(root, resolve(dirname(p), readlinkSync(p)))) return true; } catch { /* unreadable */ }
694
+ try { return under(realpathSync(root), realpathSync(p)); } catch { return false; }
695
+ };
696
+
697
+ const hits = [];
698
+ (function walk(dir, rel) {
699
+ for (const n of readdirSync(dir)) {
700
+ if (SKIP_ANYWHERE.has(n) || (!rel && SKIP_AT_ROOT.has(n))) continue;
701
+ const p = join(dir, n);
702
+ const r = rel ? `${rel}/${n}` : n;
703
+ const st = lstatSync(p, { throwIfNoEntry: false });
704
+ if (!st) continue;
705
+ if (st.isSymbolicLink()) {
706
+ if (intoOld(p)) hits.push({ file: r, line: null, text: `-> ${readlinkSync(p)}` });
707
+ continue;
708
+ }
709
+ if (st.isDirectory()) { walk(p, r); continue; }
710
+ if (PROSE_FILES.test(n) || BINARY_FILES.test(n) || ours.has(r) || st.size > 512 * 1024) continue;
711
+ const buf = readFileSync(p);
712
+ if (buf.subarray(0, 8000).includes(0)) continue;
713
+ const text = buf.toString('utf8');
714
+ const lines = text.split('\n');
715
+ const at = new Set();
716
+ for (const x of patterns) {
717
+ for (const m of text.matchAll(x)) at.add(text.slice(0, m.index).split('\n').length);
718
+ }
719
+ for (const n of [...at].sort((a, b) => a - b)) {
720
+ hits.push({ file: r, line: n, text: lines[n - 1].trim().slice(0, 160) });
721
+ }
722
+ }
723
+ })(root, '');
724
+ return hits;
725
+ }
726
+
727
+ // --- shared files ------------------------------------------------------------
728
+ //
729
+ // Each merge takes the file as it is on disk (null if absent) and the planned
730
+ // entry, and returns a status plus the new text when there is something to
731
+ // write. Our part is upserted and nothing else in the file is touched. Text is
732
+ // worked on in LF and the file's own line endings are put back, so a CRLF
733
+ // checkout does not come back with every line changed.
734
+
735
+ const MERGE = { block: mergeBlock, import: mergeImport, mcp: mergeMcp };
736
+
737
+ // A marked block in a text file: the contract in AGENTS.md, the pointer in
738
+ // .github/copilot-instructions.md and .codex/config.toml.
739
+ function mergeBlock(local, f, { recorded, force }) {
740
+ const block = f.contents;
741
+ const [begin, end] = f.markers;
742
+ if (local === null) return { status: 'created', text: `${block}\n` };
743
+ const eol = eolOf(local);
744
+ const text = lf(local);
745
+ const out = (s, status) => ({ status, text: withEol(s, eol) });
746
+
747
+ const found = findBlock(text, begin, end, { fences: f.fences !== false });
748
+ if (found) {
749
+ const current = text.slice(found.start, found.end);
750
+ if (current === block) return { status: 'unchanged' };
751
+ // Same evidence rule as every other file: an edit is only an edit if the
752
+ // record says what we wrote and the block no longer matches it.
753
+ if (recorded !== undefined && hash(current) !== recorded && !force) {
754
+ return { status: 'conflict', reason: 'edited' };
755
+ }
756
+ return out(text.slice(0, found.start) + block + text.slice(found.end), 'updated');
757
+ }
758
+
759
+ // No markers, and the whole file is exactly what an earlier version wrote:
760
+ // it was all ours, so it becomes the block.
761
+ if (recorded !== undefined && hash(local) === recorded) return out(`${block}\n`, 'updated');
762
+
763
+ // An earlier version's whole file, found verbatim inside one that has grown
764
+ // around it. We know exactly where ours starts and ends, so it is replaced in
765
+ // place and everything around it stays.
766
+ for (const old of f.legacyText ?? []) {
767
+ const i = text.indexOf(old);
768
+ if (i !== -1) return out(`${text.slice(0, i)}${block}\n${text.slice(i + old.length)}`, 'updated');
769
+ }
770
+
771
+ // An old copy of the contract with no markers, next to other content, so
772
+ // nothing says where ours ends. Never guessed without being told to: --force
773
+ // replaces from the old heading to the next top-level heading or managed
774
+ // block, or the end of the file, and keeps everything before it.
775
+ const legacy = f.legacyHeading && findLegacySection(text, f.legacyHeading);
776
+ if (legacy) {
777
+ if (!force) return { status: 'conflict', reason: 'legacy-contract' };
778
+ const after = text.slice(legacy.end);
779
+ return out(`${text.slice(0, legacy.start)}${block}\n${after ? `\n${after}` : ''}`, 'updated');
780
+ }
781
+
782
+ // The project's own file. Ours goes after it, one blank line between, as
783
+ // Next.js does with its block in AGENTS.md.
784
+ const sep = text === '' || text.endsWith('\n') ? '\n' : '\n\n';
785
+ return out(`${text}${sep}${block}\n`, text === '' ? 'updated' : 'merged');
786
+ }
787
+
788
+ // The sws server in an MCP config, next to whatever servers the project has.
789
+ //
790
+ // Their servers, their other keys and their indentation are kept. The JSON
791
+ // round-trip does normalise the rest of the layout, the same cost
792
+ // ensureDevDependency() takes with package.json, so a file that already has our
793
+ // entry is never rewritten just to reformat it.
794
+ //
795
+ // Two cases are deliberately left alone:
796
+ // - a file that is not plain JSON. VS Code allows comments in mcp.json, and
797
+ // parsing loosely then writing back would strip them. Reported, not merged.
798
+ // - an sws entry, or the whole file, the project REMOVED after we added it.
799
+ // The server is optional and the install says to remove it if unwanted,
800
+ // so putting it back on every update would be the tool overruling a
801
+ // decision. The first pilot deleted its .mcp.json; the next run made it
802
+ // again. --force puts it back.
803
+ function mergeMcp(local, f, { recorded, force }) {
804
+ if (local === null && recorded !== undefined && !force) return { status: 'unchanged', reason: 'removed' };
805
+ if (local === null || local.trim() === '') {
806
+ return { status: local === null ? 'created' : 'updated', text: f.contents };
807
+ }
808
+ if (local === f.contents) return { status: 'unchanged' };
809
+ // Exactly what an earlier version wrote: all ours, so it takes today's shape.
810
+ if (recorded !== undefined && hash(local) === recorded) return { status: 'updated', text: f.contents };
811
+
812
+ let json;
813
+ try { json = JSON.parse(local); } catch { return { status: 'conflict', reason: 'unparseable' }; }
814
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
815
+ if (!isObj(json) || (json[f.key] !== undefined && !isObj(json[f.key]))) {
816
+ return { status: 'conflict', reason: 'unparseable' };
817
+ }
818
+
819
+ // Our entry under the key an earlier version used, unedited: moved across.
820
+ let moved = false;
821
+ if (f.legacyKey && isObj(json[f.legacyKey]) && canonical(json[f.legacyKey][SERVER_NAME]) === canonical(f.legacyEntry)) {
822
+ const { [SERVER_NAME]: _ours, ...rest } = json[f.legacyKey];
823
+ json = { ...json };
824
+ if (Object.keys(rest).length) json[f.legacyKey] = rest;
825
+ else delete json[f.legacyKey];
826
+ moved = true;
827
+ }
828
+
829
+ const servers = json[f.key] ?? {};
830
+ const current = servers[SERVER_NAME];
831
+ if (current !== undefined && canonical(current) === f.part && !moved) return { status: 'unchanged' };
832
+ if (current === undefined && recorded !== undefined && !moved && !force) {
833
+ return { status: 'unchanged', reason: 'removed' };
834
+ }
835
+ // An sws entry that differs from ours is the project's own (a pinned version,
836
+ // a local path) unless the record proves it is an older entry of ours. In a
837
+ // file that is theirs, keeping theirs is the safe default.
838
+ if (current !== undefined && canonical(current) !== f.part && !force
839
+ && !(recorded !== undefined && hash(canonical(current)) === recorded)) {
840
+ return { status: 'conflict', reason: 'edited' };
841
+ }
842
+
843
+ const next = { ...json, [f.key]: { ...servers, [SERVER_NAME]: f.entry } };
844
+ const indent = local.match(/\n([ \t]+)"/)?.[1] ?? ' ';
845
+ const body = JSON.stringify(next, null, indent);
846
+ const text = withEol(/\n\s*$/.test(lf(local)) ? `${body}\n` : body, eolOf(local));
847
+ return { status: current === undefined && !moved ? 'merged' : 'updated', text };
848
+ }
849
+
850
+ // JSON with sorted keys, so an entry someone reformatted or reordered still
851
+ // compares equal to ours.
852
+ function canonical(v) {
853
+ if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
854
+ if (v !== null && typeof v === 'object') {
855
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`;
856
+ }
857
+ return JSON.stringify(v);
858
+ }
859
+
860
+ function mergeImport(local) {
861
+ if (local === null) return { status: 'created', text: IMPORT };
862
+ const eol = eolOf(local);
863
+ let text = lf(local);
864
+
865
+ const i = text.indexOf(LEGACY_POINTER_COMMENT);
866
+ if (i !== -1) {
867
+ text = text.slice(0, i) + text.slice(i + LEGACY_POINTER_COMMENT.length).replace(/^\n+/, '');
868
+ }
869
+
870
+ let status = 'updated';
871
+ if (!/^@AGENTS\.md[ \t]*$/m.test(text)) {
872
+ if (text.trim() === '') text = IMPORT;
873
+ else {
874
+ // Their own CLAUDE.md. The import is added and nothing else changes.
875
+ text = `${text}${text.endsWith('\n') ? '' : '\n'}\n${IMPORT}`;
876
+ status = 'merged';
877
+ }
878
+ }
879
+ const next = withEol(text, eol);
880
+ return next === local ? { status: 'unchanged' } : { status, text: next };
881
+ }
882
+
883
+ // A marker counts only on a line of its own. Prose that MENTIONS one, like a
884
+ // README sentence explaining the markers, is never mistaken for the block:
885
+ // treating it as one replaced part of that sentence with the contract.
886
+ //
887
+ // In Markdown, not inside a fenced code example either (``` or ~~~, closed by
888
+ // the same character at least as many times). An example of the markers in
889
+ // someone's AGENTS.md was otherwise taken for the real block, and the contract
890
+ // went inside the fence. TOML has no fences, so .codex/config.toml passes
891
+ // `fences: false` and every standalone line counts.
892
+ //
893
+ // Only a fence that CLOSES hides anything. A file that ends inside an open
894
+ // fence (a code sample missing its closing line) had our appended block read as
895
+ // part of that sample, so it was never found again and every run appended
896
+ // another copy. Our own block after an unmatched opener cannot be an example.
897
+ function findBlock(text, begin = CONTRACT_BEGIN, end = CONTRACT_END, { fences = true } = {}) {
898
+ const lines = text.split(/(?<=\n)/);
899
+ const bare = lines.map((l) => l.replace(/\n$/, ''));
900
+ const hidden = new Set();
901
+ if (fences) {
902
+ let open = null;
903
+ let inside = [];
904
+ bare.forEach((b, i) => {
905
+ const f = b.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
906
+ if (!open) {
907
+ if (f) { open = f[1]; inside = [i]; }
908
+ } else {
909
+ inside.push(i);
910
+ if (f && f[1][0] === open[0] && f[1].length >= open.length && f[2].trim() === '') {
911
+ inside.forEach((x) => hidden.add(x));
912
+ open = null;
913
+ }
914
+ }
915
+ });
916
+ }
917
+
918
+ let offset = 0;
919
+ let start = -1;
920
+ for (let i = 0; i < lines.length; i++) {
921
+ if (!hidden.has(i)) {
922
+ const t = bare[i].replace(/[ \t]+$/, '');
923
+ if (start === -1 && t === begin) start = offset;
924
+ else if (start !== -1 && t === end) return { start, end: offset + end.length };
925
+ }
926
+ offset += lines[i].length;
927
+ }
928
+ return null;
929
+ }
930
+
931
+ // From the old heading to the next H1 or `<!-- BEGIN:` block outside a code
932
+ // fence, or the end of the file. Offsets are into the LF text.
933
+ function findLegacySection(text, heading) {
934
+ let offset = 0;
935
+ let start = -1;
936
+ let fence = false;
937
+ for (const line of text.split(/(?<=\n)/)) {
938
+ const bare = line.replace(/\n$/, '');
939
+ if (/^\s*(```|~~~)/.test(bare)) fence = !fence;
940
+ else if (!fence && start === -1 && bare === heading) start = offset;
941
+ else if (!fence && start !== -1 && (/^# /.test(bare) || bare.startsWith('<!-- BEGIN:'))) {
942
+ return { start, end: offset };
943
+ }
944
+ offset += line.length;
945
+ }
946
+ return start === -1 ? null : { start, end: text.length };
947
+ }
948
+
949
+ const eolOf = (s) => (/\r\n/.test(s) ? '\r\n' : '\n');
950
+ const lf = (s) => s.replace(/\r\n/g, '\n');
951
+ const withEol = (s, eol) => (eol === '\n' ? s : s.replace(/\n/g, eol));
952
+
953
+ function sameFile(a, b) {
954
+ try { return realpathSync(a) === realpathSync(b); } catch { return false; }
955
+ }
956
+
957
+ // Whether a path's directory, or the nearest part of it that exists, resolves
958
+ // inside the project once every link along the way is followed. The file itself
959
+ // is judged separately, by the symlink handling in write().
960
+ function resolvesInside(root, p) {
961
+ try {
962
+ const base = realpathSync(root);
963
+ let dir = dirname(p);
964
+ while (!existsSync(dir) && dirname(dir) !== dir) dir = dirname(dir);
965
+ const real = realpathSync(dir);
966
+ return real === base || real.startsWith(base + sep);
967
+ } catch {
968
+ return false;
969
+ }
970
+ }
971
+
972
+ // Where a link leads, if that is a regular file inside the project; null for
973
+ // anything else, including a dangling link or one that leaves the repository.
974
+ function fileInside(root, link) {
975
+ try {
976
+ const real = realpathSync(link);
977
+ return real.startsWith(realpathSync(root) + sep) && statSync(real).isFile() ? real : null;
978
+ } catch {
979
+ return null;
980
+ }
981
+ }
982
+
983
+ // Deepest first, so `.claude/skills/x` is emptied before `.claude/skills`.
984
+ // rmdirSync fails on a non-empty directory, which is exactly the guard wanted
985
+ // here, so the error is the check and is meant to be swallowed.
986
+ function pruneEmpty(root, rels) {
987
+ const dirs = [...new Set(rels.map((rel) => dirname(join(root, rel))))]
988
+ .sort((a, b) => b.split(sep).length - a.split(sep).length);
989
+ for (const d of dirs) {
990
+ let cur = d;
991
+ while (cur.startsWith(root) && cur !== root) {
992
+ try { rmdirSync(cur); } catch { break; }
993
+ cur = dirname(cur);
994
+ }
995
+ }
996
+ }
997
+
390
998
  // --- the install record ----------------------------------------------------
391
999
  //
392
1000
  // Committed, not gitignored: it is a record of what this tool put in the
@@ -468,18 +1076,7 @@ export function remove(root, { dryRun = false, force = false } = {}) {
468
1076
  }
469
1077
 
470
1078
  if (!dryRun) {
471
- // Deepest first, so `.claude/skills/x` is emptied before `.claude/skills`.
472
- // rmdirSync fails on a non-empty directory, which is exactly the guard
473
- // wanted here, so the error is the check and is meant to be swallowed.
474
- const dirs = [...new Set(removed.map((rel) => dirname(join(root, rel))))]
475
- .sort((a, b) => b.split(sep).length - a.split(sep).length);
476
- for (const d of dirs) {
477
- let cur = d;
478
- while (cur.startsWith(root) && cur !== root) {
479
- try { rmdirSync(cur); } catch { break; }
480
- cur = dirname(cur);
481
- }
482
- }
1079
+ pruneEmpty(root, removed);
483
1080
 
484
1081
  // Keep a record only while something of ours is still on disk, so a second
485
1082
  // run can still tell our files from theirs.