@su-sws/synthetic-web-team 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/AGENTS.md +149 -0
  2. package/README.md +321 -0
  3. package/package.json +58 -0
  4. package/packages/cli/bin/sws.mjs +722 -0
  5. package/packages/cli/src/axe.mjs +164 -0
  6. package/packages/cli/src/browser.mjs +192 -0
  7. package/packages/cli/src/checks.mjs +1254 -0
  8. package/packages/cli/src/github.mjs +131 -0
  9. package/packages/cli/src/history.mjs +137 -0
  10. package/packages/cli/src/perf.mjs +245 -0
  11. package/packages/cli/src/preflight.mjs +185 -0
  12. package/packages/cli/src/report.mjs +315 -0
  13. package/packages/cli/src/states.mjs +556 -0
  14. package/packages/wizard/bin/wizard.mjs +767 -0
  15. package/packages/wizard/src/detect.mjs +135 -0
  16. package/packages/wizard/src/emit.mjs +553 -0
  17. package/skills/role-accessibility-lead/SKILL.md +183 -0
  18. package/skills/role-api-architect/SKILL.md +65 -0
  19. package/skills/role-backend-developer/SKILL.md +66 -0
  20. package/skills/role-compliance-officer/SKILL.md +73 -0
  21. package/skills/role-content-designer/SKILL.md +145 -0
  22. package/skills/role-devops/SKILL.md +200 -0
  23. package/skills/role-discoverability/SKILL.md +164 -0
  24. package/skills/role-frontend-developer/SKILL.md +167 -0
  25. package/skills/role-fullstack-developer/SKILL.md +56 -0
  26. package/skills/role-identity-engineer/SKILL.md +77 -0
  27. package/skills/role-information-architect/SKILL.md +136 -0
  28. package/skills/role-infrastructure-architect/SKILL.md +60 -0
  29. package/skills/role-qa-engineer/SKILL.md +81 -0
  30. package/skills/role-security-operations/SKILL.md +56 -0
  31. package/skills/role-software-architect/SKILL.md +75 -0
  32. package/skills/role-staff-technical-architect/SKILL.md +73 -0
  33. package/skills/role-strategist/SKILL.md +122 -0
  34. package/skills/role-user-researcher/SKILL.md +66 -0
  35. package/skills/role-ux-designer/SKILL.md +159 -0
  36. package/skills/sws-compliance-check/SKILL.md +153 -0
  37. package/skills/sws-decanter/SKILL.md +191 -0
  38. package/skills/sws-deploy/SKILL.md +162 -0
  39. package/skills/sws-diverge/SKILL.md +131 -0
  40. package/skills/sws-github/SKILL.md +171 -0
  41. package/skills/sws-install/SKILL.md +97 -0
  42. package/skills/sws-netlify/SKILL.md +110 -0
  43. package/skills/sws-onboard/SKILL.md +85 -0
  44. package/skills/sws-preflight/SKILL.md +87 -0
  45. package/skills/sws-prior-art/SKILL.md +137 -0
  46. package/skills/sws-vercel/SKILL.md +117 -0
  47. package/standards/fragments/global-footer.yml +137 -0
  48. package/standards/fragments/identity-bar.yml +180 -0
  49. package/standards/hosting/capabilities.yml +215 -0
  50. package/standards/hosting/github-pages.yml +306 -0
  51. package/standards/hosting/netlify.yml +234 -0
  52. package/standards/hosting/vercel.yml +284 -0
  53. package/standards/patterns/components.md +162 -0
  54. package/standards/patterns/content.md +130 -0
  55. package/standards/patterns/decanter.md +352 -0
  56. package/standards/patterns/discoverability.md +121 -0
  57. package/standards/patterns/forms.md +116 -0
  58. package/standards/patterns/ia.md +126 -0
  59. package/standards/patterns/motion.md +267 -0
  60. package/standards/patterns/sws-conventions.md +225 -0
  61. package/standards/policy/accessibility.md +241 -0
  62. package/standards/policy/brand.md +213 -0
  63. package/standards/policy/escalation.md +53 -0
  64. package/standards/policy/identity.md +96 -0
  65. package/standards/policy/minsec.md +119 -0
  66. package/standards/policy/minweb.md +87 -0
  67. package/standards/policy/privacy.md +114 -0
  68. package/standards/policy/procurement.md +79 -0
  69. package/standards/prior-art/README.md +205 -0
  70. package/standards/prior-art/catalog.yml +409 -0
  71. package/standards/prior-art/patterns/INDEX.md +53 -0
  72. package/standards/prior-art/repos.yml +734 -0
  73. package/standards/recipes/astro-ssr/RECIPE.md +274 -0
  74. package/standards/recipes/astro-ssr/acceptance.yml +168 -0
  75. package/standards/recipes/astro-static/RECIPE.md +468 -0
  76. package/standards/recipes/astro-static/acceptance.yml +800 -0
  77. package/standards/recipes/next-ssr/RECIPE.md +407 -0
  78. package/standards/recipes/next-ssr/acceptance.yml +187 -0
  79. package/standards/scope.md +111 -0
  80. package/standards/stack/performance-budget.yml +95 -0
  81. package/standards/stack/reference-versions.yml +168 -0
  82. package/standards/stack/requirements.yml +154 -0
