monoforge 0.9.0 → 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.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/bin/forge.mjs +34 -1
  3. package/package.json +12 -5
  4. package/packs/README.md +62 -0
  5. package/packs/public/forge-shapes/index.mjs +161 -0
  6. package/packs/public/forge-shapes/pack.json +13 -0
  7. package/packs/public/forge-shapes/test/fixtures/bad-publish/.github/workflows/publish.yml +11 -0
  8. package/packs/public/forge-shapes/test/fixtures/bad-publish/.monoforge-stamp.json +12 -0
  9. package/packs/public/forge-shapes/test/fixtures/bad-publish/README.md +3 -0
  10. package/packs/public/forge-shapes/test/fixtures/bad-publish/bin/probe.mjs +2 -0
  11. package/packs/public/forge-shapes/test/fixtures/bad-publish/package.json +14 -0
  12. package/packs/public/forge-shapes/test/fixtures/clean/.github/workflows/publish.yml +12 -0
  13. package/packs/public/forge-shapes/test/fixtures/clean/.monoforge-stamp.json +12 -0
  14. package/packs/public/forge-shapes/test/fixtures/clean/README.md +3 -0
  15. package/packs/public/forge-shapes/test/fixtures/clean/bin/probe.mjs +2 -0
  16. package/packs/public/forge-shapes/test/fixtures/clean/package.json +14 -0
  17. package/packs/public/forge-shapes/test/fixtures/missing-file/.github/workflows/publish.yml +12 -0
  18. package/packs/public/forge-shapes/test/fixtures/missing-file/.monoforge-stamp.json +13 -0
  19. package/packs/public/forge-shapes/test/fixtures/missing-file/README.md +3 -0
  20. package/packs/public/forge-shapes/test/fixtures/missing-file/bin/probe.mjs +2 -0
  21. package/packs/public/forge-shapes/test/fixtures/missing-file/package.json +14 -0
  22. package/packs/public/forge-shapes/test/fixtures/token/.github/workflows/publish.yml +12 -0
  23. package/packs/public/forge-shapes/test/fixtures/token/.monoforge-stamp.json +12 -0
  24. package/packs/public/forge-shapes/test/fixtures/token/README.md +3 -0
  25. package/packs/public/forge-shapes/test/fixtures/token/bin/probe.mjs +2 -0
  26. package/packs/public/forge-shapes/test/fixtures/token/package.json +14 -0
  27. package/packs/public/forge-shapes/test/fixtures/unfilled/.github/workflows/publish.yml +12 -0
  28. package/packs/public/forge-shapes/test/fixtures/unfilled/.monoforge-stamp.json +12 -0
  29. package/packs/public/forge-shapes/test/fixtures/unfilled/README.md +3 -0
  30. package/packs/public/forge-shapes/test/fixtures/unfilled/bin/probe.mjs +2 -0
  31. package/packs/public/forge-shapes/test/fixtures/unfilled/package.json +14 -0
  32. package/packs/public/forge-shapes/test/run.mjs +67 -0
  33. package/spec/refusals.json +35 -0
  34. package/src/doctor.mjs +46 -23
  35. package/src/fs-adapter.mjs +143 -0
  36. package/src/fs-node.mjs +15 -0
  37. package/src/harness.mjs +118 -0
  38. package/src/index.mjs +16 -1
  39. package/src/lock.mjs +1 -1
  40. package/src/packs.mjs +200 -0
  41. package/src/paths.mjs +48 -0
  42. package/src/refusals.mjs +45 -0
  43. package/src/sha256.mjs +61 -0
  44. package/src/stamp.mjs +64 -50
  45. package/src/templates.mjs +28 -14
  46. package/src/workers.mjs +16 -0
