packstruct 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -2
  3. package/bin/cli.mjs +119 -0
  4. package/conformance/cases/clean/public/clean-pack/entry.js +2 -0
  5. package/conformance/cases/clean/public/clean-pack/pack.json +7 -0
  6. package/conformance/cases/description/public/description/entry.js +2 -0
  7. package/conformance/cases/description/public/description/pack.json +7 -0
  8. package/conformance/cases/entry/public/entry/pack.json +7 -0
  9. package/conformance/cases/entry/public/entry/unreferenced.js +4 -0
  10. package/conformance/cases/name-collision/public/twin-a/entry.js +2 -0
  11. package/conformance/cases/name-collision/public/twin-a/pack.json +7 -0
  12. package/conformance/cases/name-collision/public/twin-b/entry.js +2 -0
  13. package/conformance/cases/name-collision/public/twin-b/pack.json +7 -0
  14. package/conformance/cases/name-dir-match/public/misaligned/entry.js +2 -0
  15. package/conformance/cases/name-dir-match/public/misaligned/pack.json +7 -0
  16. package/conformance/cases/name-kebab-case/public/name-kebab-case/entry.js +2 -0
  17. package/conformance/cases/name-kebab-case/public/name-kebab-case/pack.json +7 -0
  18. package/conformance/cases/schema-version/public/schema-version/entry.js +2 -0
  19. package/conformance/cases/schema-version/public/schema-version/pack.json +7 -0
  20. package/conformance/cases/version/public/version/entry.js +2 -0
  21. package/conformance/cases/version/public/version/pack.json +7 -0
  22. package/package.json +37 -4
  23. package/profiles/check.md +50 -0
  24. package/profiles/scenario.md +59 -0
  25. package/spec/SPEC.md +164 -0
  26. package/src/audit.mjs +84 -0
  27. package/src/lint.mjs +213 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dhaupin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # packstruct 0.9.0
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The shared `/packs` spec. **One manifest + entry + lifecycle contract, many
4
+ hosts**, currently [crashtest](https://github.com/dhaupin/crashtest)
5
+ (scenario profile) and [poststruct](https://github.com/dhaupin/poststruct)
6
+ (check profile).
7
+
8
+ This repo ships the normative spec ([spec/SPEC.md](spec/SPEC.md)) plus a
9
+ zero-dependency lint CLI that kills the worst pack-authoring class at author
10
+ time: a manifest declaring an entry file that doesn't actually ship
11
+ (crashtest#16). Every fleet repo uses the same core check.
12
+
13
+ ## The directory contract
14
+
15
+ ```
16
+ packs/
17
+ public/
18
+ <pack-name>/
19
+ pack.json # REQUIRED: fields per spec/SPEC.md section 2
20
+ <entry> # REQUIRED: the file pack.json's "entry" names
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```bash
26
+ npx packstruct lint packs/ # human, exit 0 clean / 1 violations / 2 usage
27
+ npx packstruct lint packs/ --json # machine-readable: {schema, packsChecked, violations}
28
+
29
+ npx packstruct lint packs/ --deep # + entry import, default-export check, id census
30
+ npx packstruct lint packs/ --deep --json # adds mode, modulesProbed, idsCensused, libraryIds
31
+ npx packstruct lint packs/ --deep --against lib/ # + host-library id census (id-library-collision)
32
+
33
+ npx packstruct audit-conformance . \
34
+ --loader "node bin/load-packs.js {packs}" # audit a HOST loader (SPEC section 7)
35
+ ```
36
+
37
+ The linter validates `schemaVersion === 1`, kebab-case name matching its
38
+ directory, dotted versions, non-empty description, relative entry paths, and
39
+ that the entry file physically exists under the pack dir. Optional
40
+ `armedByKey` string. Host-owned keys the engine also recognizes (`env`,
41
+ `plugins`, `package`) are acknowledged by name and never refused. Everything
42
+ else (extra manifest keys, snapshot files beside the entry) is
43
+ minimum-spec and left alone.
44
+
45
+ `audit-conformance` is the next half of conformance (SPEC section 7): it
46
+ materializes bundled verdict-claiming fixture packs (one clean bundle, one
47
+ per refusal norm, a name-collision pair) into scratch roots and runs YOUR
48
+ loader command over each - a conforming loader exits 0 on clean and exits
49
+ non-zero naming the pack on every violation (identity match, refusal wording
50
+ stays host-owned). The `implements: packstruct@1` pin becomes verifiable,
51
+ not honorary.
52
+
53
+ ## Profiles
54
+
55
+ The two entry profiles are declared once, with the spec (one address per
56
+ the crashtest#19 ruling): [profiles/scenario.md](profiles/scenario.md)
57
+ (crashtest - links to the host-owned contract instead of copying it) and
58
+ [profiles/check.md](profiles/check.md) (poststruct).
59
+
60
+ ## How the schema version was chosen
61
+
62
+ The baseline (formalized 2026-10-23) is exactly what crashtest's production
63
+ packs already ship: `schemaVersion: 1` with the shared field set above.
64
+ Therefore crashtest hosts v1 with **zero runtime changes**, and poststruct
65
+ adopts v1 fresh. Neither host shares an implementation with the other. They
66
+ share only this file convention.
67
+
68
+ ## Status (0.9.0)
69
+
70
+ Version ladder follows [prestruct](https://github.com/dhaupin/prestruct)'s
71
+ convention: 0.9.x is the manual `npm publish` ladder (0.9.0 is this
72
+ release); 1.0.0 flips on the CI publish lane - publish.yml refuses 0.x,
73
+ verifies the tag matches the version, and publishes with `--provenance`,
74
+ so v1.0.0 carries provenance by construction.
75
+
76
+ ## Related
77
+
78
+ - [crashtest](https://github.com/dhaupin/crashtest) (scenario-profile host)
79
+ - [poststruct](https://github.com/dhaupin/poststruct) (check-profile host)
80
+
81
+ ## Landing & docs
82
+
83
+ Landing: `packstruct.creadev.org` (Cloudflare Pages Git integration rooted at
84
+ `web/` - a Vite + React app prerendered by `prestruct build` into `web/dist/`
85
+ per-route; Pages Functions under `web/functions/`). Docs:
86
+ `docs.creadev.org/packstruct` (Jekyll + Pagefind + Freestruct via GitHub
87
+ Actions; see `.github/workflows/docs.yml` and `docs/`).
88
+
89
+ Build the site locally: `cd web && npm install && npm run build` - `prestruct`
90
+ runs the vite build, injects brand/SEO tags from `web/ssr.config.js`, and
91
+ prerenders every route to static HTML (bots get HTML, the SPA hydrates for
92
+ humans).
93
+
94
+ ## Crashtest dogfood
95
+
96
+ `crashtest run` from the repo root drives `packs/public/packstruct-lint-shapes`: hostile pack.json corpora through an in-process lint double (the same CLI wire CI uses), asserting the SPEC v1 section 5 contract - instant nameable refusal, no crashes, no deep stacks, and strict tolerance for spec-allowed shapes. Pinned to dhaupin/crashtest v1.0.0.
package/bin/cli.mjs ADDED
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ // bin/cli.mjs - the packstruct CLI, zero dependencies.
3
+ //
4
+ // packstruct lint <packs-dir> [--json] [--deep] [--against <path>]
5
+ // packstruct audit-conformance [<repo-dir>] --loader "<cmd> {packs}" [--json]
6
+ //
7
+ // The lint subcommand token is stripped when present, and a bare
8
+ // `packstruct <dir>` keeps working (the dir positionally implies lint; a
9
+ // target dir genuinely named 'lint' must not break the parser either way).
10
+ //
11
+ // lint --deep (packstruct#2): after the manifest pass, imports each declared
12
+ // entry once in-process, checks the default export exists, and censuses
13
+ // ids (module/attack/check/step names across the corpus) - mirrors the
14
+ // engine's shared-`seen` collision refusal (crashtest fc93ca6
15
+ // src/packs/loader.js :389-391) at author time. Probe only: host contract
16
+ // shapes stay host-owned (SPEC section 3). Importing runs the entry's
17
+ // top-level code; data modules are inert, and hostile modules are the
18
+ // host's isolation domain, not the linter's.
19
+ //
20
+ // lint --against <file-or-dir> (packstruct#2, requires --deep): seed the
21
+ // census with the HOST LIBRARY ids so pack-vs-library collisions refuse at
22
+ // author time (`id-library-collision`). Accepts a JSON file or an ESM
23
+ // module / directory of modules whose default exports carry ids (any house
24
+ // profile shape, generically probed).
25
+ //
26
+ // audit-conformance (M2, SPEC section 7): materializes the bundled
27
+ // verdict-claiming fixture cases into scratch roots and runs the HOST's own
28
+ // loader command over each. A conforming loader accepts the clean case
29
+ // (exit 0) and refuses every violation case with a non-zero exit that NAMES
30
+ // the offending pack (SPEC section 5, identity match - the host may word
31
+ // its refusal however it likes). Exit contract: 0 all cases honored,
32
+ // 1 any case failed, 2 usage error - same ladder as lint.
33
+ import { lintPacks, deepLintPacks } from '../src/lint.mjs'
34
+ import { auditConformance } from '../src/audit.mjs'
35
+
36
+ let args = process.argv.slice(2)
37
+ const verb = args[0] === 'audit-conformance' ? 'audit-conformance' : 'lint'
38
+ if (args[0] === 'lint' || verb === 'audit-conformance') args = args.slice(1)
39
+
40
+ const exitUsage = (msg, usage) => {
41
+ if (msg) console.error(msg)
42
+ console.error(`Usage: ${usage}`)
43
+ process.exit(2)
44
+ }
45
+
46
+ if (verb === 'audit-conformance') {
47
+ const loaderIdx = args.indexOf('--loader')
48
+ let loader
49
+ if (loaderIdx !== -1) {
50
+ loader = args[loaderIdx + 1]
51
+ if (loader === undefined || loader.startsWith('-')) {
52
+ exitUsage('--loader needs a value: --loader "<cmd> {packs}"', 'packstruct audit-conformance [<repo-dir>] --loader "<cmd> {packs}" [--json]')
53
+ }
54
+ }
55
+ const positional = []
56
+ for (let i = 0; i < args.length; i++) {
57
+ if (args[i] === '--loader') { i++; continue }
58
+ if (!args[i].startsWith('-')) positional.push(args[i])
59
+ }
60
+ if (loader === undefined) {
61
+ exitUsage(undefined, 'packstruct audit-conformance [<repo-dir>] --loader "<cmd> {packs}" [--json]')
62
+ }
63
+ const repo = positional[0] ?? '.'
64
+ const json = args.includes('--json')
65
+ const r = auditConformance({ loader, repo, json })
66
+ if (json) {
67
+ console.log(JSON.stringify({ schema: 1, mode: 'audit', repo, cases: r.caseCount, honored: r.honored, violations: r.violations }, null, 2))
68
+ } else {
69
+ console.log(`packstruct audit-conformance: ${r.honored}/${r.caseCount} case(s) honored by the loader over ${repo}`)
70
+ for (const v of r.violations) console.log(` AUDIT ${v.pack} [${v.norm}]: ${v.message}`)
71
+ }
72
+ process.exit(r.violations.length ? 1 : 0)
73
+ }
74
+
75
+ // --- lint verb (below unchanged contract) ---
76
+ const againstIdx = args.indexOf('--against')
77
+ let against
78
+ if (againstIdx !== -1) {
79
+ against = args[againstIdx + 1]
80
+ if (against === undefined || against.startsWith('-')) {
81
+ exitUsage(undefined, 'packstruct lint <packs-dir> [--json] [--deep] [--against <library-path>]')
82
+ }
83
+ }
84
+ const dirArgs = []
85
+ for (let i = 0; i < args.length; i++) {
86
+ if (args[i] === '--against') { i++; continue }
87
+ dirArgs.push(args[i])
88
+ }
89
+
90
+ const dir = dirArgs.find(a => !a.startsWith('-'))
91
+ if (!dir) exitUsage(undefined, 'packstruct lint <packs-dir> [--json] [--deep] [--against <library-path>]')
92
+ const deep = dirArgs.includes('--deep') || args.includes('--deep')
93
+ if (against !== undefined && !deep) {
94
+ exitUsage('--against requires --deep (the host-library census runs on the deep pass)', 'packstruct lint <packs-dir> [--json] [--deep] [--against <library-path>]')
95
+ }
96
+
97
+ const r = deep
98
+ ? await deepLintPacks(dir, { against })
99
+ : lintPacks(dir)
100
+ if (dirArgs.includes('--json') || args.includes('--json')) {
101
+ console.log(JSON.stringify({
102
+ schema: 1,
103
+ mode: deep ? 'deep' : 'manifest',
104
+ packsChecked: r.packsChecked,
105
+ modulesProbed: r.modulesProbed,
106
+ idsCensused: r.idsCensused,
107
+ libraryIds: r.libraryIds ?? 0,
108
+ violations: r.violations,
109
+ }, null, 2))
110
+ process.exit(r.violations.length ? 1 : 0)
111
+ }
112
+ const mode = deep ? 'lint --deep' : 'lint'
113
+ const probe = deep
114
+ ? ` - ${r.modulesProbed} module(s) probed, ${r.idsCensused} id(s) censused` +
115
+ (against !== undefined ? `, ${r.libraryIds ?? 0} library id(s) seeded` : '')
116
+ : ''
117
+ console.log(`packstruct ${mode}: ${r.packsChecked} pack(s) checked in ${dir}${probe}`)
118
+ for (const v of r.violations) console.log(` VIOLATION ${v.pack} [${v.norm}]: ${v.message}`)
119
+ process.exit(r.violations.length ? 1 : 0)
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry - imports cleanly, does nothing.
2
+ export default { name: 'clean-pack' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "clean-pack",
4
+ "description": "SPEC v1 clean pack - the accept case",
5
+ "version": "1.0.0",
6
+ "entry": "entry.js"
7
+ }
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry.
2
+ export default { name: 'description' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "description",
4
+ "description": "",
5
+ "version": "1.0.0",
6
+ "entry": "entry.js"
7
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "entry",
4
+ "description": "refuses: declared entry file does not ship (the crashtest#16 class)",
5
+ "version": "1.0.0",
6
+ "entry": "missing.js"
7
+ }
@@ -0,0 +1,4 @@
1
+ // The manifest above names missing.js as its entry. That file is deliberately
2
+ // absent - that IS the case's verdict claim. This unreferenced module exists
3
+ // so the bundle is not empty (a loader must refuse, not 404 the whole root).
4
+ export default { name: 'entry' }
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry.
2
+ export default { name: 'twin-pack-a' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "twin-pack",
4
+ "description": "refuses (with twin-b): two packs claiming one name",
5
+ "version": "1.0.0",
6
+ "entry": "entry.js"
7
+ }
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry.
2
+ export default { name: 'twin-pack-b' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "twin-pack",
4
+ "description": "refuses (with twin-a): two packs claiming one name",
5
+ "version": "1.0.0",
6
+ "entry": "entry.js"
7
+ }
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry.
2
+ export default { name: 'aligned-name' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "aligned-name",
4
+ "description": "refuses: manifest name does not match its directory (dir: misaligned)",
5
+ "version": "1.0.0",
6
+ "entry": "entry.js"
7
+ }
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry.
2
+ export default { name: 'name-kebab-case' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "BadName",
4
+ "description": "refuses: name must be kebab-case",
5
+ "version": "1.0.0",
6
+ "entry": "entry.js"
7
+ }
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry.
2
+ export default { name: 'schema-version' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 2,
3
+ "name": "schema-version",
4
+ "description": "refuses: schemaVersion 2 is not the frozen v1",
5
+ "version": "1.0.0",
6
+ "entry": "entry.js"
7
+ }
@@ -0,0 +1,2 @@
1
+ // Inert conformance fixture entry.
2
+ export default { name: 'version' }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "version",
4
+ "description": "refuses: version must be dotted MAJOR.MINOR[.PATCH]",
5
+ "version": "1",
6
+ "entry": "entry.js"
7
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "packstruct",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.9.0",
4
+ "description": "The shared /packs spec: one manifest, entry, and lifecycle contract for crashtest and poststruct packs - plus a zero-dependency lint CLI that kills broken pack manifests at author time.",
5
+ "type": "module",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "bin": {
8
+ "packstruct": "bin/cli.mjs"
9
+ },
10
+ "exports": {
11
+ ".": "./src/lint.mjs",
12
+ "./audit": "./src/audit.mjs",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "bin/",
17
+ "src/",
18
+ "spec/",
19
+ "profiles/",
20
+ "conformance/",
21
+ "LICENSE"
22
+ ],
23
+ "scripts": {
24
+ "test": "node test/run.mjs"
25
+ },
26
+ "engines": { "node": ">=20" },
27
+ "keywords": [
28
+ "packs",
29
+ "spec",
30
+ "validation",
31
+ "crashtest",
32
+ "poststruct",
33
+ "ci",
34
+ "manifest"
35
+ ],
36
+ "repository": { "type": "git", "url": "git+https://github.com/dhaupin/packstruct.git" },
37
+ "bugs": { "url": "https://github.com/dhaupin/packstruct/issues" },
38
+ "homepage": "https://github.com/dhaupin/packstruct#readme"
39
+ }
@@ -0,0 +1,50 @@
1
+ # The check profile
2
+
3
+ Declared per SPEC v1 section 3 (normative) and filed here once, per the
4
+ one-address ruling on [crashtest#19](https://github.com/dhaupin/crashtest).
5
+
6
+ This is the profile [poststruct](https://github.com/dhaupin/poststruct) will
7
+ load. Note the honest status line: poststruct is not shipping yet, so this
8
+ page declares the shape the spec froze - the engine-first rule (code first,
9
+ spec formalizes after) means any poststruct loader change that contradicts
10
+ this page updates the SPEC first, then here.
11
+
12
+ ## The module shape
13
+
14
+ An entry module under this profile is an ES module with a default export
15
+ carrying a `checks` array:
16
+
17
+ ```js
18
+ export default {
19
+ checks: [
20
+ // Declarative, pure-reading verifiers over files on disk.
21
+ // Each Check carries (at minimum) a kebab-case id and a read-only
22
+ // predicate the host runs over its target tree.
23
+ ],
24
+ }
25
+ ```
26
+
27
+ ## What the spec guarantees
28
+
29
+ - **No transport, no network by default.** A check pack reads the files the
30
+ host points it at. That whole boundary is the profile's point: check packs
31
+ prove claims about files; scenario packs attack systems.
32
+ - **Config-is-the-arm.** There is no arming key ceremony in this profile:
33
+ being enumerated in the host's `packs:` config IS the arm (SPEC section 3).
34
+ A `pack.json` may still carry `armedByKey` - the shared manifest surface
35
+ never forks between profiles - and the poststruct loader will simply not
36
+ give it a ceremony: its presence is optional surface, its semantics here
37
+ are the host's default lifecycle (config enumeration).
38
+ - **Namespaced ids.** Check ids live in the pack-slug namespace inside the
39
+ host's id space; cross-namespace collision at load = refuse to start
40
+ (SPEC section 4).
41
+ - **Refusals** are instant, one-line, and name the pack (SPEC section 5).
42
+
43
+ ## Boundary charter
44
+
45
+ The load-time boundary between the struct apps is on record:
46
+ [poststruct#2](https://github.com/dhaupin/poststruct/issues/2) - the
47
+ manifest shape validates ONCE (this spec, section 2), packstruct owns the
48
+ pack shape, poststruct owns the text shape. A conformance story for a check
49
+ pack is: packstruct lint says the manifest is v1; the poststruct loader
50
+ says the checks are check-shaped; neither pretends to speak for the other.
@@ -0,0 +1,59 @@
1
+ # The scenario profile
2
+
3
+ Declared per SPEC v1 section 3 (normative) and filed here once, per the
4
+ one-address ruling on [crashtest#19](https://github.com/dhaupin/crashtest).
5
+
6
+ This is the profile [crashtest](https://github.com/dhaupin/crashtest) loads.
7
+
8
+ ## The module shape
9
+
10
+ An entry module under this profile is an ES module with a default export
11
+ carrying three things:
12
+
13
+ ```js
14
+ export default {
15
+ name: 'my-scenario-pack', // kebab-case
16
+ description: 'one line',
17
+ attacks: [
18
+ {
19
+ name: 'kebab-case-attack', // kebab-case ids, namespaced by pack
20
+ run: (ctx) => { /* ... */ }, // OR a steps chain, not both unnamed
21
+ },
22
+ {
23
+ name: 'atted-attack',
24
+ steps: [ /* named, ordered steps */ ],
25
+ },
26
+ ],
27
+ }
28
+ ```
29
+
30
+ - Attack and step names join the host's id space under the pack-slug
31
+ namespace (SPEC section 4). Collision at load = refuse to start, never
32
+ silent dedupe.
33
+ - Exporting both a `run` and a `steps` chain on one attack: the host owns
34
+ that ruling (SPEC section 3: host-cherry-picks territory).
35
+
36
+ ## The authoritative contract is the host's
37
+
38
+ The full module-shape contract - what `ctx` carries, verdict semantics,
39
+ exit rules, ledger output - is **host-owned**. This page links to it rather
40
+ than copying it: doc drift is worse than indirection, ruled on crashtest#19
41
+ (the `register(ctx)` default-export shape in earlier drafts here was stale
42
+ and was deleted against the engine truth at `fc93ca6`).
43
+
44
+ **Authoritative reference:** [crashtest's scenario contract](https://github.com/dhaupin/crashtest/blob/main/docs/reference/scenario-contract.md)
45
+ (mirrored at [docs.creadev.org/crashtest/reference/scenario-contract](https://docs.creadev.org/crashtest/reference/scenario-contract)).
46
+
47
+ ## What the spec guarantees anyway
48
+
49
+ Under any conforming host:
50
+
51
+ - the manifest that declares the entry - `pack.json` per SPEC section 2 -
52
+ is validated against the frozen v1 table before the entry ever imports;
53
+ - `armedByKey` presence is the arming ceremony's manifest surface: the host
54
+ MAY require an arming key before activation. Absent = the host's default
55
+ lifecycle governs;
56
+ - refusals are instant, one-line, and name the pack (SPEC section 5);
57
+ - load isolation is the host's job: hostile scenarios run against the
58
+ host's fake transport and opt-out postures, never a live target unless
59
+ the host's runbook arms it.
package/spec/SPEC.md ADDED
@@ -0,0 +1,164 @@
1
+ # The packstruct spec, version 1
2
+
3
+ One `/packs` system, many hosts. This document is normative for any app that
4
+ loads packs from a `packs/` directory and for anyone authoring a pack.
5
+
6
+ **Schema base (verified 2026-10-24, crashtest#19 receipts):** every crashtest
7
+ production pack ships schemaVersion 1 with exactly the shared field set (8/8
8
+ conform, nothing drifted since the 2026-10-23 audit). The id space is clean:
9
+ 44 pack ids across the 8 packs, zero collisions pack-vs-pack and
10
+ pack-vs-library. v1 formalizes that reality; hosts either already conform
11
+ (crashtest) or adopt it fresh (poststruct). Baseline watch: if a host fleet
12
+ bumps its manifests, the spec formalizes the new number - the spec tags
13
+ whatever the fleet ships. Ordering ruled on crashtest#19: code first, spec
14
+ formalizes after; nothing schema-changing is hidden on the engine side.
15
+
16
+ ## 1. Directory contract (all hosts)
17
+
18
+ ```
19
+ packs/public/<pack-name>/
20
+ pack.json # REQUIRED, fields per section 2
21
+ <entry file> # REQUIRED: the file pack.json's "entry" names
22
+ ```
23
+
24
+ ## 2. pack.json (frozen for v1)
25
+
26
+ | Field | Rules |
27
+ |---|---|
28
+ | `schemaVersion` | integer, MUST be `1` |
29
+ | `name` | kebab-case string, MUST match its directory name (mismatch = load refuse) |
30
+ | `description` | one-line, human-readable |
31
+ | `version` | dotted MAJOR.MINOR[.PATCH] |
32
+ | `entry` | relative path inside the pack dir, MUST exist (missing entry = instant, nameable refusal - the crashtest#16 lesson is a norm now) |
33
+ | `armedByKey` | OPTIONAL string. Present: the host MAY run its arming-key ceremony before activation - presence semantics only, so an EMPTY value is "present, not yet armed" (folded from the crashtest#25 matrix fold: the engine treats empty as valid, so a non-empty rule would be a check the SPEC never promised). Absent: the host's own default lifecycle governs |
34
+
35
+ **Host-owned acknowledged keys.** The table above is the shared-facts column:
36
+ fields every conforming loader assigns meaning to. Some hosts additionally
37
+ carry their own optional manifest keys with host-side shape validation. For
38
+ v1, three are acknowledged by name because crashtest's loader already
39
+ validates them (ruled on crashtest#19):
40
+
41
+ - `env` - the env-claims block (`d1`/`kv`/`routes`, plus optional `env.seed`)
42
+ - `plugins` - bundled plugin imports, resolved against the pack dir
43
+ - `package` - optional npm name for the pack
44
+
45
+ These are **acknowledged, not shared facts**: the spec documents that they
46
+ may appear and that the HOST owns their semantics and shape rules. Their
47
+ presence is never a spec violation, `packstruct lint` must never refuse a
48
+ pack for carrying them, and a future host naming a fourth host-owned key
49
+ extends this list in a patch revision, not a schemaVersion bump.
50
+
51
+ Extra manifest keys and extra files beside the entry are allowed as
52
+ minimum-spec (the loader assigns no shared meaning to undeclared keys; e.g.
53
+ crashtest's cve-feed ships a snapshot.json beside its entry, which is fine).
54
+
55
+ **Receipts per frozen row** (added per dhaupin/packstruct#4: every row cites
56
+ the engine evidence it mirrors, so "conforming to spec" and "what this one
57
+ repo does" never blur). Engine rows are from crashtest `fc93ca6`,
58
+ `src/packs/loader.js` - the packstruct#19-audited tree:
59
+
60
+ - `schemaVersion` MUST be `1` — enforced: `loader.js:77-78` (unsupported
61
+ schemaVersion throws, "have: 1").
62
+ - `name` kebab-case — enforced: `loader.js:98` throws on non-kebab names.
63
+ - `name` MUST match its directory — the engine's narrower shape: packs are
64
+ loaded FROM their directories and the shared `seen` map keys identity by
65
+ manifest name (`loader.js:372, :389-391`), so a name/dir disagreement
66
+ surfaces as a loud collision or misattribution, never silent success. The
67
+ linter deliberately enforces the stricter contract (name == dir) at author
68
+ time; engine parity is tracked in dhaupin/packstruct#2.
69
+ - `entry` MUST exist — the engine admits a default entry (`loader.js:101`)
70
+ and a declared file that doesn't ship fails at import with a one-line,
71
+ nameable error naming the pack (`loader.js:394-396`) — the crashtest#16
72
+ class, a norm either way. The linter runs the detection at author time via
73
+ file existence, so a broken manifest refuses before any host loads it.
74
+ - `version` dotted semver-ish — pack-owned semver; the manifest reality is
75
+ the 8/8 #19 audit (every pack ships it), and the version is decoupled from
76
+ every host's and from packstruct's own release cadence (see section 6).
77
+ - `description` non-empty — enforced: `loader.js:59, :71-73`
78
+ (REQUIRED_KEYS throws on missing fields).
79
+ - `armedByKey` optional — engine shape contract: absent = unarmed-but-loadable
80
+ (crashtest#19 ruling folded into the table).
81
+ - Host-owned `env`/`plugins`/`package` — acknowledged and shape-validated:
82
+ `loader.js:24-35` (comment block), `:110` (validateEnvClaims),
83
+ `:398-401` (bundled plugin imports), `:363-364` (seed passthrough).
84
+ - Id collisions refuse at load — enforced: `loader.js:389-391` (shared
85
+ `seen` across surfaces: one loud error naming both origins).
86
+
87
+ ## 3. Entry profiles (per host, declared here)
88
+
89
+ An entry is an ES module with a default export. The manifest/dir/entry surface
90
+ never forks between hosts; execution semantics are declared as profiles:
91
+
92
+ - **`scenario` profile (crashtest):** default export = a module object
93
+ carrying `name`, `description`, and an `attacks[]` array (attack names
94
+ kebab-case, each with a `run` function or a `steps` chain). Contains
95
+ hostile scenarios executed against a transport; hosts of this profile
96
+ provide isolation (fake transport, opt-out postures) and support the
97
+ `armedByKey` ceremony. The module-shape contract is HOST-OWNED in full:
98
+ it lives with the host (crashtest's `reference/scenario-contract`);
99
+ `profiles/scenario.md` links to it rather than copying it - doc drift is
100
+ worse than indirection (ruled on crashtest#19; the `register(ctx)` shape
101
+ in earlier drafts of this section was stale, deleted against the engine
102
+ truth at `fc93ca6` per the engine-first rule). The canonical profile
103
+ pages live with the spec (one address, same ruling):
104
+ `profiles/scenario.md` and `profiles/check.md`.
105
+ - **`check` profile (poststruct):** default export = `{ checks: [Check] }`.
106
+ Declarative pure-reading verifiers over files on disk. No transport, no
107
+ network by default. Arming defaults to config enumeration: being listed in
108
+ the host's `packs:` config IS the arm; no separate key ceremony.
109
+
110
+ A host declares which profile(s) it loads. A pack never changes its own
111
+ semantics based on the host.
112
+
113
+ ## 4. Lifecycle norms (all hosts)
114
+
115
+ - **Explicit loads only.** A pack runs because the host's config enumerates
116
+ it. Remote/npm sources are NOT part of v1; adding them requires an explicit
117
+ spec version bump and stays no-auto-download.
118
+ - **Namespaced ids.** Pack check/scenario ids live in a pack-slug namespace
119
+ in the host's id space. Cross-namespace collision at load time = refuse to
120
+ start, never silent dedupe.
121
+ - **Self-audit fixtures.** Every pack ships `test/fixtures/` proving its
122
+ contents do what they claim. A pack whose fixtures fail fails its own CI
123
+ host-first. (Crashtest backfill note: fixtures are the one norm its
124
+ production packs do not ship yet; it is a lifecycle requirement, not a
125
+ manifest field, so schemaVersion does not move for it.)
126
+
127
+ ## 5. Errors (nameable, instant)
128
+
129
+ A conforming loader refuses with a one-line error naming the pack and the
130
+ broken norm the moment it sees the violation: wrong schemaVersion, name/dir
131
+ mismatch, missing entry file, id collision. Never a deep stack trace and
132
+ never silent success.
133
+
134
+ ## 6. Versioning
135
+
136
+ - Additive-first: v2 adds optional manifest fields; removing/renaming is a
137
+ major spec bump requiring a migration note.
138
+ - Hosts pin the spec they implement (`implements: packstruct@1` in host docs).
139
+ - **Pack version is the pack's own semver, decoupled from every other release
140
+ cadence.** A `pack.json` `version` bumps only when that pack's own surface
141
+ changes - not when packstruct ships a new linter, not when a consumer ships
142
+ a new CLI or spec revision. House policy verbatim from crashtest's
143
+ AGENTS.md (where it is enforced by the governance suite): pack manifests
144
+ carry their own semver - never bump those for CLI-level releases. The
145
+ shipped-stable pack keeps its shape: a consumer adopting a newer linter or
146
+ a newer consumer build does not re-roll packs it already froze.
147
+ - **Spec ↔ tool decoupling is the mirror image:** packstruct's own version
148
+ (0.9.x manual, 1.0.0 OIDC per its DEPLOY.md) tracks the linter and harness
149
+ surface only. A lint release that adds checks under the same frozen schema
150
+ is a TOOL semver bump that leaves this document's v1 number alone.
151
+
152
+ ## 7. Conformance tooling
153
+
154
+ - `packstruct lint <packs-dir>`: manifest validation + entry existence +
155
+ name/dir match (section 2, plus directory-contract checks from section 1).
156
+ Exit 0 conforming / 1 violations / 2 usage error.
157
+ - `packstruct audit-conformance <repo-dir> --loader "<cmd> {packs}"`: the
158
+ conformance harness. Bundled verdict-claiming cases (one clean bundle,
159
+ one per section-5 refusal norm, plus a name-collision pair) are
160
+ materialized into scratch roots and the HOST's own loader command runs
161
+ over each. A conforming loader exits 0 on the clean bundle and exits
162
+ non-zero AND names the offending pack on every violation bundle (section
163
+ 5: nameable refusals; identity matches, refusal wording stays host-owned).
164
+ Same exit ladder: 0 all cases honored / 1 any case failed / 2 usage.
package/src/audit.mjs ADDED
@@ -0,0 +1,84 @@
1
+ // src/audit.mjs - audit-conformance (M2): the fixture packs a host loader
2
+ // must pass/fail as promised (SPEC section 7). Zero dependencies.
3
+ //
4
+ // How it stays honest: packstruct ships verdict-claiming fixtures - one clean
5
+ // pack plus one pack (or pair) per SPEC section 5 refusal norm, each
6
+ // claiming a verdict. The host's OWN loader command runs over each
7
+ // materialized bundle in a scratch root. A conforming loader: exits 0 on the
8
+ // clean bundle, exits non-zero AND names the offending pack on every
9
+ // violation bundle (SPEC section 5: "naming the pack"; the host may word the
10
+ // refusal its own way, so the audit matches identity, not jargon). Any other
11
+ // outcome is an audit violation naming the case - the harness refuses to
12
+ // grade, it only reports what the loader actually did.
13
+ import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
14
+ import { join, resolve } from 'node:path'
15
+ import { tmpdir } from 'node:os'
16
+ import { fileURLToPath } from 'node:url'
17
+ import { spawnSync } from 'node:child_process'
18
+
19
+ export const CASES_DIR = fileURLToPath(new URL('../conformance/cases/', import.meta.url))
20
+
21
+ // The bundled cases: <case>/public/<pack-dir>/, each with a verdict claim.
22
+ // clean expects exit 0; every other case expects a refusing loader.
23
+ export function listCases() {
24
+ return readdirSync(CASES_DIR).sort().filter(name => {
25
+ try { return readdirSync(join(CASES_DIR, name)).length > 0 } catch { return false }
26
+ })
27
+ }
28
+
29
+ // Pack identities a case's output must name on refusal: the pack directory
30
+ // names and the manifest `name` values (either counts - SPEC section 5 says
31
+ // "naming the pack", the host may identify by dir or manifest name).
32
+ function casePackIdentities(root) {
33
+ const ids = new Set()
34
+ const publicDir = join(root, 'public')
35
+ if (!existsSync(publicDir)) return ids
36
+ for (const dir of readdirSync(publicDir)) {
37
+ ids.add(dir)
38
+ try {
39
+ const m = JSON.parse(readFileSync(join(publicDir, dir, 'pack.json'), 'utf8'))
40
+ if (typeof m.name === 'string' && m.name) ids.add(m.name)
41
+ } catch { /* identity by dir name is already in the set */ }
42
+ }
43
+ return ids
44
+ }
45
+
46
+ export function auditConformance(opts = {}) {
47
+ if (typeof opts.loader !== 'string' || !opts.loader.includes('{packs}')) {
48
+ return { caseCount: 0, honored: 0, violations: [{ pack: 'usage', norm: 'usage', message: 'audit-conformance needs --loader "<cmd> {packs}" - {packs} is replaced by each materialized bundle root' }] }
49
+ }
50
+ const repo = resolve(opts.repo ?? '.')
51
+ const cases = listCases()
52
+ const violations = []
53
+ let honored = 0
54
+ for (const c of cases) {
55
+ const expect = c === 'clean' ? 'accept' : 'refuse'
56
+ const tmp = mkdtempSync(join(tmpdir(), 'packstruct-audit-'))
57
+ try {
58
+ cpSync(join(CASES_DIR, c), tmp, { recursive: true })
59
+ const ids = casePackIdentities(tmp)
60
+ const cmd = opts.loader.split('{packs}').join(`"${tmp}"`)
61
+ const r = spawnSync(cmd, { shell: true, cwd: repo, encoding: 'utf8' })
62
+ const out = `${r.stdout ?? ''}\n${r.stderr ?? ''}`
63
+ const claimed = r.status === 0
64
+ let ok = expect === 'accept' ? claimed : !claimed
65
+ let why = ''
66
+ if (ok && expect === 'refuse' && ![...ids].some(id => out.includes(id))) {
67
+ ok = false
68
+ why = 'refused but did not name the pack (SPEC section 5: nameable refusals)'
69
+ }
70
+ if (ok) honored++
71
+ else {
72
+ const got = claimed ? 'exit 0 (loader accepted)' : `exit ${r.status}`
73
+ violations.push({
74
+ pack: c,
75
+ norm: `audit-${expect}`,
76
+ message: `loader ${got} on case "${c}" - the spec verdict is ${expect === 'accept' ? 'accept' : 'refuse'}${why ? ` - ${why}` : ''}`,
77
+ })
78
+ }
79
+ } finally {
80
+ rmSync(tmp, { recursive: true, force: true })
81
+ }
82
+ }
83
+ return { caseCount: cases.length, honored, violations }
84
+ }
package/src/lint.mjs ADDED
@@ -0,0 +1,213 @@
1
+ // src/lint.mjs - packstruct lint: packstruct spec v1 manifest validation.
2
+ // The immediate payoff: kills the "manifest declares an entry that doesn't
3
+ // ship" class (crashtest#16) at author time, in any fleet repo.
4
+ //
5
+ // deepLintPacks (packstruct#2) adds the load-level parity the manifest-only
6
+ // CLI never checks: import the entry once in-process, check the default
7
+ // export exists, and census ids (module/attack/check names + step names)
8
+ // across packs - mirroring the loader's shared-`seen` collision refusal
9
+ // (crashtest `fc93ca6` src/packs/loader.js:389-391) at author time.
10
+ // PROBE ONLY: host module-shape norms stay host-owned (SPEC section 3) -
11
+ // deep censes ids, it does not police the host's contract shapes.
12
+ import { readFileSync, existsSync, readdirSync } from 'node:fs'
13
+ import { join, resolve } from 'node:path'
14
+ import { pathToFileURL } from 'node:url'
15
+
16
+ export function lintPacks(dir) {
17
+ const violations = []
18
+ let packsChecked = 0
19
+ if (!existsSync(dir)) {
20
+ return { packsChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }] }
21
+ }
22
+ // Section 1 contract: packs live at <packs-root>/public/<name>/
23
+ const publicDir = join(dir, 'public')
24
+ if (!existsSync(publicDir)) {
25
+ return { packsChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }] }
26
+ }
27
+ for (const name of readdirSync(publicDir).sort()) {
28
+ const packDir = join(publicDir, name)
29
+ let isDir = true
30
+ try { readdirSync(packDir) } catch { isDir = false }
31
+ if (!isDir) continue
32
+ const manifestPath = join(packDir, 'pack.json')
33
+ if (!existsSync(manifestPath)) {
34
+ violations.push({ pack: name, norm: 'manifest-missing', message: 'pack.json missing' })
35
+ continue
36
+ }
37
+ packsChecked++
38
+ let m
39
+ try { m = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
40
+ violations.push({ pack: name, norm: 'manifest-invalid', message: `pack.json is not valid JSON: ${e.message}` })
41
+ continue
42
+ }
43
+ if (m.schemaVersion !== 1) violations.push({ pack: name, norm: 'schemaVersion', message: `schemaVersion must be 1 (got ${JSON.stringify(m.schemaVersion)})` })
44
+ if (typeof m.name !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(m.name)) violations.push({ pack: name, norm: 'name-kebab-case', message: `name must be kebab-case (got ${JSON.stringify(m.name)})` })
45
+ if (m.name !== name) violations.push({ pack: name, norm: 'name-dir-match', message: `name "${m.name}" does not match its directory "${name}"` })
46
+ if (typeof m.version !== 'string' || !/^\d+\.\d+(\.\d+)?$/.test(m.version)) violations.push({ pack: name, norm: 'version', message: `version must be dotted MAJOR.MINOR[.PATCH] (got ${JSON.stringify(m.version)})` })
47
+ if (typeof m.description !== 'string' || !m.description.trim()) violations.push({ pack: name, norm: 'description', message: 'description missing or empty' })
48
+ if (typeof m.entry !== 'string' || !m.entry.trim() || m.entry.includes('..')) {
49
+ violations.push({ pack: name, norm: 'entry', message: `entry must be a relative path inside the pack (got ${JSON.stringify(m.entry)})` })
50
+ } else if (!existsSync(join(packDir, m.entry))) {
51
+ violations.push({ pack: name, norm: 'entry', message: `entry file "${m.entry}" does not exist - instant refusal at load time (the crashtest#16 class)` })
52
+ }
53
+ // armedByKey: OPTIONAL string. Type-checked only - an EMPTY value is
54
+ // "present, not yet armed" and the host owns presence semantics
55
+ // (folded from crashtest#25: our non-empty refusal was a check the
56
+ // SPEC didn't promise; the engine treats empty as valid).
57
+ if (m.armedByKey !== undefined && typeof m.armedByKey !== 'string') {
58
+ violations.push({ pack: name, norm: 'armedByKey', message: `armedByKey, when present, must be a string (got ${typeof m.armedByKey})` })
59
+ }
60
+ }
61
+ return { packsChecked, violations }
62
+ }
63
+
64
+ // Ids a deep probe extracts from ONE default export (generic over the two
65
+ // house profiles: scenario `attacks[]/steps[]`, check `checks[]` - host
66
+ // shapes stay host-owned, this never assigns shared meaning to them).
67
+ function probeIds(def, pack) {
68
+ const out = []
69
+ const push = (id, at) => { if (typeof id === 'string' && id) out.push({ id, pack, at }) }
70
+ if (!def || typeof def !== 'object') return out
71
+ push(def.name, 'module name')
72
+ for (const key of ['attacks', 'checks', 'scenarios']) {
73
+ const arr = def[key]
74
+ if (!Array.isArray(arr)) continue
75
+ for (const item of arr) {
76
+ if (!item || typeof item !== 'object') continue
77
+ push(item.id ?? item.name, `${key}[]`)
78
+ for (const sub of ['steps', 'phases']) {
79
+ if (!Array.isArray(item[sub])) continue
80
+ for (const s of item[sub]) {
81
+ if (!s || typeof s !== 'object') continue
82
+ push(s.id ?? s.name, `${key}[].${sub}[]`)
83
+ }
84
+ }
85
+ }
86
+ }
87
+ return out
88
+ }
89
+
90
+ const DEEP_LIB_TAG = '(host-library)'
91
+
92
+ // Load the host-library census reference (--against, packstruct#2 ask: the
93
+ // id-vs-host-library census). Accepts a file or a directory: .json parses
94
+ // directly, code modules import in-process and default-export ids in one of
95
+ // the house profile shapes (generically probed - the library's internal
96
+ // shapes stay the host's business).
97
+ async function loadLibraryAgainst(ref) {
98
+ if (ref.endsWith('.json')) return JSON.parse(readFileSync(ref, 'utf8'))
99
+ if (existsSync(ref) && (await import('node:fs')).statSync(ref).isDirectory()) {
100
+ const entries = readdirSync(ref).filter(f => f.endsWith('.js') || f.endsWith('.mjs')).sort()
101
+ let merged = null
102
+ for (const f of entries) {
103
+ const mod = (await import(pathToFileURL(resolve(ref, f)).href)).default
104
+ merged = { parts: (merged?.parts ?? []).concat([{ file: f, mod }]) }
105
+ }
106
+ return merged
107
+ }
108
+ return (await import(pathToFileURL(resolve(ref)).href)).default
109
+ }
110
+
111
+ // Merge a dir-shaped library into one probeUnits list: [{id, at, from}].
112
+ function libraryProbeUnits(lib, ref) {
113
+ if (lib?.parts) {
114
+ const out = []
115
+ for (const { file, mod } of lib.parts) {
116
+ for (const u of probeIds(mod, DEEP_LIB_TAG)) out.push({ ...u, at: `${file}: ${u.at}` })
117
+ }
118
+ return out
119
+ }
120
+ return probeIds(lib, DEEP_LIB_TAG).map(u => ({ ...u, at: `ref: ${u.at}` }))
121
+ }
122
+
123
+ export async function deepLintPacks(dir, opts = {}) {
124
+ const shallow = lintPacks(dir)
125
+ const violations = [...shallow.violations]
126
+ const publicDir = join(dir, 'public')
127
+ let libraryIds = 0
128
+ if (!existsSync(publicDir)) {
129
+ return { packsChecked: shallow.packsChecked, violations, modulesProbed: 0, idsCensused: 0, libraryIds }
130
+ }
131
+ const shallowFlagged = new Map()
132
+ for (const v of shallow.violations) shallowFlagged.set(v.pack, v.norm)
133
+ const idSeen = new Map() // raw id -> first origin {pack, at}
134
+ const nameSeen = new Map() // manifest pack name -> dir
135
+ const MAX_IDS = 100000 // census floor: refuse pathological corpora loudly
136
+ let modulesProbed = 0
137
+ let idsCensused = 0
138
+ // Seed the census with the host library (--against): pack ids colliding
139
+ // with library ids refuse as id-library-collision (SPEC section 4's
140
+ // namespaced-ids norm, engine side: the #19 44-vs-49 zero-collision claim).
141
+ if (opts.against !== undefined) {
142
+ try {
143
+ const lib = await loadLibraryAgainst(opts.against)
144
+ for (const { id, at } of libraryProbeUnits(lib, opts.against)) {
145
+ if (idSeen.has(id)) continue // the library's own internals: not ours to judge
146
+ idSeen.set(id, { pack: DEEP_LIB_TAG, at: `--against (${at})` })
147
+ libraryIds++
148
+ }
149
+ } catch (err) {
150
+ violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": failed to load the host library: ${err.message}` })
151
+ }
152
+ }
153
+ for (const name of readdirSync(publicDir).sort()) {
154
+ const packDir = join(publicDir, name)
155
+ let isDir = true
156
+ try { readdirSync(packDir) } catch { isDir = false }
157
+ if (!isDir) continue
158
+ // Manifest-level parity with the engine's seen map (loader.js:389-391):
159
+ // two packs claiming the same pack name = one loud error at author time.
160
+ const flagged = shallowFlagged.get(name)
161
+ if (flagged === 'manifest-missing' || flagged === 'manifest-invalid') continue
162
+ let m = null
163
+ try { m = JSON.parse(readFileSync(join(packDir, 'pack.json'), 'utf8')) } catch { continue }
164
+ if (typeof m.name === 'string') {
165
+ const before = nameSeen.get(m.name)
166
+ if (before !== undefined && before !== name) {
167
+ violations.push({ pack: name, norm: 'name-collision', message: `pack name "${m.name}" claimed by both ${before}/ and ${name}/ - one loud error (the engine's seen map at author time)` })
168
+ }
169
+ nameSeen.set(m.name, name)
170
+ }
171
+ // Entry probe (packstruct#2 ask 1): import once, in-process.
172
+ if (flagged === 'entry') continue // missing/invalid entry: shallow already refused
173
+ if (typeof m.entry !== 'string' || !existsSync(join(packDir, m.entry))) continue
174
+ let mod = null
175
+ try {
176
+ mod = await import(pathToFileURL(resolve(packDir, m.entry)).href)
177
+ } catch (err) {
178
+ violations.push({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${err.message}` })
179
+ continue
180
+ }
181
+ if (mod === null || typeof mod !== 'object' || mod.default === undefined) {
182
+ violations.push({ pack: name, norm: 'entry-default-export', message: `entry "${m.entry}" has no default export - the loader would report it as an entry failure (SPEC section 3)` })
183
+ continue
184
+ }
185
+ modulesProbed++
186
+ // Census (packstruct#2 ask 2): raw ids across the pack corpus, plus
187
+ // within-pack duplicates - engine parity before the host ever loads.
188
+ for (const { id, at } of probeIds(mod.default, name)) {
189
+ idsCensused++
190
+ if (idsCensused > MAX_IDS) {
191
+ violations.push({ pack: name, norm: 'deep-floor', message: `census floor exceeded (>${MAX_IDS} ids) - refusing to walk further rather than pretending` })
192
+ return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
193
+ }
194
+ const first = idSeen.get(id)
195
+ if (first === undefined) { idSeen.set(id, { pack: name, at }); continue }
196
+ if (first.pack === name) {
197
+ if (!violations.some(v => v.norm === 'id-duplicate' && v.message.includes(`"${id}"`))) {
198
+ violations.push({ pack: name, norm: 'id-duplicate', message: `id "${id}" appears twice within the pack (first: ${first.at})` })
199
+ }
200
+ } else {
201
+ const vsLibrary = first.pack === DEEP_LIB_TAG
202
+ const norm = vsLibrary ? 'id-library-collision' : 'id-collision'
203
+ if (!violations.some(v => v.norm === norm && v.message.includes(`"${id}"`))) {
204
+ const who = vsLibrary
205
+ ? `the host library (${first.at})` : `${first.pack}/ (${first.at})`
206
+ violations.push({ pack: name, norm, message: `id "${id}" claimed by both ${who} and ${name}/ (${at}) - the host id space cannot carry both` })
207
+ }
208
+ }
209
+ }
210
+ }
211
+ return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
212
+ }
213
+