@wildshard/sdk 0.2.3 → 0.2.4

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/GUIDE.md CHANGED
@@ -34,7 +34,7 @@ repo's one `src/shards/<slug>/`).
34
34
 
35
35
  | # | Step | Command | Today |
36
36
  |---|---|---|---|
37
- | 1 | Start | `wildshard new my-shard` | Works. Writes a shard repo in `my-shard/`: the reference world (Template 1, Mossgate) as its shard source at `src/`, plus `package.json`, `tsconfig.json`, `.gitignore`, `.npmrc`, a README, this guide and the four `wildshard` skills |
37
+ | 1 | Start | `wildshard new my-shard` | Works. Writes a shard repo in `my-shard/`: the reference world (Template 1, Mossgate) as its shard source at `src/`, plus `package.json`, `tsconfig.json`, `.gitignore`, `.npmrc`, a README, this guide, the four `wildshard` skills and the agent files (`AGENTS.md`, `CLAUDE.md`, `.agents/skills/`) |
38
38
  | 2 | Walk it | `wildshard dev .` | **Not built yet (SA15).** See "Walking your shard" below |
39
39
  | 3 | Check | `wildshard check .` | Works: lint, build, validate, prove and the report card, one verdict |
40
40
  | 4 | Hero | `wildshard hero . --base <url>` | Works only with an engine checkout: it needs your shard in a served engine build. See "The hero" below |
@@ -53,6 +53,7 @@ with `rule`, `fix` and `guide`) for agents and scripts.
53
53
  | Verb | What it is for |
54
54
  |---|---|
55
55
  | `wildshard new <dir> [slug] [--template sdk\|blender] [--empty]` | Start a shard repo in a folder that does not exist yet, its shard source at `src/`. The slug is the folder's name unless you give one. `--template sdk` (the default) copies the reference world; `--template blender` copies the hand-written Blender template (below); any other template refuses before writing. `--empty` writes a bare shard source instead of the reference world |
56
+ | `wildshard update [dir]` | Rewrite this guide and the four `wildshard` skills from the installed sdk, after you move to a newer one (section 7) |
56
57
  | `wildshard dev <source>` | Serve the shard source on localhost and rebuild on every save (section 4). **Not built yet** for an installed sdk (SA15) |
57
58
  | `wildshard check <source> [folder] [--json]` | The loop's check: lint, build, validate, prove, report card, verdict |
58
59
  | `wildshard hero <source> --base <url>` | Capture the hero from a served build and stamp `hero.json`. `--stamp-existing` marks the images already there as current: only when you have looked at them and they show the current world |
@@ -179,7 +180,9 @@ At the repo root, around `src/`:
179
180
  | `tsconfig.json`, `.npmrc`, `.gitignore` | TypeScript settings for `src/`; exact versions for `pnpm add`; what git leaves out (build output, `node_modules/`) | No |
180
181
  | `README.md`, `GUIDE.md` | This repo's README, and this guide | No |
181
182
  | `pnpm-workspace.yaml` | pnpm's install-script allowlist (SA39): a dependency's install script runs only if listed | No |
182
- | `.claude/skills/wildshard*/SKILL.md` | The `wildshard` skill (SA14): the loop's order for Claude Code, pointing into this guide; and its siblings (SA27): `wildshard-mockup-to-model` (a picture to a model), `wildshard-goldens` (refresh the hero and proof tape), `wildshard-upgrade` (move to a newer sdk) | No |
183
+ | `.claude/skills/wildshard*/SKILL.md` | The `wildshard` skill (SA14): the loop's order for Claude Code, pointing into this guide; and its siblings (SA27): `wildshard-mockup-to-model` (a picture to a model), `wildshard-goldens` (refresh the hero and proof tape), `wildshard-upgrade` (move to a newer sdk). `wildshard update` rewrites them: never edit them | No |
184
+ | `.agents/skills/wildshard*` | Links to the four `.claude/skills/` folders, so Codex lists the same skills | No |
185
+ | `AGENTS.md`, `CLAUDE.md` | For agents: read this guide first; the skills are in `.claude/skills/`. `CLAUDE.md` is `@AGENTS.md`, so Claude Code reads the same file. Yours to change: `update` keeps your edits | No |
183
186
  | `public/shardfiles/` | Build output: the built folder and `<slug>.shardfile`. Never edit; never commit | It is the shard file |
184
187
 
185
188
  **Two files to change together.** `src/manifest.json` and `src/data/card.json` hold the same card: `new` writes
@@ -308,7 +311,8 @@ Every refusal prints the refusing code's own words, then one line:
308
311
  `wildshard check . --json` carries the same `rule`, `fix` and `guide` on each refusal. The headings below are those
309
312
  links, one per rule. The printed `fix` is the short answer; each heading adds why. Shard-format's own refusals also
310
313
  carry a stable code, listed in