package/src/packs.mjs ADDED
@@ -0,0 +1,200 @@
1
+ // src/packs.mjs - the monoforge pack loader (monoforge#3, packstruct SPEC v1).
2
+ //
3
+ // The family's two seams: FILES travel as an artifact (our `lock`), JUDGMENT
4
+ // travels as a pack. A pack is a directory under the packs ROOT carrying
5
+ // `pack.json` (schemaVersion 1) and the entry module it names; SPEC v1 has no
6
+ // field for files to write, so a pack can only ever READ a tree - which is
7
+ // exactly the doctor's lane.
8
+ //
9
+ // This loader is small on purpose and its conformance claim is the spec's own
10
+ // harness, never our say-so (SPEC section 7):
11
+ //
12
+ // npx packstruct audit-conformance . --loader "node src/packs.mjs {packs}"
13
+ //
14
+ // Every refusal is instant, one-line, and NAMES the pack (SPEC section 5) -
15
+ // wrong schemaVersion, non-kebab name, name/dir mismatch, missing entry file,
16
+ // empty description, bad version, or a cross-pack name collision. Exit 0
17
+ // conforming / 1 violations / 2 usage.
18
+ //
19
+ // The loader is Node-only (it reads disk and imports entries) and is NOT part
20
+ // of the workerd bundle: `src/workers.mjs` deliberately omits it, alongside
21
+ // doctor and lock.
22
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
23
+ import { isAbsolute, join, resolve } from 'node:path'
24
+ import { pathToFileURL } from 'node:url'
25
+
26
+ export const PACK_SCHEMA_VERSION = 1
27
+
28
+ const RE_KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
29
+ const RE_SEMVER = /^\d+\.\d+(?:\.\d+)?(?:-[\w.-]+)?$/
30
+
31
+ // The contract root is the packs ROOT - `<dir>/` with its `public/` (tracked)
32
+ // and `local/` (gitignored WIP) children - never `packs/public/` itself
33
+ // (SPEC section 1). So: if the given dir carries a `public/` child, packs live
34
+ // under it; otherwise the dir IS the pack tree (the audit's materialized
35
+ // bundle roots, and an explicit `packs/public`).
36
+ export function packsDir(root) {
37
+ const r = resolve(root)
38
+ const pub = join(r, 'public')
39
+ return existsSync(pub) ? pub : r
40
+ }
41
+
42
+ // Discover pack dirs: every immediate subdirectory of the pack tree, sorted for
43
+ // determinism. A tree that cannot be read is a usage refusal (exit 2).
44
+ export function discoverPackDirs(root) {
45
+ const dir = packsDir(root)
46
+ let entries
47
+ try {
48
+ entries = readdirSync(dir, { withFileTypes: true })
49
+ } catch (err) {
50
+ throw new UsageError(`${root} is not a readable pack tree (${dir}): ${err.message}`)
51
+ }
52
+ return entries.filter((e) => e.isDirectory()).map((e) => join(dir, e.name)).sort()
53
+ }
54
+
55
+ // A refusal that is a usage error (the loader cannot even look), distinct from
56
+ // a pack violation (exit 1). SPEC section 7's ladder: 0 clean / 1 violations /
57
+ // 2 usage.
58
+ export class UsageError extends Error {}
59
+ export class PackViolation extends Error {}
60
+
61
+ // Validate one manifest against SPEC v1. `dirName` is the pack directory's
62
+ // basename; the spec requires the manifest name to match it. Throws a
63
+ // nameable, one-line PackViolation naming the pack - the caller surfaces it.
64
+ export function validateManifest(spec, dirName) {
65
+ const where = dirName
66
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {
67
+ throw new PackViolation(`pack "${where}": pack.json is not an object`)
68
+ }
69
+ if (spec.schemaVersion !== PACK_SCHEMA_VERSION) {
70
+ throw new PackViolation(`pack "${where}": pack.json schemaVersion must be ${PACK_SCHEMA_VERSION} (got ${JSON.stringify(spec.schemaVersion)})`)
71
+ }
72
+ if (typeof spec.name !== 'string' || !RE_KEBAB.test(spec.name)) {
73
+ throw new PackViolation(`pack "${where}": manifest "name" must be a kebab-case string (got ${JSON.stringify(spec.name)})`)
74
+ }
75
+ if (spec.name !== dirName) {
76
+ throw new PackViolation(`pack "${where}": manifest name "${spec.name}" does not match its directory`)
77
+ }
78
+ if (typeof spec.version !== 'string' || !RE_SEMVER.test(spec.version)) {
79
+ throw new PackViolation(`pack "${where}": "version" must be dotted MAJOR.MINOR[.PATCH] (got ${JSON.stringify(spec.version)})`)
80
+ }
81
+ if (typeof spec.description !== 'string' || !spec.description.trim()) {
82
+ throw new PackViolation(`pack "${where}": "description" must be a non-empty string`)
83
+ }
84
+ if (typeof spec.entry !== 'string' || !spec.entry
85
+ || isAbsolute(spec.entry) || spec.entry.split(/[\\/]/).includes('..')) {
86
+ throw new PackViolation(`pack "${where}": "entry" must be a relative path inside the pack dir (got ${JSON.stringify(spec.entry)})`)
87
+ }
88
+ return spec
89
+ }
90
+
91
+ // The entry must exist PHYSICALLY inside the pack dir (SPEC section 2: "inside"
92
+ // is physical, not merely lexical). A symlink whose real target escapes the
93
+ // pack refuses - the same class as a `..` path, caught after resolution.
94
+ function assertEntryInside(dir, entryAbs, dirName) {
95
+ if (!existsSync(entryAbs)) {
96
+ throw new PackViolation(`pack "${dirName}": declared entry "${entryAbs.slice(dir.length + 1)}" does not ship (the crashtest#16 class)`)
97
+ }
98
+ let real
99
+ try { real = realpathSync(entryAbs) } catch { return }
100
+ const realDir = realpathSync(dir)
101
+ if (real !== realDir && !real.startsWith(realDir + '/')) {
102
+ throw new PackViolation(`pack "${dirName}": entry resolves outside the pack dir (${real}) - an escaping entry is not inside`)
103
+ }
104
+ }
105
+
106
+ // Load one pack dir: read + validate the manifest, confirm the entry ships
107
+ // inside the pack, import it, and unwrap a default export. `dirName` labels
108
+ // every refusal.
109
+ export async function loadPackDir(dir) {
110
+ const dirName = dir.split('/').pop()
111
+ const manifestPath = join(dir, 'pack.json')
112
+ let spec
113
+ try {
114
+ spec = JSON.parse(readFileSync(manifestPath, 'utf8'))
115
+ } catch (err) {
116
+ throw new PackViolation(`pack "${dirName}": no parseable pack.json (${err.message})`)
117
+ }
118
+ validateManifest(spec, dirName)
119
+ const entryAbs = join(dir, spec.entry)
120
+ assertEntryInside(dir, entryAbs, dirName)
121
+ let loaded
122
+ try {
123
+ loaded = await import(pathToFileURL(entryAbs).href)
124
+ } catch (err) {
125
+ throw new PackViolation(`pack "${dirName}": entry "${spec.entry}" failed to import: ${err.message}`)
126
+ }
127
+ let module = loaded
128
+ if (loaded && typeof loaded === 'object' && 'default' in loaded) {
129
+ if (loaded.default == null) throw new PackViolation(`pack "${dirName}": entry "${spec.entry}" has a null default export`)
130
+ module = loaded.default
131
+ }
132
+ return { name: spec.name, spec, module, dir }
133
+ }
134
+
135
+ // Census the ids a loaded pack declares, per the check profile (`checks[]`) or
136
+ // the scenario profile (`attacks[]`). Ids are namespaced by the pack slug at
137
+ // the host level; this only reports what the entry exposes.
138
+ export function censusIds(module) {
139
+ const out = []
140
+ for (const key of ['checks', 'attacks', 'scenarios']) {
141
+ const list = module?.[key]
142
+ if (!Array.isArray(list)) continue
143
+ for (const item of list) {
144
+ const id = typeof item === 'string' ? item : item?.id || item?.name
145
+ if (typeof id === 'string') out.push(id)
146
+ }
147
+ }
148
+ return out
149
+ }
150
+
151
+ // Load every pack under a root. A name collision refuses to start (SPEC
152
+ // section 4: one loud error naming both origins, never silent dedupe).
153
+ export async function collectPacks(root) {
154
+ const dirs = discoverPackDirs(root)
155
+ const loaded = []
156
+ const seen = new Map()
157
+ for (const dir of dirs) {
158
+ const pack = await loadPackDir(dir)
159
+ if (seen.has(pack.name)) {
160
+ throw new PackViolation(`pack "${pack.name}" collides: ${seen.get(pack.name)} and ${pack.dir}`)
161
+ }
162
+ seen.set(pack.name, pack.dir)
163
+ loaded.push(pack)
164
+ }
165
+ return loaded
166
+ }
167
+
168
+ // The CLI (SPEC section 7): `node src/packs.mjs <packs-root>`. Exit 0 clean /
169
+ // 1 violations / 2 usage. Prints one line per pack loaded, and the refusal
170
+ // verbatim on the first violation (a refusal is instant and names the pack).
171
+ export async function runLoader(argv = process.argv.slice(2)) {
172
+ const arg = argv.find((a) => !a.startsWith('-'))
173
+ const root = arg || 'packs'
174
+ try {
175
+ const packs = await collectPacks(root)
176
+ for (const p of packs) {
177
+ const ids = censusIds(p.module)
178
+ console.log(`pack ${p.name}@${p.spec.version}: loaded${ids.length ? ` (${ids.length} id(s): ${ids.join(', ')})` : ''}`)
179
+ }
180
+ console.log(`monoforge pack loader: ${packs.length} pack(s) loaded from ${packsDir(root)}`)
181
+ return 0
182
+ } catch (err) {
183
+ if (err instanceof UsageError) {
184
+ console.error(`monoforge pack loader: ${err.message}`)
185
+ return 2
186
+ }
187
+ if (err instanceof PackViolation) {
188
+ console.error(`monoforge pack loader: ${err.message}`)
189
+ return 1
190
+ }
191
+ throw err
192
+ }
193
+ }
194
+
195
+ // Node-only CLI guard: run when invoked directly, stay importable otherwise.
196
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
197
+ process.exit(await runLoader())
198
+ }
199
+
200
+ export default { run: runLoader, collectPacks, discoverPackDirs, loadPackDir, validateManifest, censusIds, packsDir }
package/src/paths.mjs ADDED
@@ -0,0 +1,48 @@
1
+ // src/paths.mjs - the tiny POSIX path helpers the stamp engine needs.
2
+ //
3
+ // The engine core must bundle for workerd, where `node:path` exists only with
4
+ // the `nodejs_compat` flag. Rather than require that flag, the engine uses these
5
+ // four helpers - join, dirname, relative, normalize - which cover exactly the
6
+ // operations a template walk performs and nothing more. They are POSIX-only
7
+ // (both adapters normalize separators to `/`), which is all the engine ever
8
+ // passes them.
9
+
10
+ const norm = (p) => {
11
+ const abs = String(p).startsWith('/')
12
+ const out = []
13
+ for (const seg of String(p).split('/')) {
14
+ if (seg === '' || seg === '.') continue
15
+ if (seg === '..') { if (out.length && out[out.length - 1] !== '..') out.pop(); else if (!abs) out.push('..'); continue }
16
+ out.push(seg)
17
+ }
18
+ const body = out.join('/')
19
+ if (abs) return '/' + body
20
+ return body === '' ? '.' : body
21
+ }
22
+
23
+ /** POSIX `path.join`: segments joined by `/`, then normalized (`.`/`..` resolved). */
24
+ export function join(...parts) {
25
+ return norm(parts.filter((p) => p != null && p !== '').join('/'))
26
+ }
27
+
28
+ /** POSIX `path.dirname`. */
29
+ export function dirname(p) {
30
+ const s = norm(p)
31
+ if (s === '/' || s === '.') return s === '/' ? '/' : '.'
32
+ const i = s.lastIndexOf('/')
33
+ if (i < 0) return '.'
34
+ if (i === 0) return '/'
35
+ return s.slice(0, i)
36
+ }
37
+
38
+ /** POSIX `path.relative`: the path from `from` to `to` (both treated as dirs/files). */
39
+ export function relative(from, to) {
40
+ const f = norm(from).split('/').filter(Boolean)
41
+ const t = norm(to).split('/').filter(Boolean)
42
+ let i = 0
43
+ while (i < f.length && i < t.length && f[i] === t[i]) i++
44
+ const up = f.slice(i).map(() => '..')
45
+ return [...up, ...t.slice(i)].join('/')
46
+ }
47
+
48
+ export { norm as normalize }
@@ -0,0 +1,45 @@
1
+ // src/refusals.mjs - the refusal-code registry (monoforge#23, the G10 model).
2
+ //
3
+ // Every refusal the harness emits is a REGISTERED code from spec/refusals.json,
4
+ // namespaced `monoforge` in the govstruct spec/refusals.json shape, so a refusal
5
+ // one tool emits is a refusal the next tool can read. A code the registry does
6
+ // not carry is refused here, loudly: a typo'd code is worse than none, because a
7
+ // consumer would log a refusal that no gate ever agreed to.
8
+ //
9
+ // Node-only (it reads the spec file). The engine core never imports it, so the
10
+ // workerd surface is unaffected.
11
+ import { readFileSync } from 'node:fs'
12
+ import { join } from './paths.mjs'
13
+ import { getDefaultFs } from './fs-adapter.mjs'
14
+
15
+ const defaultRoot = () => join(new URL('..', import.meta.url).pathname)
16
+
17
+ export const REFUSALS_SCHEMA_VERSION = 1
18
+
19
+ /** Load and validate the registry. Throws on a malformed spec (never silent). */
20
+ export function loadRefusals({ fs = getDefaultFs(), root = defaultRoot() } = {}) {
21
+ const p = join(root, 'spec', 'refusals.json')
22
+ if (!fs.existsSync(p)) throw new Error(`the refusal registry is missing: ${p} (every refusal code must be registered)`)
23
+ let doc
24
+ try { doc = JSON.parse(fs.readFileSync(p, 'utf8')) } catch (e) { throw new Error(`spec/refusals.json is not valid JSON: ${e.message}`) }
25
+ if (doc.schemaVersion !== REFUSALS_SCHEMA_VERSION) throw new Error(`spec/refusals.json schemaVersion must be ${REFUSALS_SCHEMA_VERSION} (got ${doc.schemaVersion})`)
26
+ const codes = doc?.namespaces?.monoforge
27
+ if (!codes || typeof codes !== 'object') throw new Error('spec/refusals.json carries no `monoforge` namespace')
28
+ return codes
29
+ }
30
+
31
+ /** The registered codes (a Set), for the harness's emit guard and the tests. */
32
+ export function registeredCodes(opts = {}) {
33
+ return new Set(Object.keys(loadRefusals(opts)))
34
+ }
35
+
36
+ /**
37
+ * Build a typed refusal, refusing to emit an unregistered code. This is the one
38
+ * constructor every harness refusal goes through, so the "every emitted code is
39
+ * registered" law is structural, not a convention.
40
+ */
41
+ export function refusal(code, slot, detail, opts = {}) {
42
+ const codes = registeredCodes(opts)
43
+ if (!codes.has(code)) throw new Error(`unregistered refusal code "${code}" - register it in spec/refusals.json before emitting it`)
44
+ return { code, slot: slot ?? null, detail: detail ?? '' }
45
+ }
package/src/sha256.mjs ADDED
@@ -0,0 +1,61 @@
1
+ // src/sha256.mjs - a tiny pure-JS SHA-256, so the stamp engine imports no
2
+ // `node:crypto` and bundles for workerd with no compat flag (monoforge#27).
3
+ //
4
+ // The engine records a sha256 of every path it emits (the coexistence receipt,
5
+ // monoforge#4). Under Node `node:crypto` does that; workerd does not expose it,
6
+ // and the factory's zero-dependency law rules out a hash library. This is the
7
+ // standard FIPS 180-4 SHA-256 over UTF-8 bytes, verified byte-for-byte against
8
+ // `node:crypto` in test/workers-compat.test.mjs.
9
+ const K = new Uint32Array([
10
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
11
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
12
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
13
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
14
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
15
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
16
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
17
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
18
+ ])
19
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n))
20
+
21
+ /** SHA-256 of a string (UTF-8) or Uint8Array, as lowercase hex. */
22
+ export function sha256(input) {
23
+ const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input
24
+ const len = bytes.length
25
+ const bitLen = len * 8
26
+ // Pad: 0x80, zeros, then the 64-bit big-endian bit length.
27
+ const withOne = len + 1
28
+ const padded = new Uint8Array((Math.ceil((withOne + 8) / 64)) * 64)
29
+ padded.set(bytes)
30
+ padded[len] = 0x80
31
+ const dv = new DataView(padded.buffer)
32
+ dv.setUint32(padded.length - 4, bitLen >>> 0, false)
33
+ dv.setUint32(padded.length - 8, Math.floor(bitLen / 0x100000000), false)
34
+
35
+ const H = new Uint32Array([
36
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
37
+ ])
38
+ const w = new Uint32Array(64)
39
+ for (let off = 0; off < padded.length; off += 64) {
40
+ for (let i = 0; i < 16; i++) w[i] = dv.getUint32(off + i * 4, false)
41
+ for (let i = 16; i < 64; i++) {
42
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3)
43
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10)
44
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0
45
+ }
46
+ let [a, b, c, d, e, f, g, h] = H
47
+ for (let i = 0; i < 64; i++) {
48
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)
49
+ const ch = (e & f) ^ (~e & g)
50
+ const t1 = (h + S1 + ch + K[i] + w[i]) >>> 0
51
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)
52
+ const maj = (a & b) ^ (a & c) ^ (b & c)
53
+ const t2 = (S0 + maj) >>> 0
54
+ h = g; g = f; f = e; e = (d + t1) >>> 0
55
+ d = c; c = b; b = a; a = (t1 + t2) >>> 0
56
+ }
57
+ H[0] = (H[0] + a) >>> 0; H[1] = (H[1] + b) >>> 0; H[2] = (H[2] + c) >>> 0; H[3] = (H[3] + d) >>> 0
58
+ H[4] = (H[4] + e) >>> 0; H[5] = (H[5] + f) >>> 0; H[6] = (H[6] + g) >>> 0; H[7] = (H[7] + h) >>> 0
59
+ }
60
+ return [...H].map((x) => x.toString(16).padStart(8, '0')).join('')
61
+ }
package/src/stamp.mjs CHANGED
@@ -7,28 +7,43 @@
7
7
  // factory's last emission. A template path the host has edited since - a
