packstruct 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lint.mjs CHANGED
@@ -9,57 +9,198 @@
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) {
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
+ // implements (SPEC v1.1 section 2): OPTIONAL host-owned acknowledgement of
132
+ // the spec the pack builds against, formatted `packstruct@<MAJOR>` or an
133
+ // exact `packstruct@1.0.0`. FORMAT ONLY, and format drift is a WARNING,
134
+ // never a refusal - absence is the quiet default and never colors a
135
+ // verdict (the row's own cost-to-host: none).
136
+ if (m.implements !== undefined && (typeof m.implements !== 'string' || !/^packstruct@\d+(\.\d+){0,2}$/.test(m.implements))) {
137
+ 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` })
138
+ }
139
+ // armedCoverage (packstruct#27, optional assist): a declared claim that
140
+ // this pack lane has an armed end-to-end row (a test file that simulates
141
+ // its target with the vocabulary armed). The lint CONFIRMS the declared
142
+ // file exists - it never runs the row (runs are the host's business).
143
+ // A declared claim that names a file that isn't there is the vacuous-green
144
+ // class this key exists to make loud; an absent key is the quiet default.
145
+ if (m.armedCoverage !== undefined) {
146
+ if (entryEscape(packDir, m.armedCoverage)) {
147
+ violations.push({ pack: name, norm: 'armed-coverage', message: `armedCoverage, when present, must be a relative path inside the pack (got ${JSON.stringify(m.armedCoverage)})` })
148
+ } else if (!existsSync(join(packDir, m.armedCoverage))) {
149
+ 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)` })
150
+ } else if (entryEscapesViaLink(packDir, m.armedCoverage)) {
151
+ 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)` })
152
+ }
153
+ }
154
+ return { checked: true, violations, warnings }
155
+ }
156
+
157
+ // List the pack directories of one lane (<root>/<lane>/<name>/). Anything
158
+ // that is not a directory is skipped, as the public lane always has been.
159
+ function lanePackDirs(dir, lane) {
160
+ const laneDir = join(dir, lane)
161
+ if (!existsSync(laneDir)) return []
162
+ const out = []
163
+ for (const name of readdirSync(laneDir).sort()) {
164
+ try { readdirSync(join(laneDir, name)) } catch { continue }
165
+ out.push({ name, packDir: join(laneDir, name) })
166
+ }
167
+ return out
168
+ }
169
+
170
+ // opts.local (packstruct#16): opt-in, contract-preserving. The v1 default
171
+ // stays public-only; `--local` also lints the gitignored WIP lane every
172
+ // consumer repo keeps. Local violations carry `lane: 'local'` so a CI
173
+ // consumer can tell the lanes apart; public rows stay byte-identical.
174
+ export function lintPacks(dir, opts = {}) {
18
175
  const violations = []
176
+ const warnings = []
19
177
  let packsChecked = 0
178
+ let localChecked = 0
20
179
  if (!existsSync(dir)) {
21
- return { packsChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }] }
180
+ return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }], warnings }
22
181
  }
23
182
  // Section 1 contract: packs live at <packs-root>/public/<name>/
24
183
  const publicDir = join(dir, 'public')
25
184
  if (!existsSync(publicDir)) {
26
- return { packsChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }] }
185
+ const hint = wrongArgHint(dir)
186
+ if (hint) return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'usage', message: hint }], warnings }
187
+ return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }], warnings }
27
188
  }
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})` })
189
+ for (const { name, packDir } of lanePackDirs(dir, 'public')) {
190
+ const r = manifestViolations(packDir, name)
191
+ if (r.checked) packsChecked++
192
+ violations.push(...r.violations)
193
+ warnings.push(...r.warnings)
194
+ }
195
+ if (opts.local) {
196
+ for (const { name, packDir } of lanePackDirs(dir, 'local')) {
197
+ const r = manifestViolations(packDir, name)
198
+ if (r.checked) localChecked++
199
+ for (const v of r.violations) violations.push({ ...v, lane: 'local' })
200
+ for (const w of r.warnings) warnings.push({ ...w, lane: 'local' })
60
201
  }
61
202
  }
62
- return { packsChecked, violations }
203
+ return { packsChecked, localChecked, violations, warnings }
63
204
  }
64
205
 
65
206
  // Ids ONE default export carries (generic over the two house profiles:
@@ -201,15 +342,20 @@ async function collectLibraryUnits(ref, timeoutMs) {
201
342
 
202
343
  export async function deepLintPacks(dir, opts = {}) {
203
344
  const timeoutMs = Number.isFinite(opts.probeTimeoutMs) ? opts.probeTimeoutMs : PROBE_TIMEOUT_MS
204
- const shallow = lintPacks(dir)
345
+ // Lanes to walk: public always, local only when asked (packstruct#16).
346
+ const lanes = opts.local ? LANES : ['public']
347
+ const tagLane = (v, lane) => (lane === 'local' ? { ...v, lane: 'local' } : v)
348
+ const shallow = lintPacks(dir, { local: opts.local })
205
349
  const violations = [...shallow.violations]
350
+ const warnings = [...(shallow.warnings ?? [])]
351
+ const localChecked = shallow.localChecked ?? 0
206
352
  const publicDir = join(dir, 'public')
207
353
  let libraryIds = 0
208
354
  if (!existsSync(publicDir)) {
209
- return { packsChecked: shallow.packsChecked, violations, modulesProbed: 0, idsCensused: 0, libraryIds }
355
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed: 0, idsCensused: 0, libraryIds }
210
356
  }
211
357
  const shallowFlagged = new Map()
212
- for (const v of shallow.violations) shallowFlagged.set(v.pack, v.norm)
358
+ for (const v of shallow.violations) shallowFlagged.set(`${v.lane ?? 'public'}/${v.pack}`, v.norm)
213
359
  const idSeen = new Map() // raw id -> first origin {pack, at}
214
360
  const nameSeen = new Map() // manifest pack name -> dir
215
361
  const MAX_IDS = 100000 // census floor: refuse pathological corpora loudly
@@ -230,68 +376,72 @@ export async function deepLintPacks(dir, opts = {}) {
230
376
  violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": ${err.message}` })
231
377
  }
232
378
  }
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)` })
379
+ for (const lane of lanes) {
380
+ const laneDir = join(dir, lane)
381
+ if (!existsSync(laneDir)) continue
382
+ for (const name of readdirSync(laneDir).sort()) {
383
+ const packDir = join(laneDir, name)
384
+ let isDir = true
385
+ try { readdirSync(packDir) } catch { isDir = false }
386
+ if (!isDir) continue
387
+ // Manifest-level parity with the engine's seen map (loader.js:389-391):
388
+ // two packs claiming the same pack name = one loud error at author time.
389
+ const flagged = shallowFlagged.get(`${lane}/${name}`)
390
+ if (flagged === 'manifest-missing' || flagged === 'manifest-invalid') continue
391
+ let m = null
392
+ try { m = JSON.parse(readFileSync(join(packDir, 'pack.json'), 'utf8')) } catch { continue }
393
+ if (typeof m.name === 'string') {
394
+ const before = nameSeen.get(m.name)
395
+ if (before !== undefined && before !== name) {
396
+ 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))
397
+ }
398
+ nameSeen.set(m.name, name)
248
399
  }
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 }
400
+ // Entry probe (packstruct#2 ask 1): import once, in-process.
401
+ if (flagged === 'entry') continue // missing/invalid entry: shallow already refused
402
+ if (typeof m.entry !== 'string' || !existsSync(join(packDir, m.entry))) continue
403
+ let report
404
+ try {
405
+ report = await childProbe(resolve(packDir, m.entry), timeoutMs)
406
+ } catch (err) {
407
+ violations.push(tagLane({ pack: name, norm: 'entry-import', message: `entry "${m.entry}": ${err.message}` }, lane))
408
+ continue
409
+ }
410
+ if (report.importError !== undefined) {
411
+ violations.push(tagLane({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${report.importError}` }, lane))
412
+ continue
277
413
  }
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})` })
414
+ if (!report.defaultExport) {
415
+ 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))
416
+ continue
417
+ }
418
+ modulesProbed++
419
+ // Census (packstruct#2 ask 2): raw ids across the pack corpus, plus
420
+ // within-pack duplicates - engine parity before the host ever loads.
421
+ for (const { id, at } of report.ids) {
422
+ idsCensused++
423
+ if (idsCensused > MAX_IDS) {
424
+ violations.push(tagLane({ pack: name, norm: 'deep-floor', message: `census floor exceeded (>${MAX_IDS} ids) - refusing to walk further rather than pretending` }, lane))
425
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed, idsCensused, libraryIds }
283
426
  }
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` })
427
+ const first = idSeen.get(id)
428
+ if (first === undefined) { idSeen.set(id, { pack: name, at }); continue }
429
+ if (first.pack === name) {
430
+ if (!violations.some(v => v.norm === 'id-duplicate' && v.message.includes(`"${id}"`))) {
431
+ violations.push(tagLane({ pack: name, norm: 'id-duplicate', message: `id "${id}" appears twice within the pack (first: ${first.at})` }, lane))
432
+ }
433
+ } else {
434
+ const vsLibrary = first.pack === DEEP_LIB_TAG
435
+ const norm = vsLibrary ? 'id-library-collision' : 'id-collision'
436
+ if (!violations.some(v => v.norm === norm && v.message.includes(`"${id}"`))) {
437
+ const who = vsLibrary
438
+ ? `the host library (${first.at})` : `${first.pack}/ (${first.at})`
439
+ violations.push(tagLane({ pack: name, norm, message: `id "${id}" claimed by both ${who} and ${name}/ (${at}) - the host id space cannot carry both` }, lane))
440
+ }
291
441
  }
292
442
  }
293
443
  }
294
444
  }
295
- return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
445
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed, idsCensused, libraryIds }
296
446
  }
297
447
 
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
  })