311
- [`docs/VALIDATION-CODES.md`](https://github.com/project-wildshard/shard-format/blob/main/docs/VALIDATION-CODES.md).
314
+ [`docs/VALIDATION-CODES.md`](https://github.com/project-wildshard/shard-format/blob/main/docs/VALIDATION-CODES.md);
315
+ the rule is chosen by that code, and each heading below that one names lists its codes.
312
316
 
313
317
  ### Any command
314
318
 
@@ -332,6 +336,22 @@ other name refuses before `new` writes anything. Leave the flag out or pass `--t
332
336
 
333
337
  `new` could not copy the reference world shipped with the sdk. Reinstall the sdk.
334
338
 
339
+ ### Update
340
+
341
+ #### update-target
342
+
343
+ `update` works on a shard repo: a folder whose `package.json` lists `@wildshard/sdk`, as `new` writes it. Run it in
344
+ that folder, or name it: `wildshard update my-shard`.
345
+
346
+ #### update-pins
347
+
348
+ `wildshard update --pins` (SA18) is not built yet. Move the pins by hand as the `wildshard-upgrade` skill says, then
349
+ run `wildshard update` with no flag.
350
+
351
+ #### update-refused
352
+
353
+ `update` could not copy this guide or a skill from the installed sdk. Reinstall the sdk (`pnpm install`).
354
+
335
355
  ### Build
336
356
 
337
357
  #### source-file-missing
@@ -398,31 +418,38 @@ the limit.
398
418
 
399
419
  #### budget-unmeasured
400
420
 
401
- A cost could not be measured: too few headless ticks for scripts, or native gameplay that needs a browser run.
421
+ A cost could not be measured: too few headless ticks for scripts, or native gameplay that needs a browser run. Codes
422
+ `perf-native-view-unmeasured`, `perf-native-resident-unmeasured`, `perf-script-sample-invalid`,
423
+ `perf-script-samples-missing`.
402
424
 
403
425
  #### budget-download
404
426
 
405
427
  Too many bytes to download, before play (critical) or in all (library). Shrink or drop assets, or load them later.
428
+ Codes `perf-library-download-budget`, `perf-critical-download-budget`, `perf-library-download`,
429
+ `perf-critical-download`, `perf-tile-download`, `perf-far-download`.
406
430
 
407
431
  #### budget-draws
408
432
 
409
- Too many draw calls in a view. Merge meshes that share a material, or show fewer objects from that view.
433
+ Too many draw calls in a view. Merge meshes that share a material, or show fewer objects from that view. Codes
434
+ `perf-tile-draws`, `perf-far-draws`.
410
435
 
411
436
  #### budget-triangles
412
437
 
413
- Too many triangles in a view. Use lower-detail meshes or fewer props there.
438
+ Too many triangles in a view. Use lower-detail meshes or fewer props there. Codes `perf-tile-triangles`,
439
+ `perf-far-triangles`.
414
440
 
415
441
  #### budget-memory
416
442
 
417
- A memory total is over its line. Smaller or fewer textures and meshes. Memory reports only, for now.
443
+ A memory total is over its line. Smaller or fewer textures and meshes. Memory reports only, for now. Codes
444
+ `perf-memory-target`, `perf-playing-memory`, `perf-loading-memory`.
418
445
 
419
446
  #### budget-script-cpu
420
447
 
421
- Behaviour scripts take too long per tick. Spread work over ticks, or run it on events.
448
+ Behaviour scripts take too long per tick. Spread work over ticks, or run it on events. Code `perf-script-cpu`.
422
449
 
423
450
  #### budget-script-fuel
424
451
 
425
- Behaviour scripts run too many instructions per tick. Shorten the hottest loops.
452
+ Behaviour scripts run too many instructions per tick. Shorten the hottest loops. Code `perf-script-fuel`.
426
453
 
427
454
  #### budget-over
428
455
 
@@ -431,6 +458,7 @@ A budget not named above is over its limit. The message names it; `wildshard che
431
458
  #### budget-refused
432
459
 
433
460
  Build or validate refused the whole report card. Run `wildshard check .`: its report step names each budget over.
461
+ Codes `declared-costs`, `performance-targets` (shard-format checking the costs the shard file declares).
434
462
 
435
463
  ### The shard file and the hero
436
464
 
@@ -454,6 +482,42 @@ Capture a new hero, build, prepare and upload again.
454
482
 
455
483
  The audio rules found a red problem: a recording that will not play, runs too long, or a shard over 10 MB of its own
456
484
  audio. Fix each red finding, or add a dated waiver in `audio-waiver.json`. Shard-format `docs/audio.md` explains each.
485
+ Code `audio-refused`. Build prints every finding with one of the rules below under it; only upload refuses a red one.
486
+
487
+ #### audio-unreadable
488
+
489
+ Red. The recording does not read as AAC-LC at 48 kHz, mono or stereo. Export it again in that form. Code
490
+ `audio-unreadable`.
491
+
492
+ #### audio-container
493
+
494
+ Red. The recording's bytes are FLAC, AIFF, Ogg, MP3, WebM, CAF or no container the game knows; it still counts toward
495
+ the audio budget. Export it again as AAC (in an mp4 file) or as WAV. Code `audio-container`.
496
+
497
+ #### audio-encoding
498
+
499
+ Amber. The recording plays, but it is PCM WAV, AAC at a sample rate other than 48 kHz, or AAC outside the strict
500
+ playback index. Encode it as AAC-LC at 48 kHz. Codes `audio-wav`, `audio-sample-rate`, `audio-strict-index`.
501
+
502
+ #### audio-duration
503
+
504
+ Red. The recording runs longer than the maximum the message gives. Cut it, or split it in two. Code `audio-duration`.
505
+
506
+ #### audio-bitrate
507
+
508
+ Amber. The recording's bitrate is over the cap for its role (music or sound effect) and channels. Encode it lower.
509
+ Code `audio-bitrate`.
510
+
511
+ #### audio-budget
512
+
513
+ The shard's own audio is over the amber line (amber), over the red line (red), or over the red line with a dated
514
+ waiver that holds (amber). Cut, shorten or re-encode recordings, or add a waiver in `audio-waiver.json`. Codes
515
+ `audio-budget-amber`, `audio-budget-red`, `audio-budget-waived`.
516
+
517
+ #### audio-waiver
518
+
519
+ Amber. `audio-waiver.json` names another shard, has expired, or covers fewer bytes than the shard holds, so it does
520
+ not hold; the budget finding after it says what that leaves. Code `audio-waiver-invalid`.
457
521
 
458
522
  #### shardfile-draft
459
523
 
@@ -471,7 +535,45 @@ There is no built folder to write a shard file from. Run `wildshard check .` (or
471
535
 
472
536
  #### shardfile-invalid
473
537
 
474
- The shard file breaks a format check. Upload the shard file `prepare` and `build <folder>` wrote, unedited.
538
+ The shard file breaks a format check: it is not a tarball shard-format can read. Upload the shard file `prepare` and
539
+ `build <folder>` wrote, unedited. Code `archive-invalid`.
540
+
541
+ #### shardfile-index
542
+
543
+ `shard.json` is missing, too large, not canonical JSON, or does not fit the index schema. Build again so it is written
544
+ for you; a hand-written shard file's `shard.json` must parse and fit. Code `index-invalid`.
545
+
546
+ #### shardfile-files
547
+
548
+ The files in the folder differ from the ones `shard.json` lists: one is missing, changed or a link, one is not listed,
549
+ a pack lacks a member, or the sections differ from the source hash. Something edited the built folder: build again.
550
+ Codes `file-mismatch`, `unlisted-file`, `source-hash`, `pack-invalid`.
551
+
552
+ #### shardfile-section
553
+
554
+ A section, or the whole shard file the sections make, does not fit its schema. The message gives the path;
555
+ `wildshard schema shardfile <pointer>` prints the expected shape. Codes `section-invalid`, `shard-schema`.
556
+
557
+ #### shardfile-assets
558
+
559
+ An asset's bytes do not match what the shard file declares (its kind, extension, schema, size or costs), or fail
560
+ the asset checks, or a mount or runtime file is wrong. Export the named asset again and build. Codes `blob-invalid`,
561
+ `server-file-invalid`, `ktx2-costs`, `asset-admission`, `cook-invalid`, `runtime-files`.
562
+
563
+ #### shardfile-scripts
564
+
565
+ A behaviour script runs on a side (client or server) its declaration does not allow, or the script rows are
566
+ invalid. Fix the declaration or move the script, then build again. Codes `script-side`, `script-admission`.
567
+
568
+ #### shardfile-targets
569
+
570
+ The world targets name an item or quest the shard does not declare. Declare it, or take it out. Code `world-targets`.
571
+
572
+ #### shardfile-stream
573
+
574
+ Upload's streaming check refused: a file, pack or the placed assets are over the streaming cap, or the stored file
575
+ changed while it was read. Shrink what the message names; if it changed mid-read, upload again. Codes `stream-cap`,
576
+ `stream-miss`, `stream-changed`.
475
577
 
476
578
  #### shardfile-refused
477
579
 
@@ -780,11 +882,14 @@ Code the headless simulation imports must not render.
780
882
 
781
883
  ## 7. `wildshard update`
782
884
 
783
- **Not built yet (SA28).** `new` writes the four `wildshard` skills (SA14, SA27) but no `AGENTS.md` yet (SA28). `wildshard update` will rewrite this guide and the four `wildshard` skills in `.claude/skills/` from the
784
- installed sdk, and touch nothing else; it will leave an `AGENTS.md` you changed and say so. `wildshard update --pins` (SA18, after the sdk is on npm)
785
- will also move the sdk, shard-format and `three` versions, install, apply the release's code changes and run the
786
- build.
787
-
788
- Until then: after you move to a newer sdk, copy `GUIDE.md` from the sdk (the sharddev checkout's root, or
789
- `node_modules/@wildshard/sdk/GUIDE.md` once installed from npm) over this one, and each of the sdk's
790
- `skills/wildshard*/SKILL.md` over `.claude/skills/<same name>/SKILL.md`. The `wildshard-upgrade` skill walks it.
885
+ `wildshard update` (or `wildshard update <dir>`) rewrites this guide and the four `wildshard` skills in
886
+ `.claude/skills/` from the installed sdk, and prints each file it wrote. Run it after you move to a newer sdk; the
887
+ `wildshard-upgrade` skill walks the whole move. It touches nothing else: your shard source, `package.json`, README and
888
+ every other file stay as they are. It adds the `.agents/skills/` links, `AGENTS.md` and `CLAUDE.md` only if one is
889
+ missing, and it leaves an `AGENTS.md` or `CLAUDE.md` you changed and says so (`left AGENTS.md: you changed it`). So
890
+ keep your own notes for agents in `AGENTS.md`, never in this guide or a skill: `update` rewrites those. Done when it
891
+ prints `already up to date` or the files it wrote, and `git status` shows only `GUIDE.md`, `.claude/skills/` and any
892
+ agent file it added.
893
+
894
+ `wildshard update --pins` (SA18) is not built yet: it will also move the sdk, shard-format and `three` versions,
895
+ install, apply the release's code changes and run the build.
package/bin/wildshard.mjs CHANGED
@@ -7,7 +7,7 @@ import { resolve } from 'node:path';
7
7
  import { existsSync } from 'node:fs';
8
8
  import '../src/sharddev/bake/format-hook.mjs';
9
9
 
10
- const AUTHOR = new Set(['new', 'check', 'synth', 'build', 'validate', 'prove', 'dev', 'schema', '--prepare-compiler']);
10
+ const AUTHOR = new Set(['new', 'update', 'check', 'synth', 'build', 'validate', 'prove', 'dev', 'schema', '--prepare-compiler']);
11
11
  const [command, operand] = process.argv.slice(2);
12
12
  // SA2: `wildshard <verb> --help` and `wildshard help [verb]` print help (src/cli/help.ts) before any verb runs.
13
13
  const verbHelp = command === 'help' || (command !== undefined && !command.startsWith('-') && process.argv.slice(3).some(arg => arg === '--help' || arg === '-h'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/sdk",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "The author's toolbox: the `wildshard` CLI that bakes shard source into a shardfile, the author SDK, the local dev server (engine client against engine server), the explorers, arena and drafts tool.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -82,7 +82,7 @@
82
82
  "@typescript/typescript6": "6.0.2",
83
83
  "@valibot/to-json-schema": "1.8.0",
84
84
  "@wildshard/engine": "github:project-wildshard/engine#867f3b968429d8b90ae33b363dae3f15f16f6b84",
85
- "@wildshard/format": "github:project-wildshard/shard-format#v0.4.6",
85
+ "@wildshard/format": "github:project-wildshard/shard-format#v0.4.8",
86
86
  "ajv": "6.15.0",
87
87
  "assemblyscript": "0.28.20",
88
88
  "binaryen": "132.0.0",
@@ -196,7 +196,7 @@
196
196
  "overrides": {
197
197
  "binaryen": "npm:@pre-bundled/binaryen@132.0.0-patch-1",
198
198
  "assemblyscript>binaryen": "npm:@pre-bundled/binaryen@131.0.0-nightly.20260721-patch-1",
199
- "@wildshard/format": "github:project-wildshard/shard-format#v0.4.6"
199
+ "@wildshard/format": "github:project-wildshard/shard-format#v0.4.8"
200
200
  }
201
201
  },
202
202
  "exports": {
@@ -25,17 +25,18 @@ steps below by hand.
25
25
  3. **Edit the pins** in this repo's `package.json` to those exact specs: no `^`, no `~`. Done when every pin matches.
26
26
  4. **Install:** `pnpm install`. A dependency's install script runs only if `pnpm-workspace.yaml` lists it
27
27
  (`GUIDE.md#2-the-shard-source`). Done when install exits 0 and `pnpm-lock.yaml` changed.
28
- 5. **Refresh the guide and skills.** Copy the sdk's `GUIDE.md` over this repo's, and each of the sdk's
29
- `skills/wildshard*/SKILL.md` to `.claude/skills/<same name>/SKILL.md`, adding any this repo lacks
30
- (`GUIDE.md#7-wildshard-update`). Then reread this skill: the new copy may differ. Done when `git diff` shows only
31
- those files and the step 3 and 4 files.
32
- 6. **Build** with the new sdk's CLI (point the `wildshard` alias at the newer checkout): `wildshard check .`
33
- (`GUIDE.md#1-the-loop`). Done when `wildshard --version` prints the new sdk version and the last line reads
34
- `check pass`.
28
+ 5. **Refresh the guide and skills** with the new sdk's CLI (point the `wildshard` alias at the newer checkout, or
29
+ `pnpm exec wildshard` after step 4): `wildshard update`. It rewrites `GUIDE.md` and the four skills in
30
+ `.claude/skills/`, adds any agent file the repo lacks, and keeps an `AGENTS.md` you changed
31
+ (`GUIDE.md#7-wildshard-update`). Then reread this skill: the new copy may differ. Done when update's first line
32
+ names the new sdk version and `git status` shows only those files and the step 3 and 4 files.
33
+ 6. **Build:** `wildshard check .` (`GUIDE.md#1-the-loop`). Done when `wildshard --version` prints the new sdk
34
+ version and the last line reads `check pass`.
35
35
  7. **Read each refusal.** It ends `[<rule>] fix: ... (GUIDE.md#<anchor>)`: read that heading under
36
- `GUIDE.md#6-refusals-and-their-fixes`, in the guide you copied in step 5, make the fix, and run check again. A
36
+ `GUIDE.md#6-refusals-and-their-fixes`, in the guide update wrote in step 5, make the fix, and run check again. A
37
37
  budget can tighten between releases (`GUIDE.md#3-budgets`); a lint rule can be new. Done at `check pass`.
38
- 8. **Commit** the pins, the lock file, the guide, the skills and your fixes together. Done when `git status` is clean.
38
+ 8. **Commit** the pins, the lock file, the guide, the skills, any agent file update added and your fixes together.
39
+ Done when `git status` is clean.
39
40
  A new sdk can change what the shard looks like, so before the next upload follow the `wildshard-goldens` skill.
40
41
 
41
42
  ## Rules
@@ -1,5 +1,7 @@
1
1
  import { installFormatHook } from '@wildshard/format/formatHook'
2
2
 
3
+ import { refusalHint, refusalNote } from '../../sharddev/refusals.ts'
4
+
3
5
  import type { AudioReport } from '@wildshard/format/audioRules'
4
6
 
5
7
  // AUDIO AU5 (meta docs/plans/AUDIO-PLAN.md, J299): format owns the audio
@@ -7,11 +9,24 @@ import type { AudioReport } from '@wildshard/format/audioRules'
7
9
  // refuses a red before it spends the upload, as api-server's admission
8
10
  // will. A waiver lives in the shard source (`audio-waiver.json`).
9
11
 
10
- /** The report as pack prints it: totals, then one AMBER line per finding. */
12
+ /** The report as build prints it: totals, then one AMBER line per finding,
13
+ * each followed by its rule, fix and GUIDE.md link, named by its code (SA41). */
11
14
  async function audioLines(report: Readonly<AudioReport>): Promise<string[]> {
12
15
  installFormatHook()
13
16
  const { audioReportLines } = await import('@wildshard/format/audioRules')
14
- return audioReportLines(report)
17
+ const [totals = '', ...findings] = audioReportLines(report)
18
+ return [
19
+ totals,
20
+ ...findings.flatMap((line: string, at: number): string[] => {
21
+ const finding = report.findings[at]
22
+ return finding === undefined
23
+ ? [line]
24
+ : [
25
+ line,
26
+ ` ${refusalHint(refusalNote('shardfile', finding.message, { code: finding.code }))}`,
27
+ ]
28
+ }),
29
+ ]
15
30
  }
16
31
 
17
32
  /** Refuse a red report, with format's reason. */
package/src/cli/help.ts CHANGED
@@ -24,6 +24,14 @@ const VERBS: Readonly<Record<string, string>> = {
24
24
  blender copies the hand-written Blender template
25
25
  (a shard file folder, no code). --empty writes a
26
26
  bare shard source instead`,
27
+ update: `update [dir]
28
+ Rewrite GUIDE.md and the four wildshard skills in
29
+ .claude/skills/ from the installed sdk (dir: the
30
+ shard repo, default the current folder). Adds the
31
+ .agents/skills links, AGENTS.md and CLAUDE.md if
32
+ missing; touches nothing else, and leaves an
33
+ AGENTS.md you changed (it says so). Run it after
34
+ moving to a newer sdk. --pins is not built yet`,
27
35
  dev: `dev <source> [port]
28
36
  Serve the shard source on localhost (port 0, the
29
37
  default, picks a free one) and build it again on
package/src/cli/main.ts CHANGED
@@ -211,8 +211,7 @@ async function runUpload(args: CliArgs): Promise<number> {
211
211
  await uploadShardfile(options)
212
212
  return EXIT_OK
213
213
  } catch (error: unknown) {
214
- const reason = error instanceof Error ? error.message : String(error)
215
- refuse('upload', 'upload failed: ', reason)
214
+ refuse('upload', 'upload failed: ', error)
216
215
  return EXIT_FAILED
217
216
  }
218
217
  }
package/src/cli/report.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { refusalHint, refusalNote } from '../sharddev/refusals.ts'
1
+ import { refusalCode, refusalHint, refusalNote } from '../sharddev/refusals.ts'
2
2
 
3
3
  import type { RefusalStep } from '../sharddev/refusals.ts'
4
4
 
@@ -7,9 +7,13 @@ function reportLine(line: string): void {
7
7
  process.stdout.write(`${line}\n`)
8
8
  }
9
9
 
10
- /** A refusal on stderr, then its rule, fix and GUIDE.md link (SA21). */
11
- function refuse(step: RefusalStep, prefix: string, reason: string): void {
12
- const hint = refusalHint(refusalNote(step, reason))
10
+ /** A refusal on stderr, then its rule, fix and GUIDE.md link (SA21). `refusal` is the words, or the error: its message,
11
+ * and its shard-format code names the rule when it has one (SA41). */
12
+ function refuse(step: RefusalStep, prefix: string, refusal: unknown): void {
13
+ const reason = refusal instanceof Error ? refusal.message : String(refusal)
14
+ const hint = refusalHint(
15
+ refusalNote(step, reason, { code: refusalCode(refusal) }),
16
+ )
13
17
  process.stderr.write(`sharddev: ${prefix}${reason}\n ${hint}\n`)
14
18
  }
15
19
 
@@ -32,8 +32,7 @@ async function runShardfile(
32
32
  })
33
33
  return EXIT_OK
34
34
  } catch (error: unknown) {
35
- const reason = error instanceof Error ? error.message : String(error)
36
- refuse(STEP, `${step} failed: `, reason)
35
+ refuse(STEP, `${step} failed: `, error)
37
36
  return EXIT_FAILED
38
37
  }
39
38
  }
@@ -0,0 +1,127 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- `new` and `update` own only a shard repo's agent files.
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, symlinkSync, writeFileSync } from 'node:fs';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Resolve files beneath the shard repo and the installed sdk.
4
+ import { dirname, resolve } from 'node:path';
5
+
6
+ // SHARD-AUTHORING SA28 (J314 Q7, Q8, Q27): the agent files of a shard repo. `new` and `update` both run
7
+ // `syncAgentFiles`: GUIDE.md and the four skills are the sdk's and are rewritten from the installed sdk; the
8
+ // `.agents/skills` links, AGENTS.md and CLAUDE.md are written when missing and otherwise left as the author keeps them.
9
+
10
+ /** The installed sdk's package root: GUIDE.md, `skills/` and package.json ship there (`files`). */
11
+ export const SDK_ROOT: string = resolve(import.meta.dirname, '../..');
12
+
13
+ /** SA13 (J314): the author's manual at the package root; `new` and `update` copy it into the repo. */
14
+ export const GUIDE_SOURCE: string = resolve(SDK_ROOT, 'GUIDE.md');
15
+
16
+ /** SA14, SA27 (J314 Q6): the core `wildshard` skill and its three siblings, at the package's `skills/`. */
17
+ export const SKILLS = ['wildshard', 'wildshard-mockup-to-model', 'wildshard-goldens', 'wildshard-upgrade'] as const;
18
+ export type SkillName = (typeof SKILLS)[number];
19
+ /** A skill's file in the installed sdk (or in `root`, another sdk). */
20
+ export const skillSource = (name: SkillName, root: string = SDK_ROOT): string => resolve(root, `skills/${name}/SKILL.md`);
21
+ /** Where a repo keeps a skill: Claude Code lists project skills from `.claude/skills/<name>/SKILL.md`. */
22
+ export const skillFile = (name: SkillName): string => `.claude/skills/${name}/SKILL.md`;
23
+ /** Codex lists project skills from `.agents/skills/<name>/`: a link to the Claude Code folder, so both read one copy. */
24
+ export const skillLink = (name: SkillName): string => `.agents/skills/${name}`;
25
+ /** The link's target, relative to `.agents/skills/`, so the repo keeps working wherever it is cloned. */
26
+ export const skillLinkTarget = (name: SkillName): string => `../../.claude/skills/${name}`;
27
+ /** The core `wildshard` skill (SA14). */
28
+ export const SKILL_SOURCE: string = skillSource('wildshard');
29
+ export const SKILL_FILE: string = skillFile('wildshard');
30
+
31
+ export const AGENTS_FILE = 'AGENTS.md';
32
+ export const CLAUDE_FILE = 'CLAUDE.md';
33
+ /** The repo's AGENTS.md as `new` writes it (Q8): read the guide first; the skills are in `.claude/skills/`. */
34
+ export const AGENTS_TEXT = `# AGENTS.md
35
+
36
+ This is a Wildshard shard repo: its shard source is at \`src/\`.
37
+
38
+ - Read \`GUIDE.md\` first. It is the author's manual: the loop, the shard source layout, budgets, and every refusal
39
+ with its fix.
40
+ - The skills are in \`.claude/skills/\`: \`wildshard\` (the loop, in order), \`wildshard-mockup-to-model\`,
41
+ \`wildshard-goldens\` and \`wildshard-upgrade\`. \`.agents/skills/\` links to the same folders, for Codex.
42
+ - \`wildshard update\` rewrites \`GUIDE.md\` and those four skills from the installed sdk, so never edit them here.
43
+ It leaves this file alone once you change it: add your own rules below.
44
+ `;
45
+ /** Claude Code reads CLAUDE.md; it imports AGENTS.md so both agents read one file. */
46
+ export const CLAUDE_TEXT = '@AGENTS.md\n';
47
+ /** Every AGENTS.md text an earlier sdk wrote. `update` replaces an untouched copy of one of these and leaves any other
48
+ * text, which the author wrote. When AGENTS_TEXT changes, add the old text here. */
49
+ const PAST_AGENTS_TEXTS: readonly string[] = [];
50
+
51
+ /** What `syncAgentFiles` did to one file. `left` is a file the author changed, kept as it is. */
52
+ export type AgentFileAction = 'added' | 'updated' | 'unchanged' | 'left';
53
+ export interface AgentFileChange { readonly file: string; readonly action: AgentFileAction }
54
+
55
+ /** Write `text` to `file` unless it already holds it; the sdk's files are always the sdk's. */
56
+ function writeOwned(project: string, file: string, text: Buffer): AgentFileAction {
57
+ const path = resolve(project, file);
58
+ if (!existsSync(path)) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); return 'added'; }
59
+ if (readFileSync(path).equals(text)) return 'unchanged';
60
+ writeFileSync(path, text);
61
+ return 'updated';
62
+ }
63
+
64
+ /** Write `text` to `file` only when it is missing, or still one of the sdk's own `past` texts. */
65
+ function writeAuthored(project: string, file: string, text: string, past: readonly string[]): AgentFileAction {
66
+ const path = resolve(project, file);
67
+ if (!existsSync(path)) { writeFileSync(path, text); return 'added'; }
68
+ const now = readFileSync(path, 'utf8');
69
+ if (now === text) return 'unchanged';
70
+ if (!past.includes(now)) return 'left';
71
+ writeFileSync(path, text);
72
+ return 'updated';
73
+ }
74
+
75
+ /** Link `.agents/skills/<name>` to the Claude Code skill folder, unless something of the author's is there. */
76
+ function writeLink(project: string, name: SkillName): AgentFileAction {
77
+ const path = resolve(project, skillLink(name)), target = skillLinkTarget(name);
78
+ let stat;
79
+ try { stat = lstatSync(path); } catch { stat = undefined; }
80
+ if (stat === undefined) { mkdirSync(dirname(path), { recursive: true }); symlinkSync(target, path, 'dir'); return 'added'; }
81
+ return stat.isSymbolicLink() && readlinkSync(path) === target ? 'unchanged' : 'left';
82
+ }
83
+
84
+ /**
85
+ * SA28: `new` and `update`. Rewrite GUIDE.md and the four skills from the sdk at `root` (the installed one), and write
86
+ * the `.agents/skills` links, AGENTS.md and CLAUDE.md when missing. Touches nothing else: a file whose bytes already
87
+ * match is not rewritten, and an AGENTS.md, CLAUDE.md or link the author changed is left as it is.
88
+ */
89
+ export function syncAgentFiles(project: string, root: string = SDK_ROOT, pastAgentsTexts: readonly string[] = PAST_AGENTS_TEXTS): readonly AgentFileChange[] {
90
+ const changes: AgentFileChange[] = [{ file: 'GUIDE.md', action: writeOwned(project, 'GUIDE.md', readFileSync(resolve(root, 'GUIDE.md'))) }];
91
+ for (const name of SKILLS) changes.push({ file: skillFile(name), action: writeOwned(project, skillFile(name), readFileSync(skillSource(name, root))) });
92
+ for (const name of SKILLS) changes.push({ file: skillLink(name), action: writeLink(project, name) });
93
+ changes.push({ file: AGENTS_FILE, action: writeAuthored(project, AGENTS_FILE, AGENTS_TEXT, pastAgentsTexts) });
94
+ changes.push({ file: CLAUDE_FILE, action: writeAuthored(project, CLAUDE_FILE, CLAUDE_TEXT, []) });
95
+ return changes;
96
+ }
97
+
98
+ /** The sdk version at `root`, for update's first line. */
99
+ function sdkVersion(root: string): string {
100
+ const parsed: unknown = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
101
+ return typeof parsed === 'object' && parsed !== null && 'version' in parsed && typeof parsed.version === 'string' ? parsed.version : 'unknown';
102
+ }
103
+
104
+ /** A shard repo is a folder whose package.json lists `@wildshard/sdk` (`new` writes it; a blender repo as a dev dependency). */
105
+ function assertShardRepo(project: string): void {
106
+ const file = resolve(project, 'package.json');
107
+ let parsed: unknown;
108
+ try { parsed = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : undefined; }
109
+ catch (error) { throw new Error(`update: ${project} is not a shard repo: its package.json is not valid JSON (${error instanceof Error ? error.message : String(error)})`, { cause: error }); }
110
+ const fields: unknown[] = typeof parsed === 'object' && parsed !== null
111
+ ? [Reflect.get(parsed, 'dependencies'), Reflect.get(parsed, 'devDependencies')] : [];
112
+ if (!fields.some(field => typeof field === 'object' && field !== null && Object.hasOwn(field, '@wildshard/sdk'))) throw new Error(`update: ${project} is not a shard repo: its package.json does not list @wildshard/sdk (or it has none)`);
113
+ }
114
+
115
+ /** `wildshard update [dir]`: sync the agent files of the shard repo at `project`, and say what changed, one line each. */
116
+ export function updateShardRepo(project: string, root: string = SDK_ROOT): string[] {
117
+ assertShardRepo(project);
118
+ const changes = syncAgentFiles(project, root);
119
+ const lines = [`wildshard update: GUIDE.md and the skills from @wildshard/sdk ${sdkVersion(root)}`];
120
+ for (const { file, action } of changes) {
121
+ if (action === 'left') lines.push(` left ${file}: you changed it, so update kept yours`);
122
+ else if (action !== 'unchanged') lines.push(` ${action} ${file}`);
123
+ }
124
+ const touched = changes.filter(change => change.action === 'added' || change.action === 'updated').length;
125
+ lines.push(touched === 0 ? ' already up to date' : ` ${String(touched)} file${touched === 1 ? '' : 's'} written; nothing else touched`);
126
+ return lines;
127
+ }
@@ -3,7 +3,7 @@
3
3
  // SA21: every refusal carries a rule id, a one-line fix and a GUIDE.md link, from refusals.ts.