8
8
  // crashtest.config.js, an AGENTS house-rules edit, a CI lane - is skipped by
9
9
  // name and never clobbered, so convergence never eats host state.
10
- import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, rmSync, copyFileSync } from 'node:fs'
11
- import { createHash } from 'node:crypto'
12
- import { join, relative, dirname } from 'node:path'
13
- import { fileURLToPath } from 'node:url'
10
+ //
11
+ // Storage seam (monoforge#27): every filesystem touch goes through an injected
12
+ // adapter (src/fs-adapter.mjs). The default IS `node:fs` under Node, so the CLI
13
+ // is unchanged; a workers consumer passes `memoryFs()` to run the SAME engine
14
+ // with no disk (the coreforge fork's reason for existing). The engine core
15
+ // imports no `node:*` - paths come from src/paths.mjs and the receipt hash from
16
+ // src/sha256.mjs - so it bundles for workerd with no compat flag.
17
+ import { join, relative, dirname } from './paths.mjs'
18
+ import { getDefaultFs } from './fs-adapter.mjs'
19
+ import { sha256 } from './sha256.mjs'
14
20
  import { resolveTemplate, resolveChain, TEMPLATES } from './templates.mjs'
15
21
 
16
- const ROOT = join(fileURLToPath(new URL('..', import.meta.url)))
22
+ // Pure-JS file-URL reader so the engine core imports no `node:*` (workerd
23
+ // bundleable). A worker consumer passes `root`, so this default is Node-only.
24
+ let ROOT_CACHE
25
+ const fileUrlToPath = (u) => decodeURIComponent(String(u).replace(/^file:\/\//, '').replace(/^\/([A-Za-z]:)/, '$1'))
26
+ const defaultRoot = () => (ROOT_CACHE ??= join(fileUrlToPath(new URL('..', import.meta.url))))
27
+ const defaultFs = () => {
28
+ const fs = getDefaultFs()
29
+ if (!fs) throw new Error('no storage adapter is set - pass { fs: memoryFs() } (see src/fs-adapter.mjs)')
30
+ return fs
31
+ }
17
32
 
18
- export function readFactoryConfig(dir) {
33
+ export function readFactoryConfig(dir, { fs = defaultFs() } = {}) {
19
34
  const cfgPath = join(dir, 'factory.json')
20
- if (!existsSync(cfgPath)) {
21
- return { ok: false, error: `no factory.json in ${dir}/ - monoforge new <dir> needs a config; see README for the schema` }
35
+ if (!fs.existsSync(cfgPath)) {
36
+ return { ok: false, code: 'E_CONFIG_MISSING', slot: 'factory.json', error: `no factory.json in ${dir}/ - monoforge new <dir> needs a config; see README for the schema` }
22
37
  }
23
38
  let cfg
24
- try { cfg = JSON.parse(readFileSync(cfgPath, 'utf8')) } catch (e) {
25
- return { ok: false, error: `factory.json is not valid JSON: ${e.message}` }
39
+ try { cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8')) } catch (e) {
40
+ return { ok: false, code: 'E_CONFIG_INVALID', slot: 'factory.json', error: `factory.json is not valid JSON: ${e.message}` }
26
41
  }
27
42
  const required = ['name', 'species', 'pitch', 'description', 'siteDomain']
28
43
  const missing = required.filter((k) => typeof cfg[k] !== 'string' || !cfg[k].trim())
29
- if (missing.length) return { ok: false, error: `factory.json missing required keys: ${missing.join(', ')}` }
30
- if (!/^[a-z0-9][a-z0-9-]*$/.test(cfg.name)) return { ok: false, error: `name must be kebab-case (got ${JSON.stringify(cfg.name)})` }
31
- if (!/^https:\/\//.test(cfg.siteDomain)) return { ok: false, error: 'siteDomain must be an absolute https URL (the landing domain)' }
44
+ if (missing.length) return { ok: false, code: 'E_FIELD_MISSING', slot: missing.join(', '), error: `factory.json missing required keys: ${missing.join(', ')}` }
45
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(cfg.name)) return { ok: false, code: 'E_ID_FORMAT', slot: 'name', error: `name must be kebab-case (got ${JSON.stringify(cfg.name)})` }
46
+ if (!/^https:\/\//.test(cfg.siteDomain)) return { ok: false, code: 'E_SITE_DOMAIN', slot: 'siteDomain', error: 'siteDomain must be an absolute https URL (the landing domain)' }
32
47
  cfg.docsPath = typeof cfg.docsPath === 'string' && cfg.docsPath.trim() ? cfg.docsPath.trim() : `docs.creadev.org/${cfg.name}`
33
48
  cfg.version = typeof cfg.version === 'string' && /^\d+\.\d+(\.\d+)?$/.test(cfg.version) ? cfg.version : '0.9.0'
34
49
  cfg.docsHost = cfg.docsPath.split('/')[0]
@@ -58,45 +73,44 @@ export function tokenReplacements(cfg, stampDate) {
58
73
 
59
74
  export const stampToolName = STAMP_TOOL
60
75
 
61
- // The receipt's per-file content hash. `stamp` records the sha256 of every
62
- // file it emits so a later re-stamp can tell a pristine template file (safe
63
- // to update) from a host-authored one (never clobbered): a stamped-template
64
- // path whose bytes no longer hash to the receipt is the host's now.
65
- export function sha256(s) {
66
- return createHash('sha256').update(s).digest('hex')
67
- }
76
+ // The receipt's per-file content hash (see src/sha256.mjs for why it is pure
77
+ // JS rather than `node:crypto`). Re-exported so the engine's public surface is
78
+ // unchanged.
79
+ export { sha256 }
68
80
 
69
81
  // The receipt path a stamped tree carries. Its presence is what makes a
70
82
  // non-empty directory a RE-STAMP rather than a stray dir to refuse.
71
83
  export const RECEIPT = '.monoforge-stamp.json'
72
84
 
73
- export function readReceipt(dir) {
85
+ export function readReceipt(dir, { fs = defaultFs() } = {}) {
74
86
  const p = join(dir, RECEIPT)
75
- if (!existsSync(p)) return null
87
+ if (!fs.existsSync(p)) return null
76
88
  try {
77
- const r = JSON.parse(readFileSync(p, 'utf8'))
89
+ const r = JSON.parse(fs.readFileSync(p, 'utf8'))
78
90
  return r && r.stampTool === STAMP_TOOL ? r : null
79
91
  } catch { return null }
80
92
  }
81
93
 
82
- export default async function stamp(dir) {
83
- const cfgRes = readFactoryConfig(dir)
84
- if (!cfgRes.ok) return { ok: false, error: cfgRes.error }
94
+ export default async function stamp(dir, opts = {}) {
95
+ const fs = opts.fs ?? defaultFs()
96
+ const root = opts.root ?? defaultRoot()
97
+ const cfgRes = readFactoryConfig(dir, { fs })
98
+ if (!cfgRes.ok) return { ok: false, code: cfgRes.code, slot: cfgRes.slot, error: cfgRes.error }
85
99
  const cfg = cfgRes.cfg
86
100
 
87
101
  // A re-stamp overlays a tree this factory already stamped (it carries our
88
102
  // receipt). Any OTHER non-empty directory is refused: never half-merge a
89
103
  // stranger's content. The receipt's own identity is checked, so a re-stamp
90
104
  // can never silently rewrite a repo that answers to a different name.
91
- const receipt = readReceipt(dir)
105
+ const receipt = readReceipt(dir, { fs })
92
106
  const restamp = Boolean(receipt)
93
- if (existsSync(dir)) {
94
- const stray = readdirSync(dir).filter((f) => !['factory.json', '.git'].includes(f))
107
+ if (fs.existsSync(dir)) {
108
+ const stray = fs.readdirSync(dir).filter((f) => !['factory.json', '.git'].includes(f))
95
109
  if (stray.length && !restamp) {
96
- return { ok: false, error: `${dir} already contains ${stray.join(', ')} - run in an empty directory holding only factory.json` }
110
+ return { ok: false, code: 'E_STRAY_DIR', slot: dir, error: `${dir} already contains ${stray.join(', ')} - run in an empty directory holding only factory.json` }
97
111
  }
98
112
  if (restamp && receipt.name && receipt.name !== cfg.name) {
99
- return { ok: false, error: `${dir} was stamped as "${receipt.name}" - refusing to re-stamp it as "${cfg.name}" (identity drift is not a re-stamp)` }
113
+ return { ok: false, code: 'E_IDENTITY_DRIFT', slot: 'name', error: `${dir} was stamped as "${receipt.name}" - refusing to re-stamp it as "${cfg.name}" (identity drift is not a re-stamp)` }
100
114
  }
101
115
  }
102
116
  // Resolve the profile's chain (children first, parent wins on collision) and
@@ -105,17 +119,17 @@ export default async function stamp(dir) {
105
119
  // same law as a bad config.
106
120
  const profile = typeof cfg.profile === 'string' && cfg.profile.trim() ? cfg.profile.trim() : 'monoforge'
107
121
  if (!TEMPLATES[profile]) {
108
- return { ok: false, error: `factory.json profile "${profile}" is not a known profile (known: ${Object.keys(TEMPLATES).join(', ')})` }
122
+ return { ok: false, code: 'E_PROFILE_UNKNOWN', slot: 'profile', error: `factory.json profile "${profile}" is not a known profile (known: ${Object.keys(TEMPLATES).join(', ')})` }
109
123
  }
110
124
  let resolved
111
125
  try {
112
- resolved = resolveTemplate(profile)
126
+ resolved = resolveTemplate(profile, { fs, root })
113
127
  } catch (e) {
114
- return { ok: false, error: `template resolution failed: ${e.message}` }
128
+ return { ok: false, code: 'E_TEMPLATE_RESOLUTION', slot: profile, error: `template resolution failed: ${e.message}` }
115
129
  }
116
- if (resolved.size === 0) return { ok: false, error: `profile "${profile}" resolved to no files - the scaffold is missing templates/${profile}/` }
130
+ if (resolved.size === 0) return { ok: false, code: 'E_TEMPLATE_EMPTY', slot: profile, error: `profile "${profile}" resolved to no files - the scaffold is missing templates/${profile}/` }
117
131
 
118
- mkdirSync(dir, { recursive: true })
132
+ fs.mkdirSync(dir, { recursive: true })
119
133
  // Coexistence: on a re-stamp, a template path whose on-disk bytes no longer
120
134
  // match the receipt's recorded hash is host-authored (crashtest.config.js,
121
135
  // scenario packs, an edited AGENTS/CI lane) - skip it, loudly, never bleed.
@@ -125,14 +139,14 @@ export default async function stamp(dir) {
125
139
  const copied = []
126
140
  for (const [rel, src] of resolved) {
127
141
  const dest = join(dir, rel)
128
- const exists = existsSync(dest)
142
+ const exists = fs.existsSync(dest)
129
143
  if (exists && restamp) {
130
144
  const recorded = priorHashes[rel]
131
- const onDisk = sha256(readFileSync(dest, 'utf8'))
145
+ const onDisk = sha256(fs.readFileSync(dest, 'utf8'))
132
146
  if (recorded && onDisk !== recorded) { skipped.push(rel); continue }
133
147
  }
134
- mkdirSync(dirname(dest), { recursive: true })
135
- copyFileSync(src, dest)
148
+ fs.mkdirSync(dirname(dest), { recursive: true })
149
+ fs.copyFileSync(src, dest)
136
150
  copied.push(rel)
137
151
  }
138
152
 
@@ -144,30 +158,30 @@ export default async function stamp(dir) {
144
158
  // host-authored file keeps its bytes verbatim (a re-stamp never rewrites
145
159
  // the host's state, not even a stray token in it).
146
160
  const walk = (d) => {
147
- for (const f of readdirSync(d, { withFileTypes: true })) {
161
+ for (const f of fs.readdirSync(d, { withFileTypes: true })) {
148
162
  const p = join(d, f.name)
149
163
  if (f.isDirectory()) { walk(p); continue }
150
164
  const rel = relative(dir, p)
151
165
  if (restamp && skipped.includes(rel)) continue
152
166
  if (restamp && !copied.includes(rel) && rel !== 'gitignore.tmpl') continue
153
- let s = readFileSync(p, 'utf8')
167
+ let s = fs.readFileSync(p, 'utf8')
154
168
  const before = s
155
169
  for (const [tok, val] of reps) s = s.replaceAll(tok, val)
156
- if (s !== before) { writeFileSync(p, s); filled++ }
170
+ if (s !== before) { fs.writeFileSync(p, s); filled++ }
157
171
  touched.push(rel)
158
172
  }
159
173
  }
160
174
  walk(dir)
161
175
  // gitignore.tmpl -> .gitignore
162
176
  const gi = join(dir, 'gitignore.tmpl')
163
- if (existsSync(gi)) {
177
+ if (fs.existsSync(gi)) {
164
178
  const giRel = '.gitignore'
165
- if (!(restamp && priorHashes[giRel] && sha256(readFileSync(join(dir, giRel), 'utf8')) !== priorHashes[giRel])) {
166
- writeFileSync(join(dir, giRel), readFileSync(gi, 'utf8'))
179
+ if (!(restamp && priorHashes[giRel] && sha256(fs.readFileSync(join(dir, giRel), 'utf8')) !== priorHashes[giRel])) {
180
+ fs.writeFileSync(join(dir, giRel), fs.readFileSync(gi, 'utf8'))
167
181
  } else {
168
182
  skipped.push(giRel)
169
183
  }
170
- rmSync(gi)
184
+ fs.rmSync(gi)
171
185
  if (!touched.includes(giRel)) touched.push(giRel)
172
186
  }
173
187
  // receipt: the record of what the stamp actually emitted. `files` keeps its
@@ -177,10 +191,10 @@ export default async function stamp(dir) {
177
191
  // sha256 of every path the stamp touched, as the factory LAST emitted it,
178
192
  // which a later re-stamp reads to tell a pristine template file from a
179
193
  // host-authored one.
180
- const emitted = [...new Set([...touched, ...copied, ...skipped])].filter((rel) => existsSync(join(dir, rel)))
194
+ const emitted = [...new Set([...touched, ...copied, ...skipped])].filter((rel) => fs.existsSync(join(dir, rel)))
181
195
  const hashes = {}
182
196
  for (const rel of emitted) {
183
- try { hashes[rel] = sha256(readFileSync(join(dir, rel), 'utf8')) } catch {}
197
+ try { hashes[rel] = sha256(fs.readFileSync(join(dir, rel), 'utf8')) } catch {}
184
198
  }
185
199
  // A skipped (host-authored) template path keeps the factory's LAST recorded
186
200
  // emission hash - not its own bytes - so every future re-stamp still reads
@@ -189,7 +203,7 @@ export default async function stamp(dir) {
189
203
  for (const rel of skipped) {
190
204
  if (priorHashes[rel]) hashes[rel] = priorHashes[rel]
191
205
  }
192
- writeFileSync(join(dir, RECEIPT), JSON.stringify({
206
+ fs.writeFileSync(join(dir, RECEIPT), JSON.stringify({
193
207
  stampTool: STAMP_TOOL,
194
208
  name: cfg.name,
195
209
  version: cfg.version,
package/src/templates.mjs CHANGED
@@ -18,11 +18,21 @@
18
18
  // The registry is the source of truth for `stamp` (which copies a resolved
19
19
  // profile into a new repo) and for the tests. It is the only place a profile
20
20
  // is declared; adding one is one entry here.
21
- import { existsSync, readdirSync, readFileSync } from 'node:fs'
22
- import { join } from 'node:path'
23
- import { fileURLToPath, pathToFileURL } from 'node:url'
21
+ import { join } from './paths.mjs'
22
+ import { getDefaultFs } from './fs-adapter.mjs'
24
23
 
25
- const ROOT = join(fileURLToPath(new URL('..', import.meta.url)))
24
+ // The template root is computed lazily from `import.meta.url` with a pure-JS
25
+ // file-URL reader, so the engine core imports NO `node:*` and stays bundleable
26
+ // for workerd. A worker consumer always passes an explicit `root` (it has no
27
+ // repo tree on disk), so this default is only ever evaluated under Node.
28
+ let ROOT_CACHE
29
+ const fileUrlToPath = (u) => decodeURIComponent(String(u).replace(/^file:\/\//, '').replace(/^\/([A-Za-z]:)/, '$1'))
30
+ const defaultRoot = () => (ROOT_CACHE ??= join(fileUrlToPath(new URL('..', import.meta.url))))
31
+ const defaultFs = () => {
32
+ const fs = getDefaultFs()
33
+ if (!fs) throw new Error('no storage adapter is set - pass { fs: memoryFs() } (see src/fs-adapter.mjs)')
34
+ return fs
35
+ }
26
36
 
27
37
  // The profiles. `from` names the template dirs/files the stamp copies;
28
38
  // `chain` names child profiles composed underneath this one. A leaf profile
@@ -83,13 +93,15 @@ export function resolveChain(name, seen = []) {
83
93
  }
84
94
 
85
95
  // Load a profile's file map (rel -> source path) by walking templates/<name>/.
86
- // TEMPLATE.md is forge metadata, not payload, so it is skipped.
87
- export function loadProfile(name) {
88
- const dir = join(ROOT, 'templates', name)
89
- if (!existsSync(dir)) throw new Error(`template "${name}" is not present - the scaffold is missing templates/${name}/`)
96
+ // TEMPLATE.md is forge metadata, not payload, so it is skipped. The walk runs
97
+ // through the storage adapter, so a workers consumer seeding the template tree
98
+ // into memoryFs resolves the SAME chain as Node does on disk.
99
+ export function loadProfile(name, { fs = defaultFs(), root = defaultRoot() } = {}) {
100
+ const dir = join(root, 'templates', name)
101
+ if (!fs.existsSync(dir)) throw new Error(`template "${name}" is not present - the scaffold is missing templates/${name}/`)
90
102
  const files = new Map()
91
103
  const walk = (d, rel) => {
92
- for (const e of readdirSync(d, { withFileTypes: true })) {
104
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
93
105
  const r = rel ? `${rel}/${e.name}` : e.name
94
106
  if (e.isDirectory()) { walk(join(d, e.name), r); continue }
95
107
  if (r === 'TEMPLATE.md') continue
@@ -102,16 +114,18 @@ export function loadProfile(name) {
102
114
 
103
115
  // Resolve a profile into the file map `stamp` copies: children first, then the
104
116
  // parent, parent wins on collision (vant's override rule).
105
- export function resolveTemplate(name) {
117
+ export function resolveTemplate(name, opts = {}) {
106
118
  const merged = new Map()
107
119
  for (const profile of resolveChain(name)) {
108
- for (const [rel, src] of loadProfile(profile)) merged.set(rel, src)
120
+ for (const [rel, src] of loadProfile(profile, opts)) merged.set(rel, src)
109
121
  }
110
122
  return merged
111
123
  }
112
124
 
113
- // CLI: --list / --resolve NAME, for eyeballing and for the tests.
114
- if (import.meta.url === pathToFileURL(process.argv[1] || '').href) {
125
+ // CLI: --list / --resolve NAME, for eyeballing and for the tests. Guarded so a
126
+ // worker bundle (no `process.argv`) evaluates nothing here.
127
+ const isNodeCli = typeof process !== 'undefined' && Array.isArray(process.argv) && process.argv[1]
128
+ if (isNodeCli && fileUrlToPath(import.meta.url) === fileUrlToPath(process.argv[1])) {
115
129
  const argv = process.argv.slice(2)
116
130
  if (argv.includes('--list')) {
117
131
  for (const [name, cfg] of Object.entries(TEMPLATES)) {
@@ -123,7 +137,7 @@ if (import.meta.url === pathToFileURL(process.argv[1] || '').href) {
123
137
  const i = argv.indexOf('--resolve')
124
138
  if (i !== -1) {
125
139
  const name = argv[i + 1]
126
- const files = resolveTemplate(name)
140
+ const files = resolveTemplate(name, { root: defaultRoot() })
127
141
  for (const rel of [...files.keys()].sort()) console.log(rel)
128
142
  console.log(`# ${files.size} file(s) from ${resolveChain(name).join(' + ')}`)
129
143
  process.exit(0)