monoforge 0.9.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +2 -8
  2. package/bin/forge.mjs +34 -1
  3. package/package.json +15 -6
  4. package/packs/README.md +50 -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 +70 -51
  45. package/src/templates.mjs +28 -14
  46. package/src/workers.mjs +16 -0
  47. package/templates/monoforge/AGENTS.md +6 -15
  48. package/templates/monoforge/CHANGELOG.md +2 -5
  49. package/templates/monoforge/DEPLOY.md +13 -30
  50. package/templates/monoforge/README.md +1 -2
  51. package/templates/monoforge/TEMPLATE.md +1 -4
  52. package/templates/monoforge/docs/index.md +1 -2
  53. package/templates/monoforge/horcrux/HORCRUX.md +1 -5
  54. package/templates/monoforge/labs/TASKS.md +2 -6
  55. package/templates/monoforge/scripts/check-docs-frontmatter.cjs +1 -1
  56. package/templates/monoforge/scripts/check-fiction-signatures.cjs +1 -1
  57. package/templates/monoforge/scripts/unwrap-prose.cjs +178 -0
  58. package/templates/monoforge-headless/.github/workflows/docs.yml +15 -82
  59. package/templates/monoforge-headless/.github/workflows/publish.yml +11 -9
  60. package/templates/monoforge-headless/.github/workflows/test.yml +2 -2
  61. package/templates/monoforge-headless/TEMPLATE.md +1 -4
@@ -0,0 +1,67 @@
1
+ // packs/public/forge-shapes/test/run.mjs - the pack's self-audit (packstruct
2
+ // SPEC section 4: every pack ships test/fixtures/ proving its own claims).
3
+ //
4
+ // Runs the pack against each fixture tree and asserts the verdict each one
5
+ // claims. A fixture that stops producing its verdict fails here, in the pack's
6
+ // own CI, before any host loads it. Zero dependencies.
7
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
8
+ import { join, resolve } from 'node:path'
9
+ import { run } from '../index.mjs'
10
+
11
+ const HERE = resolve(new URL('.', import.meta.url).pathname)
12
+ const FIXTURES = join(HERE, 'fixtures')
13
+
14
+ function treeAt(root) {
15
+ const inside = (rel) => {
16
+ if (typeof rel !== 'string' || !rel) return null
17
+ const abs = resolve(root, rel)
18
+ return abs === root || abs.startsWith(root + '/') ? abs : null
19
+ }
20
+ return {
21
+ root,
22
+ exists(rel) { const abs = inside(rel); return abs ? statSync(abs, { throwIfNoEntry: false }) != null : false }, // file OR dir
23
+ text(rel) {
24
+ const abs = inside(rel)
25
+ if (!abs) return null
26
+ try { return statSync(abs).isFile() ? readFileSync(abs, 'utf8') : null } catch { return null }
27
+ },
28
+ readdir(rel) { const abs = inside(rel ?? ''); try { return readdirSync(abs) } catch { return [] } },
29
+ }
30
+ }
31
+
32
+ const verdicts = (root) => new Map(run({ forgeTree: treeAt(root) }).rows.map((r) => [r.id, r.verdict]))
33
+
34
+ let failures = 0
35
+ const check = (label, cond) => { if (!cond) { console.error(` FAIL ${label}`); failures++ } else { console.log(` ok ${label}`) } }
36
+
37
+ // Each fixture claims a verdict for one check id.
38
+ const CASES = [
39
+ ['clean', 'forge/receipt-present', 'PASSED'],
40
+ ['clean', 'forge/receipt-files-exist', 'PASSED'],
41
+ ['clean', 'forge/truth-slot-clean', 'PASSED'],
42
+ ['clean', 'forge/stamp-token-clean', 'PASSED'],
43
+ ['clean', 'forge/package-paths', 'PASSED'],
44
+ ['clean', 'forge/publish-gate', 'PASSED'],
45
+ ['unfilled', 'forge/truth-slot-clean', 'EXPLOITED'],
46
+ ['unfilled', 'forge/receipt-present', 'PASSED'],
47
+ ['token', 'forge/stamp-token-clean', 'EXPLOITED'],
48
+ ['missing-file', 'forge/receipt-files-exist', 'EXPLOITED'],
49
+ ['missing-file', 'forge/receipt-present', 'PASSED'],
50
+ ['bad-publish', 'forge/publish-gate', 'EXPLOITED'],
51
+ ['bad-publish', 'forge/truth-slot-clean', 'PASSED'],
52
+ ]
53
+
54
+ console.log('forge-shapes self-audit:')
55
+ const cache = new Map()
56
+ for (const [fixture, id, want] of CASES) {
57
+ if (!cache.has(fixture)) cache.set(fixture, verdicts(join(FIXTURES, fixture)))
58
+ const got = cache.get(fixture).get(id)
59
+ check(`${fixture}: ${id} -> ${want} (got ${got})`, got === want)
60
+ }
61
+
62
+ // An absent target dockets BOUNDED and never a pass.
63
+ const absent = new Map(run({ forgeTree: { root: null } }).rows.map((r) => [r.id, r.verdict]))
64
+ check('absent target: forge/receipt-present -> BOUNDED', absent.get('forge/receipt-present') === 'BOUNDED')
65
+
66
+ console.log(failures ? `forge-shapes self-audit: ${failures} FAILURE(S)` : 'forge-shapes self-audit: PASS')
67
+ process.exit(failures ? 1 : 0)
@@ -0,0 +1,35 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "description": "monoforge's refusal-code registry, in the govstruct spec/refusals.json shape (the G10 model): one namespaced vocabulary so a refusal one tool emits is a refusal the next tool can read. The harness refuses to emit a code it has not registered here, and test/harness.test.mjs holds that law. Codes are namespaced by tool; monoforge's namespace is `monoforge`.",
4
+ "namespaces": {
5
+ "monoforge": {
6
+ "E_BIN_PATH": "a package.json bin entry does not exist in the tree",
7
+ "E_CANON_PIN": "the .eyes canon manifest carries no pin block, or a pin is missing or still UNSET",
8
+ "E_CONFIG_INVALID": "factory.json is not valid JSON",
9
+ "E_CONFIG_MISSING": "factory.json is absent (the stamp needs a config)",
10
+ "E_DANGLING_CANON": "a .eyes canon ledger row points at a file that does not exist, escapes the canon home, or the ledger is corrupt",
11
+ "E_DASH_LAW": "an em or en dash appears in md prose (the house law is none, ever)",
12
+ "E_DOCS_GATE": "a docs gate script failed over the tree",
13
+ "E_EXPORTS_PATH": "a package.json exports entry does not exist in the tree",
14
+ "E_FIELD_MISSING": "a required factory.json key is missing or empty",
15
+ "E_FILES_PATH": "a package.json files entry does not exist in the tree",
16
+ "E_GRANT_INVALID": "the grant context is malformed (kind and scope must be non-empty strings)",
17
+ "E_IDENTITY_DRIFT": "a re-stamp targets a tree stamped under a different name",
18
+ "E_ID_FORMAT": "factory.json name is not kebab-case",
19
+ "E_LOCK_REFUSED": "lock refused because the doctor reported at least one failure",
20
+ "E_NPM_TEST": "npm test failed over the tree",
21
+ "E_PACKAGE_JSON": "package.json is not valid JSON",
22
+ "E_PROFILE_UNKNOWN": "factory.json profile is not a known profile",
23
+ "E_PUBLISH_GATE": "publish.yml does not refuse 0.x refs (the OIDC ladder gate)",
24
+ "E_PUBLISH_TOKEN": "publish.yml references a publish token (the law is OIDC only)",
25
+ "E_SITE_DOMAIN": "factory.json siteDomain is not an absolute https URL",
26
+ "E_STAMP_MANIFEST": ".monoforge-stamp.json is present but unparseable",
27
+ "E_STAMP_TOKEN": "a raw __TOKEN__ survived the stamp (the stamp never finished)",
28
+ "E_STRAY_DIR": "the stamp target is a non-empty directory that is not a re-stamp",
29
+ "E_TEMPLATE_EMPTY": "a profile resolved to no files (the scaffold is missing its template dir)",
30
+ "E_TEMPLATE_RESOLUTION": "template chain resolution failed (a cycle, or a missing chained profile)",
31
+ "E_TRUTH_SLOT": "a FORGE-TODO truth slot is still unfilled (a shipped placeholder is a shipped lie)",
32
+ "E_VERB_UNKNOWN": "the harness was asked for a verb it does not drive"
33
+ }
34
+ }
35
+ }
package/src/doctor.mjs CHANGED
@@ -9,6 +9,27 @@ import { join, relative } from 'node:path'
9
9
 