4
4
  import { diagnosticNow } from '@wildshard/engine/core/clock';
5
5
  import { authorErrorText } from './authorError';
6
- import { refusalHint, refusalNote, type RefusalStep } from './refusals';
6
+ import { refusalCode, refusalHint, refusalNote, type RefusalStep } from './refusals';
7
7
 
8
8
  /** The five steps, in the order they run. */
9
9
  export type CheckStepName = 'lint' | 'build' | 'validate' | 'prove' | 'report';
@@ -19,8 +19,9 @@ export interface CheckRefusal {
19
19
  readonly guide: string;
20
20
  readonly file?: string;
21
21
  }
22
- /** A refusal as a step reports it: a lint diagnostic brings oxlint's code and help; refusals.ts fills in the rest. */
23
- export interface StepRefusal { readonly message: string; readonly lint?: { readonly code: string | null; readonly help: string | null }; readonly file?: string; readonly as?: RefusalStep }
22
+ /** A refusal as a step reports it: a lint diagnostic brings oxlint's code and help, a shard-format refusal its stable
23
+ * code (SA41); refusals.ts fills in the rest. */
24
+ export interface StepRefusal { readonly message: string; readonly lint?: { readonly code: string | null; readonly help: string | null }; readonly code?: string | undefined; readonly file?: string; readonly as?: RefusalStep }
24
25
  /** A warning: the same fields as a refusal, but it does not fail the verdict (an unprepared draft, J198). */
