packstruct 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lint.mjs CHANGED
@@ -9,71 +9,238 @@
9
9
  // (crashtest `fc93ca6` src/packs/loader.js:389-391) at author time.
10
10
  // PROBE ONLY: host module-shape norms stay host-owned (SPEC section 3) -
11
11
  // deep censes ids, it does not police the host's contract shapes.
12
- import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs'
13
- import { join, resolve } from 'node:path'
12
+ import { readFileSync, existsSync, readdirSync, statSync, realpathSync } from 'node:fs'
13
+ import { join, resolve, relative, isAbsolute, dirname, basename, sep } from 'node:path'
14
14
  import { pathToFileURL } from 'node:url'
15
15
  import { runCapped } from './run-capped.mjs'
16
16
 
17
- export function lintPacks(dir) {
17
+ const LANES = ['public', 'local']
18
+
19
+ // The wrong-argument lane (packstruct#13, #17): the packs ROOT is the
20
+ // argument, but the natural first-time gestures - the `public/` dir itself
21
+ // (that is exactly what the tree shows), one pack dir, the repo root - all
22
+ // produced the same doubled-segment `directory-contract` nonsense that
23
+ // blames the hypothetical packs under the arg instead of naming the fix.
24
+ // Those shapes answer with a `usage` hint naming the probable intent; a
25
+ // genuinely empty root still refuses `directory-contract` (the refusal
26
+ // matrix's missing-public-dir row depends on it).
27
+ function wrongArgHint(dir) {
28
+ const abs = resolve(dir)
29
+ if (existsSync(join(abs, 'pack.json'))) {
30
+ const parent = dirname(dir)
31
+ const root = /(^|[\\/])(public|local)$/.test(parent) ? dirname(parent) : parent
32
+ return `'${dir}' looks like a single pack (pack.json found inside) - pass the packs ROOT (the parent of public/), for example: packstruct lint ${root}`
33
+ }
34
+ let isFile = false
35
+ try { isFile = statSync(abs).isFile() } catch { /* missing path: the caller's existence check owns it */ }
36
+ if (isFile) {
37
+ return `'${dir}' is a file - pass the packs ROOT (the directory whose public/ holds the packs), for example: packstruct lint ${dirname(dir)}`
38
+ }
39
+ if (/(^|[\\/])(public|local)[\\/]?$/.test(String(dir))) {
40
+ const lane = basename(abs)
41
+ return `'${dir}' looks like a ${lane}/ directory itself - pass the packs ROOT (the parent of ${lane}/), for example: packstruct lint ${dirname(dir)}`
42
+ }
43
+ if (existsSync(join(abs, 'packs'))) {
44
+ return `'${dir}' looks like a repo root - the packs live in packs/, try: packstruct lint ${join(dir, 'packs')}`
45
+ }
46
+ return null
47
+ }
48
+
49
+ // Is `entry` a relative path that STAYS INSIDE `packDir` (SPEC section 2)?
50
+ // The old check was a `..` substring proxy: it false-refused a legitimate
51
+ // filename like `a..b.js`, yet PASSED an absolute path (`/index.js`), which
52
+ // node's `join` silently re-roots inside the pack (so shallow said clean)
53
+ // while `resolve` (the deep probe) treated as `/index.js` and refused - the
54
+ // two passes disagreed on the same manifest. Containment is a real test:
55
+ // reject non-strings, NUL, and absolute paths (POSIX or Windows-drive), then
56
+ // resolve against the pack dir and require the result to stay under it.
57
+ function entryEscape(packDir, entry) {
58
+ if (typeof entry !== 'string' || !entry.trim()) return true
59
+ if (entry.includes('\0')) return true
60
+ if (entry.startsWith('/') || entry.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(entry)) return true
61
+ const abs = resolve(packDir, entry)
62
+ const rel = relative(packDir, abs)
63
+ return rel === '' || rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)
64
+ }
65
+
66
+ // Lexical containment is not enough: a SYMLINK whose target lives outside
67
+ // the pack passes the string test yet loads code from elsewhere (a silent
68
+ // success, worse than a shallow/deep split). Compare the PHYSICAL paths -
69
+ // both sides realpath'd, so a symlinked ancestor of packDir itself (macOS
70
+ // /tmp -> /private/tmp, a vendored packs/ link) does not false-refuse. Only
71
+ // called once the entry exists as a file, so realpathSync has a target;
72
+ // an unresolvable path here is the existence check's business, not ours.
73
+ function entryEscapesViaLink(packDir, entry) {
74
+ let realPack, realEntry
75
+ try {
76
+ realPack = realpathSync(packDir)
77
+ realEntry = realpathSync(join(packDir, entry))
78
+ } catch { return false }
79
+ const rel = relative(realPack, realEntry)
80
+ return rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)
81
+ }
82
+
83
+ // Manifest validation for ONE pack dir (SPEC v1 section 2). Returns the
84
+ // violations plus whether the pack counted as checked (a pack.json exists).
85
+ // The caller tags lane and tallies; the checks never learn which lane they
86
+ // run in - public and local packs obey the same frozen manifest contract.
87
+ //
88
+ // `warnings` (SPEC v1.1 section 2) are advisory rows: they never redden a
89
+ // run, never change the exit code, and are reported separately from
90
+ // violations. The first warning shape is `implements` format.
91
+ function manifestViolations(packDir, name) {
18
92
  const violations = []
93
+ const warnings = []
94
+ const manifestPath = join(packDir, 'pack.json')
95
+ if (!existsSync(manifestPath)) {
96
+ return { checked: false, violations: [{ pack: name, norm: 'manifest-missing', message: 'pack.json missing' }], warnings }
97
+ }
98
+ let m
99
+ try { m = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
100
+ return { checked: true, violations: [{ pack: name, norm: 'manifest-invalid', message: `pack.json is not valid JSON: ${e.message}` }], warnings }
101
+ }
102
+ if (m.schemaVersion !== 1) violations.push({ pack: name, norm: 'schemaVersion', message: `schemaVersion must be 1 (got ${JSON.stringify(m.schemaVersion)})` })
103
+ 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)})` })
104
+ if (m.name !== name) violations.push({ pack: name, norm: 'name-dir-match', message: `name "${m.name}" does not match its directory "${name}"` })
105
+ 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)})` })
106
+ if (typeof m.description !== 'string' || !m.description.trim()) violations.push({ pack: name, norm: 'description', message: 'description missing or empty' })
107
+ if (entryEscape(packDir, m.entry)) {
108
+ violations.push({ pack: name, norm: 'entry', message: `entry must be a relative path inside the pack (got ${JSON.stringify(m.entry)})` })
109
+ } else {
110
+ // MUST exist AND be a file: SPEC §3 says an entry is an ES module, so a
111
+ // path that is a directory is not one. Checking existence alone let a
112
+ // directory entry pass shallow while the deep probe's import refused it -
113
+ // the same shallow/deep disagreement the containment fix closed.
114
+ let entryStat = null
115
+ try { entryStat = statSync(join(packDir, m.entry)) } catch { /* absent */ }
116
+ if (!entryStat) {
117
+ violations.push({ pack: name, norm: 'entry', message: `entry file "${m.entry}" does not exist - instant refusal at load time (the crashtest#16 class)` })
118
+ } else if (!entryStat.isFile()) {
119
+ violations.push({ pack: name, norm: 'entry', message: `entry "${m.entry}" is not a file - an entry is an ES module (SPEC section 3)` })
120
+ } else if (entryEscapesViaLink(packDir, m.entry)) {
121
+ violations.push({ pack: name, norm: 'entry', message: `entry "${m.entry}" is a symlink resolving OUTSIDE the pack - the manifest path is contained, but the physical target is not (SPEC section 2)` })
122
+ }
123
+ }
124
+ // armedByKey: OPTIONAL string. Type-checked only - an EMPTY value is
125
+ // "present, not yet armed" and the host owns presence semantics
126
+ // (folded from crashtest#25: our non-empty refusal was a check the
127
+ // SPEC didn't promise; the engine treats empty as valid).
128
+ if (m.armedByKey !== undefined && typeof m.armedByKey !== 'string') {
129
+ violations.push({ pack: name, norm: 'armedByKey', message: `armedByKey, when present, must be a string (got ${typeof m.armedByKey})` })
130
+ }
131
+ // requires (SPEC v1.3.0 section 2): OPTIONAL array of host-owned capability
132
+ // tokens the pack needs from a run root (e.g. ["wordpress"]). Shape-checked
133
+ // only - the VOCABULARY is host-owned and free-form (the spec never forks a
134
+ // shared fact), so the lint validates kebab-case tokens, non-empty and
135
+ // unique, and never assigns them meaning. The engine receipt is crashtest's
136
+ // loader (src/packs/relevance.js), which skips a pack whose requires the
137
+ // target does not provide.
138
+ if (m.requires !== undefined) {
139
+ if (!Array.isArray(m.requires) || m.requires.some((t) => typeof t !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(t))) {
140
+ violations.push({ pack: name, norm: 'requires', message: `requires, when present, must be an array of kebab-case capability tokens (got ${JSON.stringify(m.requires)})` })
141
+ } else if (new Set(m.requires).size !== m.requires.length) {
142
+ violations.push({ pack: name, norm: 'requires', message: `requires lists a token twice (got ${JSON.stringify(m.requires)})` })
143
+ }
144
+ }
145
+ // implements (SPEC v1.1 section 2): OPTIONAL host-owned acknowledgement of
146
+ // the spec the pack builds against, formatted `packstruct@<MAJOR>` or an
147
+ // exact `packstruct@1.0.0`. FORMAT ONLY, and format drift is a WARNING,
148
+ // never a refusal - absence is the quiet default and never colors a
149
+ // verdict (the row's own cost-to-host: none).
150
+ if (m.implements !== undefined && (typeof m.implements !== 'string' || !/^packstruct@\d+(\.\d+){0,2}$/.test(m.implements))) {
151
+ warnings.push({ pack: name, norm: 'implements', message: `implements, when present, should be "packstruct@<major>" or an exact pin like "packstruct@1.0.0" (got ${JSON.stringify(m.implements)}) - advisory only, never a refusal` })
152
+ }
153
+ // armedCoverage (packstruct#27, optional assist): a declared claim that
154
+ // this pack lane has an armed end-to-end row (a test file that simulates
155
+ // its target with the vocabulary armed). The lint CONFIRMS the declared
156
+ // file exists - it never runs the row (runs are the host's business).
157
+ // A declared claim that names a file that isn't there is the vacuous-green
158
+ // class this key exists to make loud; an absent key is the quiet default.
159
+ if (m.armedCoverage !== undefined) {
160
+ if (entryEscape(packDir, m.armedCoverage)) {
161
+ violations.push({ pack: name, norm: 'armed-coverage', message: `armedCoverage, when present, must be a relative path inside the pack (got ${JSON.stringify(m.armedCoverage)})` })
162
+ } else if (!existsSync(join(packDir, m.armedCoverage))) {
163
+ violations.push({ pack: name, norm: 'armed-coverage', message: `armedCoverage declares "${m.armedCoverage}" but that file does not ship - the declared armed row is vacuous (packstruct#27)` })
164
+ } else if (entryEscapesViaLink(packDir, m.armedCoverage)) {
165
+ violations.push({ pack: name, norm: 'armed-coverage', message: `armedCoverage "${m.armedCoverage}" is a symlink resolving OUTSIDE the pack - the declared row is not the pack's own (SPEC section 2)` })
166
+ }
167
+ }
168
+ return { checked: true, violations, warnings }
169
+ }
170
+
171
+ // List the pack directories of one lane (<root>/<lane>/<name>/). Anything
172
+ // that is not a directory is skipped, as the public lane always has been.
173
+ function lanePackDirs(dir, lane) {
174
+ const laneDir = join(dir, lane)
175
+ if (!existsSync(laneDir)) return []
176
+ const out = []
177
+ for (const name of readdirSync(laneDir).sort()) {
178
+ try { readdirSync(join(laneDir, name)) } catch { continue }
179
+ out.push({ name, packDir: join(laneDir, name) })
180
+ }
181
+ return out
182
+ }
183
+
184
+ // opts.local (packstruct#16): opt-in, contract-preserving. The v1 default
185
+ // stays public-only; `--local` also lints the gitignored WIP lane every
186
+ // consumer repo keeps. Local violations carry `lane: 'local'` so a CI
187
+ // consumer can tell the lanes apart; public rows stay byte-identical.
188
+ export function lintPacks(dir, opts = {}) {
189
+ const violations = []
190
+ const warnings = []
19
191
  let packsChecked = 0
192
+ let localChecked = 0
20
193
  if (!existsSync(dir)) {
21
- return { packsChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }] }
194
+ return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }], warnings }
22
195
  }