10
10
  const TODO_MARK = 'FORGE-TODO'
11
11
 
12
+ // The refusal code each finding id maps to (monoforge#23): a doctor failure is
13
+ // a typed refusal, so a harness consumer reads `code`/`slot` rather than prose.
14
+ // Warns carry no code (a warn is not a refusal). A failing id absent from this
15
+ // map is a bug the harness test catches, never a silent prose-only failure.
16
+ export const CODE_BY_ID = {
17
+ 'stamp-manifest': 'E_STAMP_MANIFEST',
18
+ 'truth-slot': 'E_TRUTH_SLOT',
19
+ 'stamp-token': 'E_STAMP_TOKEN',
20
+ 'package-json': 'E_PACKAGE_JSON',
21
+ 'bin-path': 'E_BIN_PATH',
22
+ 'exports-path': 'E_EXPORTS_PATH',
23
+ 'files-path': 'E_FILES_PATH',
24
+ 'publish-gate': 'E_PUBLISH_GATE',
25
+ 'publish-token': 'E_PUBLISH_TOKEN',
26
+ 'npm-test': 'E_NPM_TEST',
27
+ 'docs-gate': 'E_DOCS_GATE',
28
+ 'dash-law': 'E_DASH_LAW',
29
+ 'canon-pin': 'E_CANON_PIN',
30
+ 'dangling-canon': 'E_DANGLING_CANON',
31
+ }
32
+
12
33
  // Untracked scratch trees used to land in the battery through the walk
13
34
  // (prestruct's beta false-positive class): a .gitignore at the root is the