25
26
  export type CheckWarning = CheckRefusal;
26
27
  /** One step's result and wall-clock duration in milliseconds. */
@@ -53,15 +54,15 @@ const NEEDS_BUILD = new Set<CheckStepName>(['validate', 'prove', 'report']);
53
54
 
54
55
  async function outcomeOf(work: () => Promise<StepOutcome>): Promise<StepOutcome> {
55
56
  try { return await work(); }
56
- catch (error) { return { status: 'fail', refusals: [{ message: authorErrorText(error) }] }; }
57
+ catch (error) { return { status: 'fail', refusals: [{ message: authorErrorText(error), code: refusalCode(error) }] }; }
57
58
  }
58
59
 
59
60
  /** Run every step in order, timing each, and give the verdict. `output` is read after the build; `now` is for tests. */
60
61
  export async function runCheck(project: string, output: () => string | null, steps: CheckSteps, now: () => number = diagnosticNow): Promise<CheckResult> {
61
62
  const started = now(), rows: CheckStep[] = [], refusals: CheckRefusal[] = [], warnings: CheckWarning[] = [];
62
- const named = (step: CheckStepName, { message, lint, file, as }: StepRefusal): CheckRefusal => {
63
+ const named = (step: CheckStepName, { message, lint, code, file, as }: StepRefusal): CheckRefusal => {
63
64
  // SA3: build's shard file step names its rules by its own step (a format refusal is not a source one).
64
- const { rule, fix, guide } = refusalNote(as ?? step, message, lint);
65
+ const { rule, fix, guide } = refusalNote(as ?? step, message, { lint, code });
65
66
  return { step, rule, message, fix, guide, ...(file === undefined ? {} : { file }) };
66
67
  };
67
68
  let built = true;
@@ -19,6 +19,7 @@ import { performanceReport, type PerformanceObservations } from './reportCard';
19
19
  import { lintOutcome, runCheck, type CheckResult, type StepOutcome } from './check';
20
20
  import type { ProjectManifestSource } from './projectManifest';
21
21
  import { authorErrorText } from './authorError';
22
+ import { refusalCode } from './refusals';
22
23
  import { DRAFT_SDK, draftMessage } from './draft';
23
24
 
24
25
  /** The author proof tape `check` runs when the project has one (format: `AuthorProofPlanSchema`). */
@@ -96,7 +97,7 @@ export async function checkProject(projectPath: string, outputPath: string | und
96
97
  let file: string | undefined;
97
98
  // The draft warning goes in the verdict (below), so the writer leaves it out.
98
99
  try { file = await options.writeShardfile?.(output, project, { draftWarning: false }); }
99
- catch (error) { return { status: 'fail', refusals: [{ message: authorErrorText(error), as: 'shardfile' }] }; }
100
+ catch (error) { return { status: 'fail', refusals: [{ message: authorErrorText(error), code: refusalCode(error), as: 'shardfile' }] }; }
100
101
  const warnings = isDraft(output) ? [{ message: draftMessage(shard.identity.slug), as: 'shardfile' as const }] : [];
101
102
  return { status: 'pass', note: `built ${shard.identity.slug} v${shard.version}${file === undefined ? '' : `, ${file}`}`, warnings };
102
103
  },
@@ -120,7 +121,7 @@ export async function checkProject(projectPath: string, outputPath: string | und
120
121
  const warnings = card.issues.length - refused.length;
121
122
  const note = `${(card.download.total / 1024 / 1024).toFixed(2)} MB download, ~${card.estimatedPlayable.seconds.toFixed(1)} s to playable, ${warnings} warning${warnings === 1 ? '' : 's'}`;
122
123
  return await Promise.resolve({ status: card.pass ? 'pass' : 'fail', note,
123
- refusals: refused.map(issue => ({ message: `${issue.metric}: ${String(issue.actual)} over ${String(issue.limit)}` })) });
124
+ refusals: refused.map(issue => ({ message: `${issue.metric}: ${String(issue.actual)} over ${String(issue.limit)}`, code: issue.code })) });
124
125
  },