23
196
  // Section 1 contract: packs live at <packs-root>/public/<name>/
24
197
  const publicDir = join(dir, 'public')
25
198
  if (!existsSync(publicDir)) {
26
- return { packsChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }] }
199
+ const hint = wrongArgHint(dir)
200
+ if (hint) return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'usage', message: hint }], warnings }
201
+ return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }], warnings }
27
202
  }
28
- for (const name of readdirSync(publicDir).sort()) {
29
- const packDir = join(publicDir, name)
30
- let isDir = true
31
- try { readdirSync(packDir) } catch { isDir = false }
32
- if (!isDir) continue
33
- const manifestPath = join(packDir, 'pack.json')
34
- if (!existsSync(manifestPath)) {
35
- violations.push({ pack: name, norm: 'manifest-missing', message: 'pack.json missing' })
36
- continue
37
- }
38
- packsChecked++
39
- let m
40
- try { m = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
41
- violations.push({ pack: name, norm: 'manifest-invalid', message: `pack.json is not valid JSON: ${e.message}` })
42
- continue
43
- }
44
- if (m.schemaVersion !== 1) violations.push({ pack: name, norm: 'schemaVersion', message: `schemaVersion must be 1 (got ${JSON.stringify(m.schemaVersion)})` })
45
- 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)})` })
46
- if (m.name !== name) violations.push({ pack: name, norm: 'name-dir-match', message: `name "${m.name}" does not match its directory "${name}"` })
47
- 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)})` })
48
- if (typeof m.description !== 'string' || !m.description.trim()) violations.push({ pack: name, norm: 'description', message: 'description missing or empty' })
49
- if (typeof m.entry !== 'string' || !m.entry.trim() || m.entry.includes('..')) {
50
- violations.push({ pack: name, norm: 'entry', message: `entry must be a relative path inside the pack (got ${JSON.stringify(m.entry)})` })
51
- } else if (!existsSync(join(packDir, m.entry))) {
52
- violations.push({ pack: name, norm: 'entry', message: `entry file "${m.entry}" does not exist - instant refusal at load time (the crashtest#16 class)` })
53
- }
54
- // armedByKey: OPTIONAL string. Type-checked only - an EMPTY value is
55
- // "present, not yet armed" and the host owns presence semantics
56
- // (folded from crashtest#25: our non-empty refusal was a check the
57
- // SPEC didn't promise; the engine treats empty as valid).
58
- if (m.armedByKey !== undefined && typeof m.armedByKey !== 'string') {
59
- violations.push({ pack: name, norm: 'armedByKey', message: `armedByKey, when present, must be a string (got ${typeof m.armedByKey})` })
203
+ for (const { name, packDir } of lanePackDirs(dir, 'public')) {
204
+ const r = manifestViolations(packDir, name)
205
+ if (r.checked) packsChecked++
206
+ violations.push(...r.violations)
207
+ warnings.push(...r.warnings)
208
+ }
209
+ if (opts.local) {
210
+ for (const { name, packDir } of lanePackDirs(dir, 'local')) {
211
+ const r = manifestViolations(packDir, name)
212
+ if (r.checked) localChecked++
213
+ for (const v of r.violations) violations.push({ ...v, lane: 'local' })
214
+ for (const w of r.warnings) warnings.push({ ...w, lane: 'local' })
60
215
  }
61
216
  }
62
- return { packsChecked, violations }
217
+ return { packsChecked, localChecked, violations, warnings }
63
218
  }
