@se-studio/skills 1.10.27 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # @se-studio/skills
2
2
 
3
+ ## 1.13.1
4
+
5
+ ### Patch Changes
6
+
7
+ - cd4c17c: Redirects skill: `skeleton:check` now enforces the live redirect path (the redirects-sync route and sitemap routes that call `getRedirectMap`), and the rollout checks can be skipped only with an expiry date and owner. PHILOSOPHY R6.9 to R6.11 (live redirects, the fail-closed sync route, project-scoped credentials) are approved.
8
+
9
+ ## 1.13.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 24262f4: `fleet-audit` flags a site that still carries a local `scripts/check-cms-driven.mjs`, a `cms-driven.baseline.json` with more than 25 violations ("needs work"), and a baseline that has not changed in 90 days with debt still in it.
14
+ - 4163446: `fleet-audit` lists sites in remake mode with their deadline and flags a remake window that has passed but is still in `cms-driven.config.json`. The customer-simplicity skill points at the new `check-cms-driven` R3/R4 enforcement.
15
+
16
+ ## 1.12.0
17
+
18
+ ### Minor Changes
19
+
20
+ - dfa21ee: New `se-agent-guard doctor`: checks that a checkout is actually protected. It runs the guard-health checks from `fleet-audit` on the working tree and adds local-only ones: missing `node_modules`, installed version differs from the exact pin (or not installed), git not running the shipped hooks (or a hook not executable), the guard bin missing, dangling skill links in `.agents/skills` and the per-agent directories, stale copied skills left by `skills add`, and broken relative links in installed or repo-owned skills (resolved from the skill's real location). Exit 0 healthy, 1 problems, 2 could not run. It reads only small regular files whose real path stays under the repo or its `node_modules`, so a hostile repo can neither hang it with a device or FIFO symlink nor make it read files outside the repo. It reads `CI` the same way the guard does. `fleet-audit`'s file selection is now the exported `wantedPaths`, shared with the doctor.
21
+
22
+ ## 1.11.0
23
+
24
+ ### Minor Changes
25
+
26
+ - 3b685dd: `pnpm skills:validate` now fails on broken relative links in every markdown file of a skill (`SKILL.md` and nested references). A link must point at a file with exactly matching case, and a link in a published skill must point at something the package actually ships (its `files` list: `skills`, `references`, `agent-guard`, root `*.md`), so a core-repo path or a `core-only` skill can never be linked. The checker (`agent-guard/skill-links.mjs`) skips URLs, anchors, templates and code, and reports a malformed `%` escape as a broken link instead of crashing. Fixes two wrong paths and turns core-repo paths in `coding-discipline` and five other skills (plus one directory link) into plain code text.
27
+
3
28
  ## 1.10.27
4
29
 
5
30
  ### Patch Changes
@@ -30,6 +30,29 @@ Grok and Cursor rely on the git hooks and the CI audit. Add thin adapters that c
30
30
  - For `gh pr merge`, checks **every** merge in the command against the merge gate. Any failure denies. If `gh` cannot be reached it asks. When all pass it allows without asking: the approval comment is the confirmation.
31
31
  - A malformed hook payload exits 0 (never breaks the session).
32
32
 
33
+ ## Doctor: is this checkout protected?
34
+
35
+ ```bash
36
+ pnpm exec se-agent-guard doctor
37
+ ```
38
+
39
+ Run it in a repo or worktree whose **root** `package.json` has `@se-studio/skills` as a dependency (the hooks run `pnpm exec se-agent-guard` from the repo root; without it you get a single `skills-dependency-missing` finding). It exits 0 when healthy, 1 with one line per problem, and 2 when it could not run (not a git repo, git missing, or an unexpected failure). `fleet-audit` finds the same class of problem from remote refs; the doctor finds it on the machine where it bites, including uncommitted state.
40
+
41
+ It reuses the guard-health checks from `fleet-audit` on the working tree (a hook that does not call the guard, a missing Claude hook or merge audit, a pin that is not exact, skills linked by the old sync, tracked skill symlinks) and adds checks only a local run can do:
42
+
43
+ | Finding | Meaning |
44
+ |---|---|
45
+ | `node-modules-missing` | no install: the git hooks fail closed, the Claude hook fails open |
46
+ | `pin-not-installed` | `node_modules` holds a different version than the exact pin in `package.json` |
47
+ | `guard-bin-missing` | `node_modules/.bin/se-agent-guard` is absent, so the hooks cannot run |
48
+ | `hooks-not-installed`, `hook-not-active` | the repo ships a hook but git is not running it (`core.hooksPath` unset, or no wrapper for it) |
49
+ | `hook-not-executable` | the active hook file lacks the execute bit |
50
+ | `skills-not-linked`, `skills-link-dangling` | `.agents/skills` is empty or has links to nothing, in it or in `.claude/skills`, `.cursor/skills`, `.grok/skills` (run `skills-npm --yes`) |
51
+ | `skills-stale-copy` | a package skill in `.agents/skills` or an agent skills directory is a real copy (left by `skills add`), not a link into the pinned package |
52
+ | `skill-link-broken`, `own-skill-link-broken`, `skill-unreadable` | a relative link in an installed skill, or in a skill the repo owns (including per-entry skills under `.claude/skills`), points at a missing file, or a `SKILL.md` cannot be read. Links are resolved from the skill's real location, the way an agent reads them |
53
+
54
+ The skills checks are skipped when `CI` is set (anything but `false`, the same rule the guard uses) or `VERCEL` is set, because `skills-npm` does not run there. Every file the doctor reads must be a regular file under 1 MB whose real path stays under the repo or its `node_modules` (which a worktree may symlink to a shared install), so a hook or `SKILL.md` that is a symlink to a device, a FIFO or a file outside the repo is not read. Review-doc copies, wording and deploy-script findings stay in `fleet-audit`: they are hygiene, not guard health.
55
+
33
56
  ## Merge gate
34
57
 
35
58
  `merge-gate.mjs <pr>`: the PR needs a `## Merge approval` comment that names the current head SHA and cites a review. **Anyone** may post it (Nick's decision, 30 Oct 2026: what matters is that the PR was reviewed, not who clicks approve), so the author is not checked. The review is: a link into this PR to a review comment (agent or human; its first heading says "review", it names the head SHA, it gives a verdict such as PASS/BLOCKERS/NITs/LGTM, and it was posted strictly before the approval), or a line that is exactly `none, Nick override`. The head SHA match is the full SHA or a prefix of at least 12 hex characters. A later lint, typecheck, test, or format push may keep that review only when the review names the current head that way; a different hex string shared with the approval does not. A production promote (`dev` → `main`, or `develop` → `main` / `production`, and `isCrossRepository` false) may instead use a whole line `CI covers the changes since` and does not need a review comment on that PR (Nick, 4 Nov 2026: no second AI review; CI covers the commits since the feature review). `dev` → `production` and a fork head do not. Words after that line do not count. Links to PR reviews (`#pullrequestreview-N`) are not accepted because `gh` returns no numeric review id to match them to; post the review as a comment. A bare "reviewed", an external link, a link to a comment that does not exist, a review of an older SHA, a `#pullrequestreview-` link, a minimized comment, or the approval citing itself all fail. Also: not a draft, not "do not merge". `--audit` labels `pushed-through` after a breach and comments that no post-merge AI review will run.
@@ -8,6 +8,7 @@
8
8
  * se-agent-guard merge-gate <pr> [--audit]
9
9
  * se-agent-guard core-request --from <key> --feature <slug> --why "..." file a tracked Core request
10
10
  * se-agent-guard worktrees-clean [--apply] [--remote] remove merged worktrees and branches
11
+ * se-agent-guard doctor is this checkout protected? hooks, installs, pins, skills links
11
12
  */
12
13
  import { spawnSync } from 'node:child_process';
13
14
  import path from 'node:path';
@@ -20,6 +21,7 @@ const SUBCOMMANDS = {
20
21
  'merge-gate': ['merge-gate.mjs', []],
21
22
  'core-request': ['core-request.mjs', []],
22
23
  'worktrees-clean': ['worktrees-clean.mjs', []],
24
+ doctor: ['doctor.mjs', []],
23
25
  };
24
26
 
25
27
  const [sub, ...rest] = process.argv.slice(2);
@@ -0,0 +1,367 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `se-agent-guard doctor`: is this checkout actually protected? Run it in a repo (or worktree)
4
+ * that depends on @se-studio/skills. `fleet-audit` finds these problems from remote refs; this
5
+ * finds them on the machine where they bite: a hook git is not running, a missing node_modules,
6
+ * a skills link that points at nothing.
7
+ *
8
+ * The policy checks are `auditFiles` from fleet-audit, fed the working tree instead of a remote
9
+ * ref, so there is one definition of "a correct customer repo". The rest are local-only.
10
+ * Everything it reads is repo-controlled, so every read goes through `isReadable`: the file must
11
+ * be regular (not a device or FIFO, which would hang a read), small, and its real path must stay
12
+ * under the repo or its node_modules. Content from outside is never read, so it cannot be printed.
13
+ *
14
+ * se-agent-guard doctor exit 0 healthy, 1 problems found, 2 could not run
15
+ */
16
+ import { execFileSync } from 'node:child_process';
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { auditFiles, wantedPaths } from '../references/agent-session/fleet-audit.mjs';
22
+ import { inCi } from './rules.mjs';
23
+ import { findBrokenLinks } from './skill-links.mjs';
24
+
25
+ const SKILLS = '@se-studio/skills';
26
+ const HOOKS = ['pre-commit', 'pre-push'];
27
+ const AGENT_SKILL_DIRS = ['.claude/skills', '.cursor/skills', '.grok/skills'];
28
+ const MAX_FILE_BYTES = 1024 * 1024;
29
+ const MAX_GIT_OUTPUT = 64 * 1024 * 1024;
30
+
31
+ /**
32
+ * The fleet checks that say whether the guard and the pinned skills work. The rest of
33
+ * `auditFiles` (review-doc copies, wording, deploy scripts) is fleet hygiene: `fleet-audit`
34
+ * reports it, and burying a broken hook under it would hide the one thing doctor is for.
35
+ */
36
+ export const GUARD_HEALTH_FINDINGS = new Set([
37
+ 'hook-commit-missing',
38
+ 'hook-push-missing',
39
+ 'claude-hook-missing',
40
+ 'merge-audit-missing',
41
+ 'pin-not-exact',
42
+ 'skills-too-old',
43
+ 'skills-npm-missing',
44
+ 'skills-sync-legacy',
45
+ 'skills-links-tracked',
46
+ 'skills-update-script',
47
+ ]);
48
+
49
+ const safeJson = (text) => {
50
+ try {
51
+ return JSON.parse(text);
52
+ } catch {
53
+ return null;
54
+ }
55
+ };
56
+
57
+ function git(root, args) {
58
+ return execFileSync('git', args, {
59
+ cwd: root,
60
+ encoding: 'utf8',
61
+ maxBuffer: MAX_GIT_OUTPUT,
62
+ stdio: ['ignore', 'pipe', 'ignore'],
63
+ });
64
+ }
65
+
66
+ /** Does the path exist once symlinks are followed? A dangling link is false. */
67
+ const resolves = (p) => fs.existsSync(p);
68
+
69
+ const within = (real, base) => real === base || real.startsWith(base + path.sep);
70
+
71
+ /**
72
+ * Is it safe to read? A regular file (a device or FIFO would hang the read), not huge, and whose
73
+ * real path is under one of `bases`.
74
+ * @param {string} file
75
+ * @param {string[]} bases real paths
76
+ */
77
+ function isReadable(file, bases) {
78
+ try {
79
+ const stat = fs.statSync(file);
80
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return false;
81
+ const real = fs.realpathSync(file);
82
+ return bases.some((base) => within(real, base));
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ const readRegular = (file, bases) =>
89
+ isReadable(file, bases) ? fs.readFileSync(file, 'utf8') : null;
90
+
91
+ const readJson = (file, bases) => safeJson(readRegular(file, bases) ?? '');
92
+
93
+ const realOrNull = (p) => {
94
+ try {
95
+ return fs.realpathSync(p);
96
+ } catch {
97
+ return null;
98
+ }
99
+ };
100
+
101
+ function listDir(dir) {
102
+ try {
103
+ return fs.readdirSync(dir).filter((name) => !name.startsWith('.'));
104
+ } catch {
105
+ return []; // missing, or not a directory
106
+ }
107
+ }
108
+
109
+ /**
110
+ * The skills the agents can see: entries of .agents/skills and of the per-agent directories,
111
+ * each once (the agent directories usually link to .agents/skills).
112
+ * @returns {{ dangling: string[], skills: { name: string, rel: string, real: string, isLink: boolean }[] }}
113
+ */
114
+ function visibleSkills(root) {
115
+ const dangling = [];
116
+ const skills = [];
117
+ const seen = new Set();
118
+ for (const dirRel of ['.agents/skills', ...AGENT_SKILL_DIRS]) {
119
+ const dir = path.join(root, dirRel);
120
+ try {
121
+ fs.lstatSync(dir);
122
+ } catch {
123
+ continue; // the directory is optional
124
+ }
125
+ if (!resolves(dir)) {
126
+ dangling.push(dirRel);
127
+ continue;
128
+ }
129
+ for (const name of listDir(dir)) {
130
+ const entry = path.join(dir, name);
131
+ const rel = `${dirRel}/${name}`;
132
+ if (!resolves(entry)) {
133
+ dangling.push(rel);
134
+ continue;
135
+ }
136
+ const real = fs.realpathSync(entry);
137
+ if (seen.has(real)) continue;
138
+ seen.add(real);
139
+ skills.push({ name, rel, real, isLink: fs.lstatSync(entry).isSymbolicLink() });
140
+ }
141
+ }
142
+ return { dangling, skills };
143
+ }
144
+
145
+ /**
146
+ * @param {{ root: string, env?: Record<string, string | undefined> }} input root: the repo top level
147
+ * @returns {{ findings: { id: string, text: string }[] }}
148
+ */
149
+ export function diagnose({ root, env = process.env }) {
150
+ const findings = [];
151
+ const add = (id, text) => findings.push({ id, text });
152
+
153
+ // Paths come NUL-separated: without -z git quotes non-ASCII names and they would never match.
154
+ const tree = git(root, ['ls-files', '-s', '-z'])
155
+ .split('\0')
156
+ .filter(Boolean)
157
+ .map((entry) => ({
158
+ mode: entry.slice(0, entry.indexOf(' ')),
159
+ path: entry.slice(entry.indexOf('\t') + 1),
160
+ }));
161
+ const untracked = git(root, ['ls-files', '-o', '--exclude-standard', '-z'])
162
+ .split('\0')
163
+ .filter(Boolean);
164
+ const rootReal = fs.realpathSync(root);
165
+ const modules = path.join(root, 'node_modules');
166
+ const modulesReal = realOrNull(modules); // a worktree may symlink this to a shared install
167
+ const bases = modulesReal ? [rootReal, modulesReal] : [rootReal];
168
+ const files = {};
169
+ for (const rel of wantedPaths([...tree.map((t) => t.path), ...untracked])) {
170
+ const body = readRegular(path.join(root, rel), [rootReal]);
171
+ if (body !== null) files[rel] = body;
172
+ }
173
+
174
+ const pkg = files['package.json'] ? safeJson(files['package.json']) : null;
175
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
176
+ if (!(SKILLS in deps)) {
177
+ // Everything below assumes the pinned guard is installed from the root package.json.
178
+ const source = readJson(path.join(root, 'packages/skills/package.json'), [rootReal]);
179
+ add(
180
+ 'skills-dependency-missing',
181
+ !pkg
182
+ ? 'package.json is missing or not valid JSON, so there is no pinned guard to check'
183
+ : source?.name === SKILLS
184
+ ? `this is the source repo of ${SKILLS}: doctor is for repos that depend on it`
185
+ : `${SKILLS} is not a dependency in the root package.json. The hooks run \`pnpm exec se-agent-guard\` from the repo root, so it must be a root devDependency at an exact version`,
186
+ );
187
+ return { findings };
188
+ }
189
+
190
+ // 1. The shared policy checks, on the working tree (uncommitted state included).
191
+ // No remote to compare with: skip "behind core" and "block stale".
192
+ for (const f of auditFiles({ files, tree, coreBlockVersion: 0, coreVersions: {} }).findings) {
193
+ if (GUARD_HEALTH_FINDINGS.has(f.id)) add(f.id, f.text);
194
+ }
195
+
196
+ // 2. Dependencies are installed, and at the pinned version.
197
+ if (!fs.existsSync(modules)) {
198
+ add(
199
+ 'node-modules-missing',
200
+ 'node_modules is missing: run `pnpm install`. The git hooks fail closed without it (commits are refused); the Claude hook fails open.',
201
+ );
202
+ } else {
203
+ for (const [name, spec] of Object.entries(deps)) {
204
+ if (!name.startsWith('@se-studio/') || String(spec).startsWith('workspace:')) continue;
205
+ if (!/^\d+\.\d+\.\d+/.test(String(spec))) continue; // a range is reported by pin-not-exact
206
+ const installed = readJson(path.join(modules, name, 'package.json'), bases)?.version;
207
+ if (installed === undefined) {
208
+ add(
209
+ 'pin-not-installed',
210
+ `${name} is pinned ${spec} but is not installed: run \`pnpm install\``,
211
+ );
212
+ } else if (installed !== spec) {
213
+ add(
214
+ 'pin-not-installed',
215
+ `${name} is pinned ${spec} but ${installed} is installed: run \`pnpm install\``,
216
+ );
217
+ }
218
+ }
219
+ if (!resolves(path.join(modules, '.bin', 'se-agent-guard'))) {
220
+ add(
221
+ 'guard-bin-missing',
222
+ 'node_modules/.bin/se-agent-guard is missing: the hooks call it and will fail. Run `pnpm install`',
223
+ );
224
+ }
225
+ }
226
+
227
+ // 3. Git is actually running the hooks the repo ships.
228
+ const present = HOOKS.filter((name) => `.husky/${name}` in files || `.githooks/${name}` in files);
229
+ if (present.length > 0) {
230
+ let hooksPath = '';
231
+ try {
232
+ hooksPath = git(root, ['config', 'core.hooksPath']).trim();
233
+ } catch {
234
+ // unset
235
+ }
236
+ // Plain `git config` (--type=path needs git 2.18): expand a leading ~ the way git would.
237
+ if (hooksPath === '~' || hooksPath.startsWith('~/')) {
238
+ hooksPath = path.join(os.homedir(), hooksPath.slice(1));
239
+ }
240
+ if (!hooksPath) {
241
+ add(
242
+ 'hooks-not-installed',
243
+ 'git core.hooksPath is not set, so the pre-commit and pre-push guards do not run: run `pnpm install` (the `prepare` script sets it)',
244
+ );
245
+ } else {
246
+ const active = path.resolve(root, hooksPath);
247
+ for (const name of present) {
248
+ const hook = path.join(active, name);
249
+ if (!resolves(hook)) {
250
+ add(
251
+ 'hook-not-active',
252
+ `the repo has a ${name} hook but core.hooksPath (${hooksPath}) has none, so git does not run it: run \`pnpm install\``,
253
+ );
254
+ } else if (!(fs.statSync(hook).mode & 0o111)) {
255
+ add(
256
+ 'hook-not-executable',
257
+ `${hooksPath}/${name} is not executable: run \`chmod +x ${hooksPath}/${name}\``,
258
+ );
259
+ }
260
+ }
261
+ }
262
+ }
263
+
264
+ // 4. Skills are linked from the installed package. skills-npm does not run on Vercel or CI.
265
+ if (!inCi(env) && !env.VERCEL && fs.existsSync(path.join(modules, SKILLS))) {
266
+ if (listDir(path.join(root, '.agents/skills')).length === 0) {
267
+ add(
268
+ 'skills-not-linked',
269
+ '.agents/skills is missing or empty: run `pnpm exec skills-npm --yes`',
270
+ );
271
+ }
272
+ const { dangling, skills } = visibleSkills(root);
273
+ if (dangling.length > 0) {
274
+ add(
275
+ 'skills-link-dangling',
276
+ `${dangling.length} skill link(s) point at nothing (${dangling.slice(0, 3).join(', ')}): run \`pnpm install\`, then \`pnpm exec skills-npm --yes\``,
277
+ );
278
+ }
279
+
280
+ // A real directory in .agents/skills that shares a name with a package skill is a copy left
281
+ // by `skills add`, not a link: its relative links no longer resolve, and it never updates.
282
+ const packaged = new Set(listDir(path.join(modules, SKILLS, 'skills')));
283
+ const copies = skills.filter((s) => !s.isLink && packaged.has(s.name));
284
+ if (copies.length > 0) {
285
+ add(
286
+ 'skills-stale-copy',
287
+ `${copies.length} skill(s) are copies, not links into the pinned package (${copies
288
+ .slice(0, 3)
289
+ .map((s) => s.name)
290
+ .join(', ')}): delete them and run \`pnpm exec skills-npm --yes\``,
291
+ );
292
+ }
293
+
294
+ // Links inside a skill resolve from the skill's real location: .agents/skills/<name> is a
295
+ // symlink into node_modules, and `../../references/x.md` means the package's references/.
296
+ const fromPackage = [];
297
+ const fromRepo = [];
298
+ const unreadable = [];
299
+ for (const skill of skills.filter((s) => !copies.includes(s))) {
300
+ const file = path.join(skill.real, 'SKILL.md');
301
+ if (!resolves(file)) continue;
302
+ // The link checker reads the file itself, so apply the same guard first.
303
+ if (!isReadable(file, bases)) {
304
+ unreadable.push(skill.rel);
305
+ continue;
306
+ }
307
+ const bucket = modulesReal && within(skill.real, modulesReal) ? fromPackage : fromRepo;
308
+ try {
309
+ for (const { link } of findBrokenLinks(file)) bucket.push(`${skill.name}: ${link}`);
310
+ } catch {
311
+ unreadable.push(skill.rel);
312
+ }
313
+ }
314
+ if (fromPackage.length > 0) {
315
+ add(
316
+ 'skill-link-broken',
317
+ `${fromPackage.length} broken link(s) in installed skills (${fromPackage.slice(0, 3).join('; ')}): the pinned ${SKILLS} ships a bad link, update it`,
318
+ );
319
+ }
320
+ if (fromRepo.length > 0) {
321
+ add(
322
+ 'own-skill-link-broken',
323
+ `${fromRepo.length} broken link(s) in this repo's own skills (${fromRepo.slice(0, 3).join('; ')}): they do not resolve from where the agent reads them`,
324
+ );
325
+ }
326
+ if (unreadable.length > 0) {
327
+ add(
328
+ 'skill-unreadable',
329
+ `${unreadable.length} skill(s) have a SKILL.md that cannot be read (${unreadable.slice(0, 3).join(', ')})`,
330
+ );
331
+ }
332
+ }
333
+
334
+ return { findings };
335
+ }
336
+
337
+ function main() {
338
+ let root;
339
+ try {
340
+ root = git(process.cwd(), ['rev-parse', '--show-toplevel']).trim();
341
+ } catch (error) {
342
+ console.error(
343
+ error?.code === 'ENOENT'
344
+ ? 'se-agent-guard doctor: git is not installed'
345
+ : 'se-agent-guard doctor: could not read a git repository here (not a repo, or a broken worktree)',
346
+ );
347
+ process.exit(2);
348
+ }
349
+ let findings;
350
+ try {
351
+ ({ findings } = diagnose({ root }));
352
+ } catch (error) {
353
+ console.error(
354
+ `se-agent-guard doctor: could not finish: ${error instanceof Error ? error.message : error}`,
355
+ );
356
+ process.exit(2);
357
+ }
358
+ if (findings.length === 0) {
359
+ console.log('se-agent-guard doctor: ok');
360
+ return;
361
+ }
362
+ console.error(`se-agent-guard doctor: ${findings.length} problem(s)\n`);
363
+ for (const f of findings) console.error(` ${f.id}: ${f.text}`);
364
+ process.exit(1);
365
+ }
366
+
367
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
@@ -32,7 +32,7 @@ function isOn(env, name) {
32
32
  }
33
33
 
34
34
  /** CI runs the same checks as audits; the hooks are for local laptops. */
35
- function inCi(env) {
35
+ export function inCi(env) {
36
36
  return Boolean(env.CI) && env.CI !== 'false';
37
37
  }
38
38
 
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Check that relative markdown links in a skill file point at files that exist.
3
+ * Links resolve against the file's own directory. Code spans, fenced code, URLs,
4
+ * absolute paths, in-page anchors and URL templates (`<x>`, `{x}`, `?query`) are skipped.
5
+ *
6
+ * A target must be a file (not a directory) and must match case exactly, so a link that only
7
+ * works on a case-insensitive filesystem is reported before it 404s on Linux. With a
8
+ * `packageRoot` and the package's `files` list, a link to something that does not ship is
9
+ * reported too: a customer never gets it. `packageRoot` and `filePath` must be in the same
10
+ * path space (both realpaths, or both not).
11
+ *
12
+ * Not checked (known gaps): reference-style links, HTML `<a href>` / `<img src>`, `?query`
13
+ * links, `#fragment` targets, and link text containing brackets.
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ // One level of balanced parentheses in the path; a double- or single-quoted title is allowed.
19
+ const LINK = /\[[^\]]*\]\(((?:[^()\s]|\([^()\s]*\))+)(?:\s+(?:"[^"]*"|'[^']*'))?\)/g;
20
+ // A backtick fence's info string may not contain a backtick (CommonMark: that is inline code).
21
+ const FENCE_OPEN = /^\s*(`{3,}(?=[^`]*$)|~{3,})/;
22
+
23
+ /** Blank out fenced blocks (matched by character and length) and inline code. */
24
+ function stripCode(markdown) {
25
+ const lines = markdown.split('\n');
26
+ const out = [];
27
+ let fence = null; // { char, length, from } while inside a block
28
+ for (let i = 0; i < lines.length; i++) {
29
+ const line = lines[i];
30
+ if (fence === null) {
31
+ const open = line.match(FENCE_OPEN);
32
+ if (open) {
33
+ fence = { char: open[1][0], length: open[1].length, from: out.length };
34
+ out.push('');
35
+ } else {
36
+ out.push(line);
37
+ }
38
+ continue;
39
+ }
40
+ const close = line.match(/^\s*(`{3,}|~{3,})\s*$/);
41
+ out.push('');
42
+ if (close && close[1][0] === fence.char && close[1].length >= fence.length) fence = null;
43
+ }
44
+ // An unterminated fence hides nothing: a typo must not switch checking off for the rest of the file.
45
+ if (fence !== null) {
46
+ for (let i = fence.from; i < lines.length; i++) out[i] = lines[i];
47
+ }
48
+ return out.join('\n').replace(/(`+)[^\n]*?\1/g, '');
49
+ }
50
+
51
+ /** @returns {string | null} the path to check, or null when the link is not a file link */
52
+ function localTarget(raw) {
53
+ if (/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(raw)) return null;
54
+ if (/[<>{}?]/.test(raw)) return null;
55
+ const target = raw.split('#')[0];
56
+ if (target === '') return null;
57
+ try {
58
+ return decodeURIComponent(target);
59
+ } catch {
60
+ return target; // malformed escape: check it as written, which reports it as missing
61
+ }
62
+ }
63
+
64
+ /**
65
+ * A regular file whose every path segment, below `stopAt`, matches the directory listing exactly.
66
+ * @param {string} resolved
67
+ * @param {string} stopAt the link file's own directory: it and everything above it exist
68
+ */
69
+ function isFileExact(resolved, stopAt) {
70
+ try {
71
+ if (!fs.statSync(resolved).isFile()) return false;
72
+ } catch {
73
+ return false;
74
+ }
75
+ let current = resolved;
76
+ while (stopAt !== current && !stopAt.startsWith(current + path.sep)) {
77
+ const parent = path.dirname(current);
78
+ if (parent === current) return true;
79
+ try {
80
+ if (!fs.readdirSync(parent).includes(path.basename(current))) return false;
81
+ } catch {
82
+ return false;
83
+ }
84
+ current = parent;
85
+ }
86
+ return true;
87
+ }
88
+
89
+ /** npm always publishes these, whatever `files` says. */
90
+ const ALWAYS_PUBLISHED = /^(package\.json|README(\..*)?|LICENSE(\..*)?|CHANGELOG(\..*)?)$/i;
91
+
92
+ /** Does a package.json `files` list publish this path (relative to the package root, posix)? */
93
+ function isPublished(rel, files) {
94
+ if (ALWAYS_PUBLISHED.test(rel)) return true;
95
+ return files.some((entry) => {
96
+ if (entry.includes('*')) {
97
+ const glob = entry.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*');
98
+ return new RegExp(`^${glob}$`).test(rel);
99
+ }
100
+ return rel === entry || rel.startsWith(`${entry}/`);
101
+ });
102
+ }
103
+
104
+ const inside = (root, target, files) => {
105
+ const rel = path.relative(root, target);
106
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return false;
107
+ return files ? isPublished(rel.split(path.sep).join('/'), files) : true;
108
+ };
109
+
110
+ /**
111
+ * @param {string} filePath absolute path of the markdown file
112
+ * @param {{ packageRoot?: string, files?: string[] }} [options] files: the package.json `files` list
113
+ * @returns {{ link: string, resolved: string, reason: 'missing' | 'outside-package' }[]}
114
+ */
115
+ export function findBrokenLinks(filePath, { packageRoot, files } = {}) {
116
+ const text = stripCode(fs.readFileSync(filePath, 'utf8'));
117
+ const dir = path.dirname(filePath);
118
+ const broken = [];
119
+ for (const match of text.matchAll(LINK)) {
120
+ const target = localTarget(match[1]);
121
+ if (target === null) continue;
122
+ const resolved = path.resolve(dir, target);
123
+ if (packageRoot && !inside(packageRoot, resolved, files)) {
124
+ broken.push({ link: match[1], resolved, reason: 'outside-package' });
125
+ } else if (!isFileExact(resolved, dir)) {
126
+ broken.push({ link: match[1], resolved, reason: 'missing' });
127
+ }
128
+ }
129
+ return broken;
130
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@se-studio/skills",
3
- "version": "1.10.27",
3
+ "version": "1.13.1",
4
4
  "description": "SE Studio agent skills for marketing site development with Contentful CMS",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  # Customer guardrail files (v1)
2
2
 
3
- Thin files a customer repo copies once. The hook, Claude settings, and merge-gate audit call the pinned `se-agent-guard` bin from `@se-studio/skills`, so that behaviour is versioned by the lockfile and cannot drift. `site-ci.yml` calls the shared workflow in se-core-product. A check that a repo still has them (`se-agent-guard check`, and a fleet-wide run from core) is planned and not shipped yet.
3
+ Thin files a customer repo copies once. The hook, Claude settings, and merge-gate audit call the pinned `se-agent-guard` bin from `@se-studio/skills`, so that behaviour is versioned by the lockfile and cannot drift. `site-ci.yml` calls the shared workflow in se-core-product. `pnpm exec se-agent-guard doctor` checks that this checkout still has them and that they work (see the agent-guard README); `fleet-audit` does the same from remote refs across the fleet.
4
4
 
5
5
  | Copy | To | Purpose |
6
6
  |------|----|---------|
@@ -20,6 +20,14 @@ const repoRoot = join(here, '..', '..', '..', '..');
20
20
  /** First `@se-studio/skills` release that understands the promote line `CI covers the changes since`. */
21
21
  export const SKILLS_PROMOTE_LINE_MIN = '1.10.7';
22
22
 
23
+ /**
24
+ * A site whose cms-driven.baseline.json holds more than this many violations needs work.
25
+ * Keep equal to DEBT_THRESHOLD in @se-studio/site-check (a test checks this).
26
+ */
27
+ export const BASELINE_DEBT_MAX = 25;
28
+ /** A baseline this many days old with debt still in it has stopped shrinking. */
29
+ export const BASELINE_STALE_DAYS = 90;
30
+
23
31
  /** Compare `1.2.3` style versions; anything unparsable sorts as 0.0.0. */
24
32
  export function compareVersions(a, b) {
25
33
  const parse = (v) => (String(v).match(/\d+/g) ?? []).slice(0, 3).map(Number);
@@ -42,7 +50,13 @@ const numeric = (spec) => String(spec).replace(/^[^\d]*/, '');
42
50
  * @returns {{ findings: {id: string, owner: 'core'|'customer', text: string}[],
43
51
  * pins: Record<string, {spec: string, where: string}[]> }}
44
52
  */
45
- export function auditFiles({ files, tree = [], coreBlockVersion, coreVersions }) {
53
+ export function auditFiles({
54
+ files,
55
+ tree = [],
56
+ coreBlockVersion,
57
+ coreVersions,
58
+ today = new Date().toISOString().slice(0, 10),
59
+ }) {
46
60
  const findings = [];
47
61
  const add = (id, owner, text) => findings.push({ id, owner, text });
48
62
  /** @type {Record<string, {spec: string, where: string}[]>} */
@@ -249,9 +263,99 @@ export function auditFiles({ files, tree = [], coreBlockVersion, coreVersions })
249
263
  );
250
264
  }
251
265
 
266
+ const localGuard = tree.find((t) => /(^|\/)scripts\/check-cms-driven\.mjs$/.test(t.path));
267
+ if (localGuard) {
268
+ add(
269
+ 'local-cms-driven-copy',
270
+ 'customer',
271
+ `${localGuard.path} is a local copy of the colour and layout guard: use the \`check-cms-driven\` bin from @se-studio/site-check and delete the copy`,
272
+ );
273
+ }
274
+
275
+ for (const [path, body] of Object.entries(files)) {
276
+ if (!/(^|\/)cms-driven\.baseline\.json$/.test(path)) continue;
277
+ const baseline = safeJson(body);
278
+ if (!baseline || !Number.isInteger(baseline.total) || baseline.total === 0) continue;
279
+ const dir = path.slice(0, path.length - 'cms-driven.baseline.json'.length);
280
+ if (!safeJson(files[`${dir}cms-driven.config.json`] ?? '')?.r3) {
281
+ add(
282
+ 'guardrail-baseline-orphan',
283
+ 'customer',
284
+ `${path}: there is a baseline but \`${dir}cms-driven.config.json\` has no \`r3\`, so the guard is off and the debt is not being checked`,
285
+ );
286
+ }
287
+ if (baseline.total > BASELINE_DEBT_MAX) {
288
+ add(
289
+ 'guardrail-baseline-debt',
290
+ 'customer',
291
+ `${path}: ${baseline.total} baselined colour violations (over ${BASELINE_DEBT_MAX}): this site needs work. Replace literals with palette tokens, then run \`check-cms-driven --update-baseline\``,
292
+ );
293
+ }
294
+ const age = (Date.parse(today) - Date.parse(baseline.generatedAt)) / 86_400_000;
295
+ if (age > BASELINE_STALE_DAYS) {
296
+ add(
297
+ 'guardrail-baseline-stale',
298
+ 'customer',
299
+ `${path}: baseline last changed ${baseline.generatedAt} (${Math.floor(age)} days ago) with ${baseline.total} violation(s) still in it: debt is not shrinking`,
300
+ );
301
+ }
302
+ }
303
+
304
+ for (const [path, body] of Object.entries(files)) {
305
+ if (!/(^|\/)cms-driven\.config\.json$/.test(path)) continue;
306
+ const until = safeJson(body)?.remake?.until;
307
+ if (typeof until !== 'string') continue;
308
+ const daysLeft = (Date.parse(until) - Date.parse(today)) / 86_400_000;
309
+ if (daysLeft < 0) {
310
+ add(
311
+ 'remake-mode-expired',
312
+ 'customer',
313
+ `${path}: remake mode ended ${until} but is still in the config: remove it. The guard is strict again, so any copied styles not in the baseline now fail`,
314
+ );
315
+ } else {
316
+ add(
317
+ 'remake-mode-active',
318
+ 'customer',
319
+ `${path}: remake mode until ${until} (${Math.floor(daysLeft)} day(s) left): colour and CSS-island guards are relaxed. Snapshot the debt with \`check-cms-driven --update-baseline\` before it ends`,
320
+ );
321
+ }
322
+ }
323
+
252
324
  return { findings, pins };
253
325
  }
254
326
 
327
+ const GUARD_FILES = new Set([
328
+ '.husky/pre-commit',
329
+ '.husky/pre-push',
330
+ '.githooks/pre-commit',
331
+ '.githooks/pre-push',
332
+ '.claude/settings.json',
333
+ '.github/workflows/merge-gate-audit.yml',
334
+ ]);
335
+
336
+ /**
337
+ * Which tracked paths `auditFiles` needs the contents of. Shared with `se-agent-guard doctor`,
338
+ * which audits the working tree with the same checks.
339
+ * @param {string[]} paths
340
+ */
341
+ export function wantedPaths(paths) {
342
+ return paths.filter((f) => {
343
+ if (GUARD_FILES.has(f)) return true;
344
+ if (f.includes('node_modules/')) return false;
345
+ if (
346
+ f === 'AGENTS.md' ||
347
+ /^\.cursor\/rules\/[^/]+\.mdc$/.test(f) ||
348
+ /^docs\/[^/]+\.md$/.test(f)
349
+ ) {
350
+ return true;
351
+ }
352
+ return (
353
+ /(^|\/)(package\.json|cms-driven\.baseline\.json|cms-driven\.config\.json)$/.test(f) &&
354
+ f.split('/').length <= 4
355
+ );
356
+ });
357
+ }
358
+
255
359
  // ---------- git and gh plumbing (not used by tests) ----------
256
360
 
257
361
  const run = (cmd, args, cwd) =>
@@ -324,27 +428,7 @@ function readFromOrigin(path, branch) {
324
428
  mode: line.slice(0, line.indexOf(' ')),
325
429
  path: line.slice(line.indexOf('\t') + 1),
326
430
  }));
327
- const GUARD_FILES = new Set([
328
- '.husky/pre-commit',
329
- '.husky/pre-push',
330
- '.githooks/pre-commit',
331
- '.githooks/pre-push',
332
- '.claude/settings.json',
333
- '.github/workflows/merge-gate-audit.yml',
334
- ]);
335
- const wanted = tree
336
- .map((t) => t.path)
337
- .filter((f) => {
338
- if (GUARD_FILES.has(f)) return true;
339
- if (f.includes('node_modules/')) return false;
340
- if (
341
- f === 'AGENTS.md' ||
342
- /^\.cursor\/rules\/[^/]+\.mdc$/.test(f) ||
343
- /^docs\/[^/]+\.md$/.test(f)
344
- )
345
- return true;
346
- return /(^|\/)package\.json$/.test(f) && f.split('/').length <= 4;
347
- });
431
+ const wanted = wantedPaths(tree.map((t) => t.path));
348
432
  const files = {};
349
433
  for (const f of wanted) {
350
434
  const body = tryRun('git', ['show', `${ref}:${f}`], path);
@@ -122,7 +122,7 @@ Step-by-step guides are available as **Cursor skills**. Use them when creating o
122
122
  | **CMS guidelines — orchestration** (full **fresh** clean regen vs **sync** incremental + stale removal vs **merge-only**) | `.agents/skills/contentful-cms-update-cms-guidelines/SKILL.md` — if the user is vague (“regenerate guidelines”), confirm **fresh** vs **sync** before acting |
123
123
  | **CMS guidelines — fragments** (full / single / merge-only; prefer **update-cms-guidelines** for true total regeneration) | `.agents/skills/contentful-cms-generate-cms-guidelines/SKILL.md` |
124
124
 
125
- **Skills — canonical source and sync:** All SE Studio skills live in **`packages/skills/skills/`** (the `@se-studio/skills` npm package). **In the monorepo**, edit sources there, run **`pnpm skills:validate`**, then **`pnpm skills:sync`** to copy into **`.agents/skills`**. The repo root keeps **`.cursor/skills`** as a **symlink** to **`.agents/skills`**. **Customer sites** depend on `@se-studio/skills` at an exact version and link its skills with `skills-npm --yes` in `prepare`; `npx skills add @se-studio/skills` is only for a one-off project without the dependency. Do not edit skills under **`.agents/skills`** by hand. Frontmatter rules: [`packages/skills/README.md`](packages/skills/README.md).
125
+ **Skills — canonical source and sync:** All SE Studio skills live in **`packages/skills/skills/`** (the `@se-studio/skills` npm package). **In the monorepo**, edit sources there, run **`pnpm skills:validate`**, then **`pnpm skills:sync`** to copy into **`.agents/skills`**. The repo root keeps **`.cursor/skills`** as a **symlink** to **`.agents/skills`**. **Customer sites** depend on `@se-studio/skills` at an exact version and link its skills with `skills-npm --yes` in `prepare`; `npx skills add @se-studio/skills` is only for a one-off project without the dependency. Do not edit skills under **`.agents/skills`** by hand. Frontmatter rules: `packages/skills/README.md`.
126
126
 
127
127
  See also **docs/AI_QUICK_REFERENCE.md** for a short task → doc/skill index.
128
128
 
@@ -379,22 +379,22 @@ When making changes, update the relevant documentation:
379
379
 
380
380
  ## Links
381
381
 
382
- - [Related Projects](./docs/RELATED_PROJECTS.md) – Client and studio projects that consume these packages (Contentful space IDs, environments, repo paths)
383
- - [AI Quick Reference](./docs/AI_QUICK_REFERENCE.md) – Task → doc/skill index for common app tasks
384
- - [GitHub issues implementation status](./docs/GITHUB_ISSUES_IMPLEMENTATION_STATUS.md) – closed issues mapped to code; open backlog summary
385
- - [Content Structure Guide](./docs/CONTENT_STRUCTURE_GUIDE.md) – Content author guide for CMS workflows
386
- - [Server vs Client Boundaries](./docs/SERVER_CLIENT_BOUNDARIES.md) – cms-server rule and pattern
387
- - [core-ui package export boundaries](./packages/core-ui/docs/PACKAGE_EXPORT_BOUNDARIES.md) – main vs `/server` entry; prevent client bundle CMS leaks
388
- - [Contentful webhook revalidation](./docs/CONTENTFUL_WEBHOOK_REVALIDATION.md) – Contentful webhooks for cache revalidation
389
- - [CMS Infrastructure Guide](./packages/core-ui/CMS_INFRASTRUCTURE.md)
390
- - [Contentful REST API Docs](./packages/contentful-rest-api/README.md) — LLM ref: [docs/llms.md](./packages/contentful-rest-api/docs/llms.md)
391
- - [Core Data Types Docs](./packages/core-data-types/README.md) — LLM ref: [docs/llms.md](./packages/core-data-types/docs/llms.md)
392
- - [Core UI Docs](./packages/core-ui/README.md) — LLM ref: [docs/llms.md](./packages/core-ui/docs/llms.md)
393
- - [A/B Testing Docs](./packages/ab-testing/README.md) — LLM ref: [docs/llms.md](./packages/ab-testing/docs/llms.md)
394
- - [HubSpot Docs](./packages/hubspot/README.md) — LLM ref: [docs/llms.md](./packages/hubspot/docs/llms.md) (optional package; **not** the fleet default forms provider)
395
- - [Search Docs](./packages/search/README.md) — LLM ref: [docs/llms.md](./packages/search/docs/llms.md)
396
- - [Markdown Renderer Docs](./packages/markdown-renderer/README.md) — LLM ref: [docs/llms.md](./packages/markdown-renderer/docs/llms.md)
397
- - [Contentful CMS CLI Docs](./packages/contentful-cms/README.md)
382
+ - Related Projects (`./docs/RELATED_PROJECTS.md`) – Client and studio projects that consume these packages (Contentful space IDs, environments, repo paths)
383
+ - AI Quick Reference (`./docs/AI_QUICK_REFERENCE.md`) – Task → doc/skill index for common app tasks
384
+ - GitHub issues implementation status (`./docs/GITHUB_ISSUES_IMPLEMENTATION_STATUS.md`) – closed issues mapped to code; open backlog summary
385
+ - Content Structure Guide (`./docs/CONTENT_STRUCTURE_GUIDE.md`) – Content author guide for CMS workflows
386
+ - Server vs Client Boundaries (`./docs/SERVER_CLIENT_BOUNDARIES.md`) – cms-server rule and pattern
387
+ - core-ui package export boundaries (`./packages/core-ui/docs/PACKAGE_EXPORT_BOUNDARIES.md`) – main vs `/server` entry; prevent client bundle CMS leaks
388
+ - Contentful webhook revalidation (`./docs/CONTENTFUL_WEBHOOK_REVALIDATION.md`) – Contentful webhooks for cache revalidation
389
+ - CMS Infrastructure Guide (`./packages/core-ui/CMS_INFRASTRUCTURE.md`)
390
+ - Contentful REST API Docs (`./packages/contentful-rest-api/README.md`) — LLM ref: docs/llms.md (`./packages/contentful-rest-api/docs/llms.md`)
391
+ - Core Data Types Docs (`./packages/core-data-types/README.md`) — LLM ref: docs/llms.md (`./packages/core-data-types/docs/llms.md`)
392
+ - Core UI Docs (`./packages/core-ui/README.md`) — LLM ref: docs/llms.md (`./packages/core-ui/docs/llms.md`)
393
+ - A/B Testing Docs (`./packages/ab-testing/README.md`) — LLM ref: docs/llms.md (`./packages/ab-testing/docs/llms.md`)
394
+ - HubSpot Docs (`./packages/hubspot/README.md`) — LLM ref: docs/llms.md (`./packages/hubspot/docs/llms.md`) (optional package; **not** the fleet default forms provider)
395
+ - Search Docs (`./packages/search/README.md`) — LLM ref: docs/llms.md (`./packages/search/docs/llms.md`)
396
+ - Markdown Renderer Docs (`./packages/markdown-renderer/README.md`) — LLM ref: docs/llms.md (`./packages/markdown-renderer/docs/llms.md`)
397
+ - Contentful CMS CLI Docs (`./packages/contentful-cms/README.md`)
398
398
 
399
399
  ### For consuming projects (in node_modules)
400
400
 
@@ -282,7 +282,7 @@ These links:
282
282
 
283
283
  ## Pipeline reference
284
284
 
285
- All per-component pipeline docs live in [`references/contentful-cms-cms-guidelines/`](../../references/contentful-cms-cms-guidelines/):
285
+ All per-component pipeline docs live in `references/contentful-cms-cms-guidelines/`:
286
286
 
287
287
  | File | Purpose |
288
288
  |---|---|
@@ -18,9 +18,9 @@ The management token must have permission to read API keys for each target space
18
18
 
19
19
  ## Site registry
20
20
 
21
- Canonical site list: [`docs/schema-audit/sites.registry.json`](../../../docs/schema-audit/sites.registry.json)
21
+ Canonical site list: `docs/schema-audit/sites.registry.json` (core repo)
22
22
 
23
- Customer-specific types/fields (excluded from core gap noise): [`docs/schema-audit/customer-overrides.registry.json`](../../../docs/schema-audit/customer-overrides.registry.json)
23
+ Customer-specific types/fields (excluded from core gap noise): `docs/schema-audit/customer-overrides.registry.json` (core repo)
24
24
 
25
25
  ## Two-phase workflow
26
26
 
@@ -251,7 +251,7 @@ rm <appDir>/docs/cms-guidelines/externals/<slug>.md
251
251
 
252
252
  **New components** (one or more):
253
253
 
254
- Run the [generate-all-guidelines](../generate-all-guidelines/SKILL.md) skill's Phase 1 (screenshots)
254
+ Run the [generate-all-guidelines](../contentful-cms-generate-all-guidelines/SKILL.md) skill's Phase 1 (screenshots)
255
255
  and Phase 3 (component subagents) for **only the new types**, then skip to Phase 4 (merge).
256
256
 
257
257
  If the new component does not yet have an `accepted-variants/components/<slug>.json` file (or `collections/<slug>.json` for a collection), run:
@@ -34,6 +34,7 @@ Canonical: `docs/PHILOSOPHY.md` §5a. Review: `customer-code-review.md`. Session
34
34
  ## Escape hatches (narrow)
35
35
 
36
36
  - `globals.css`: shared primitives only (keyframes, RTF element maps, true design-system utilities) — **not** per-page layout ports
37
+ - **Enforced, not just advised:** `check-cms-driven` (R3 colour literals, R4 new CSS files) fails a remake that copies live-site CSS. Open a time-boxed `remake` window in `cms-driven.config.json` only for the copy phase, then snapshot with `--update-baseline`. See the `@se-studio/site-check` README.
37
38
  - HtmlComponent + `customCss`: only when the recorded call is **keep** (`create-html-component.md`). A layout a registered type cannot express does not make that call. Do not move a section onto or off HtmlComponent after **keep** or **promote** is recorded. **Not** the default Webflow remake path.
38
39
 
39
40
  ## Related
@@ -55,12 +55,12 @@ Use exactly one:
55
55
 
56
56
  ## Report assembly
57
57
 
58
- Write [`docs/reports/markdown-accuracy-audit.md`](../../../../docs/reports/markdown-accuracy-audit.md):
58
+ Write `docs/reports/markdown-accuracy-audit.md` (core repo):
59
59
 
60
60
  1. Run metadata (timestamp, site count, URL count).
61
61
  2. Summary table of verdict counts.
62
62
  3. Per-site sections with table columns: **URL | HTML size | MD size | HTML ms | MD ms | Cache | Review**.
63
- 4. JSON sidecar [`docs/reports/markdown-accuracy-audit.json`](../../../../docs/reports/markdown-accuracy-audit.json) merging metrics + verdict + review text.
63
+ 4. JSON sidecar `docs/reports/markdown-accuracy-audit.json` (core repo) merging metrics + verdict + review text.
64
64
 
65
65
  Review in site batches (~6–13 URLs). Commit `.md` and `.json` to `dev`; artifacts dir stays gitignored.
66
66
 
@@ -192,20 +192,27 @@ Recommended pattern (in `app/sitemap.xml/route.ts` and the unindexed route — n
192
192
 
193
193
  ```ts
194
194
  import { createSitemapXmlRouteHandler } from '@se-studio/core-ui';
195
- import { redirects } from '@/generated/redirects';
196
- import { getSitemapEntries } from '@/lib/cms-server';
197
- import { baseUrl } from '@/lib/server-config';
195
+ import { getRedirectMap, getSitemapEntries } from '@/lib/cms-server';
196
+ import { baseUrl, draftOnly } from '@/lib/server-config';
198
197
 
199
198
  export const dynamic = 'force-dynamic';
200
199
  export const revalidate = 0;
201
200
 
202
201
  export const GET = createSitemapXmlRouteHandler({
203
- getEntries: () => getSitemapEntries({ includeUnindexed: false, redirectMap: redirects }),
202
+ // Live map (tag `redirect`, expired by the redirect sync route). `cache: 'force-cache'` is
203
+ // required: without it this read reaches Contentful on every crawler request.
204
+ getEntries: async () =>
205
+ getSitemapEntries({
206
+ includeUnindexed: false,
207
+ redirectMap: await getRedirectMap({ preview: draftOnly, cache: 'force-cache' }),
208
+ }),
204
209
  baseUrl,
205
210
  trailingSlash: true,
206
211
  });
207
212
  ```
208
213
 
214
+ A site still on the baked-map path can pass `redirects` from `@/generated/redirects` instead; sites on the live path (section 9) use the live map above so a redirect edit reaches the sitemap without a rebuild.
215
+
209
216
  Pure `fromPath` vanity redirects were already absent from sitemaps (no backing content entry). This mainly helps when you redirect *away from* live CMS pages/articles.
210
217
 
211
218
  ### 4.3 Webhook = Deploy Hook (the trigger)
@@ -228,7 +235,7 @@ Baked redirects require a **rebuild**, not ISR revalidation. Use a Contentful we
228
235
  ```
229
236
  This creates/replaces Contentful webhooks named `Vercel Deploy Hook (Redirects)` (and `… – Preview` when the preview URL is set). They fire on **Entry publish / unpublish / delete** filtered to content type `redirect`.
230
237
 
231
- The script lives at [`scripts/setup-redirect-deploy-hook.ts`](../../../../scripts/setup-redirect-deploy-hook.ts) in the monorepo; `example-empty` wires it via `package.json`.
238
+ The script lives at `scripts/setup-redirect-deploy-hook.ts` in the monorepo; `example-empty` wires it via `package.json`.
232
239
 
233
240
  **Manual setup:** same triggers and filter (`redirect` only), POST to the deploy hook URL. Do **not** point this at `/api/revalidate` — that only invalidates cache tags and will not regenerate `src/generated/redirects.ts`.
234
241
 
@@ -246,7 +253,7 @@ That's it. Publish a redirect → Vercel starts a build → `prebuild` runs `gen
246
253
  5. After the build finishes: `curl -I https://your-site/from-page-url/` → 301 to the target.
247
254
  6. Also test a raw-path rule and an external URL.
248
255
  7. Edit the rule → republish → new build → new behaviour.
249
- 8. (Optional) If you also want to clean up legacy per-page `redirectTo` fields, run migration 19.
256
+ 8. The legacy per-entry `redirectTo` field is gone (migration 39 removes it from page, pageVariant, article, articleType and tag; nothing ever read it). The `redirect` content type is the only supported mechanism. Count entries with `scripts/count-redirect-to.sh <site-repo>` before running it on a space: deleting a field deletes its data.
250
257
 
251
258
  ## 6. Preview / draft deployments
252
259
 
@@ -267,7 +274,7 @@ Then commit the updated `.agents/skills/...` (the monorepo keeps them in sync wi
267
274
 
268
275
  ## 8. Future work (explicitly out of scope for v1)
269
276
 
270
- - Edge Config + instant sync route (user request: "don't do the fast version at the moment").
277
+ - Edge Config for redirects: superseded by Vercel Bulk Redirects (see section 9).
271
278
  - Wildcards / prefix matching / query param control.
272
279
  - A "Redirects index" page visible to editors on the live site.
273
280
  - Host-based or A/B-aware redirects.
@@ -276,6 +283,59 @@ The `redirect` content type and the `buildRedirectMap` / `getRedirectMap` helper
276
283
 
277
284
  `buildRedirectMap` automatically drops self-redirects (A → A after normalization) and any rules that participate in longer cycles, emitting a console warning for cycles during build/generate. Internal paths are normalized with a trailing `/` to match your urlCalculators and sitemap hrefs.
278
285
 
286
+
287
+ ## 9. Live path: Vercel Bulk Redirects (no rebuild)
288
+
289
+ Vercel Bulk Redirects are a project-level list updated through the REST API (or `vercel redirects` CLI). A change goes live in seconds with no deployment, and the platform answers before Next.js (so before `proxy.ts`). Needs a Pro or Enterprise team (Pro: 1,000 rules). Proven in a pilot spike; the deploy-hook path above remains the fallback.
290
+
291
+ Library support in `@se-studio/contentful-rest-api`:
292
+
293
+ - `redirectMapToBulkRedirects(buildRedirectMap(redirects), options)` returns `{ rules, skipped }`. It emits each internal rule for the slashed **and** bare source, validates every rule, and sorts the output.
294
+ - `syncVercelBulkRedirects({ token, projectId, teamId, rules })` (from `/server`) does one `PUT overwrite:true` then promotes the staged version. It is idempotent: it reads Vercel's live list first and writes nothing (no new version) when it already matches. It refuses an empty list unless `allowEmpty` is set, a list over `maxRules`, and invalid or duplicate rules. A drop guard (`maxDropFraction`) exists but is **off by default**: a complete CMS read with fewer redirects is an intentional edit and is obeyed.
295
+
296
+ Verified behaviour (pilot spike, 2026-11-17):
297
+
298
+ - `PATCH` only edits an existing rule (404 on an empty project). `PUT` without `overwrite` merges; with `overwrite:true` it replaces the whole list.
299
+ - Matching is **exact on the trailing slash**: a rule for `/old/` does not match `/old`, so both are emitted.
300
+ - A matching platform rule fires before Next's trailing-slash 308.
301
+ - Staged changes are not live but are reachable on the staging alias; promote makes them live (about 1-5 s to reach the edge).
302
+ - Query strings are dropped unless `preserveQueryParams` is true.
303
+ - Vercel accepts a source without a leading `/` and self-redirects, so validation is ours.
304
+ - Every internal CMS rule becomes **two** Vercel rules (slashed and bare), so `maxRules` (default 1000, the Pro cap) is reached at about 500 CMS redirects.
305
+ - Sources must be literal paths: whitespace, control characters, backslash and the pattern characters `*`, `:`, `(`, `)` are rejected. Destinations may not contain whitespace, control characters or a backslash (a browser reads `/\evil.com` as `//evil.com`). Sources that differ only by case collide on Vercel (matching is case-insensitive); the later one is skipped and reported as `duplicate-source-case`.
306
+ - `allowedExternalHosts` (mapper and sync) restricts external destinations to listed hosts. Unset allows any `http(s)` host.
307
+
308
+ Token handling: use one **project-scoped** token per site, a Sensitive env var for Production only, a short expiry, and never reuse `REVALIDATION_SECRET` for the sync route. The sync route must read the published list from Contentful and take no redirect data from the request.
309
+
310
+ ### Wiring a site (live path)
311
+
312
+ 1. Copy `apps/example-empty/src/app/api/redirects-sync/route.ts`. It is two lines of handler: `createRedirectSyncHandler` (POST, the Contentful webhook target) and `createRedirectSyncStatusHandler` (GET, "does Vercel match the CMS?"), both from `@se-studio/contentful-rest-api/server`.
313
+ 2. Set env on the **one deployment allowed to write** (normally Production): `REDIRECT_SYNC_ENABLED=true`, `REDIRECT_SYNC_SECRET` (a dedicated secret, not `REVALIDATION_SECRET`), `VERCEL_API_TOKEN` (project-scoped, Sensitive), `VERCEL_PROJECT_ID` and `VERCEL_TEAM_ID` (**required even with a project-scoped token**: Vercel rejects the write with "projectId and teamId are required" without it). Anywhere else, or with any of these missing, the route returns 404 (a startup warning in the logs names what is missing).
314
+ If the site has a `route-build-policy.json`, add `/api/redirects-sync` to `allowedDynamic` (the route is a webhook plus a status view, so it renders per request). The template's comments are written as `why-external:` constraints so a verbatim copy passes a site's `check:comments` guard.
315
+ 3. Create the webhook: set `REDIRECT_SYNC_URL` (`https://<site>/api/redirects-sync`) and `REDIRECT_SYNC_SECRET` in `.env.local`, then `pnpm setup:redirect-sync-webhook`. It does not remove the old deploy-hook webhook; remove that once the live path is proven or redirects still rebuild the site.
316
+ 4. Keep the secrets in your local env file(s) too. `REDIRECT_SYNC_SECRET` and the Vercel values live in Vercel and Contentful (the webhook header); the setup script and the status check also need them on your machine, and nothing else records them. Never commit them. Write the token's expiry date down.
317
+ 5. Check: `curl -H "x-redirect-sync-secret: $REDIRECT_SYNC_SECRET" https://<site>/api/redirects-sync` returns the status view (below).
318
+
319
+ ### The status view (GET)
320
+
321
+ What is going on with redirects, in one call:
322
+
323
+ - `inSync`: `true` / `false`, or `null` when the Contentful read was partial (a comparison would mislead). A sync that failed, or never ran, shows up here as `false` with `drift.missing`, `drift.extra` and `drift.changed` (the sources that differ).
324
+ - `cms`: `complete`, `entries` (redirect entries in Contentful), `rules` (Vercel rules they produce, two per internal redirect), `inactive`, `warnings` (live entries worth a look, such as a From that is a published page), `errors` (entries that failed to convert), `problems` (entries that are **not live and why**: `missing-to` = the target page is unpublished or unresolved, `missing-from`, `self-redirect`, `cycle`, `duplicate-overridden`, or `rejected` with a `reason` such as an unsafe character or a disallowed host) and `skipped` (the rejected rules by source).
325
+ - `live`: how many rules Vercel serves now and the version (`id`, `name`, `lastModified`).
326
+
327
+ The CMS half is read through the Next data cache on the `redirect` tag. The production `/api/revalidate` webhook deliberately excludes `redirect`, so the sync route expires that tag itself after **every sync attempt, successful or not** (`afterSync`); it stays cached until the next redirect webhook arrives. That is why a **failed** sync shows as drift: the tag is expired, the next status call reads the new CMS list, and Vercel still has the old one. The Vercel half is read fresh on every call. A cache cannot show a **missed webhook** (nothing reached the route, so nothing changed from its point of view): add `?fresh=true` to read Contentful directly, and `cms.source` tells you which you got (`cached` or `fresh`). Check `problems` after unpublishing or moving a page: a redirect whose target is gone is dropped from the live list, not blocked.
328
+
329
+ How the handler behaves: the request body is never read (a caller can only trigger a re-sync, never inject a rule); the secret is compared in constant time; it refuses to sync when the Contentful read failed or was partial (502), and obeys a complete read, including an empty list; a sync that finds Vercel already up to date writes nothing; it waits a few seconds and re-reads Contentful, syncing again if the list changed (a webhook can fire before the delivery API shows the publish); a burst of webhooks is coalesced, so requests that arrive while a sync runs share one follow-up sync instead of each starting their own (this is per server instance; across instances the re-read and the skip-if-unchanged check keep the end state right). Rules it skips as invalid are listed in the response.
330
+
331
+ Renames and unpublishes: a redirect that points at a CMS page (`toInternal`) uses that page's URL as of the last sync, so the sync must also run when a page changes. `setup:redirect-sync-webhook` therefore fires on publish, unpublish and delete of `redirect` **and** of the types the Redirect pickers can point at, plus `personType` (a person's URL includes it): page, article, articleType, person, personType, tag, customType, tagType. Save and autosave are not topics. Most deliveries find nothing changed and write nothing, but each one still costs at least four Contentful reads (the redirect list is read twice, the second after the settle delay, and each read is at least two requests because core pages until an empty page) plus a Vercel read, so a bulk publish of 100 entries costs about 400 reads and 100 short function runs. The unpublish payload is documented to match the filter only if it carries `sys.contentType`; if a site's unpublishes do not re-sync, `?fresh=true` on the status view will show the drift. If a target page is unpublished, its redirect is dropped from the live list and shows as `missing-to` in `cms.problems`.
332
+
333
+ Use the **From internal** picker only for a page that is being retired. If the From page is still published, the redirect takes that live page out of service (and if the page is later renamed, the redirect follows it to the new URL). The status view lists these under `cms.warnings` (`source-is-live-page`). For an old URL that you are replacing, type it into `fromPath`.
334
+
335
+ `skeleton:check` enforces the live path (rule R6.9): the route above must exist, and the `sitemap.xml` / `sitemap-unindexed.xml` routes must call `getRedirectMap`. A site mid-rollout can skip `presence.t1.redirects-sync`, `redirects-sync.handlers` or `sitemap.redirects-live` in `skeleton.check.json` only with an expiry date (`until`, inclusive; add an `owner` so people know who finishes it), for example `{ "skip": [{ "id": "sitemap.redirects-live", "until": "2026-12-15", "owner": "<name>" }] }`; once the date passes the check fails as `skip.expired`.
336
+
337
+ Keep the baked `generate-redirects` map and `proxy.ts` lookup in place until a site's live path is proven; they are the fallback.
338
+
279
339
  ---
280
340
 
281
341
  **You now have editor-managed redirects that are as robust and low-surprise as your A/B tests, using only patterns that already exist in the codebase.**
@@ -29,7 +29,7 @@ Preview / `DRAFT_ONLY` Contentful access in local dev is expected and not a smok
29
29
  | `pnpm smoke-test:cache` | `build` + `start:dev` + double-pass `x-nextjs-cache` verify |
30
30
  | `pnpm smoke-test:deploy-check` | Post-build gate: `start:dev` (no rebuild) + functional smoke — use in Vercel `buildCommand` |
31
31
  | `pnpm smoke-test:live` | Live deployment URL smoke — GitHub Action + Vercel Deployment Checks |
32
- | `pnpm revalidation-test` | `build` + `start:dev` + revalidation matrix (warm → invalidate → cold → warm); see `revalidation.cases.json` and [CONTENTFUL_WEBHOOK_REVALIDATION.md](../../../../docs/CONTENTFUL_WEBHOOK_REVALIDATION.md) |
32
+ | `pnpm revalidation-test` | `build` + `start:dev` + revalidation matrix (warm → invalidate → cold → warm); see `revalidation.cases.json` and `docs/CONTENTFUL_WEBHOOK_REVALIDATION.md` (core repo) |
33
33
 
34
34
  Example `package.json` entries:
35
35
 
@@ -286,7 +286,7 @@ When placement says **core** (or the site is blocked on package behaviour): emit
286
286
 
287
287
  Before asking to merge to `dev` / `develop`, follow the review file once, at the final head SHA, and stop. Do not re-review on every push. A design review is only for schema, forms, analytics, caching, or security. A production promote does not get a second AI review (`CI covers the changes since`). Do not start a post-merge AI review; a skipped merge is labelled `pushed-through` only. Do not restate the checklist here.
288
288
 
289
- - **Core:** [`CODE_REVIEW_PROMPT.md`](../../../../CODE_REVIEW_PROMPT.md)
289
+ - **Core:** `CODE_REVIEW_PROMPT.md` (core repo)
290
290
  - **Customer:** [`customer-code-review.md`](../../references/agent-session/customer-code-review.md) (copied into the site as `CODE_REVIEW.md`)
291
291
 
292
292
  Findings: **BLOCKER** / **NIT**. No Bugbot; no `nick-go` label — Nick approves merges to integration branches **in chat**.