125
126
  });
126
127
  }
@@ -21,10 +21,11 @@ import { outputScriptAdmissionRows, validateOutputProduct } from './outputProduc
21
21
  import { locatedError } from './authorError';
22
22
  import type { ProjectManifestSource } from './projectManifest';
23
23
  import { templateNamed, writeShardRepo } from './newProject';
24
+ import { updateShardRepo } from './agentFiles';
24
25
  import { findShardSource, isHandwrittenSource, isRepoSource, shardOutputRoot } from './shardSource';
25
26
  import { checkProject, readProofTape } from './checkProject';
26
27
  import { checkLines } from './check';
27
- import { refusalHint, refusalNote, type RefusalStep } from './refusals';
28
+ import { refusalCode, refusalHint, refusalNote, type RefusalStep } from './refusals';
28
29
 
29
30
  const unmeasured: PerformanceObservations = { scripts: { p95Micros: 0, maxMicros: 0, samples: 0 }, fuel: { p95: 0, max: 0, samples: 0 } };
30
31
  function printReport(shard: Shardfile, observed: PerformanceObservations, policy: 'warn' | 'refuse'): void {
@@ -80,6 +81,14 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
80
81
  if (result.verdict === 'fail') process.exitCode = 1;
81
82
  return;
82
83
  }
84
+ if (command === 'update') {
85
+ // SA28 (J314 Q7, Q27): one verb; `update --pins` (SA18) will also move the pins, install and run the build.
86
+ const rest = args.slice(1);
87
+ if (rest.includes('--pins')) throw new Error('update --pins is not built yet (SA18): move the pins by hand (the wildshard-upgrade skill), then run wildshard update');
88
+ if (rest.length > 1 || rest.some(value => value.startsWith('-'))) throw new Error('usage: wildshard update [dir]');
89
+ for (const line of updateShardRepo(resolve(rest[0] ?? '.'))) console.info(line);
90
+ return;
91
+ }
83
92
  if (input === undefined) throw new Error('usage: wildshard new <dir> | check <source> [folder] [--json] | synth <source> | build <source> [folder] [--shardfile-only|--folder-only] [--no-placeholders] [--output=<slug>] | build <source> --behaviour-only | validate <source|shard.json> | dev <source> [port] (wildshard --help lists them all)');
84
93
  // SA16 (J314): a hand-written src/ (--template blender) has no shard.config.ts to build, synth or serve; check settles it.
85
94
  if ((command === 'build' || command === 'synth' || command === 'dev') && isRepoSource(resolve(input)) && isHandwrittenSource(resolve(input))) throw new Error(`${command}: ${input} is a hand-written shard file (--template blender): run wildshard check on the repo, which settles and builds it`);
@@ -176,13 +185,13 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
176
185
  throw new Error('unknown wildshard command');
177
186
  }
178
187
  /** The step a verb's refusal comes from (SA21): `dev` and `synth` build. */