@@ -0,0 +1,135 @@
1
+ // Editor detection. Deliberately generous about what counts as evidence, and
2
+ // deliberately never authoritative: everything detected is a PRE-CHECKED
3
+ // SUGGESTION the person can override. Guessing wrong and writing config for an
4
+ // editor somebody does not use is a small harm; failing to offer one they do
5
+ // use is a bigger one.
6
+
7
+ import { existsSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { homedir } from 'node:os';
10
+
11
+ // `emits` lists the files this editor needs BEYOND the universal core.
12
+ // Skills come from .agents/skills and .claude/skills, which every entry shares.
13
+ export const EDITORS = [
14
+ {
15
+ id: 'claude-code',
16
+ label: 'Claude Code',
17
+ localSigns: ['.claude', 'CLAUDE.md'],
18
+ homeSigns: ['.claude'],
19
+ emits: ['CLAUDE.md', '.mcp.json'],
20
+ note: 'reads .claude/skills natively',
21
+ },
22
+ {
23
+ id: 'vscode',
24
+ label: 'VS Code + Copilot',
25
+ localSigns: ['.vscode', '.github/copilot-instructions.md'],
26
+ homeSigns: [],
27
+ emits: ['.github/copilot-instructions.md', '.vscode/mcp.json'],
28
+ note: 'reads .claude/skills by default, so no extra skill copy needed',
29
+ },
30
+ {
31
+ id: 'cursor',
32
+ label: 'Cursor',
33
+ localSigns: ['.cursor'],
34
+ homeSigns: ['.cursor'],
35
+ emits: ['.cursor/rules/sws.mdc', '.cursor/mcp.json'],
36
+ note: 'reads .agents/skills; rules file must be .mdc, not .md',
37
+ },
38
+ {
39
+ id: 'codex',
40
+ label: 'Codex CLI',
41
+ localSigns: ['.codex'],
42
+ homeSigns: ['.codex'],
43
+ emits: ['.codex/config.toml'],
44
+ note: 'reads AGENTS.md and .agents/skills already',
45
+ },
46
+ {
47
+ id: 'antigravity',
48
+ label: 'Antigravity',
49
+ localSigns: ['.agents/rules', 'GEMINI.md'],
50
+ homeSigns: ['.gemini'],
51
+ emits: ['GEMINI.md', '.agents/mcp_config.json'],
52
+ note: 'ranks GEMINI.md above AGENTS.md, so it needs its own pointer',
53
+ },
54
+ {
55
+ id: 'gemini-cli',
56
+ label: 'Gemini CLI',
57
+ localSigns: ['.gemini'],
58
+ homeSigns: ['.gemini'],
59
+ emits: ['GEMINI.md'],
60
+ note: 'does not read AGENTS.md natively',
61
+ },
62
+ {
63
+ id: 'zed',
64
+ label: 'Zed',
65
+ localSigns: ['.zed'],
66
+ homeSigns: ['.config/zed'],
67
+ emits: [],
68
+ note: 'reads AGENTS.md and .agents/skills; nothing extra needed',
69
+ },
70
+ {
71
+ id: 'windsurf',
72
+ label: 'Windsurf / Devin',
73
+ localSigns: ['.windsurf', '.devin'],
74
+ homeSigns: ['.codeium'],
75
+ emits: ['.devin/rules/sws.md'],
76
+ note: 'rules extension is .md, not .mdc',
77
+ },
78
+ ];
79
+
80
+ export function detect(root = process.cwd()) {
81
+ const home = homedir();
82
+ return EDITORS.map((e) => {
83
+ const local = e.localSigns.filter((s) => existsSync(join(root, s)));
84
+ const global = e.homeSigns.filter((s) => existsSync(join(home, s)));
85
+ return {
86
+ ...e,
87
+ detected: local.length > 0 || global.length > 0,
88
+ evidence: [
89
+ ...local.map((s) => `./${s}`),
90
+ ...global.map((s) => `~/${s}`),
91
+ ],
92
+ };
93
+ });
94
+ }
95
+
96
+ // Tier derivation. The person is asked about the WORLD, never about MinSec.
97
+ // Nobody should have to read a security matrix to start a website.
98
+ export function deriveTier({ collectsPersonalData, authenticates, payments, regulated }) {
99
+ if (payments || regulated) {
100
+ return {
101
+ tier: 'high',
102
+ because: payments ? 'the site handles payments' : 'the site handles regulated data',
103
+ adds: [
104
+ 'Data Risk Assessment before deployment',
105
+ 'administrative access only from a privileged access workstation',
106
+ 'PCI DSS, HIPAA, FISMA, or export controls as applicable',
107
+ 'everything in the moderate tier',
108
+ ],
109
+ };
110
+ }
111
+ if (collectsPersonalData || authenticates) {
112
+ return {
113
+ tier: 'moderate',
114
+ because: authenticates ? 'the site authenticates users' : 'the site collects personal information',
115
+ adds: [
116
+ 'Duo two-step for all users and administrators',
117
+ 'centralised logging',
118
+ 'secure SDLC: security as a design requirement, code review, static analysis',
119
+ 'annual developer training',
120
+ 'weekly encrypted backups',
121
+ ],
122
+ };
123
+ }
124
+ return {
125
+ tier: 'low',
126
+ because: 'the site shows public information only',
127
+ adds: [
128
+ 'patch high-severity findings within 7 days, others within 90',
129
+ 'monthly vulnerability scanning',
130
+ 'quarterly inventory with risk class',
131
+ 'quarterly account and privilege review',
132
+ 'least-privilege administrative accounts',
133
+ ],
134
+ };
135
+ }
@@ -0,0 +1,553 @@
1
+ // File emission.
2
+ //
3
+ // Two rules that shape everything here:
4
+ //
5
+ // 1. Per-editor files are THIN POINTERS, never content copies. There is then no
6
+ // place for content to diverge, and no reason to regenerate anything later.
7
+ // 2. Every emitted file is self-sufficient about being a pointer, because
8
+ // precedence and merge order are not uniform across editors and layering
9
+ // cannot be relied on.
10
+
11
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, rmSync, rmdirSync } from 'node:fs';
12
+ import { createHash } from 'node:crypto';
13
+ import { join, dirname, sep } from 'node:path';
14
+
15
+ const POINTER = (target) => `<!--
16
+ Stanford Web Services agent team.
17
+
18
+ This file is a POINTER, not content. The behavioral contract is ${target},
19
+ and the team is in .agents/skills/ and .claude/skills/.
20
+
21
+ Editing this file will not change how the agent behaves. Edit ${target}.
22
+ -->
23
+
24
+ @${target}
25
+ `;
26
+
27
+ // The two paths skills are read from. Neither is read by every editor, so two
28
+ // copies is the floor rather than a design flaw -- see docs/skill-paths.md.
29
+ export const SKILL_TARGETS = ['.agents/skills', '.claude/skills'];
30
+
31
+ const skillNames = (source) => readdirSync(join(source, 'skills'))
32
+ .filter((d) => existsSync(join(source, 'skills', d, 'SKILL.md')));
33
+
34
+ export function plan({ root, source, editors, answers, tier, scope = 'project' }) {
35
+ const files = [];
36
+ const add = (path, contents, note, opts = {}) => files.push({ path, contents, note, ...opts });
37
+
38
+ // ---- user scope: the skills, and nothing else ---------------------------
39
+ //
40
+ // Paths stay RELATIVE. The only thing separating a user install from a project
41
+ // one is the `root` they are written under -- a home directory or a repository
42
+ // -- so every hash, verdict and record mechanism below serves both with no
43
+ // second implementation.
44
+ //
45
+ // Nothing per-site is emitted here, because at this point there is no site.
46
+ if (scope === 'user') {
47
+ for (const target of SKILL_TARGETS) {
48
+ for (const name of skillNames(source)) {
49
+ add(`${target}/${name}/SKILL.md`,
50
+ readFileSync(join(source, 'skills', name, 'SKILL.md'), 'utf8'), null);
51
+ }
52
+ }
53
+ return files;
54
+ }
55
+
56
+ // ---- project scope: the contract, the standards, the per-site record ----
57
+ //
58
+ // NO SKILLS HERE. They install once into the person's tool instead, because
59
+ // they are byte-identical in every repository and referencing them in place is
60
+ // not available: most editors that read .agents/skills offer no configurable
61
+ // 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');
64
+
65
+ const skills = skillNames(source);
66
+
67
+ // Standards, vendored so the project is self-contained and reviewable.
68
+ const walk = (d, base) => {
69
+ for (const n of readdirSync(d)) {
70
+ const p = join(d, n);
71
+ if (statSync(p).isDirectory()) walk(p, `${base}/${n}`);
72
+ else add(`${base}/${n}`, readFileSync(p, 'utf8'), null);
73
+ }
74
+ };
75
+ walk(join(source, 'standards'), 'standards');
76
+
77
+ // PROJECT STATE, NOT CONTENT. These two accumulate real answers, resolved
78
+ // versions, recorded divergences, and accepted risks with review dates. They
79
+ // are never overwritten once they exist.
80
+ //
81
+ // This was a data-loss bug, and an agent-shaped one: a re-run "to be sure the
82
+ // install happened" replaced real business-owner and technical-administrator
83
+ // emails with nulls. MinWeb requires both to be identifiable, so the wizard
84
+ // was quietly undoing the one thing it exists to record. Everything else here
85
+ // is content and is safe to rewrite.
86
+ add('.sws/manifest.yml', manifestYaml({ answers, tier, editors, skills: skills.length }),
87
+ 'what this project is, and what was decided', { preserve: true });
88
+ add('.sws/acknowledged.yml', ACKNOWLEDGED_TEMPLATE,
89
+ 'accepted risks, with reasons and review dates', { preserve: true });
90
+
91
+ // ---- per editor, thin pointers only -------------------------------------
92
+ for (const e of editors) {
93
+ for (const f of e.emits) {
94
+ if (files.some((x) => x.path === f)) continue;
95
+ const c = pointerFor(f);
96
+ if (c !== null) add(f, c, `for ${e.label}`);
97
+ }
98
+ }
99
+
100
+ return files;
101
+ }
102
+
103
+ function pointerFor(path) {
104
+ if (path === 'CLAUDE.md' || path === 'GEMINI.md') return POINTER('AGENTS.md');
105
+
106
+ if (path === '.github/copilot-instructions.md') {
107
+ return `<!-- Pointer. The contract is AGENTS.md; skills are in .claude/skills/. -->
108
+
109
+ Follow the Stanford Web Services agent contract in \`AGENTS.md\` at the repository
110
+ root, and the standards in \`standards/\`.
111
+
112
+ Non-negotiables: WCAG 2.1 AA, the Global Footer is immutable
113
+ (\`standards/fragments/global-footer.yml\`), never commit credentials.
114
+ `;
115
+ }
116
+
117
+ if (path === '.cursor/rules/sws.mdc') {
118
+ // .mdc is mandatory here; a .md file is silently ignored by Cursor.
119
+ return `---
120
+ description: Stanford Web Services standards
121
+ alwaysApply: true
122
+ ---
123
+
124
+ Follow the agent contract in \`AGENTS.md\` at the repository root. Skills are in
125
+ \`.agents/skills/\`. Standards are in \`standards/\`.
126
+
127
+ Non-negotiables: WCAG 2.1 AA, the Global Footer is immutable
128
+ (\`standards/fragments/global-footer.yml\`), never commit credentials.
129
+ `;
130
+ }
131
+
132
+ if (path === '.devin/rules/sws.md') {
133
+ return `---
134
+ trigger: always_on
135
+ description: Stanford Web Services standards
136
+ ---
137
+
138
+ Follow the agent contract in \`AGENTS.md\`. Skills are in \`.agents/skills/\`.
139
+ `;
140
+ }
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
+ return null;
172
+ }
173
+
174
+ function manifestYaml({ answers, tier, editors, skills }) {
175
+ const q = (s) => (s ? JSON.stringify(String(s)) : 'null');
176
+ return `# What this project is, and what was decided when it was set up.
177
+ # Read by sws-onboard and the sws CLI. Safe to edit by hand.
178
+
179
+ standards_version: 0.1.0
180
+ recipe: ${answers.recipe}
181
+ created: ${new Date().toISOString().slice(0, 10)}
182
+
183
+ # Compliance tier, DERIVED from what the site handles rather than chosen.
184
+ # Changing what the site does can change the tier. Adding a form that collects
185
+ # personal data, an authentication flow, or a payment processor is a TIER
186
+ # CHANGE, not a feature.
187
+ tier: ${tier.tier}
188
+ tier_because: ${q(tier.because)}
189
+
190
+ site:
191
+ name: ${q(answers.siteName)}
192
+ unit: ${q(answers.unit)}
193
+ purpose: ${q(answers.purpose)}
194
+ url: ${q(answers.url)}
195
+
196
+ # MinWeb requires both, discoverable on the site, with valid Stanford affiliation.
197
+ owners:
198
+ business:
199
+ name: ${q(answers.businessOwnerName)}
200
+ email: ${q(answers.businessOwnerEmail)}
201
+ technical:
202
+ name: ${q(answers.techAdminName)}
203
+ email: ${q(answers.techAdminEmail)}
204
+
205
+ # WHERE THIS SITE IS SERVED. SWS runs BOTH Netlify and Vercel, one per family,
206
+ # so neither is a divergence -- pick whichever the unit already administers.
207
+ # Profiles, with what each host does and does not cover:
208
+ # standards/hosting/. Leave provider null until the choice is made.
209
+ #
210
+ # Recording this matters more than it looks. Until 2026-09-03 this project
211
+ # believed Netlify was the only SWS host, because hosting was inferred from
212
+ # package.json and package.json does not record a deploy target.
213
+ hosting:
214
+ provider: null # github-pages | netlify | vercel
215
+ production_url: null # the approved Stanford subdomain, NOT a *.vercel.app
216
+ # or *.netlify.app preview domain
217
+ dashboard_mfa: null # set to the date MFA was confirmed on the host account.
218
+ # MinWeb's "MFA on all administrative logins" includes
219
+ # the hosting dashboard, which is the most-missed item.
220
+ csp: false # OPTIONAL and off by default. A CSP breaks pages at
221
+ # content-edit time, so if you enable it, record it in
222
+ # divergences and name who owns the breakage.
223
+
224
+ # Required for public-facing Stanford sites. Google Analytics is NOT required.
225
+ siteimprove:
226
+ registered: null # set to the date once the intake form is submitted
227
+
228
+ # Set by the ODA accessibility review, which is a pre-launch gate with a lead time.
229
+ accessibility:
230
+ standard: WCAG 2.1 AA
231
+ oda_review_requested: null
232
+
233
+ editors:
234
+ ${editors.map((e) => ` - ${e.id}`).join('\n') || ' []'}
235
+
236
+ # Skills are installed at USER scope (~/.claude/skills, ~/.agents/skills), once
237
+ # per machine, not into this project. This is the count that was available when
238
+ # this project was set up, recorded as provenance -- it is not a count of files
239
+ # in this repository, and nothing reads it as one.
240
+ skills_available_at_install: ${skills}
241
+
242
+ # What actually resolved at install time. Recorded, never enforced: recipes
243
+ # install latest and pin nothing, so this is provenance rather than a gate.
244
+ resolved:
245
+ node: ${q(process.versions.node)}
246
+
247
+ # 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.
249
+ # A CMS is not a divergence you can record here -- it is out of scope, which is
250
+ # a different thing. If a project needs one, raise it rather than recording it.
251
+ content:
252
+ source: repo
253
+ cms: none
254
+
255
+ # What was reused from existing SWS work, so the next person can trace it.
256
+ prior_art: []
257
+
258
+ # Deliberate departures from the recipe. Each needs a reason. Silent divergence
259
+ # is the only kind that is a problem. See the sws-diverge skill.
260
+ divergences: []
261
+ `;
262
+ }
263
+
264
+ const ACKNOWLEDGED_TEMPLATE = `# Accepted risks.
265
+ #
266
+ # When a finding cannot be fixed now, record it here rather than ignoring it.
267
+ # It then moves out of the nag and into an "accepted risks" section of the
268
+ # report, and it still counts toward the score with the total annotated.
269
+ #
270
+ # This is the same shape a MinSec temporary exception takes, so the record is
271
+ # useful beyond this tool. Expired review dates resurface once.
272
+ #
273
+ # - check: a11y.contrast
274
+ # path: src/components/Legacy.astro
275
+ # reason: Vendor widget; contrast fix requested from vendor 2026-08-04
276
+ # accepted_by: you@stanford.edu
277
+ # date: 2026-08-11
278
+ # review_by: 2026-11-10
279
+
280
+ []
281
+ `;
282
+
283
+ /**
284
+ * Write, and report what happened to each file.
285
+ *
286
+ * THIS IS ALSO THE UPDATE MECHANISM. There is no separate `sws update`: a
287
+ * re-install IS the update, because the content is vendored into the project
288
+ * rather than resolved at runtime. That only works safely if three things are
289
+ * true, and each is a per-file verdict below.
290
+ *
291
+ * preserved Project state is never overwritten. `.sws/manifest.yml` and
292
+ * `.sws/acknowledged.yml` accumulate real owners, resolved
293
+ * versions, recorded divergences and accepted risks. An earlier
294
+ * version of this function replaced real business-owner emails
295
+ * with nulls on a re-run, which is the one thing the wizard exists
296
+ * to record.
297
+ *
298
+ * conflict A file the user EDITED is never silently overwritten. Detected by
299
+ * comparing against `.sws/installed.json`, a record of the hashes
300
+ * this tool last wrote. If the file on disk no longer matches that
301
+ * record, the edit was somebody's deliberate work, and an update
302
+ * that discards it is data loss with extra steps. Reported and
303
+ * skipped; `force` overrides.
304
+ *
305
+ * orphan A file that this tool wrote before and no longer ships is
306
+ * reported, NOT deleted. Deleting files in someone else's
307
+ * repository on the strength of a version bump is not a risk worth
308
+ * taking for tidiness.
309
+ *
310
+ * Comparison is by content, never mtime: re-running the same version must be
311
+ * `unchanged` even though the source files have newer timestamps.
312
+ */
313
+ export function write(root, files, { force = false, version = null, scope = 'project' } = {}) {
314
+ const prev = readInstalled(root);
315
+ const planned = new Set(files.map((f) => f.path));
316
+ const results = [];
317
+ const nextHashes = {};
318
+
319
+ for (const f of files) {
320
+ const p = join(root, f.path);
321
+ const newHash = hash(f.contents);
322
+ let status;
323
+
324
+ if (!existsSync(p)) {
325
+ status = 'created';
326
+ } else {
327
+ const local = readFileSync(p, 'utf8');
328
+ if (f.preserve) status = 'preserved';
329
+ else if (local === f.contents) status = 'unchanged';
330
+ else {
331
+ const recorded = prev?.files?.[f.path];
332
+ // No record means we cannot tell an edit from an old version, so the
333
+ // safe default is to update. Conflict detection needs evidence.
334
+ const edited = recorded !== undefined && hash(local) !== recorded;
335
+ status = edited && !force ? 'conflict' : 'updated';
336
+ }
337
+ }
338
+
339
+ if (status === 'created' || status === 'updated') {
340
+ mkdirSync(dirname(p), { recursive: true });
341
+ writeFileSync(p, f.contents);
342
+ nextHashes[f.path] = newHash;
343
+ } else if (status === 'conflict') {
344
+ // Keep the hash of what we LAST WROTE, never what is on disk now.
345
+ //
346
+ // Recording the edited file as though we had written it made the conflict
347
+ // disappear on the following run -- and the protection with it, so the run
348
+ // after that reported `updated` and overwrote the edit. Verified before
349
+ // this change: an edited 7356-byte skill came back as the canonical 7355
350
+ // bytes on run three, silently. That contradicted this function's own
351
+ // contract, which is that an edited file is never silently overwritten.
352
+ //
353
+ // So a conflict is sticky until the file matches what we ship again. That
354
+ // is already how orphans behave a few lines below, for the same stated
355
+ // reason: a one-shot warning is easy to miss, and an agent discards the
356
+ // output entirely. It is also what makes `remove()` safe, since the record
357
+ // stays a description of OUR content rather than drifting onto theirs.
358
+ nextHashes[f.path] = prev?.files?.[f.path] ?? newHash;
359
+ } else {
360
+ nextHashes[f.path] = existsSync(p) ? hash(readFileSync(p, 'utf8')) : newHash;
361
+ }
362
+ results.push({ path: f.path, status });
363
+ }
364
+
365
+ const orphans = Object.keys(prev?.files ?? {}).filter((x) => !planned.has(x) && existsSync(join(root, x)));
366
+
367
+ // Keep orphans in the record while the file still exists, so they are reported
368
+ // on EVERY run rather than once. A one-shot warning is easy to miss -- an agent
369
+ // discards the output, a human scrolls past it -- and then a stale standard
370
+ // sits in the project looking authoritative. Same instinct as resurfacing an
371
+ // expired `review_by` date: the nag stops when the situation is resolved, not
372
+ // when it has been seen once.
373
+ for (const x of orphans) nextHashes[x] = prev.files[x];
374
+
375
+ writeInstalled(root, { version, files: nextHashes, scope });
376
+
377
+ const count = (s) => results.filter((r) => r.status === s).length;
378
+ return {
379
+ results,
380
+ orphans,
381
+ previousVersion: prev?.version ?? null,
382
+ created: count('created'),
383
+ updated: count('updated'),
384
+ unchanged: count('unchanged'),
385
+ preserved: count('preserved'),
386
+ conflicts: results.filter((r) => r.status === 'conflict').map((r) => r.path),
387
+ };
388
+ }
389
+
390
+ // --- the install record ----------------------------------------------------
391
+ //
392
+ // Committed, not gitignored: it is a record of what this tool put in the
393
+ // repository, in the same spirit as a lockfile. Hashes are truncated because
394
+ // their only job is to answer "has this changed since we wrote it".
395
+
396
+ export const INSTALLED_PATH = join('.sws', 'installed.json');
397
+
398
+ const hash = (s) => createHash('sha256').update(s).digest('hex').slice(0, 12);
399
+
400
+ export function readInstalled(root) {
401
+ const p = join(root, INSTALLED_PATH);
402
+ if (!existsSync(p)) return null;
403
+ try {
404
+ const j = JSON.parse(readFileSync(p, 'utf8'));
405
+ return j && typeof j.files === 'object' ? j : null;
406
+ } catch {
407
+ // A corrupt record means we lose conflict detection for one run, which is
408
+ // survivable. Silently starting over beats refusing to install.
409
+ return null;
410
+ }
411
+ }
412
+
413
+ function writeInstalled(root, { version, files, scope = 'project' }) {
414
+ // The advice differs by scope, and getting it wrong matters: "commit this" is
415
+ // right in a repository and nonsense in a home directory.
416
+ const advice = scope === 'user'
417
+ ? 'Do not delete while the skills are installed: `install --remove` reads this to '
418
+ + 'know which files are ours, and without it an uninstall cannot tell your '
419
+ + 'skills from ours and so removes nothing.'
420
+ : 'Commit this. Safe to delete: you lose conflict detection until the next install.';
421
+
422
+ mkdirSync(join(root, '.sws'), { recursive: true });
423
+ writeFileSync(join(root, INSTALLED_PATH), `${JSON.stringify({
424
+ _comment: 'Written by @su-sws/synthetic-web-team. Records what was installed so a '
425
+ + `re-install can tell an update from a local edit. ${advice}`,
426
+ tool: '@su-sws/synthetic-web-team',
427
+ scope,
428
+ version,
429
+ at: new Date().toISOString(),
430
+ files,
431
+ }, null, 2)}\n`);
432
+ }
433
+
434
+ /**
435
+ * Uninstall, driven entirely by the install record.
436
+ *
437
+ * WHY THE RECORD IS THE ONLY INPUT. A user-scope install writes into a home
438
+ * directory that already holds other people's work -- 584 unrelated skills on
439
+ * the machine this was developed on. Deleting `~/.claude/skills` wholesale, or
440
+ * anything matched by pattern, would take those with it. So the ONLY files
441
+ * eligible for removal are ones `.sws/installed.json` says we wrote, and the
442
+ * hash has to still match.
443
+ *
444
+ * Three verdicts, mirroring the install:
445
+ *
446
+ * removed we wrote it, it is unchanged, it is gone
447
+ * kept we wrote it and it was EDITED since. Their edit is their work, so
448
+ * it stays and is reported. `force` overrides.
449
+ * missing already gone. Not an error; someone tidied up before us.
450
+ *
451
+ * Empty directories we created are pruned, deepest first, and only when empty
452
+ * -- so a skills directory that still holds anything else survives.
453
+ */
454
+ export function remove(root, { dryRun = false, force = false } = {}) {
455
+ const prev = readInstalled(root);
456
+ if (!prev) return { status: 'no-record', removed: [], kept: [], missing: [] };
457
+
458
+ const removed = [];
459
+ const kept = [];
460
+ const missing = [];
461
+
462
+ for (const [rel, recorded] of Object.entries(prev.files ?? {})) {
463
+ const p = join(root, rel);
464
+ if (!existsSync(p)) { missing.push(rel); continue; }
465
+ if (!force && hash(readFileSync(p, 'utf8')) !== recorded) { kept.push(rel); continue; }
466
+ if (!dryRun) rmSync(p);
467
+ removed.push(rel);
468
+ }
469
+
470
+ 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
+ }
483
+
484
+ // Keep a record only while something of ours is still on disk, so a second
485
+ // run can still tell our files from theirs.
486
+ const recordPath = join(root, INSTALLED_PATH);
487
+ if (kept.length) {
488
+ writeInstalled(root, {
489
+ version: prev.version ?? null,
490
+ scope: prev.scope ?? 'project',
491
+ files: Object.fromEntries(kept.map((k) => [k, prev.files[k]])),
492
+ });
493
+ } else if (existsSync(recordPath)) {
494
+ rmSync(recordPath);
495
+ try { rmdirSync(join(root, '.sws')); } catch { /* other state lives there */ }
496
+ }
497
+ }
498
+
499
+ return { status: 'ok', removed, kept, missing, scope: prev.scope ?? 'project' };
500
+ }
501
+
502
+ // --- the project's dependency on this package ------------------------------
503
+ //
504
+ // WHY THIS EXISTS. Every verify step this tool documents is spelled
505
+ // `npx sws ...`, and unscoped `sws` is an UNRELATED package on the public
506
+ // registry (sws@0.0.2, not ours). With no local dependency there is no
507
+ // node_modules/.bin/sws to shadow it, so `npx sws doctor` in a fresh project
508
+ // fetches a stranger's code. Declaring the dependency makes `npx sws` resolve
509
+ // locally, and it is also how `sws doctor` can tell that a project is behind.
510
+ //
511
+ // package.json is NOT ours, so this is a targeted merge and never a rewrite:
512
+ // one key added, the file's own indentation kept, an existing declaration left
513
+ // alone, and NO entry in installed.json -- a file the user edits constantly
514
+ // must not be under conflict detection.
515
+ //
516
+ // Caveat, stated because it is the one real cost: the JSON round-trip
517
+ // normalises formatting, so an unusual layout will reformat. This is the same
518
+ // thing `npm install --save` does to the same file.
519
+ export function ensureDevDependency(root, { name, range, dryRun = false } = {}) {
520
+ const p = join(root, 'package.json');
521
+ if (!existsSync(p)) return { status: 'no-package-json' };
522
+
523
+ // No resolved version means no honest range to write. Writing `*` or a
524
+ // dist-tag to dodge that is the placeholder problem this file avoids
525
+ // everywhere else, so it reports instead.
526
+ if (!range) return { status: 'skipped-unknown-version' };
527
+
528
+ let raw;
529
+ let json;
530
+ try {
531
+ raw = readFileSync(p, 'utf8');
532
+ json = JSON.parse(raw);
533
+ if (!json || typeof json !== 'object' || Array.isArray(json)) throw new Error('not a JSON object');
534
+ } catch (err) {
535
+ return { status: 'unparseable', detail: err.message };
536
+ }
537
+
538
+ // An existing declaration wins, in either block. A pin someone chose is a
539
+ // decision, and quietly "upgrading" it is the same data loss this module
540
+ // guards against for .sws/manifest.yml.
541
+ const existing = json.devDependencies?.[name] ?? json.dependencies?.[name];
542
+ if (existing) return { status: 'present', range: existing };
543
+
544
+ if (dryRun) return { status: 'would-add', range };
545
+
546
+ const indent = raw.match(/\n(\s+)"/)?.[1] ?? ' ';
547
+ json.devDependencies = Object.fromEntries(
548
+ Object.entries({ ...(json.devDependencies ?? {}), [name]: range })
549
+ .sort(([a], [b]) => a.localeCompare(b)));
550
+ const out = JSON.stringify(json, null, indent);
551
+ writeFileSync(p, raw.endsWith('\n') ? `${out}\n` : out);
552
+ return { status: 'added', range };
553
+ }