14
35
  // cheap truth about what is scratch, and scratch is by definition not
@@ -55,7 +76,9 @@ function gitClean(dir) {
55
76
 
56
77
  export default async function doctor(dir, opts = {}) {
57
78
  const findings = []
58
- const fail = (id, message) => findings.push({ level: 'fail', id, message })
79
+ // A fail carries its registered refusal code and the slot it names; a warn
80
+ // carries neither (a warn is not a refusal).
81
+ const fail = (id, message, slot = null) => findings.push({ level: 'fail', id, code: CODE_BY_ID[id] || null, slot, message })
59
82
  const warn = (id, message) => findings.push({ level: 'warn', id, message })
60
83
 
61
84
  // 1. git state (warn: dirty tree ships? no. but a lock needs clean)
@@ -70,7 +93,7 @@ export default async function doctor(dir, opts = {}) {
70
93
  if (existsSync(manifestPath)) {
71
94
  let manifest
72
95
  try { manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
73
- fail('stamp-manifest', `.monoforge-stamp.json is unparseable: ${e.message}`)
96
+ fail('stamp-manifest', `.monoforge-stamp.json is unparseable: ${e.message}`, '.monoforge-stamp.json')
74
97
  manifest = { files: [] }
75
98
  }
76
99
  for (const rel of manifest.files || []) {
@@ -80,12 +103,12 @@ export default async function doctor(dir, opts = {}) {
80
103
  let s
81
104
  try { s = readFileSync(p, 'utf8') } catch { continue }
82
105
  const n = (s.match(new RegExp(TODO_MARK, 'g')) || []).length
83
- if (n) fail('truth-slot', `${rel} still carries ${n} ${TODO_MARK} slot(s): a shipped placeholder is a shipped lie`)
106
+ if (n) fail('truth-slot', `${rel} still carries ${n} ${TODO_MARK} slot(s): a shipped placeholder is a shipped lie`, rel)
84
107
  // stamp-token pass (eyestruct dogfood, 2026-10-24): raw __X__ tokens
85
108
  // are the truth-slot class wearing a different uniform; the same law
86
109
  // applies (a shipped placeholder is a shipped lie).
87
110
  const raw = s.match(/__[A-Z][A-Z0-9_]*__/g) || []
88
- if (raw.length) fail('stamp-token', `${rel} still carries raw stamp token(s): ${[...new Set(raw)].join(', ')} - the stamp never finished`)
111
+ if (raw.length) fail('stamp-token', `${rel} still carries raw stamp token(s): ${[...new Set(raw)].join(', ')} - the stamp never finished`, rel)
89
112
  }
90
113
  }
91
114
 
@@ -93,23 +116,23 @@ export default async function doctor(dir, opts = {}) {
93
116
  const pkgPath = join(dir, 'package.json')
94
117
  if (existsSync(pkgPath)) {
95
118
  let pkg
96
- try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) } catch (e) { fail('package-json', `unparseable: ${e.message}`); pkg = null }
119
+ try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) } catch (e) { fail('package-json', `unparseable: ${e.message}`, 'package.json'); pkg = null }
97
120
  if (pkg) {
98
121
  if (pkg?.bin) {
99
122
  for (const b of Object.values(pkg.bin)) {
100
- if (!existsSync(join(dir, b))) fail('bin-path', `bin entry ${b} does not exist (the crashtest#16 class, in our own clothes)`)
123
+ if (!existsSync(join(dir, b))) fail('bin-path', `bin entry ${b} does not exist (the crashtest#16 class, in our own clothes)`, b)
101
124
  }
102
125
  }
103
126
  if (pkg?.exports) {
104
127
  for (const v of Object.values(pkg.exports)) {
105
128
  const p2 = typeof v === 'string' ? v : v?.import
106
- if (p2 && !p2.includes('*') && !existsSync(join(dir, p2))) fail('exports-path', `exports entry ${p2} does not exist`) // deep-import glob passthroughs are valid package.json (prestruct beta class #1)
129
+ if (p2 && !p2.includes('*') && !existsSync(join(dir, p2))) fail('exports-path', `exports entry ${p2} does not exist`, p2) // deep-import glob passthroughs are valid package.json (prestruct beta class #1)
107
130
  }
108
131
  }
109
132
  for (const f of pkg.files || []) {
110
133
  if (f.startsWith('!')) continue // negation: npm's exclude mechanism inside the whitelist, never a must-exist path (prestruct beta class #2)
111
134
  const p3 = join(dir, f)
112
- if (!existsSync(p3) && !f.includes('*')) fail('files-path', `files entry ${f} does not exist in the tree`)
135
+ if (!existsSync(p3) && !f.includes('*')) fail('files-path', `files entry ${f} does not exist in the tree`, f)
113
136
  }
114
137
  if (!pkg.description || pkg.description.length < 10) warn('description', 'package.json description missing or too thin')
115
138
  if ((pkg.engines?.node || '') < '>=20') warn('engines', 'engines.node floor not >=20 (house runtime floor)')
@@ -119,14 +142,14 @@ export default async function doctor(dir, opts = {}) {
119
142
  const w = readFileSync(pub, 'utf8')
120
143
  // Two accepted shapes: the `startsWith(github.ref_name,'v0.')` job
121
144
  // guard, or the OIDC ladder's `case "$V" in 0.*)` version gate.
122
- if (!/startsWith\(['"]v0\.|0\.\*\)/.test(w)) fail('publish-gate', '.github/workflows/publish.yml does not refuse 0.x refs (the OIDC ladder gate)')
145
+ if (!/startsWith\(['"]v0\.|0\.\*\)/.test(w)) fail('publish-gate', '.github/workflows/publish.yml does not refuse 0.x refs (the OIDC ladder gate)', '.github/workflows/publish.yml')
123
146
  // The family law (rule #3: the NPM_TOKEN bug was caught twice - in the
124
147
  // live workflow and in the template - so it becomes a gate). A real
125
148
  // `secrets.NPM_TOKEN` reference is a violation; a comment that merely
126
149
  // names the removed line is not. Strip comment lines, then scan.
127
150
  const codeLines = w.split('\n').filter((l) => !/^\s*#/.test(l)).join('\n')
128
151
  if (/secrets\.NPM_TOKEN|NODE_AUTH_TOKEN/.test(codeLines)) {
129
- fail('publish-token', '.github/workflows/publish.yml references a publish token (secrets.NPM_TOKEN / NODE_AUTH_TOKEN) - the family law is OIDC trusted publishing only, no publish tokens anywhere')
152
+ fail('publish-token', '.github/workflows/publish.yml references a publish token (secrets.NPM_TOKEN / NODE_AUTH_TOKEN) - the family law is OIDC trusted publishing only, no publish tokens anywhere', '.github/workflows/publish.yml')
130
153
  }
131
154
  }
132
155
  // 5. npm test
@@ -134,7 +157,7 @@ export default async function doctor(dir, opts = {}) {
134
157
  try {
135
158
  execFileSync('npm', ['test', '--silent'], { cwd: dir, stdio: 'pipe' })
136
159
  } catch {
137
- fail('npm-test', 'npm test failed: the negative test is the product, not an optional extra')
160
+ fail('npm-test', 'npm test failed: the negative test is the product, not an optional extra', 'npm test')
138
161
  }
139
162
  } else warn('npm-test', 'no test script: nothing self-audits')
140
163
  }
@@ -148,7 +171,7 @@ export default async function doctor(dir, opts = {}) {
148
171
  const gp = join(dir, 'scripts', g2)
149
172
  if (!existsSync(gp)) { warn('docs-gate', `missing gate script scripts/${g2} (stamped repos always carry them)`); continue }
150
173
  try { execFileSync('node', [gp, d], { cwd: dir, stdio: 'pipe' }) }
151
- catch (e) { fail('docs-gate', `scripts/${g2} failed: ${String(e.stderr || e.message).split('\n')[0]}`) }
174
+ catch (e) { fail('docs-gate', `scripts/${g2} failed: ${String(e.stderr || e.message).split('\n')[0]}`, `scripts/${g2}`) }
152
175
  }
153
176
  }
154
177
  for (const p of files) {
@@ -157,7 +180,7 @@ export default async function doctor(dir, opts = {}) {
157
180
  try { s = readFileSync(p, 'utf8') } catch { continue }
158
181
  if (/[\u2014\u2013]/.test(s)) {
159
182
  const line = s.split('\n').findIndex((l) => /[\u2014\u2013]/.test(l)) + 1
160
- fail('dash-law', `${relative(dir, p)} line ${line}: em/en dash in prose (house law: none, ever)`)
183
+ fail('dash-law', `${relative(dir, p)} line ${line}: em/en dash in prose (house law: none, ever)`, relative(dir, p))
161
184
  }
162
185
  }
163
186
 
@@ -172,7 +195,7 @@ export default async function doctor(dir, opts = {}) {
172
195
  if (existsSync(manifestFile)) {
173
196
  let s
174
197
  try { s = readFileSync(manifestFile, 'utf8') } catch {
175
- fail('canon-pin', `${eyesHome}/manifest.yml is not readable`)
198
+ fail('canon-pin', `${eyesHome}/manifest.yml is not readable`, `${eyesHome}/manifest.yml`)
176
199
  return
177
200
  }
178
201
  // The pin block parses in the family subset, and every seeded pin
@@ -184,16 +207,16 @@ export default async function doctor(dir, opts = {}) {
184
207
  for (const line of m[1].split('\n')) {
185
208
  if (!line.trim()) continue
186
209
  const kv = line.trim().match(/^([\w-]+):\s*(.+)$/)
187
- if (!kv) { fail('canon-pin', `${eyesHome}/manifest.yml pin row is not key: value -> "${line.trim()}"`); continue }
210
+ if (!kv) { fail('canon-pin', `${eyesHome}/manifest.yml pin row is not key: value -> "${line.trim()}"`, `${eyesHome}/manifest.yml`); continue }
188
211
  pin[kv[1]] = kv[2].trim()
189
212
  }
190
213
  } else {
191
- fail('canon-pin', `${eyesHome}/manifest.yml carries no pin block (the canon token the captures resolve)`)
214
+ fail('canon-pin', `${eyesHome}/manifest.yml carries no pin block (the canon token the captures resolve)`, `${eyesHome}/manifest.yml`)
192
215
  }
193
216
  for (const key of ['browser-image', 'renderer']) {
194
217
  const v = pin[key] || ''
195
- if (!v) fail('canon-pin', `${eyesHome}/manifest.yml pin.${key} is missing (the canon cannot resolve without it)`)
196
- else if (/\bUNSET\b|edit-me/i.test(v)) fail('canon-pin', `${eyesHome}/manifest.yml pin.${key} is still "${v}" - a shipped UNSET pin is a canon token pointing at nothing`)
218
+ if (!v) fail('canon-pin', `${eyesHome}/manifest.yml pin.${key} is missing (the canon cannot resolve without it)`, `${eyesHome}/manifest.yml`)
219
+ else if (/\bUNSET\b|edit-me/i.test(v)) fail('canon-pin', `${eyesHome}/manifest.yml pin.${key} is still "${v}" - a shipped UNSET pin is a canon token pointing at nothing`, `${eyesHome}/manifest.yml`)
197
220
  }
198
221
  }
199
222
  if (!existsSync(ledgerFile)) return
@@ -201,24 +224,24 @@ export default async function doctor(dir, opts = {}) {
201
224
  try {
202
225
  rows = JSON.parse(readFileSync(ledgerFile, 'utf8'))
203
226
  } catch (e) {
204
- fail('dangling-canon', `${eyesHome}/ledger.json does not parse (LEDGER_CORRUPT): the gate would refuse it loudly - the doctor refuses first`)
227
+ fail('dangling-canon', `${eyesHome}/ledger.json does not parse (LEDGER_CORRUPT): the gate would refuse it loudly - the doctor refuses first`, `${eyesHome}/ledger.json`)
205
228
  return
206
229
  }
207
230
  if (!Array.isArray(rows)) {
208
- fail('dangling-canon', `${eyesHome}/ledger.json is not an array of rows (LEDGER_CORRUPT)`)
231
+ fail('dangling-canon', `${eyesHome}/ledger.json is not an array of rows (LEDGER_CORRUPT)`, `${eyesHome}/ledger.json`)
209
232
  return
210
233
  }
211
234
  const refs = []
212
235
  for (const row of rows) {
213
- if (!row || typeof row !== 'object') { fail('dangling-canon', `${eyesHome}/ledger.json carries a row that is not an object`); continue }
236
+ if (!row || typeof row !== 'object') { fail('dangling-canon', `${eyesHome}/ledger.json carries a row that is not an object`, `${eyesHome}/ledger.json`); continue }
214
237
  if (typeof row.artifact === 'string') refs.push({ id: row.id, p: row.artifact })
215
238
  if (Array.isArray(row.artifacts)) for (const a of row.artifacts) if (typeof a === 'string') refs.push({ id: row.id, p: a })
216
239
  }
217
240
  for (const { id, p } of refs) {
218
241
  if (typeof p !== 'string' || p.startsWith('/') || p.split(/[\\/]/).includes('..')) {
219
- fail('dangling-canon', `${eyesHome}/ledger.json row ${id || '?'} path "${p}" escapes the eyes home (UNSAFE_PATH)`)
242
+ fail('dangling-canon', `${eyesHome}/ledger.json row ${id || '?'} path "${p}" escapes the eyes home (UNSAFE_PATH)`, id || null)
220
243
  } else if (!existsSync(join(dir, eyesHome, p))) {
221
- fail('dangling-canon', `${eyesHome}/ledger.json row ${id || '?'} points at "${p}" and no such committed artifact exists (DANGLING_ROW: the row references a file that no longer exists)`)
244
+ fail('dangling-canon', `${eyesHome}/ledger.json row ${id || '?'} points at "${p}" and no such committed artifact exists (DANGLING_ROW: the row references a file that no longer exists)`, id || null)
222
245
  }
223
246
  }
224
247
  }
@@ -0,0 +1,143 @@
1
+ // src/fs-adapter.mjs - the storage seam for the stamp engine.
2
+ //
3
+ // The stamp engine touches the filesystem through one narrow surface: does a
4
+ // path exist, read/write a file, make a directory, list a directory, remove a
5
+ // path, copy a file, stat a path. Under Node those are `node:fs`; under a
6
+ // Cloudflare Worker (workerd) there is no `node:fs` at all, which is why the
7
+ // coreforge rig vendored a fork that swapped the boundary for an in-memory map.
8
+ // This module is that swap, made upstream.
9
+ //
10
+ // This file imports NOTHING from `node:fs` on purpose: the engine modules
11
+ // (stamp.mjs, templates.mjs) and this adapter must be bundleable for workerd.
12
+ // The Node default lives in `fs-node.mjs`, which installs itself through
13
+ // `setDefaultFs` — so the engine's default is real disk under Node and unset
14
+ // under a worker (where the caller passes `memoryFs()` explicitly).
15
+ //
16
+ // The adapter contract (a structural subset of `node:fs`, so the Node default
17
+ // is the real module, not a wrapper):
18
+ //
19
+ // existsSync(path) -> boolean
20
+ // readFileSync(path, enc?) -> string | Uint8Array
21
+ // writeFileSync(path, data, enc?)
22
+ // mkdirSync(path, { recursive })
23
+ // readdirSync(path, { withFileTypes }) -> [{ name, isDirectory(), isFile() }]
24
+ // rmSync(path, { recursive, force })
25
+ // copyFileSync(src, dest)
26
+ // statSync(path) -> { isDirectory(), isFile() }
27
+ //
28
+ // Paths are POSIX strings; the memory adapter normalizes separators so a caller
29
+ // never branches on which adapter is in play.
30
+
31
+ // The methods the engine is allowed to call. Kept as data so a consumer (or a
32
+ // test) can assert an adapter is complete rather than discover a hole mid-stamp.
33
+ export const FS_ADAPTER_METHODS = [
34
+ 'existsSync', 'readFileSync', 'writeFileSync', 'mkdirSync',
35
+ 'readdirSync', 'rmSync', 'copyFileSync', 'statSync',
36
+ ]
37
+
38
+ // The process-wide default, installed by the Node entry (fs-node.mjs). Null
39
+ // under a worker, which is the signal to the engine that an adapter is owed.
40
+ let defaultFs = null
41
+ export function setDefaultFs(adapter) { defaultFs = adapter }
42
+ export function getDefaultFs() { return defaultFs }
43
+
44
+ const normalize = (p) => {
45
+ const s = String(p).replace(/\\/g, '/').replace(/\/+/g, '/')
46
+ if (s.length > 1 && s.endsWith('/')) return s.slice(0, -1)
47
+ return s === '' ? '/' : s
48
+ }
49
+
50
+ const parentOf = (p) => {
51
+ const i = p.lastIndexOf('/')
52
+ return i <= 0 ? '/' : p.slice(0, i)
53
+ }
54
+
55
+ /**
56
+ * An in-memory adapter with the same contract as `node:fs`. `initial` seeds the
57
+ * tree: `{ '/path/file.txt': 'contents' }` — every parent directory is created
58
+ * implicitly. Values may be strings (UTF-8) or Uint8Array (binary).
59
+ *
60
+ * Workers use this because `node:fs` does not exist under workerd; tests use it
61
+ * to prove a whole stamp runs with no disk at all.
62
+ */
63
+ export function memoryFs(initial = {}) {
64
+ const nodes = new Map() // path -> { dir: true } | { dir: false, data }
65
+
66
+ const put = (rawPath, data) => nodes.set(normalize(rawPath), { dir: false, data })
67
+ const ensureDir = (rawPath) => {
68
+ const p = normalize(rawPath)
69
+ if (p === '/' || nodes.has(p)) return
70
+ ensureDir(parentOf(p))
71
+ nodes.set(p, { dir: true })
72
+ }
73
+
74
+ for (const [path, data] of Object.entries(initial)) {
75
+ ensureDir(parentOf(normalize(path)))
76
+ put(path, typeof data === 'string' ? new TextEncoder().encode(data) : data)
77
+ }
78
+
79
+ const readFileSync = (path, enc) => {
80
+ const node = nodes.get(normalize(path))
81
+ if (!node || node.dir) throw Object.assign(new Error(`ENOENT: no such file, '${path}'`), { code: 'ENOENT' })
82
+ if (enc === 'utf8' || enc === 'utf-8') return new TextDecoder().decode(node.data)
83
+ return node.data
84
+ }
85
+
86
+ return {
87
+ memory: true,
88
+ existsSync: (path) => nodes.has(normalize(path)),
89
+ readFileSync,
90
+ writeFileSync: (path, data, enc) => {
91
+ ensureDir(parentOf(normalize(path)))
92
+ const bytes = typeof data === 'string'
93
+ ? new TextEncoder().encode(data)
94
+ : data instanceof Uint8Array ? data : new TextEncoder().encode(String(data))
95
+ void enc
96
+ put(path, bytes)
97
+ },
98
+ mkdirSync: (path) => { ensureDir(path) },
99
+ readdirSync: (path, opts = {}) => {
100
+ const base = normalize(path)
101
+ const prefix = base === '/' ? '/' : base + '/'
102
+ const seen = new Map()
103
+ for (const key of nodes.keys()) {
104
+ if (key === base || !key.startsWith(prefix)) continue
105
+ const rest = key.slice(prefix.length)
106
+ const name = rest.split('/')[0]
107
+ if (!name) continue
108
+ const isDir = rest.includes('/') || nodes.get(key)?.dir === true
109
+ if (!seen.has(name)) seen.set(name, isDir)
110
+ }
111
+ const entries = [...seen.entries()].map(([name, isDir]) => ({
112
+ name,
113
+ isDirectory: () => isDir,
114
+ isFile: () => !isDir,
115
+ }))
116
+ if (opts.withFileTypes) return entries
117
+ return entries.map((e) => e.name)
118
+ },
119
+ rmSync: (path, opts = {}) => {
120
+ const target = normalize(path)
121
+ if (!nodes.has(target)) {
122
+ if (opts.force) return
123
+ throw Object.assign(new Error(`ENOENT: no such file or directory, '${path}'`), { code: 'ENOENT' })
124
+ }
125
+ if (!opts.recursive) { nodes.delete(target); return }
126
+ const prefix = target + '/'
127
+ for (const key of [...nodes.keys()]) {
128
+ if (key === target || key.startsWith(prefix)) nodes.delete(key)
129
+ }
130
+ },
131
+ copyFileSync: (src, dest) => {
132
+ const node = nodes.get(normalize(src))
133
+ if (!node || node.dir) throw Object.assign(new Error(`ENOENT: no such file, '${src}'`), { code: 'ENOENT' })
134
+ ensureDir(parentOf(normalize(dest)))
135
+ put(dest, node.data)
136
+ },
137
+ statSync: (path) => {
138
+ const node = nodes.get(normalize(path))
139
+ if (!node) throw Object.assign(new Error(`ENOENT: no such file, '${path}'`), { code: 'ENOENT' })
140
+ return { isDirectory: () => node.dir === true, isFile: () => node.dir !== true }
141
+ },
142
+ }
143
+ }
@@ -0,0 +1,15 @@
1
+ // src/fs-node.mjs - the Node default storage adapter.
2
+ //
3
+ // Split from fs-adapter.mjs so the engine core (stamp.mjs, templates.mjs,
4
+ // fs-adapter.mjs) carries NO static `node:fs` import and stays bundleable for
5
+ // workerd. Importing this module installs real `node:fs` as the default
6
+ // adapter. The three engine entrypoints (index.mjs, stamp.mjs, templates.mjs)
7
+ // import it, so under Node the default is unchanged; a bundler targeting a
8
+ // worker simply never pulls it in.
9
+ import * as nodeFs from 'node:fs'
10
+ import { setDefaultFs } from './fs-adapter.mjs'
11
+
12
+ setDefaultFs(nodeFs)
13
+
14
+ export const nodeFsAdapter = nodeFs
15
+ export default nodeFs
@@ -0,0 +1,118 @@
1
+ // src/harness.mjs - the headless stamp harness (monoforge#23).
2
+ //
3
+ // The verbs already work as a human CLI; this is the same machinery as an
4
+ // in-process, structured surface so railyard's door can drive the stamp loop
5
+ // (`new -> doctor -> lock`) without a shell and read a typed result instead of
6
+ // prose. No sockets, no subprocess: the family's in-process law.
7
+ //
8
+ // The shape railyard's `railyard_stamp` consumes:
9
+ //
10
+ // { verb, ok, verdicts: [{ gate, ok, counts }], refusals: [{ code, slot, detail }], grant, receipt }
11
+ //
12
+ // Every refusal code is REGISTERED in spec/refusals.json (the G10 model); the
13
+ // harness refuses to emit a code it has not registered, so a consumer can log
14
+ // and route refusals portably.
15
+ //
16
+ // A grant `{ kind, scope }` is optional and opaque: the forge never sees the
17
+ // credential, it echoes the grant back so railyard's audit ledger can record
18
+ // the spend (G5 + G14). The harness never reads a secret.
19
+ import { getDefaultFs } from './fs-adapter.mjs'
20
+ import { refusal } from './refusals.mjs'
21
+ import stamp from './stamp.mjs'
22
+ import doctor from './doctor.mjs'
23
+ import lock from './lock.mjs'
24
+
25
+ const VERBS = new Set(['new', 'doctor', 'lock', 'stamp'])
26
+
27
+ // Normalize the doctor's findings into typed refusals. A warn is not a refusal.
28
+ function refusalsFromDoctor(r) {
29
+ return r.findings
30
+ .filter((f) => f.level === 'fail')
31
+ .map((f) => refusal(f.code, f.slot ?? null, f.message))
32
+ }
33
+
34
+ function grantEcho(grant) {
35
+ if (grant == null) return null
36
+ const bad = typeof grant !== 'object' || typeof grant.kind !== 'string' || !grant.kind
37
+ || typeof grant.scope !== 'string' || !grant.scope
38
+ if (bad) return { invalid: refusal('E_GRANT_INVALID', 'grant', 'grant must be { kind: string, scope: string }') }
39
+ // Echo kind + scope only: a grant row for the ledger, never the credential.
40
+ return { kind: grant.kind, scope: grant.scope, spent: true }
41
+ }
42
+
43
+ /**
44
+ * Drive one verb in-process and return a structured receipt.
45
+ *
46
+ * @param {string} verb one of new | doctor | lock | stamp
47
+ * @param {string} dir the target tree
48
+ * @param {object} opts { fs, root, grant, out }
49
+ */
50
+ export async function run(verb, dir, opts = {}) {
51
+ if (!VERBS.has(verb)) {
52
+ return {
53
+ verb, ok: false, dir,
54
+ verdicts: [],
55
+ refusals: [refusal('E_VERB_UNKNOWN', 'verb', `unknown verb "${verb}" (known: ${[...VERBS].join(', ')})`)],
56
+ grant: null, receipt: null,
57
+ }
58
+ }
59
+
60
+ const grant = grantEcho(opts.grant)
61
+ const base = { verb, dir, grant: grant?.invalid ? null : grant, receipt: null }
62
+
63
+ // A malformed grant is refused before any write: the ledger row is the point,
64
+ // and an unreadable grant is not a row.
65
+ if (grant?.invalid) return { ...base, ok: false, verdicts: [], refusals: [grant.invalid] }
66
+
67
+ if (verb === 'doctor') {
68
+ const r = await doctor(dir, opts)
69
+ const refusals = refusalsFromDoctor(r)
70
+ return {
71
+ ...base, ok: r.ok,
72
+ verdicts: [{ gate: 'monoforge doctor', ok: r.ok, counts: r.counts }],
73
+ refusals,
74
+ receipt: { gate: 'monoforge doctor', counts: r.counts, findings: r.findings },
75
+ }
76
+ }
77
+
78
+ if (verb === 'new' || verb === 'stamp') {
79
+ const r = await stamp(dir, opts)
80
+ if (!r.ok) return { ...base, ok: false, verdicts: [], refusals: [refusal(r.code, r.slot ?? null, r.error)] }
81
+ return {
82
+ ...base, ok: true,
83
+ verdicts: [{ gate: 'monoforge new', ok: true, counts: { fail: 0, warn: 0 } }],
84
+ refusals: [],
85
+ receipt: { gate: 'monoforge new', name: r.cfg.name, files: r.manifest, skipped: r.skipped, restamp: r.restamp },
86
+ }
87
+ }
88
+
89
+ // lock = doctor (typed) then archive. A doctor fail refuses before the write.
90
+ const d = await doctor(dir, opts)
91
+ const drefusals = refusalsFromDoctor(d)
92
+ if (!d.ok) {
93
+ return {
94
+ ...base, ok: false,
95
+ verdicts: [{ gate: 'monoforge doctor', ok: false, counts: d.counts }],
96
+ refusals: drefusals,
97
+ receipt: { gate: 'monoforge doctor', counts: d.counts, findings: d.findings },
98
+ }
99
+ }
100
+ const r = await lock(dir, opts)
101
+ if (!r.ok) {
102
+ return {
103
+ ...base, ok: false,
104
+ verdicts: [{ gate: 'monoforge doctor', ok: true, counts: d.counts }],
105
+ refusals: [refusal(r.code, r.slot ?? null, r.error)],
106
+ receipt: { gate: 'monoforge lock', counts: d.counts, archive: null, sha: null },
107
+ }
108
+ }
109
+ return {
110
+ ...base, ok: true,
111
+ verdicts: [{ gate: 'monoforge doctor', ok: true, counts: d.counts }, { gate: 'monoforge lock', ok: true, counts: { fail: 0, warn: d.counts.warn } }],
112
+ refusals: [],
113
+ receipt: { gate: 'monoforge lock', name: r.archive.replace(/-lock\.tar\.gz$/, ''), archive: r.archive, sha: r.sha, counts: d.counts },
114
+ }
115
+ }
116
+
117
+ export default run
118
+ export { VERBS }
package/src/index.mjs CHANGED
@@ -1,4 +1,19 @@
1
- // src/index.mjs - programmatic surface: the three verbs of the factory.
1
+ // src/index.mjs - programmatic surface: the three verbs of the factory, plus
2
+ // the storage adapters a workers consumer imports instead of vendoring the
3
+ // engine (monoforge#27). Importing this module installs `node:fs` as the
4
+ // default adapter under Node; under a worker the caller passes `memoryFs()`
5
+ // to `stamp` explicitly and never reaches the Node default.
6
+ // Node entry: installing the default adapter here (a static side-effect import)
7
+ // keeps `node:fs` out of the engine core, so `src/workers.mjs` bundles for
8
+ // workerd with no compat flag. A worker imports `src/workers.mjs`, never this.
9
+ import './fs-node.mjs'
10
+
2
11
  export { default as stamp } from './stamp.mjs'
3
12
  export { default as doctor } from './doctor.mjs'
4
13
  export { default as lock } from './lock.mjs'
14
+ export { default as harness, run as runHarness } from './harness.mjs'
15
+ export { loadRefusals, registeredCodes, refusal } from './refusals.mjs'
16
+ export { memoryFs, FS_ADAPTER_METHODS, setDefaultFs, getDefaultFs } from './fs-adapter.mjs'
17
+ export { nodeFsAdapter } from './fs-node.mjs'
18
+ export { sha256 } from './sha256.mjs'
19
+ export { resolveTemplate, resolveChain, TEMPLATES } from './templates.mjs'
package/src/lock.mjs CHANGED
@@ -9,7 +9,7 @@ import doctor from './doctor.mjs'
9
9
  export default async function lock(dir, opts = {}) {
10
10
  const r = await doctor(dir, opts)
11
11
  if (r.counts.fail > 0) {
12
- return { ok: false, error: `lock refused: ${r.counts.fail} doctor fail(s) - fix first, locks do not ship broken`, doctor: r }
12
+ return { ok: false, code: 'E_LOCK_REFUSED', slot: null, error: `lock refused: ${r.counts.fail} doctor fail(s) - fix first, locks do not ship broken`, doctor: r }
13
13
  }
14
14
  let pkg
15
15
  try { pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) } catch { pkg = {} }