179
- const STEPS: Readonly<Record<string, RefusalStep>> = { new: 'new', validate: 'validate', prove: 'prove' };
188
+ const STEPS: Readonly<Record<string, RefusalStep>> = { new: 'new', update: 'update', validate: 'validate', prove: 'prove' };
180
189
  /** The refusal with its rule, fix and GUIDE.md link on a second line; the first line stays the refusing code's words. */
181
190
  function authorRefusal(command: string | undefined, error: unknown): unknown {
182
191
  const located = locatedError(error);
183
192
  const message = located instanceof Error ? located.message : String(located);
184
193
  const step = error instanceof ShardfileRefusalError ? 'shardfile' : command !== undefined && Object.hasOwn(STEPS, command) ? STEPS[command] : undefined;
185
- const hint = refusalHint(refusalNote(step ?? 'build', message));
194
+ const hint = refusalHint(refusalNote(step ?? 'build', message, { code: refusalCode(error) }));
186
195
  return new Error(`${message}\n ${hint}`, { cause: error });
187
196
  }
188
197
  /** Run the author CLI; returns only after validation/build completes. */
@@ -5,6 +5,7 @@ import { resolve } from 'node:path';
5
5
  import { encodeCanonicalJson } from './immutable';
6
6
  import { authorCard } from './authorManifest';
7
7
  import { writeHandwrittenSource } from './handwritten';
8
+ import { syncAgentFiles } from './agentFiles';
8
9
 
9
10
  /**
10
11
  * SA39 (J319): generators may install any npm package, so a dependency's install scripts run only when listed here.
@@ -30,29 +31,6 @@ function writeInstallScriptPolicy(project: string): void {
30
31
  writeFileSync(resolve(project, 'pnpm-workspace.yaml'), INSTALL_SCRIPT_POLICY);
31
32
  }
32
33
 
33
- /** SA13 (J314): the author's manual at the package root, shipped by `files`; `new` copies it into every project. */
34
- export const GUIDE_SOURCE: string = resolve(import.meta.dirname, '../../GUIDE.md');
35
-
36
- /** SA14, SA27 (J314 Q6): the core `wildshard` skill and its three siblings, at the package's `skills/`, shipped by `files`. */
37
- export const SKILLS = ['wildshard', 'wildshard-mockup-to-model', 'wildshard-goldens', 'wildshard-upgrade'] as const;
38
- export type SkillName = (typeof SKILLS)[number];
39
- /** A skill's file in the installed sdk. */
40
- export const skillSource = (name: SkillName): string => resolve(import.meta.dirname, `../../skills/${name}/SKILL.md`);
41
- /** Where a project keeps a skill: Claude Code lists project skills from `.claude/skills/<name>/SKILL.md`. */
42
- export const skillFile = (name: SkillName): string => `.claude/skills/${name}/SKILL.md`;
43
- /** The core `wildshard` skill (SA14). */
44
- export const SKILL_SOURCE: string = skillSource('wildshard');
45
- export const SKILL_FILE: string = skillFile('wildshard');
46
-
47
- /** Copy the installed sdk's GUIDE.md and the four `wildshard` skills into the project, byte for byte. */
48
- function writeGuide(project: string): void {
49
- cpSync(GUIDE_SOURCE, resolve(project, 'GUIDE.md'));
50
- for (const name of SKILLS) {
51
- mkdirSync(resolve(project, `.claude/skills/${name}`), { recursive: true });
52
- cpSync(skillSource(name), resolve(project, skillFile(name)));
53
- }
54
- }
55
-
56
34
  /** SA16 (J314, J317): `new --template <name>`. `sdk` is Mossgate (sharddev's `_template`); `blender` is shard-format's
57
35
  * hand-written `blender-template` (`corpus/handwritten`): a shard file folder held by hand, no sdk at runtime, no three. */
58
36
  export const TEMPLATES = ['sdk', 'blender'] as const;
@@ -170,7 +148,8 @@ ${layout}
170
148
  `;
171
149
  }
172
150
 
173
- /** Write the repo files around a shard source at `src/`: package.json, tsconfig, ignores, README, guide and skill. */
151
+ /** Write the repo files around a shard source at `src/`: package.json, tsconfig, ignores, README, and the agent files
152
+ * (GUIDE.md, the four skills, their `.agents/skills` links, AGENTS.md and CLAUDE.md; SA28). */
174
153
  function writeRepoFiles(project: string, slug: string, template: TemplateName, empty: boolean): void {
175
154
  writeFileSync(resolve(project, 'package.json'), repoPackageJson(slug, empty ? DEFAULT_TEMPLATE : template));
176
155
  // A hand-written repo holds no TypeScript to check.
@@ -179,7 +158,7 @@ function writeRepoFiles(project: string, slug: string, template: TemplateName, e
179
158
  writeFileSync(resolve(project, '.npmrc'), NPMRC);
180
159
  writeFileSync(resolve(project, 'README.md'), repoReadme(slug, template, empty));
181
160
  writeInstallScriptPolicy(project);
182
- writeGuide(project);
161
+ syncAgentFiles(project);
183
162
  }
184
163
 
185
164
  /** Copy the shipped teaching world into `source`; generation and gameplay remain authored there. */
@@ -1,15 +1,26 @@
1
1
  // oxlint-disable-next-line import/no-nodejs-modules -- Only canonical checkout paths can receive the old-six offline warning policy.
2
- import { existsSync, realpathSync } from 'node:fs';
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
3
  // oxlint-disable-next-line import/no-nodejs-modules -- Author identities and symlink spellings do not confer checkout provenance.
4
4
  import { resolve } from 'node:path';
5
5
  import type { Shardfile } from '@wildshard/engine/host/shardfile';
6
6
 
7
7
  const legacy = new Set(['driftwood-isle', 'pine-hollow', 'nalati-grasslands', 'far-reach', 'sunscar-dunes', 'nine-dragon-stack']);
8
+ /** A first-party shard repo is `project-wildshard/shard-*`, its package `@wildshard/shard-*`. SA28: `wildshard new` writes
9
+ * an AGENTS.md into every author repo, so AGENTS.md alone no longer tells a first-party checkout from a `new` one. */
10
+ function firstPartyCheckout(root: string): boolean {
11
+ const file = resolve(root, 'package.json');
12
+ if (!existsSync(file) || !existsSync(resolve(root, 'AGENTS.md'))) return false;
13
+ try {
14
+ const parsed: unknown = JSON.parse(readFileSync(file, 'utf8'));
15
+ const name: unknown = typeof parsed === 'object' && parsed !== null ? Reflect.get(parsed, 'name') : undefined;
16
+ return typeof name === 'string' && name.startsWith('@wildshard/shard-');
17
+ } catch { return false; }
18
+ }
8
19
  /** Offline policy is selected by trusted checkout provenance, never by author slug or a product flag. */
9
- export function projectPerformancePolicy(project: string | undefined, source: Pick<Shardfile,'identity'>): 'warn' | 'refuse' {
20
+ export function projectPerformancePolicy(project: string | undefined, source: Pick<Shardfile,'identity'>, root: string = process.cwd()): 'warn' | 'refuse' {
10
21
  if (project === undefined || !legacy.has(source.identity.slug)) return 'refuse';
11
- const root = process.cwd(); // P4: a first-party shard repo is the checkout, and it holds the shard at this path.
12
- if (!existsSync(resolve(root, 'AGENTS.md'))) return 'refuse';
22
+ // P4: a first-party shard repo is the checkout (the cwd), and it holds the shard at this path.
23
+ if (!firstPartyCheckout(root)) return 'refuse';
13
24
  // SA16 (J317): a single-shard repo holds it at src/ (SA24 moves the six there), a multi-shard repo at src/shards/<slug>/.
14
25
  const canonical = existsSync(resolve(root, 'src/shard.config.ts')) ? resolve(root, 'src') : resolve(root, 'src/shards', source.identity.slug);
15
26
  if (!existsSync(project) || !existsSync(canonical)) return 'refuse';
@@ -3,21 +3,32 @@
3
3
  // local checks) names a stable rule id, a one-line fix and a
4
4
  // GUIDE.md section. This file is the one table. GUIDE.md (SA13) writes one heading per anchor below, so
5
5
  // `GUIDE.md#<anchor>` lands on it; refusals.test.ts fails a row with no fix or anchor and a wildshard lint rule with no
