packstruct 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +98 -2
- package/bin/cli.mjs +121 -0
- package/conformance/cases/clean/public/clean-pack/entry.js +2 -0
- package/conformance/cases/clean/public/clean-pack/pack.json +7 -0
- package/conformance/cases/description/public/description/entry.js +2 -0
- package/conformance/cases/description/public/description/pack.json +7 -0
- package/conformance/cases/entry/public/entry/pack.json +7 -0
- package/conformance/cases/entry/public/entry/unreferenced.js +4 -0
- package/conformance/cases/name-collision/public/twin-a/entry.js +2 -0
- package/conformance/cases/name-collision/public/twin-a/pack.json +7 -0
- package/conformance/cases/name-collision/public/twin-b/entry.js +2 -0
- package/conformance/cases/name-collision/public/twin-b/pack.json +7 -0
- package/conformance/cases/name-dir-match/public/misaligned/entry.js +2 -0
- package/conformance/cases/name-dir-match/public/misaligned/pack.json +7 -0
- package/conformance/cases/name-kebab-case/public/name-kebab-case/entry.js +2 -0
- package/conformance/cases/name-kebab-case/public/name-kebab-case/pack.json +7 -0
- package/conformance/cases/schema-version/public/schema-version/entry.js +2 -0
- package/conformance/cases/schema-version/public/schema-version/pack.json +7 -0
- package/conformance/cases/version/public/version/entry.js +2 -0
- package/conformance/cases/version/public/version/pack.json +7 -0
- package/package.json +37 -4
- package/profiles/check.md +50 -0
- package/profiles/scenario.md +59 -0
- package/spec/SPEC.md +164 -0
- package/src/audit.mjs +116 -0
- package/src/lint.mjs +297 -0
- package/src/run-capped.mjs +95 -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,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# packstruct 1.0.0
|
|
2
2
|
|
|
3
|
-
|
|
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 (1.0.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 was the manual
|
|
72
|
+
release that seeded the package); 1.0.0 and later flip on the CI publish
|
|
73
|
+
lane - tag v1.0.0 and publish.yml runs (refuses 0.x, verifies the tag
|
|
74
|
+
matches the version, and publishes with `--provenance`, so v1.0.0 carries
|
|
75
|
+
provenance by construction).
|
|
76
|
+
|
|
77
|
+
## Related
|
|
78
|
+
|
|
79
|
+
- [crashtest](https://github.com/dhaupin/crashtest) (scenario-profile host)
|
|
80
|
+
- [poststruct](https://github.com/dhaupin/poststruct) (check-profile host)
|
|
81
|
+
- **The workshop** -> [Creadev.org](https://creadev.org) (the same home as the
|
|
82
|
+
docs, npm, and site surfaces above)
|
|
83
|
+
|
|
84
|
+
## Landing & docs
|
|
85
|
+
|
|
86
|
+
Landing: `packstruct.creadev.org` (Cloudflare Pages Git integration rooted at
|
|
87
|
+
`web/` - a Vite + React app prerendered by `prestruct build` into `web/dist/`
|
|
88
|
+
per-route; Pages Functions under `web/functions/`). Docs:
|
|
89
|
+
`docs.creadev.org/packstruct` (Jekyll + Pagefind + Freestruct via GitHub
|
|
90
|
+
Actions; see `.github/workflows/docs.yml` and `docs/`).
|
|
91
|
+
|
|
92
|
+
Build the site locally: `cd web && npm install && npm run build` - `prestruct`
|
|
93
|
+
runs the vite build, injects brand/SEO tags from `web/ssr.config.js`, and
|
|
94
|
+
prerenders every route to static HTML (bots get HTML, the SPA hydrates for
|
|
95
|
+
humans).
|
|
96
|
+
|
|
97
|
+
## Crashtest dogfood
|
|
98
|
+
|
|
99
|
+
`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,121 @@
|
|
|
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, probes each declared
|
|
12
|
+
// entry in a DISPOSABLE CHILD PROCESS (pack code runs nowhere near the
|
|
13
|
+
// linter's own process or exit code - the QC finding: a top-level exit()
|
|
14
|
+
// used to hijack the wire exit and a spin-lock entry hung the CLI), checks
|
|
15
|
+
// the default export exists, and censuses ids (module/attack/check/step
|
|
16
|
+
// names across the corpus) - mirrors the engine's shared-`seen` collision
|
|
17
|
+
// refusal (crashtest fc93ca6 src/packs/loader.js :389-391) at author time.
|
|
18
|
+
// Probe only: host contract shapes stay host-owned (SPEC section 3).
|
|
19
|
+
// Probing runs the entry's top-level code - in the child's domain, not
|
|
20
|
+
// the linter's; a 5s probe timeout makes stalls honest refusals.
|
|
21
|
+
//
|
|
22
|
+
// lint --against <file-or-dir> (packstruct#2, requires --deep): seed the
|
|
23
|
+
// census with the HOST LIBRARY ids so pack-vs-library collisions refuse at
|
|
24
|
+
// author time (`id-library-collision`). Accepts a JSON file or an ESM
|
|
25
|
+
// module / directory of modules whose default exports carry ids (any house
|
|
26
|
+
// profile shape, generically probed).
|
|
27
|
+
//
|
|
28
|
+
// audit-conformance (M2, SPEC section 7): materializes the bundled
|
|
29
|
+
// verdict-claiming fixture cases into scratch roots and runs the HOST's own
|
|
30
|
+
// loader command over each. A conforming loader accepts the clean case
|
|
31
|
+
// (exit 0) and refuses every violation case with a non-zero exit that NAMES
|
|
32
|
+
// the offending pack (SPEC section 5, identity match - the host may word
|
|
33
|
+
// its refusal however it likes). Exit contract: 0 all cases honored,
|
|
34
|
+
// 1 any case failed, 2 usage error - same ladder as lint.
|
|
35
|
+
import { lintPacks, deepLintPacks } from '../src/lint.mjs'
|
|
36
|
+
import { auditConformance } from '../src/audit.mjs'
|
|
37
|
+
|
|
38
|
+
let args = process.argv.slice(2)
|
|
39
|
+
const verb = args[0] === 'audit-conformance' ? 'audit-conformance' : 'lint'
|
|
40
|
+
if (args[0] === 'lint' || verb === 'audit-conformance') args = args.slice(1)
|
|
41
|
+
|
|
42
|
+
const exitUsage = (msg, usage) => {
|
|
43
|
+
if (msg) console.error(msg)
|
|
44
|
+
console.error(`Usage: ${usage}`)
|
|
45
|
+
process.exit(2)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (verb === 'audit-conformance') {
|
|
49
|
+
const loaderIdx = args.indexOf('--loader')
|
|
50
|
+
let loader
|
|
51
|
+
if (loaderIdx !== -1) {
|
|
52
|
+
loader = args[loaderIdx + 1]
|
|
53
|
+
if (loader === undefined || loader.startsWith('-')) {
|
|
54
|
+
exitUsage('--loader needs a value: --loader "<cmd> {packs}"', 'packstruct audit-conformance [<repo-dir>] --loader "<cmd> {packs}" [--json]')
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const positional = []
|
|
58
|
+
for (let i = 0; i < args.length; i++) {
|
|
59
|
+
if (args[i] === '--loader') { i++; continue }
|
|
60
|
+
if (!args[i].startsWith('-')) positional.push(args[i])
|
|
61
|
+
}
|
|
62
|
+
if (loader === undefined) {
|
|
63
|
+
exitUsage(undefined, 'packstruct audit-conformance [<repo-dir>] --loader "<cmd> {packs}" [--json]')
|
|
64
|
+
}
|
|
65
|
+
const repo = positional[0] ?? '.'
|
|
66
|
+
const json = args.includes('--json')
|
|
67
|
+
const r = await auditConformance({ loader, repo, json })
|
|
68
|
+
if (json) {
|
|
69
|
+
console.log(JSON.stringify({ schema: 1, mode: 'audit', repo, cases: r.caseCount, honored: r.honored, violations: r.violations }, null, 2))
|
|
70
|
+
} else {
|
|
71
|
+
console.log(`packstruct audit-conformance: ${r.honored}/${r.caseCount} case(s) honored by the loader over ${repo}`)
|
|
72
|
+
for (const v of r.violations) console.log(` AUDIT ${v.pack} [${v.norm}]: ${v.message}`)
|
|
73
|
+
}
|
|
74
|
+
process.exit(r.violations.length ? 1 : 0)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// --- lint verb (below unchanged contract) ---
|
|
78
|
+
const againstIdx = args.indexOf('--against')
|
|
79
|
+
let against
|
|
80
|
+
if (againstIdx !== -1) {
|
|
81
|
+
against = args[againstIdx + 1]
|
|
82
|
+
if (against === undefined || against.startsWith('-')) {
|
|
83
|
+
exitUsage(undefined, 'packstruct lint <packs-dir> [--json] [--deep] [--against <library-path>]')
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const dirArgs = []
|
|
87
|
+
for (let i = 0; i < args.length; i++) {
|
|
88
|
+
if (args[i] === '--against') { i++; continue }
|
|
89
|
+
dirArgs.push(args[i])
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const dir = dirArgs.find(a => !a.startsWith('-'))
|
|
93
|
+
if (!dir) exitUsage(undefined, 'packstruct lint <packs-dir> [--json] [--deep] [--against <library-path>]')
|
|
94
|
+
const deep = dirArgs.includes('--deep') || args.includes('--deep')
|
|
95
|
+
if (against !== undefined && !deep) {
|
|
96
|
+
exitUsage('--against requires --deep (the host-library census runs on the deep pass)', 'packstruct lint <packs-dir> [--json] [--deep] [--against <library-path>]')
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const r = deep
|
|
100
|
+
? await deepLintPacks(dir, { against })
|
|
101
|
+
: lintPacks(dir)
|
|
102
|
+
if (dirArgs.includes('--json') || args.includes('--json')) {
|
|
103
|
+
console.log(JSON.stringify({
|
|
104
|
+
schema: 1,
|
|
105
|
+
mode: deep ? 'deep' : 'manifest',
|
|
106
|
+
packsChecked: r.packsChecked,
|
|
107
|
+
modulesProbed: r.modulesProbed,
|
|
108
|
+
idsCensused: r.idsCensused,
|
|
109
|
+
libraryIds: r.libraryIds ?? 0,
|
|
110
|
+
violations: r.violations,
|
|
111
|
+
}, null, 2))
|
|
112
|
+
process.exit(r.violations.length ? 1 : 0)
|
|
113
|
+
}
|
|
114
|
+
const mode = deep ? 'lint --deep' : 'lint'
|
|
115
|
+
const probe = deep
|
|
116
|
+
? ` - ${r.modulesProbed} module(s) probed, ${r.idsCensused} id(s) censused` +
|
|
117
|
+
(against !== undefined ? `, ${r.libraryIds ?? 0} library id(s) seeded` : '')
|
|
118
|
+
: ''
|
|
119
|
+
console.log(`packstruct ${mode}: ${r.packsChecked} pack(s) checked in ${dir}${probe}`)
|
|
120
|
+
for (const v of r.violations) console.log(` VIOLATION ${v.pack} [${v.norm}]: ${v.message}`)
|
|
121
|
+
process.exit(r.violations.length ? 1 : 0)
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "packstruct",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.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,116 @@
|
|
|
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
|
+
//
|
|
14
|
+
// Loader caps (QC hardening): a HOST loader is arbitrary code in the shell
|
|
15
|
+
// it owns, and a refusal is instant - so a loader that HANGS is killed at
|
|
16
|
+
// the 120s audit timeout (neither verdict), and output past the 1MB cap is
|
|
17
|
+
// unverifiable output (neither verdict). Both surface as audit violations
|
|
18
|
+
// naming the case. The spawn is runCapped (async, exit-event-closed, no
|
|
19
|
+
// pipe-EOF hostage and no unaccounted scratch-file growth) - the two caps
|
|
20
|
+
// are the ONLY things that can end a loader early, and both are reported
|
|
21
|
+
// honestly, not graded through.
|
|
22
|
+
import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
|
|
23
|
+
import { join, resolve } from 'node:path'
|
|
24
|
+
import { tmpdir } from 'node:os'
|
|
25
|
+
import { fileURLToPath } from 'node:url'
|
|
26
|
+
import { runCapped } from './run-capped.mjs'
|
|
27
|
+
|
|
28
|
+
export const AUDIT_TIMEOUT_MS = 120000
|
|
29
|
+
export const AUDIT_MAXBUFFER_BYTES = 1024 * 1024
|
|
30
|
+
|
|
31
|
+
export const CASES_DIR = fileURLToPath(new URL('../conformance/cases/', import.meta.url))
|
|
32
|
+
|
|
33
|
+
// The bundled cases: <case>/public/<pack-dir>/, each with a verdict claim.
|
|
34
|
+
// clean expects exit 0; every other case expects a refusing loader.
|
|
35
|
+
export function listCases() {
|
|
36
|
+
return readdirSync(CASES_DIR).sort().filter(name => {
|
|
37
|
+
try { return readdirSync(join(CASES_DIR, name)).length > 0 } catch { return false }
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Pack identities a case's output must name on refusal: the pack directory
|
|
42
|
+
// names and the manifest `name` values (either counts - SPEC section 5 says
|
|
43
|
+
// "naming the pack", the host may identify by dir or manifest name).
|
|
44
|
+
function casePackIdentities(root) {
|
|
45
|
+
const ids = new Set()
|
|
46
|
+
const publicDir = join(root, 'public')
|
|
47
|
+
if (!existsSync(publicDir)) return ids
|
|
48
|
+
for (const dir of readdirSync(publicDir)) {
|
|
49
|
+
ids.add(dir)
|
|
50
|
+
try {
|
|
51
|
+
const m = JSON.parse(readFileSync(join(publicDir, dir, 'pack.json'), 'utf8'))
|
|
52
|
+
if (typeof m.name === 'string' && m.name) ids.add(m.name)
|
|
53
|
+
} catch { /* identity by dir name is already in the set */ }
|
|
54
|
+
}
|
|
55
|
+
return ids
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function auditConformance(opts = {}) {
|
|
59
|
+
if (typeof opts.loader !== 'string' || !opts.loader.includes('{packs}')) {
|
|
60
|
+
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' }] }
|
|
61
|
+
}
|
|
62
|
+
const repo = resolve(opts.repo ?? '.')
|
|
63
|
+
const cases = listCases()
|
|
64
|
+
const violations = []
|
|
65
|
+
let honored = 0
|
|
66
|
+
for (const c of cases) {
|
|
67
|
+
const expect = c === 'clean' ? 'accept' : 'refuse'
|
|
68
|
+
const tmp = mkdtempSync(join(tmpdir(), 'packstruct-audit-'))
|
|
69
|
+
try {
|
|
70
|
+
cpSync(join(CASES_DIR, c), tmp, { recursive: true })
|
|
71
|
+
const ids = casePackIdentities(tmp)
|
|
72
|
+
const cmd = opts.loader.split('{packs}').join(`"${tmp}"`)
|
|
73
|
+
const auditTimeoutMs = Number.isFinite(opts.auditTimeoutMs) ? opts.auditTimeoutMs : AUDIT_TIMEOUT_MS
|
|
74
|
+
const r = await runCapped({ cmd, shell: true, cwd: repo, timeoutMs: auditTimeoutMs, maxBuffer: AUDIT_MAXBUFFER_BYTES, killSignal: 'SIGKILL' })
|
|
75
|
+
if (r.spawnError) throw r.spawnError
|
|
76
|
+
const out = `${r.stdout}\n${r.stderr}`
|
|
77
|
+
let ok
|
|
78
|
+
let why = ''
|
|
79
|
+
if (r.capped) {
|
|
80
|
+
ok = false
|
|
81
|
+
why = `loader output exceeded the audit buffer (${AUDIT_MAXBUFFER_BYTES} bytes) - no verdict is observable past the cap, so the case carries no claim`
|
|
82
|
+
} else if (r.timedOut) {
|
|
83
|
+
ok = false
|
|
84
|
+
why = `loader hung past the audit timeout (${auditTimeoutMs}ms, killed with ${r.signal ?? 'SIGKILL'}) - writes no verdict; a refusal is instant, hangs are neither accept nor refuse`
|
|
85
|
+
} else {
|
|
86
|
+
const claimed = r.status === 0
|
|
87
|
+
if (expect === 'accept') {
|
|
88
|
+
ok = claimed
|
|
89
|
+
} else {
|
|
90
|
+
ok = !claimed
|
|
91
|
+
if (!ok) why = '' // exit 0 on a refuse case: the main message covers it
|
|
92
|
+
else if (![...ids].some(id => out.includes(id))) {
|
|
93
|
+
ok = false
|
|
94
|
+
why = 'refused but did not name the pack (SPEC section 5: nameable refusals)'
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (ok) honored++
|
|
99
|
+
else {
|
|
100
|
+
const got = r.capped ? `output capped at ${AUDIT_MAXBUFFER_BYTES} bytes`
|
|
101
|
+
: r.timedOut ? `killed at the ${auditTimeoutMs}ms timeout (${r.signal ?? 'SIGKILL'})`
|
|
102
|
+
: r.status === null ? `killed on signal ${r.signal ?? '?'}`
|
|
103
|
+
: r.status === 0 ? 'exit 0 (loader accepted)'
|
|
104
|
+
: `exit ${r.status}`
|
|
105
|
+
violations.push({
|
|
106
|
+
pack: c,
|
|
107
|
+
norm: `audit-${expect}`,
|
|
108
|
+
message: `loader ${got} on case "${c}" - the spec verdict is ${expect}${why ? ` - ${why}` : ''}`,
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
} finally {
|
|
112
|
+
rmSync(tmp, { recursive: true, force: true })
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { caseCount: cases.length, honored, violations }
|
|
116
|
+
}
|
package/src/lint.mjs
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
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, statSync } from 'node:fs'
|
|
13
|
+
import { join, resolve } from 'node:path'
|
|
14
|
+
import { pathToFileURL } from 'node:url'
|
|
15
|
+
import { runCapped } from './run-capped.mjs'
|
|
16
|
+
|
|
17
|
+
export function lintPacks(dir) {
|
|
18
|
+
const violations = []
|
|
19
|
+
let packsChecked = 0
|
|
20
|
+
if (!existsSync(dir)) {
|
|
21
|
+
return { packsChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }] }
|
|
22
|
+
}
|
|
23
|
+
// Section 1 contract: packs live at <packs-root>/public/<name>/
|
|
24
|
+
const publicDir = join(dir, 'public')
|
|
25
|
+
if (!existsSync(publicDir)) {
|
|
26
|
+
return { packsChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }] }
|
|
27
|
+
}
|
|
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})` })
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { packsChecked, violations }
|
|
63
|
+
}
|
|
64
|
+
|
|
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).
|
|
71
|
+
function probeIds(def, pack) {
|
|
72
|
+
const out = []
|
|
73
|
+
const push = (id, at) => { if (typeof id === 'string' && id) out.push({ id, pack, at }) }
|
|
74
|
+
if (!def || typeof def !== 'object') return out
|
|
75
|
+
push(def.name, 'module name')
|
|
76
|
+
for (const key of ['attacks', 'checks', 'scenarios']) {
|
|
77
|
+
const arr = def[key]
|
|
78
|
+
if (!Array.isArray(arr)) continue
|
|
79
|
+
for (const item of arr) {
|
|
80
|
+
if (!item || typeof item !== 'object') continue
|
|
81
|
+
push(item.id ?? item.name, `${key}[]`)
|
|
82
|
+
for (const sub of ['steps', 'phases']) {
|
|
83
|
+
if (!Array.isArray(item[sub])) continue
|
|
84
|
+
for (const s of item[sub]) {
|
|
85
|
+
if (!s || typeof s !== 'object') continue
|
|
86
|
+
push(s.id ?? s.name, `${key}[].${sub}[]`)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return out
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const DEEP_LIB_TAG = '(host-library)'
|
|
95
|
+
|
|
96
|
+
// QC finding (crash class, fixed): deep used to import entries in-process,
|
|
97
|
+
// so an entry and its own top-level code could drive the probe's process -
|
|
98
|
+
// process.exit(7) made the CLI wire-exit 7 with no output, and an infinite
|
|
99
|
+
// top-level loop hung it forever. Probes now run in a disposable child
|
|
100
|
+
// (no shared module cache/no shared process). Kill on the timeout: a
|
|
101
|
+
// refusal is instant, and a pack that stalls the exit-code contract is an
|
|
102
|
+
// entry-import violation, not a hint.
|
|
103
|
+
export const PROBE_TIMEOUT_MS = 5000
|
|
104
|
+
const PROBE_MARKER = 'PROBE::'
|
|
105
|
+
|
|
106
|
+
function childProbeScript(fileUrl) {
|
|
107
|
+
return `
|
|
108
|
+
try {
|
|
109
|
+
const m = await import(${JSON.stringify(fileUrl)});
|
|
110
|
+
const d = m && m.default;
|
|
111
|
+
const out = { defaultExport: d !== undefined && d !== null, ids: [] };
|
|
112
|
+
const push = (id, at) => { if (typeof id === 'string' && id) out.ids.push({ id, at }) };
|
|
113
|
+
if (d && typeof d === 'object') {
|
|
114
|
+
push(d.name, 'module name');
|
|
115
|
+
for (const key of ['attacks', 'checks', 'scenarios']) {
|
|
116
|
+
const arr = d[key];
|
|
117
|
+
if (!Array.isArray(arr)) continue;
|
|
118
|
+
for (const item of arr) {
|
|
119
|
+
if (!item || typeof item !== 'object') continue;
|
|
120
|
+
push(item.id ?? item.name, key + '[]');
|
|
121
|
+
for (const sub of ['steps', 'phases']) {
|
|
122
|
+
if (!Array.isArray(item[sub])) continue;
|
|
123
|
+
for (const s of item[sub]) {
|
|
124
|
+
if (!s || typeof s !== 'object') continue;
|
|
125
|
+
push(s.id ?? s.name, key + '[].' + sub + '[]');
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
process.stdout.write(${JSON.stringify(PROBE_MARKER)} + JSON.stringify(out));
|
|
132
|
+
} catch (e) {
|
|
133
|
+
process.stdout.write(${JSON.stringify(PROBE_MARKER)} + JSON.stringify({ importError: String((e && e.message) || e) }));
|
|
134
|
+
}
|
|
135
|
+
`
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Probe one code module in the child. Returns the probe report or throws a
|
|
139
|
+
// plain Error carrying the reason the probe could not report.
|
|
140
|
+
//
|
|
141
|
+
// Stdio through runCapped (async): a killed probe must never wait on
|
|
142
|
+
// pipe-EOF that an orphaned grandchild spawned by the entry can hold
|
|
143
|
+
// forever, and an output-flooding entry hits the 1MB cap (an honest
|
|
144
|
+
// entry-import refusal), not a scratch-file flood that fills the disk.
|
|
145
|
+
async function childProbe(absPath, timeoutMs = PROBE_TIMEOUT_MS) {
|
|
146
|
+
const fileUrl = pathToFileURL(absPath).href
|
|
147
|
+
const r = await runCapped({
|
|
148
|
+
cmd: process.execPath,
|
|
149
|
+
args: ['--input-type=module', '--no-warnings', '-e', childProbeScript(fileUrl)],
|
|
150
|
+
timeoutMs,
|
|
151
|
+
maxBuffer: 1024 * 1024,
|
|
152
|
+
killSignal: 'SIGKILL',
|
|
153
|
+
})
|
|
154
|
+
if (r.spawnError && r.spawnError.code === 'ENOENT') throw new Error(`no node runtime to probe with`)
|
|
155
|
+
const out = r.stdout
|
|
156
|
+
const idx = out.lastIndexOf(PROBE_MARKER)
|
|
157
|
+
if (idx === -1) {
|
|
158
|
+
if (r.capped) throw new Error(`probe output hit the ${1 << 20}B cap before the probe reported (an entry flooding its own stdout) - a pack that floods the probe is refusing the exit-code contract, and a refusal is instant`)
|
|
159
|
+
if (r.timedOut) throw new Error(`probe killed after the ${timeoutMs}ms timeout (signal ${r.signal ?? 'SIGKILL'}) - a pack stalling the probe is refusing the exit-code contract, and a refusal is instant`)
|
|
160
|
+
throw new Error(`entry terminated the probe process (exit ${r.status ?? 'null'}) before the probe could report`)
|
|
161
|
+
}
|
|
162
|
+
let report
|
|
163
|
+
try {
|
|
164
|
+
report = JSON.parse(out.slice(idx + PROBE_MARKER.length).trim())
|
|
165
|
+
} catch {
|
|
166
|
+
throw new Error('probe output was not parseable as a probe report')
|
|
167
|
+
}
|
|
168
|
+
return report
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Load the host-library census reference (--against, packstruct#2 ask: the
|
|
172
|
+
// id-vs-host-library census). Accepts a file or a directory: .json parses
|
|
173
|
+
// in-process (inert data - no code execution needed); code modules are
|
|
174
|
+
// child-probed one by one, same as pack entries. The library's internal
|
|
175
|
+
// shapes stay the host's business.
|
|
176
|
+
async function collectLibraryUnits(ref, timeoutMs) {
|
|
177
|
+
const units = []
|
|
178
|
+
if (ref.endsWith('.json')) {
|
|
179
|
+
const obj = JSON.parse(readFileSync(ref, 'utf8'))
|
|
180
|
+
for (const u of probeIds(obj, DEEP_LIB_TAG)) units.push({ id: u.id, at: `json ref: ${u.at}` })
|
|
181
|
+
return units
|
|
182
|
+
}
|
|
183
|
+
let files
|
|
184
|
+
if (existsSync(ref) && statSync(ref).isDirectory()) {
|
|
185
|
+
files = readdirSync(ref).filter(f => f.endsWith('.js') || f.endsWith('.mjs')).sort().map(f => join(ref, f))
|
|
186
|
+
} else {
|
|
187
|
+
files = [resolve(ref)]
|
|
188
|
+
}
|
|
189
|
+
for (const file of files) {
|
|
190
|
+
let report
|
|
191
|
+
try {
|
|
192
|
+
report = await childProbe(file, timeoutMs)
|
|
193
|
+
} catch (err) {
|
|
194
|
+
throw new Error(`${file}: ${err.message}`)
|
|
195
|
+
}
|
|
196
|
+
if (report.importError !== undefined) throw new Error(`${file}: failed to import: ${report.importError}`)
|
|
197
|
+
for (const { id, at } of report.ids) units.push({ id, at: `${file}: ${at}` })
|
|
198
|
+
}
|
|
199
|
+
return units
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export async function deepLintPacks(dir, opts = {}) {
|
|
203
|
+
const timeoutMs = Number.isFinite(opts.probeTimeoutMs) ? opts.probeTimeoutMs : PROBE_TIMEOUT_MS
|
|
204
|
+
const shallow = lintPacks(dir)
|
|
205
|
+
const violations = [...shallow.violations]
|
|
206
|
+
const publicDir = join(dir, 'public')
|
|
207
|
+
let libraryIds = 0
|
|
208
|
+
if (!existsSync(publicDir)) {
|
|
209
|
+
return { packsChecked: shallow.packsChecked, violations, modulesProbed: 0, idsCensused: 0, libraryIds }
|
|
210
|
+
}
|
|
211
|
+
const shallowFlagged = new Map()
|
|
212
|
+
for (const v of shallow.violations) shallowFlagged.set(v.pack, v.norm)
|
|
213
|
+
const idSeen = new Map() // raw id -> first origin {pack, at}
|
|
214
|
+
const nameSeen = new Map() // manifest pack name -> dir
|
|
215
|
+
const MAX_IDS = 100000 // census floor: refuse pathological corpora loudly
|
|
216
|
+
let modulesProbed = 0
|
|
217
|
+
let idsCensused = 0
|
|
218
|
+
// Seed the census with the host library (--against): pack ids colliding
|
|
219
|
+
// with library ids refuse as id-library-collision (SPEC section 4's
|
|
220
|
+
// namespaced-ids norm, engine side: the #19 44-vs-49 zero-collision claim).
|
|
221
|
+
if (opts.against !== undefined) {
|
|
222
|
+
try {
|
|
223
|
+
const lib = await collectLibraryUnits(opts.against, timeoutMs)
|
|
224
|
+
for (const { id, at } of lib) {
|
|
225
|
+
if (idSeen.has(id)) continue // the library's own internals: not ours to judge
|
|
226
|
+
idSeen.set(id, { pack: DEEP_LIB_TAG, at: `--against (${at})` })
|
|
227
|
+
libraryIds++
|
|
228
|
+
}
|
|
229
|
+
} catch (err) {
|
|
230
|
+
violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": ${err.message}` })
|
|
231
|
+
}
|
|
232
|
+
}
|
|
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)` })
|
|
248
|
+
}
|
|
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 }
|
|
277
|
+
}
|
|
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})` })
|
|
283
|
+
}
|
|
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` })
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
|
|
296
|
+
}
|
|
297
|
+
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// src/run-capped.mjs - the one gated child runner both spawned surfaces use
|
|
2
|
+
// (the audit's HOST loader and the deep probe's entry reader). Zero deps.
|
|
3
|
+
//
|
|
4
|
+
// Why async spawn and not spawnSync pipes (the QC finding, CI-reproduced):
|
|
5
|
+
// a sync pipe read waits for EOF on stdout, and EOF needs every writer gone -
|
|
6
|
+
// a timeout-killed loader that leaves an ORPHANED grandchild holding the
|
|
7
|
+
// pipe makes spawnSync block forever. Killing is fine; waiting on the
|
|
8
|
+
// orphan's EOF is not. This runner resolves on the direct child's `exit`
|
|
9
|
+
// event - never on EOF - so an orphan can't hold the harness hostage.
|
|
10
|
+
//
|
|
11
|
+
// Caps, both hard (kill on exceed, no soft drift):
|
|
12
|
+
// timeoutMs - the child is SIGKILLed at the deadline; `timedOut` reports it
|
|
13
|
+
// maxBuffer - accumulated stdout+stderr bytes; past the cap the child is
|
|
14
|
+
// killed and `capped` reports it (the cap is an honesty cap:
|
|
15
|
+
// output beyond it is unverifiable output)
|
|
16
|
+
// After `exit` (or a kill), later data events from orphans are ignored and
|
|
17
|
+
// only the bytes captured before exit are returned.
|
|
18
|
+
//
|
|
19
|
+
// Group kill (2026-10-25 leak finding): caps that kill the child alone
|
|
20
|
+
// leaked /bin/sh's node grandchildren when the shell forked instead of
|
|
21
|
+
// exec'ing - a flood loader that survives its own death keeps console.log
|
|
22
|
+
// buffering into a pipe nobody reads, gigabytes per child in seconds (4
|
|
23
|
+
// leaked children ballooned this workspace 104MB -> 3.3GB and starved CI
|
|
24
|
+
// runners mid-suite). The child now spawns detached - its own process
|
|
25
|
+
// group - and every kill path signals the NEGATIVE pid: the direct child,
|
|
26
|
+
// any forked shell, and every grandchild, in one shot.
|
|
27
|
+
//
|
|
28
|
+
// Battlefield note (2026-10-24 QC): the predecessor of this file was the
|
|
29
|
+
// audit's sync spawn with file-stdio scratch - under an output-flooding
|
|
30
|
+
// loader there was NO cap on file growth, and a 20GB scratch file filled the
|
|
31
|
+
// disk before the 120s deadline. The flood name in the tests is the same,
|
|
32
|
+
// but the killer is now the cap, not the clock.
|
|
33
|
+
import { spawn } from 'node:child_process'
|
|
34
|
+
|
|
35
|
+
function makeKill(p, killSignal) {
|
|
36
|
+
// Negated pid = the whole process group (the child is a group leader
|
|
37
|
+
// because the spawn is detached). Falls back to the direct-child kill
|
|
38
|
+
// when the group is already gone; both no-op if the child never spawned.
|
|
39
|
+
return () => {
|
|
40
|
+
if (!p.pid) return
|
|
41
|
+
try { process.kill(-p.pid, killSignal) }
|
|
42
|
+
catch { try { p.kill(killSignal) } catch { /* already gone */ } }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function runCapped({ cmd, args = [], shell = false, cwd, timeoutMs = 5000, maxBuffer = 1024 * 1024, killSignal = 'SIGKILL' }) {
|
|
47
|
+
return new Promise((resolve) => {
|
|
48
|
+
let done = false
|
|
49
|
+
let total = 0
|
|
50
|
+
let capped = false
|
|
51
|
+
let timedOut = false
|
|
52
|
+
let spawnError = null
|
|
53
|
+
const chunks = []
|
|
54
|
+
const stderrChunks = []
|
|
55
|
+
// detached on POSIX: the child leads its own process group, which is
|
|
56
|
+
// what makes the negated-pid group kill total (shell forks die too).
|
|
57
|
+
const p = spawn(cmd, args, { shell, cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] })
|
|
58
|
+
const killTree = makeKill(p, killSignal)
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
timedOut = true
|
|
61
|
+
killTree()
|
|
62
|
+
}, timeoutMs)
|
|
63
|
+
const finish = () => {
|
|
64
|
+
if (done) return
|
|
65
|
+
done = true
|
|
66
|
+
clearTimeout(timer)
|
|
67
|
+
try { p.stdout.destroy(); p.stderr.destroy() } catch { /* already dead */ }
|
|
68
|
+
resolve({
|
|
69
|
+
status: p.exitCode,
|
|
70
|
+
signal: p.signalCode,
|
|
71
|
+
stdout: Buffer.concat(chunks).toString('utf8'),
|
|
72
|
+
stderr: stderrChunks.join(''),
|
|
73
|
+
capped,
|
|
74
|
+
timedOut,
|
|
75
|
+
spawnError,
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
// stdout is capped hard: past maxBuffer the child dies. stderr counts
|
|
79
|
+
// against the same gate so a stderr flood cannot OOM the harness either.
|
|
80
|
+
p.stdout.on('data', (d) => {
|
|
81
|
+
if (done || capped) return
|
|
82
|
+
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
|
+
})
|
|
92
|
+
p.on('error', (e) => { spawnError = e; finish() })
|
|
93
|
+
p.on('exit', finish)
|
|
94
|
+
})
|
|
95
|
+
}
|