64
219
 
65
- // Ids ONE default export carries (generic over the two house profiles:
66
- // scenario `attacks[]/steps[]`, check `checks[]` - host shapes stay
67
- // host-owned, this never assigns shared meaning to them). Runs in-process
68
- // ONLY on inert data (JSON libraries); code modules are probed in a child
69
- // process via childProbe below - their top-level code must never run inside
70
- // the linter (it could exit() the CLI or spin it forever).
220
+ // The default-export keys that carry declared ids, per house profile:
221
+ // scenario `attacks[]/steps[]`, check `checks[]`, memory `records[]`
222
+ // (memstruct@1 - a store's record ids). ONE source of truth for BOTH the
223
+ // in-process probeIds walk and the child probe script below, so a new
224
+ // profile's key is added once and the two enumerations can never drift.
225
+ // They drifted once: `records` was missing from both, so a memory pack's
226
+ // duplicate record ids and cross-pack record collisions were invisible to
227
+ // --deep (the SPEC section 7 census promise). Fixed, and pinned by
228
+ // test/fixtures/deep/bad/packs/public/memstruct-dup.
229
+ const ID_BEARING_KEYS = ['attacks', 'checks', 'scenarios', 'records']
230
+
231
+ // Ids ONE default export carries (generic over the house profiles:
232
+ // scenario `attacks[]/steps[]`, check `checks[]`, memory `records[]` -
233
+ // host shapes stay host-owned, this never assigns shared meaning to them).
234
+ // Runs in-process ONLY on inert data (JSON libraries); code modules are
235
+ // probed in a child process via childProbe below - their top-level code
236
+ // must never run inside the linter (it could exit() the CLI or spin it
237
+ // forever).
71
238
  function probeIds(def, pack) {
72
239
  const out = []
73
240
  const push = (id, at) => { if (typeof id === 'string' && id) out.push({ id, pack, at }) }
74
241
  if (!def || typeof def !== 'object') return out
75
242
  push(def.name, 'module name')
76
- for (const key of ['attacks', 'checks', 'scenarios']) {
243
+ for (const key of ID_BEARING_KEYS) {
77
244
  const arr = def[key]
78
245
  if (!Array.isArray(arr)) continue
79
246
  for (const item of arr) {
@@ -112,7 +279,7 @@ try {
112
279
  const push = (id, at) => { if (typeof id === 'string' && id) out.ids.push({ id, at }) };
113
280
  if (d && typeof d === 'object') {
114
281
  push(d.name, 'module name');
115
- for (const key of ['attacks', 'checks', 'scenarios']) {
282
+ for (const key of ${JSON.stringify(ID_BEARING_KEYS)}) {
116
283
  const arr = d[key];
117
284
  if (!Array.isArray(arr)) continue;
118
285
  for (const item of arr) {
@@ -201,15 +368,20 @@ async function collectLibraryUnits(ref, timeoutMs) {
201
368
 
202
369
  export async function deepLintPacks(dir, opts = {}) {
203
370
  const timeoutMs = Number.isFinite(opts.probeTimeoutMs) ? opts.probeTimeoutMs : PROBE_TIMEOUT_MS
204
- const shallow = lintPacks(dir)
371
+ // Lanes to walk: public always, local only when asked (packstruct#16).
372
+ const lanes = opts.local ? LANES : ['public']
373
+ const tagLane = (v, lane) => (lane === 'local' ? { ...v, lane: 'local' } : v)
374
+ const shallow = lintPacks(dir, { local: opts.local })
205
375
  const violations = [...shallow.violations]
376
+ const warnings = [...(shallow.warnings ?? [])]
377
+ const localChecked = shallow.localChecked ?? 0
206
378
  const publicDir = join(dir, 'public')
207
379
  let libraryIds = 0
208
380
  if (!existsSync(publicDir)) {
209
- return { packsChecked: shallow.packsChecked, violations, modulesProbed: 0, idsCensused: 0, libraryIds }
381
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed: 0, idsCensused: 0, libraryIds }
210
382
  }
211
383
  const shallowFlagged = new Map()
212
- for (const v of shallow.violations) shallowFlagged.set(v.pack, v.norm)
384
+ for (const v of shallow.violations) shallowFlagged.set(`${v.lane ?? 'public'}/${v.pack}`, v.norm)
213
385
  const idSeen = new Map() // raw id -> first origin {pack, at}
214
386
  const nameSeen = new Map() // manifest pack name -> dir
215
387
  const MAX_IDS = 100000 // census floor: refuse pathological corpora loudly
@@ -230,68 +402,72 @@ export async function deepLintPacks(dir, opts = {}) {
230
402
  violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": ${err.message}` })
231
403
  }
232
404
  }
233
- for (const name of readdirSync(publicDir).sort()) {
234
- const packDir = join(publicDir, name)
235
- let isDir = true
236
- try { readdirSync(packDir) } catch { isDir = false }
237
- if (!isDir) continue
238
- // Manifest-level parity with the engine's seen map (loader.js:389-391):
239
- // two packs claiming the same pack name = one loud error at author time.
240
- const flagged = shallowFlagged.get(name)
241
- if (flagged === 'manifest-missing' || flagged === 'manifest-invalid') continue
242
- let m = null
243
- try { m = JSON.parse(readFileSync(join(packDir, 'pack.json'), 'utf8')) } catch { continue }
244
- if (typeof m.name === 'string') {
245
- const before = nameSeen.get(m.name)
246
- if (before !== undefined && before !== name) {
247
- 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)` })
405
+ for (const lane of lanes) {
406
+ const laneDir = join(dir, lane)
407
+ if (!existsSync(laneDir)) continue
408
+ for (const name of readdirSync(laneDir).sort()) {
409
+ const packDir = join(laneDir, name)
410
+ let isDir = true
411
+ try { readdirSync(packDir) } catch { isDir = false }
412
+ if (!isDir) continue
413
+ // Manifest-level parity with the engine's seen map (loader.js:389-391):
414
+ // two packs claiming the same pack name = one loud error at author time.
415
+ const flagged = shallowFlagged.get(`${lane}/${name}`)
416
+ if (flagged === 'manifest-missing' || flagged === 'manifest-invalid') continue
417
+ let m = null
418
+ try { m = JSON.parse(readFileSync(join(packDir, 'pack.json'), 'utf8')) } catch { continue }
419
+ if (typeof m.name === 'string') {
420
+ const before = nameSeen.get(m.name)
421
+ if (before !== undefined && before !== name) {
422
+ violations.push(tagLane({ 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)` }, lane))
423
+ }
424
+ nameSeen.set(m.name, name)
248
425
  }
249
- nameSeen.set(m.name, name)
250
- }
251
- // Entry probe (packstruct#2 ask 1): import once, in-process.
252
- if (flagged === 'entry') continue // missing/invalid entry: shallow already refused
253
- if (typeof m.entry !== 'string' || !existsSync(join(packDir, m.entry))) continue
254
- let report
255
- try {
256
- report = await childProbe(resolve(packDir, m.entry), timeoutMs)
257
- } catch (err) {
258
- violations.push({ pack: name, norm: 'entry-import', message: `entry "${m.entry}": ${err.message}` })
259
- continue
260
- }
261
- if (report.importError !== undefined) {
262
- violations.push({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${report.importError}` })
263
- continue
264
- }
265
- if (!report.defaultExport) {
266
- 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)` })
267
- continue
268
- }
269
- modulesProbed++
270
- // Census (packstruct#2 ask 2): raw ids across the pack corpus, plus
271
- // within-pack duplicates - engine parity before the host ever loads.
272
- for (const { id, at } of report.ids) {
273
- idsCensused++
274
- if (idsCensused > MAX_IDS) {
275
- violations.push({ pack: name, norm: 'deep-floor', message: `census floor exceeded (>${MAX_IDS} ids) - refusing to walk further rather than pretending` })
276
- return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
426
+ // Entry probe (packstruct#2 ask 1): import once, in-process.
427
+ if (flagged === 'entry') continue // missing/invalid entry: shallow already refused
428
+ if (typeof m.entry !== 'string' || !existsSync(join(packDir, m.entry))) continue
429
+ let report
430
+ try {
431
+ report = await childProbe(resolve(packDir, m.entry), timeoutMs)
432
+ } catch (err) {
433
+ violations.push(tagLane({ pack: name, norm: 'entry-import', message: `entry "${m.entry}": ${err.message}` }, lane))
434
+ continue
435
+ }
436
+ if (report.importError !== undefined) {
437
+ violations.push(tagLane({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${report.importError}` }, lane))
438
+ continue
277
439
  }
278
- const first = idSeen.get(id)
279
- if (first === undefined) { idSeen.set(id, { pack: name, at }); continue }
280
- if (first.pack === name) {
281
- if (!violations.some(v => v.norm === 'id-duplicate' && v.message.includes(`"${id}"`))) {
282
- violations.push({ pack: name, norm: 'id-duplicate', message: `id "${id}" appears twice within the pack (first: ${first.at})` })
440
+ if (!report.defaultExport) {
441
+ violations.push(tagLane({ 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)` }, lane))
442
+ continue
443
+ }
444
+ modulesProbed++
445
+ // Census (packstruct#2 ask 2): raw ids across the pack corpus, plus
446
+ // within-pack duplicates - engine parity before the host ever loads.
447
+ for (const { id, at } of report.ids) {
448
+ idsCensused++
449
+ if (idsCensused > MAX_IDS) {
450
+ violations.push(tagLane({ pack: name, norm: 'deep-floor', message: `census floor exceeded (>${MAX_IDS} ids) - refusing to walk further rather than pretending` }, lane))
451
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed, idsCensused, libraryIds }
283
452
  }
284
- } else {
285
- const vsLibrary = first.pack === DEEP_LIB_TAG
286
- const norm = vsLibrary ? 'id-library-collision' : 'id-collision'
287
- if (!violations.some(v => v.norm === norm && v.message.includes(`"${id}"`))) {
288
- const who = vsLibrary
289
- ? `the host library (${first.at})` : `${first.pack}/ (${first.at})`
290
- violations.push({ pack: name, norm, message: `id "${id}" claimed by both ${who} and ${name}/ (${at}) - the host id space cannot carry both` })
453
+ const first = idSeen.get(id)
454
+ if (first === undefined) { idSeen.set(id, { pack: name, at }); continue }
455
+ if (first.pack === name) {
456
+ if (!violations.some(v => v.norm === 'id-duplicate' && v.message.includes(`"${id}"`))) {
457
+ violations.push(tagLane({ pack: name, norm: 'id-duplicate', message: `id "${id}" appears twice within the pack (first: ${first.at})` }, lane))
458
+ }
459
+ } else {
460
+ const vsLibrary = first.pack === DEEP_LIB_TAG
461
+ const norm = vsLibrary ? 'id-library-collision' : 'id-collision'
462
+ if (!violations.some(v => v.norm === norm && v.message.includes(`"${id}"`))) {
463
+ const who = vsLibrary
464
+ ? `the host library (${first.at})` : `${first.pack}/ (${first.at})`
465
+ violations.push(tagLane({ pack: name, norm, message: `id "${id}" claimed by both ${who} and ${name}/ (${at}) - the host id space cannot carry both` }, lane))
466
+ }
291
467
  }
292
468
  }
293
469
  }
294
470
  }
295
- return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
471
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed, idsCensused, libraryIds }
296
472
  }
297
473
 
package/src/new.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // src/new.mjs - packstruct new: generate a conforming pack skeleton at
2
+ // author time (packstruct#24). Zero dependencies; no network.
3
+ //
4
+ // The charter is to kill broken pack manifests at author time. The cheapest
5
+ // break class - a new author guessing the field list from a friend's
6
+ // manifest, forgetting version's dotted form, getting name/dir parity wrong -
7
+ // dies even earlier if the starting point is GENERATED correct instead of
8
+ // post-hoc refused. Refusals are the net; a conforming skeleton is the
9
+ // trampoline. `new` is pure convenience: its output is just another manifest
10
+ // the lint grades, so the lint stays the one truth enforcer.
11
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
12
+ import { join, resolve, dirname } from 'node:path'
13
+
14
+ const KEBAB = /^[a-z0-9][a-z0-9-]*$/
15
+
16
+ // The default version: a fresh pack is pre-1.0 by convention (the shipped
17
+ // packstruct-lint-shapes pack and the deep fixtures all start at 0.1.0).
18
+ const DEFAULT_VERSION = '0.1.0'
19
+
20
+ // The packs ROOT for a run. --dir wins; else walk up from cwd looking for
21
+ // an existing `packs/` (the git-style discovery every host repo satisfies);
22
+ // else fall back to ./packs so the output is always a lint-clean tree
23
+ // (<root>/public/<name>/), never a bare pack dir the lint would refuse.
24
+ export function resolvePacksRoot(cwd, dir) {
25
+ if (dir) return resolve(cwd, dir)
26
+ let cur = resolve(cwd)
27
+ for (;;) {
28
+ const candidate = join(cur, 'packs')
29
+ if (existsSync(join(candidate, 'public'))) return candidate
30
+ const parent = dirname(cur)
31
+ if (parent === cur) break
32
+ cur = parent
33
+ }
34
+ return join(resolve(cwd), 'packs')
35
+ }
36
+
37
+ function entryStub(name) {
38
+ // ESM default export (the #19 section 3 clarifier: the default export is
39
+ // the loaded thing). Neutral shape - name + description only, no ids - so
40
+ // it deep-lints clean with nothing to collide against.
41
+ return `// ${name} - packstruct@1 pack entry.
42
+ // The default export is the loaded thing (ESM is the house default).
43
+ export default {
44
+ name: '${name}',
45
+ description: 'TODO: one-line description of ${name}.',
46
+ }
47
+ `
48
+ }
49
+
50
+ function manifestJson(name) {
51
+ return JSON.stringify({
52
+ schemaVersion: 1,
53
+ name,
54
+ description: `TODO: one-line description of ${name}.`,
55
+ version: DEFAULT_VERSION,
56
+ entry: 'index.js',
57
+ }, null, 2) + '\n'
58
+ }
59
+
60
+ // newPack(name, { dir, cwd }). Returns { dir, packDir, files, violations }.
61
+ // Refusals are nameable and non-destructive: a bad name or an occupied
62
+ // target refuses without writing (never clobber).
63
+ export function newPack(name, opts = {}) {
64
+ const cwd = opts.cwd ?? process.cwd()
65
+ if (typeof name !== 'string' || !KEBAB.test(name)) {
66
+ return { dir: null, packDir: null, files: [], violations: [{ norm: 'name-kebab-case', message: `pack name must be kebab-case (got ${JSON.stringify(name)}) - for example: packstruct new my-shapes` }] }
67
+ }
68
+ const dir = resolvePacksRoot(cwd, opts.dir)
69
+ const packDir = join(dir, 'public', name)
70
+ if (existsSync(packDir)) {
71
+ return { dir, packDir, files: [], violations: [{ norm: 'pack-exists', message: `${packDir} already exists - refusing to clobber it (pick another name or remove the directory)` }] }
72
+ }
73
+ mkdirSync(packDir, { recursive: true })
74
+ const manifestPath = join(packDir, 'pack.json')
75
+ const entryPath = join(packDir, 'index.js')
76
+ writeFileSync(manifestPath, manifestJson(name))
77
+ writeFileSync(entryPath, entryStub(name))
78
+ return { dir, packDir, files: [manifestPath, entryPath], violations: [] }
79
+ }
@@ -77,18 +77,24 @@ export function runCapped({ cmd, args = [], shell = false, cwd, timeoutMs = 5000
77
77
  }
78
78
  // stdout is capped hard: past maxBuffer the child dies. stderr counts
79
79
  // against the same gate so a stderr flood cannot OOM the harness either.
80
- p.stdout.on('data', (d) => {
80
+ // A chunk larger than the remaining budget is truncated to it and the
81
+ // child is killed - pushing it whole would return output past the cap
82
+ // (the honesty cap admits nothing it did not measure).
83
+ const absorb = (d, into) => {
81
84
  if (done || capped) return
85
+ const remaining = maxBuffer - total
86
+ if (d.length > remaining) {
87
+ if (remaining > 0) into.push(d.subarray(0, remaining))
88
+ total = maxBuffer
89
+ capped = true
90
+ killTree()
91
+ return
92
+ }
93
+ into.push(d)
82
94
  total += d.length
83
- chunks.push(d)
84
- if (total > maxBuffer) { capped = true; killTree() }
85
- })
86
- p.stderr.on('data', (d) => {
87
- if (done) return
88
- total += d.length
89
- stderrChunks.push(d)
90
- if (total > maxBuffer) { capped = true; killTree() }
91
- })
95
+ }
96
+ p.stdout.on('data', (d) => absorb(d, chunks))
97
+ p.stderr.on('data', (d) => absorb(d, stderrChunks))
92
98
  p.on('error', (e) => { spawnError = e; finish() })
93
99
  p.on('exit', finish)
94
100
  })