6
- // row. Rule ids are stable: rename one only together with its GUIDE.md heading. A message takes the first row (in table
7
- // order) for its step whose pattern matches, else its step's catch-all (the row with no pattern), wherever that sits.
6
+ // row. Rule ids are stable: rename one only together with its GUIDE.md heading.
7
+ //
8
+ // SA41: shard-format's refusals carry a stable code (its `issue-codes.ts`, docs/VALIDATION-CODES.md): a validator's
9
+ // `error.code`, `PerformanceIssue.code`, `AudioFinding.code`. A coded refusal takes the row that lists its code, from any
10
+ // step; every one of shard-format's codes has a row (refusals.test.ts fails a new code with none). Words are the fallback
11
+ // for refusals with no code (sharddev's own, and shard-format's admitted-with-warning lines): a message takes the first
12
+ // row (in table order) for its step whose pattern matches, else its step's catch-all (the row with neither pattern nor
13
+ // codes), wherever that sits.
8
14
  //
9
15
  // Messages stay as the refusing code (and shard-format) words them: a row matches them, it never rewrites them.
16
+ import type { IssueCode } from '@wildshard/format/issue-codes';
10
17
 
11
18
  /** Where a refusal came from: `check`'s five steps, then the other verbs. `shardfile` is the shard file build writes (SA3). */
12
- export type RefusalStep = 'lint' | 'build' | 'validate' | 'prove' | 'report' | 'new' | 'shardfile' | 'pack' | 'upload' | 'account' | 'delete';
13
- /** One rule: its id, its GUIDE.md anchor, the fix, and the refusal messages it names (none: the step's catch-all). */
19
+ export type RefusalStep = 'lint' | 'build' | 'validate' | 'prove' | 'report' | 'new' | 'update' | 'shardfile' | 'pack' | 'upload' | 'account' | 'delete';
20
+ /** One rule: its id, its GUIDE.md anchor, the fix, the shard-format codes it names (from any step) and the refusal
21
+ * messages it names in `steps` (neither: the step's catch-all). */
14
22
  export interface RefusalRule {
15
23
  readonly id: string;
16
24
  readonly anchor: string;
17
25
  readonly fix: string;
18
26
  readonly steps: readonly RefusalStep[] | 'any';
27
+ readonly codes?: readonly IssueCode[];
19
28
  readonly match?: RegExp;
20
29
  }
30
+ /** What a refusal carries besides its words: oxlint's code and help, or shard-format's issue code. */
31
+ export interface RefusalSource { readonly lint?: { readonly code: string | null; readonly help: string | null } | undefined; readonly code?: string | undefined }
21
32
  /** What a printed refusal carries besides its message. `guide` is `GUIDE.md#<anchor>`. */
22
33
  export interface RefusalNote { readonly rule: string; readonly fix: string; readonly guide: string }
23
34
 
@@ -35,6 +46,13 @@ export const REFUSAL_RULES: readonly RefusalRule[] = [
35
46
  fix: 'Leave out --template, or pass `--template sdk` (the reference world) or `--template blender` (the hand-written Blender template).' },
36
47
  { id: 'new-refused', anchor: 'new-refused', steps: ['new'],
37
48
  fix: 'Reinstall @wildshard/sdk (`pnpm install`); `new` copies the reference world shipped with it.' },
49
+ // update (SA28)
50
+ { id: 'update-target', anchor: 'update-target', steps: ['update'], match: /^update: .* is not a shard repo/u,
51
+ fix: 'Run `wildshard update` in the repo `wildshard new` made, or name it: `wildshard update my-isle`.' },
52
+ { id: 'update-pins', anchor: 'update-pins', steps: ['update'], match: /^update --pins is not built yet/u,
53
+ fix: 'Move the pins by hand as the wildshard-upgrade skill says, then run `wildshard update` alone.' },
54
+ { id: 'update-refused', anchor: 'update-refused', steps: ['update'],
55
+ fix: 'Reinstall @wildshard/sdk (`pnpm install`); `update` copies GUIDE.md and the skills shipped with it.' },
38
56
  // build
39
57
  { id: 'source-file-missing', anchor: 'source-file-missing', steps: ['build', 'validate', 'prove'], match: /ENOENT: no such file or directory|Cannot resolve entry module/u,
40
58
  fix: 'Check the path shown: the shard source or shard file folder, or a file it names, is not there.' },
@@ -62,24 +80,27 @@ export const REFUSAL_RULES: readonly RefusalRule[] = [
62
80
  fix: 'Fix the proof tape (proof.json) where the message says; its shape is the author proof plan.' },
63
81
  { id: 'proof-failed', anchor: 'proof-failed', steps: ['prove'],
64
82
  fix: 'Walk the quest in `wildshard dev`, then fix the data or the tape step that did not happen.' },
65
- // the report card (budgets, J303); a metric is shard-format's name for it
66
- { id: 'budget-unmeasured', anchor: 'budget-unmeasured', steps: ['report'], match: /measurement required|missing execution samples|^invalid measured/u,
83
+ // the report card (budgets, J303): shard-format's PerformanceIssue codes
84
+ { id: 'budget-unmeasured', anchor: 'budget-unmeasured', steps: 'any',
85
+ codes: ['perf-native-view-unmeasured', 'perf-native-resident-unmeasured', 'perf-script-sample-invalid', 'perf-script-samples-missing'],
67
86
  fix: 'Run the shard long enough to measure: `wildshard check` measures it headlessly; native gameplay needs a browser proof.' },
68
- { id: 'budget-download', anchor: 'budget-download', steps: ['report'], match: /download (?:budget )?bytes/u,
87
+ { id: 'budget-download', anchor: 'budget-download', steps: 'any',
88
+ codes: ['perf-library-download-budget', 'perf-critical-download-budget', 'perf-library-download', 'perf-critical-download', 'perf-tile-download', 'perf-far-download'],
69
89
  fix: 'Shrink or drop assets on the named download tier, or move them to a later tier.' },
70
- { id: 'budget-draws', anchor: 'budget-draws', steps: ['report'], match: /\bdraws\b/u,
90
+ { id: 'budget-draws', anchor: 'budget-draws', steps: 'any', codes: ['perf-tile-draws', 'perf-far-draws'],
71
91
  fix: 'Merge meshes that share a material, or cut objects from the named view.' },
72
- { id: 'budget-triangles', anchor: 'budget-triangles', steps: ['report'], match: /\btriangles\b/u,
92
+ { id: 'budget-triangles', anchor: 'budget-triangles', steps: 'any', codes: ['perf-tile-triangles', 'perf-far-triangles'],
73
93
  fix: 'Lower the mesh detail (LODs, fewer props) in the named view.' },
74
- { id: 'budget-memory', anchor: 'budget-memory', steps: ['report'], match: /resident target|loading total bytes|playing total bytes/u,
94
+ { id: 'budget-memory', anchor: 'budget-memory', steps: 'any', codes: ['perf-memory-target', 'perf-playing-memory', 'perf-loading-memory'],
75
95
  fix: 'Cut texture size or count and mesh bytes until the named total fits.' },
76
- { id: 'budget-script-cpu', anchor: 'budget-script-cpu', steps: ['report'], match: /^script CPU/u,
96
+ { id: 'budget-script-cpu', anchor: 'budget-script-cpu', steps: 'any', codes: ['perf-script-cpu'],
77
97
  fix: 'Do less work per tick in behaviour scripts: spread it over ticks or run it on events.' },
78
- { id: 'budget-script-fuel', anchor: 'budget-script-fuel', steps: ['report'], match: /^script fuel/u,
98
+ { id: 'budget-script-fuel', anchor: 'budget-script-fuel', steps: 'any', codes: ['perf-script-fuel'],
79
99
  fix: 'Shorten the hottest behaviour script loops; fuel counts instructions per tick.' },
80
100
  { id: 'budget-over', anchor: 'budget-over', steps: ['report'],
81
101
  fix: 'Run `wildshard check`: its report step names each budget over its limit and the row here for each.' },
82
- { id: 'budget-refused', anchor: 'budget-refused', steps: ['build', 'validate'], match: /Performance report refused/u,
102
+ // `Performance report refused` is sharddev's own words (cli.ts); the two codes are shard-format's preflight of the same.
103
+ { id: 'budget-refused', anchor: 'budget-refused', steps: ['build', 'validate'], codes: ['declared-costs', 'performance-targets'], match: /Performance report refused/u,
83
104
  fix: 'Run `wildshard check`: its report step names each budget over its limit and the row here for each.' },
84
105
  // the shard file build writes (SA3; `pack` is its deprecated alias) and upload, before a byte is sent. `shardfile-draft` is
85
106
  // a warning from build and check and a refusal from upload (draft.ts).
@@ -89,16 +110,48 @@ export const REFUSAL_RULES: readonly RefusalRule[] = [
89
110
  fix: 'Build again after the hero capture: `wildshard build` writes a shard file that carries it.' },
90
111
  { id: 'hero-unchanged', anchor: 'hero-unchanged', steps: ['upload'], match: /the hero is unchanged since/u,
91
112
  fix: 'Capture a new hero (`wildshard hero`), then build and upload again.' },
92
- { id: 'audio-refused', anchor: 'audio-refused', steps: ['pack', 'upload'], match: /^Audio rules \(AU5\) refuse/u,
113
+ // the audio rules (AU5): `audio-refused` is upload's refusal of a red report; the rest are its findings, which build
114
+ // prints with their rows (red or amber, a build never refuses on them)
115
+ { id: 'audio-refused', anchor: 'audio-refused', steps: 'any', codes: ['audio-refused'],
93
116
  fix: 'Fix each red audio finding listed, or waive it in the shard\'s audio-waiver.json.' },
117
+ { id: 'audio-unreadable', anchor: 'audio-unreadable', steps: 'any', codes: ['audio-unreadable'],
118
+ fix: 'Export the recording again as AAC-LC 48 kHz, mono or stereo: this one does not read as that.' },
119
+ { id: 'audio-container', anchor: 'audio-container', steps: 'any', codes: ['audio-container'],
120
+ fix: 'Export the recording again as AAC (in mp4) or WAV: its bytes are FLAC, AIFF, Ogg, MP3, WebM, CAF or unknown.' },
121
+ { id: 'audio-encoding', anchor: 'audio-encoding', steps: 'any', codes: ['audio-strict-index', 'audio-wav', 'audio-sample-rate'],
122
+ fix: 'Encode the recording as AAC-LC at 48 kHz; it plays as it is, but ships larger or less safely.' },
123
+ { id: 'audio-duration', anchor: 'audio-duration', steps: 'any', codes: ['audio-duration'],
124
+ fix: 'Cut the recording under the maximum length the message gives, or split it in two.' },
125
+ { id: 'audio-bitrate', anchor: 'audio-bitrate', steps: 'any', codes: ['audio-bitrate'],
126
+ fix: 'Encode the recording at a lower bitrate: the message gives the cap for its role and channels.' },
127
+ { id: 'audio-budget', anchor: 'audio-budget', steps: 'any', codes: ['audio-budget-amber', 'audio-budget-red', 'audio-budget-waived'],
128
+ fix: 'Cut, shorten or re-encode recordings until the shard\'s own audio fits, or add a dated audio-waiver.json.' },
129
+ { id: 'audio-waiver', anchor: 'audio-waiver', steps: 'any', codes: ['audio-waiver-invalid'],
130
+ fix: 'Fix audio-waiver.json: this shard\'s slug, a date not yet past, and at least the bytes its audio holds.' },
94
131
  { id: 'shardfile-draft', anchor: 'shardfile-draft', steps: ['shardfile', 'upload'], match: /is an unprepared draft \(sdk 0\.2\)/u,
95
132
  fix: 'Run `wildshard prepare <folder> --base <url>`, then `wildshard build <folder>`; a shard repo\'s `pack:shards` does both (WILDSHARD_PREPARATION_URL).' },
96
133
  { id: 'shardfile-link', anchor: 'shardfile-link', steps: ['shardfile', 'pack'], match: /not a regular file|link is refused/u,
97
134
  fix: 'Replace links in the shard file folder with real files, then build again.' },
98
135
  { id: 'shardfile-folder-missing', anchor: 'shardfile-folder-missing', steps: ['shardfile', 'pack'], match: /(?:build|pack) needs a shard file folder|ENOENT/u,
99
136
  fix: 'Build the shard source: `wildshard build <source>` writes public/shardfiles/<slug>.shardfile.' },
100
- { id: 'shardfile-invalid', anchor: 'shardfile-invalid', steps: ['shardfile', 'pack', 'upload'], match: /^no \S+ in the shard ?file|is larger than \d+ bytes|Invalid [a-z]+: /u,
137
+ // shard-format's validator refusals (SA41's validate and stream codes), from validate, the shard file step or upload
138
+ { id: 'shardfile-invalid', anchor: 'shardfile-invalid', steps: 'any', codes: ['archive-invalid'],
101
139
  fix: 'Upload the shard file `wildshard build` wrote, unedited: the format checks refuse this one.' },
140
+ { id: 'shardfile-index', anchor: 'shardfile-index', steps: 'any', codes: ['index-invalid'],
141
+ fix: 'Build again so shard.json is written for you; a hand-written shard.json must parse and fit the index schema.' },
142
+ { id: 'shardfile-files', anchor: 'shardfile-files', steps: 'any', codes: ['file-mismatch', 'unlisted-file', 'source-hash', 'pack-invalid'],
143
+ fix: 'Build again: the folder\'s files differ from the ones shard.json lists, so never edit a built folder by hand.' },
144
+ { id: 'shardfile-section', anchor: 'shardfile-section', steps: 'any', codes: ['section-invalid', 'shard-schema'],
145
+ fix: 'Give the field at the path shown the value it expects; `wildshard schema shardfile <pointer>` prints its shape.' },
146
+ { id: 'shardfile-assets', anchor: 'shardfile-assets', steps: 'any',
147
+ codes: ['blob-invalid', 'server-file-invalid', 'ktx2-costs', 'asset-admission', 'cook-invalid', 'runtime-files'],
148
+ fix: 'Export the asset the message names again and build: its bytes do not match what the shard file declares.' },
149
+ { id: 'shardfile-scripts', anchor: 'shardfile-scripts', steps: 'any', codes: ['script-side', 'script-admission'],
150
+ fix: 'Run each behaviour script only on the side its declaration allows, then build again.' },
151
+ { id: 'shardfile-targets', anchor: 'shardfile-targets', steps: 'any', codes: ['world-targets'],
152
+ fix: 'Declare the item or quest the message names, or take it out of the world targets.' },
153
+ { id: 'shardfile-stream', anchor: 'shardfile-stream', steps: 'any', codes: ['stream-cap', 'stream-miss', 'stream-changed'],
154
+ fix: 'Shrink the file or pack the message names under the streaming cap; if the file changed mid-read, upload again.' },
102
155
  { id: 'shardfile-refused', anchor: 'shardfile-refused', steps: ['shardfile', 'pack'],
103
156
  fix: 'Build the shard source again with `wildshard build`: it writes and checks the shard file.' },
104
157
  { id: 'upload-shardfile-missing', anchor: 'upload-shardfile-missing', steps: ['upload'], match: /upload needs a shard ?file|ENOENT/u,
@@ -215,15 +268,32 @@ export function lintRuleId(code: string): string {
215
268
  return match === null ? code : `${match[1] ?? ''}/${match[2] ?? ''}`;
216
269
  }
217
270
 
218
- /** The rule, fix and guide link for a refusal message from `step`. A known lint rule's code wins over the message. */
219
- export function refusalNote(step: RefusalStep, message: string, lint?: { readonly code: string | null; readonly help: string | null }): RefusalNote {
271
+ /** shard-format's codes, each to the row that names it. */
272
+ const RULE_BY_CODE: ReadonlyMap<string, RefusalRule> = new Map(REFUSAL_RULES.flatMap(row => (row.codes ?? []).map(code => [code, row] as const)));
273
+
274
+ /** The shard-format code a refusal carries (SA41): on the error or, when sharddev wrapped it, on a cause beneath it. */
275
+ export function refusalCode(error: unknown): string | undefined {
276
+ for (let at = error, depth = 0; typeof at === 'object' && at !== null && depth < 8; depth += 1) {
277
+ const code: unknown = 'code' in at ? at.code : undefined;
278
+ if (typeof code === 'string' && RULE_BY_CODE.has(code)) return code;
279
+ at = 'cause' in at ? at.cause : undefined;
280
+ }
281
+ return undefined;
282
+ }
283
+
284
+ /** The rule, fix and guide link for a refusal message from `step`. A known lint rule's code wins over the message, and
285
+ * so does a shard-format code (SA41); the message's words are the fallback. */
286
+ export function refusalNote(step: RefusalStep, message: string, source: RefusalSource = {}): RefusalNote {
287
+ const { lint, code } = source;
220
288
  if (lint?.code !== undefined && lint.code !== null) {
221
289
  const id = lintRuleId(lint.code), known = LINT_BY_ID.get(id);
222
290
  const help = lint.help?.split('\n')[0]?.trim() ?? '';
223
291
  return known === undefined ? note(LINT_OTHER, id, help === '' ? LINT_OTHER.fix : help) : note(known);
224
292
  }
293
+ const coded = code === undefined ? undefined : RULE_BY_CODE.get(code);
294
+ if (coded !== undefined) return note(coded);
225
295
  const rule = REFUSAL_RULES.find(row => appliesTo(row, step) && row.match?.test(message) === true)
226
- ?? REFUSAL_RULES.find(row => appliesTo(row, step) && row.match === undefined);
296
+ ?? REFUSAL_RULES.find(row => appliesTo(row, step) && row.match === undefined && row.codes === undefined);
227
297
  if (rule === undefined) throw new Error(`no refusal rule for step ${step}`);
228
298
  return note(rule);
229
299
  }