monoforge 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.
Files changed (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/bin/forge.mjs +98 -0
  4. package/package.json +56 -4
  5. package/packs/README.md +62 -0
  6. package/packs/public/forge-shapes/index.mjs +161 -0
  7. package/packs/public/forge-shapes/pack.json +13 -0
  8. package/packs/public/forge-shapes/test/fixtures/bad-publish/.github/workflows/publish.yml +11 -0
  9. package/packs/public/forge-shapes/test/fixtures/bad-publish/.monoforge-stamp.json +12 -0
  10. package/packs/public/forge-shapes/test/fixtures/bad-publish/README.md +3 -0
  11. package/packs/public/forge-shapes/test/fixtures/bad-publish/bin/probe.mjs +2 -0
  12. package/packs/public/forge-shapes/test/fixtures/bad-publish/package.json +14 -0
  13. package/packs/public/forge-shapes/test/fixtures/clean/.github/workflows/publish.yml +12 -0
  14. package/packs/public/forge-shapes/test/fixtures/clean/.monoforge-stamp.json +12 -0
  15. package/packs/public/forge-shapes/test/fixtures/clean/README.md +3 -0
  16. package/packs/public/forge-shapes/test/fixtures/clean/bin/probe.mjs +2 -0
  17. package/packs/public/forge-shapes/test/fixtures/clean/package.json +14 -0
  18. package/packs/public/forge-shapes/test/fixtures/missing-file/.github/workflows/publish.yml +12 -0
  19. package/packs/public/forge-shapes/test/fixtures/missing-file/.monoforge-stamp.json +13 -0
  20. package/packs/public/forge-shapes/test/fixtures/missing-file/README.md +3 -0
  21. package/packs/public/forge-shapes/test/fixtures/missing-file/bin/probe.mjs +2 -0
  22. package/packs/public/forge-shapes/test/fixtures/missing-file/package.json +14 -0
  23. package/packs/public/forge-shapes/test/fixtures/token/.github/workflows/publish.yml +12 -0
  24. package/packs/public/forge-shapes/test/fixtures/token/.monoforge-stamp.json +12 -0
  25. package/packs/public/forge-shapes/test/fixtures/token/README.md +3 -0
  26. package/packs/public/forge-shapes/test/fixtures/token/bin/probe.mjs +2 -0
  27. package/packs/public/forge-shapes/test/fixtures/token/package.json +14 -0
  28. package/packs/public/forge-shapes/test/fixtures/unfilled/.github/workflows/publish.yml +12 -0
  29. package/packs/public/forge-shapes/test/fixtures/unfilled/.monoforge-stamp.json +12 -0
  30. package/packs/public/forge-shapes/test/fixtures/unfilled/README.md +3 -0
  31. package/packs/public/forge-shapes/test/fixtures/unfilled/bin/probe.mjs +2 -0
  32. package/packs/public/forge-shapes/test/fixtures/unfilled/package.json +14 -0
  33. package/packs/public/forge-shapes/test/run.mjs +67 -0
  34. package/spec/refusals.json +35 -0
  35. package/src/cut.mjs +244 -0
  36. package/src/doctor.mjs +253 -0
  37. package/src/fs-adapter.mjs +143 -0
  38. package/src/fs-node.mjs +15 -0
  39. package/src/harness.mjs +118 -0
  40. package/src/index.mjs +19 -0
  41. package/src/lint-packs.mjs +77 -0
  42. package/src/lock.mjs +37 -0
  43. package/src/packs.mjs +200 -0
  44. package/src/paths.mjs +48 -0
  45. package/src/refusals.mjs +45 -0
  46. package/src/sha256.mjs +61 -0
  47. package/src/stamp.mjs +215 -0
  48. package/src/templates.mjs +147 -0
  49. package/src/workers.mjs +16 -0
  50. package/templates/monoforge/AGENTS.md +30 -0
  51. package/templates/monoforge/CHANGELOG.md +19 -0
  52. package/templates/monoforge/DEPLOY.md +53 -0
  53. package/templates/monoforge/LICENSE +21 -0
  54. package/templates/monoforge/README.md +16 -0
  55. package/templates/monoforge/TEMPLATE.md +19 -0
  56. package/templates/monoforge/docs/Gemfile +5 -0
  57. package/templates/monoforge/docs/_config.yml +36 -0
  58. package/templates/monoforge/docs/_layouts/default.html +29 -0
  59. package/templates/monoforge/docs/assets/css/style.css +14 -0
  60. package/templates/monoforge/docs/freestruct.config.yml +7 -0
  61. package/templates/monoforge/docs/index.md +27 -0
  62. package/templates/monoforge/docs/search.md +28 -0
  63. package/templates/monoforge/functions/api/health.js +10 -0
  64. package/templates/monoforge/gitignore.tmpl +9 -0
  65. package/templates/monoforge/horcrux/HORCRUX.md +7 -0
  66. package/templates/monoforge/labs/.eyes/ledger.json +1 -0
  67. package/templates/monoforge/labs/.eyes/manifest.yml +5 -0
  68. package/templates/monoforge/labs/TASKS.md +11 -0
  69. package/templates/monoforge/scripts/build-docs.sh +12 -0
  70. package/templates/monoforge/scripts/check-docs-frontmatter.cjs +112 -0
  71. package/templates/monoforge/scripts/check-docs-links.cjs +81 -0
  72. package/templates/monoforge/scripts/check-docs-style.cjs +79 -0
  73. package/templates/monoforge/scripts/check-fiction-signatures.cjs +69 -0
  74. package/templates/monoforge/scripts/check-jekyll-filters.cjs +62 -0
  75. package/templates/monoforge/scripts/check-language.cjs +171 -0
  76. package/templates/monoforge/site/robots.txt +4 -0
  77. package/templates/monoforge/wrangler.toml +11 -0
  78. package/templates/monoforge-headless/.github/workflows/docs.yml +102 -0
  79. package/templates/monoforge-headless/.github/workflows/publish.yml +141 -0
  80. package/templates/monoforge-headless/.github/workflows/staging-ff-sync.yml +44 -0
  81. package/templates/monoforge-headless/.github/workflows/test.yml +21 -0
  82. package/templates/monoforge-headless/TEMPLATE.md +17 -0
package/src/doctor.mjs ADDED
@@ -0,0 +1,253 @@
1
+ // src/doctor.mjs - forge doctor: the truth battery. Every check is a
2
+ // refusal-shaped gate. Findings carry level (fail|warn) and the reason.
3
+ // The battery runs against the tree itself; factory.json (when present)
4
+ // supplies name/domain context. Generated green is never shipped: an
5
+ // unfilled FORGE-TODO slot here is the same thing a broken test is.
6
+ import { execFileSync } from 'node:child_process'
7
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
8
+ import { join, relative } from 'node:path'
9
+
10
+ const TODO_MARK = 'FORGE-TODO'
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
+
33
+ // Untracked scratch trees used to land in the battery through the walk
34
+ // (prestruct's beta false-positive class): a .gitignore at the root is the
35
+ // cheap truth about what is scratch, and scratch is by definition not
36
+ // shipped, so it never self-flags truth slots. Prefix/name matching covers
37
+ // the common classes (ignored dirs, trailing-slash dirs, *.log globs,
38
+ // top-level names); full glob semantics stay out of scope on purpose.
39
+ function gitignorePatterns(dir) {
40
+ try {
41
+ return readFileSync(join(dir, '.gitignore'), 'utf8').split('\n')
42
+ .map((l) => l.trim()).filter((l) => l && !l.startsWith('#') && !l.startsWith('!'))
43
+ .map((l) => l.replace(/\\/g, '/').replace(/\*+$/, '').replace(/\/+$/, ''))
44
+ .filter(Boolean)
45
+ }
46
+ catch { return [] }
47
+ }
48
+
49
+ function walkFiles(dir, skip = new Set(['.git', 'node_modules', 'docs/_site'])) {
50
+ const ignored = gitignorePatterns(dir)
51
+ const ignoreHit = (relp, name) =>
52
+ ignored.some((g) => relp === g || relp.startsWith(g + '/') || name === g || (g.includes('/') && name === g.split('/').pop()))
53
+ const out = []
54
+ const rec = (d, rel = '') => {
55
+ for (const f of readdirSync(d, { withFileTypes: true })) {
56
+ if (skip.has(f.name)) continue
57
+ const relp = rel ? rel + '/' + f.name : f.name
58
+ if (ignoreHit(relp, f.name)) continue
59
+ const p = join(d, f.name)
60
+ if (f.isDirectory()) rec(p, relp)
61
+ else out.push(p)
62
+ }
63
+ }
64
+ rec(dir)
65
+ return out
66
+ }
67
+
68
+ function gitClean(dir) {
69
+ try {
70
+ const out = execFileSync('git', ['status', '--porcelain'], { cwd: dir, encoding: 'utf8' })
71
+ return { dirty: out.trim().length > 0, detail: out.trim() }
72
+ } catch {
73
+ return { dirty: false, detail: '(not a git repo: skipped)' }
74
+ }
75
+ }
76
+
77
+ export default async function doctor(dir, opts = {}) {
78
+ const findings = []
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 })
82
+ const warn = (id, message) => findings.push({ level: 'warn', id, message })
83
+
84
+ // 1. git state (warn: dirty tree ships? no. but a lock needs clean)
85
+ const g = gitClean(dir)
86
+ if (g.dirty) warn('git-dirty', `uncommitted changes:\n${g.detail}`)
87
+
88
+ // 2. unfilled truth slots. Scoped by the stamp manifest when one
89
+ // exists (monoforge-scanned trees that merely document the FORGE-TODO
90
+ // convention never self-flag; prose ABOUT the law is not a slot).
91
+ const files = walkFiles(dir)
92
+ const manifestPath = join(dir, '.monoforge-stamp.json')
93
+ if (existsSync(manifestPath)) {
94
+ let manifest
95
+ try { manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
96
+ fail('stamp-manifest', `.monoforge-stamp.json is unparseable: ${e.message}`, '.monoforge-stamp.json')
97
+ manifest = { files: [] }
98
+ }
99
+ for (const rel of manifest.files || []) {
100
+ const p = join(dir, rel)
101
+ if (!existsSync(p)) continue
102
+ if (!/\.(md|json|yml|toml|sh|html|txt)$/.test(p)) continue
103
+ let s
104
+ try { s = readFileSync(p, 'utf8') } catch { continue }
105
+ const n = (s.match(new RegExp(TODO_MARK, 'g')) || []).length
106
+ if (n) fail('truth-slot', `${rel} still carries ${n} ${TODO_MARK} slot(s): a shipped placeholder is a shipped lie`, rel)
107
+ // stamp-token pass (eyestruct dogfood, 2026-10-24): raw __X__ tokens
108
+ // are the truth-slot class wearing a different uniform; the same law
109
+ // applies (a shipped placeholder is a shipped lie).
110
+ const raw = s.match(/__[A-Z][A-Z0-9_]*__/g) || []
111
+ if (raw.length) fail('stamp-token', `${rel} still carries raw stamp token(s): ${[...new Set(raw)].join(', ')} - the stamp never finished`, rel)
112
+ }
113
+ }
114
+
115
+ // 3. package.json sanity (when present)
116
+ const pkgPath = join(dir, 'package.json')
117
+ if (existsSync(pkgPath)) {
118
+ let pkg
119
+ try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) } catch (e) { fail('package-json', `unparseable: ${e.message}`, 'package.json'); pkg = null }
120
+ if (pkg) {
121
+ if (pkg?.bin) {
122
+ for (const b of Object.values(pkg.bin)) {
123
+ if (!existsSync(join(dir, b))) fail('bin-path', `bin entry ${b} does not exist (the crashtest#16 class, in our own clothes)`, b)
124
+ }
125
+ }
126
+ if (pkg?.exports) {
127
+ for (const v of Object.values(pkg.exports)) {
128
+ const p2 = typeof v === 'string' ? v : v?.import
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)
130
+ }
131
+ }
132
+ for (const f of pkg.files || []) {
133
+ if (f.startsWith('!')) continue // negation: npm's exclude mechanism inside the whitelist, never a must-exist path (prestruct beta class #2)
134
+ const p3 = join(dir, f)
135
+ if (!existsSync(p3) && !f.includes('*')) fail('files-path', `files entry ${f} does not exist in the tree`, f)
136
+ }
137
+ if (!pkg.description || pkg.description.length < 10) warn('description', 'package.json description missing or too thin')
138
+ if ((pkg.engines?.node || '') < '>=20') warn('engines', 'engines.node floor not >=20 (house runtime floor)')
139
+ // 4. publish.yml refuses 0.x AND carries no publish token
140
+ const pub = join(dir, '.github', 'workflows', 'publish.yml')
141
+ if (existsSync(pub)) {
142
+ const w = readFileSync(pub, 'utf8')
143
+ // Two accepted shapes: the `startsWith(github.ref_name,'v0.')` job
144
+ // guard, or the OIDC ladder's `case "$V" in 0.*)` version 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')
146
+ // The family law (rule #3: the NPM_TOKEN bug was caught twice - in the
147
+ // live workflow and in the template - so it becomes a gate). A real
148
+ // `secrets.NPM_TOKEN` reference is a violation; a comment that merely
149
+ // names the removed line is not. Strip comment lines, then scan.
150
+ const codeLines = w.split('\n').filter((l) => !/^\s*#/.test(l)).join('\n')
151
+ if (/secrets\.NPM_TOKEN|NODE_AUTH_TOKEN/.test(codeLines)) {
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')
153
+ }
154
+ }
155
+ // 5. npm test
156
+ if (pkg.scripts?.test) {
157
+ try {
158
+ execFileSync('npm', ['test', '--silent'], { cwd: dir, stdio: 'pipe' })
159
+ } catch {
160
+ fail('npm-test', 'npm test failed: the negative test is the product, not an optional extra', 'npm test')
161
+ }
162
+ } else warn('npm-test', 'no test script: nothing self-audits')
163
+ }
164
+ }
165
+
166
+ // 6. docs gates + dash law over md prose
167
+ const dirs = existsSync(join(dir, 'docs')) ? ['docs'] : []
168
+ for (const d of dirs) {
169
+ const gates = ['check-docs-frontmatter.cjs', 'check-docs-links.cjs', 'check-docs-style.cjs', 'check-language.cjs']
170
+ for (const g2 of gates) {
171
+ const gp = join(dir, 'scripts', g2)
172
+ if (!existsSync(gp)) { warn('docs-gate', `missing gate script scripts/${g2} (stamped repos always carry them)`); continue }
173
+ try { execFileSync('node', [gp, d], { cwd: dir, stdio: 'pipe' }) }
174
+ catch (e) { fail('docs-gate', `scripts/${g2} failed: ${String(e.stderr || e.message).split('\n')[0]}`, `scripts/${g2}`) }
175
+ }
176
+ }
177
+ for (const p of files) {
178
+ if (!p.endsWith('.md')) continue
179
+ let s
180
+ try { s = readFileSync(p, 'utf8') } catch { continue }
181
+ if (/[\u2014\u2013]/.test(s)) {
182
+ const line = s.split('\n').findIndex((l) => /[\u2014\u2013]/.test(l)) + 1
183
+ fail('dash-law', `${relative(dir, p)} line ${line}: em/en dash in prose (house law: none, ever)`, relative(dir, p))
184
+ }
185
+ }
186
+
187
+ // 7. the .eyes canon, when the tree docks it (monoforge#12 rider, the
188
+ // eyestruct DANGLING_ROW refusal scored as a doctor check; the canon is
189
+ // a second truth surface, so its rows must resolve exactly like bin /
190
+ // exports / files paths do above). A canon-free tree stays silent -
191
+ // the canon is opt-in; auditing nothing is never dressed up as a pass.
192
+ const canonCheck = (eyesHome) => {
193
+ const ledgerFile = join(dir, eyesHome, 'ledger.json')
194
+ const manifestFile = join(dir, eyesHome, 'manifest.yml')
195
+ if (existsSync(manifestFile)) {
196
+ let s
197
+ try { s = readFileSync(manifestFile, 'utf8') } catch {
198
+ fail('canon-pin', `${eyesHome}/manifest.yml is not readable`, `${eyesHome}/manifest.yml`)
199
+ return
200
+ }
201
+ // The pin block parses in the family subset, and every seeded pin
202
+ // must have been replaced by a real reference: 'UNSET' markers are
203
+ // the unfilled truth-slot class wearing the canon's uniform.
204
+ const pin = {}
205
+ const m = s.match(/^pin:\s*\n((?:\s{2}.+\n?)+)?/m)
206
+ if (m && m[1]) {
207
+ for (const line of m[1].split('\n')) {
208
+ if (!line.trim()) continue
209
+ const kv = line.trim().match(/^([\w-]+):\s*(.+)$/)
210
+ if (!kv) { fail('canon-pin', `${eyesHome}/manifest.yml pin row is not key: value -> "${line.trim()}"`, `${eyesHome}/manifest.yml`); continue }
211
+ pin[kv[1]] = kv[2].trim()
212
+ }
213
+ } else {
214
+ fail('canon-pin', `${eyesHome}/manifest.yml carries no pin block (the canon token the captures resolve)`, `${eyesHome}/manifest.yml`)
215
+ }
216
+ for (const key of ['browser-image', 'renderer']) {
217
+ const v = pin[key] || ''
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`)
220
+ }
221
+ }
222
+ if (!existsSync(ledgerFile)) return
223
+ let rows
224
+ try {
225
+ rows = JSON.parse(readFileSync(ledgerFile, 'utf8'))
226
+ } catch (e) {
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`)
228
+ return
229
+ }
230
+ if (!Array.isArray(rows)) {
231
+ fail('dangling-canon', `${eyesHome}/ledger.json is not an array of rows (LEDGER_CORRUPT)`, `${eyesHome}/ledger.json`)
232
+ return
233
+ }
234
+ const refs = []
235
+ for (const row of rows) {
236
+ if (!row || typeof row !== 'object') { fail('dangling-canon', `${eyesHome}/ledger.json carries a row that is not an object`, `${eyesHome}/ledger.json`); continue }
237
+ if (typeof row.artifact === 'string') refs.push({ id: row.id, p: row.artifact })
238
+ if (Array.isArray(row.artifacts)) for (const a of row.artifacts) if (typeof a === 'string') refs.push({ id: row.id, p: a })
239
+ }
240
+ for (const { id, p } of refs) {
241
+ if (typeof p !== 'string' || p.startsWith('/') || p.split(/[\\/]/).includes('..')) {
242
+ fail('dangling-canon', `${eyesHome}/ledger.json row ${id || '?'} path "${p}" escapes the eyes home (UNSAFE_PATH)`, id || null)
243
+ } else if (!existsSync(join(dir, eyesHome, p))) {
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)
245
+ }
246
+ }
247
+ }
248
+ canonCheck('labs/.eyes')
249
+ canonCheck('labs/.eyes-receipt')
250
+
251
+ const counts = { fail: findings.filter((f) => f.level === 'fail').length, warn: findings.filter((f) => f.level === 'warn').length }
252
+ return { dir, counts, findings, ok: counts.fail === 0 }
253
+ }
@@ -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 ADDED
@@ -0,0 +1,19 @@
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
+
11
+ export { default as stamp } from './stamp.mjs'
12
+ export { default as doctor } from './doctor.mjs'
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'
@@ -0,0 +1,77 @@
1
+ // monoforge lint-packs - the opt-in packstruct passthrough (issue-shaped
2
+ // after crashtest's lint-packs verb, issue #32, ported from eyestruct's
3
+ // lib/lint-packs.js): when the factory's own packs land, the pack lint
4
+ // lane runs packstruct over the repo's own install - node_modules/.bin
5
+ // first, then PATH - never downloading or bundling one (zero-dependency
6
+ // law of the factory: no install step exists to run).
7
+ //
8
+ // Policy (pinned, honest-skip vs loud):
9
+ // - explicitly invoked with no packstruct installed -> exit 2 naming the
10
+ // fix (a never-working requested lane is a broken config, not a skip)
11
+ // - present but exits non-zero -> verdicts pass through verbatim; the
12
+ // exit code rides (0 clean / 1 findings / 2 packstruct's own config
13
+ // class).
14
+ // Passthrough fidelity: the exit code IS the verdict. The default dir is
15
+ // the packs ROOT (never packs/public alone - the gistory footgun that
16
+ // reads as "0 packs checked, missing packs/public/public/"); an explicit
17
+ // dir passes through UNTOUCHED.
18
+ //
19
+ // Usage: monoforge lint-packs [--deep] [--json] [--against <lib>] [dir]
20
+
21
+ 'use strict'
22
+
23
+ import { spawnSync } from 'node:child_process'
24
+ import { existsSync } from 'node:fs'
25
+ import path from 'node:path'
26
+
27
+ export const PACKSTRUCT_FIX =
28
+ 'fix: npm i -D packstruct@<exact> - install packstruct as an EXACT devDependency (same commit -> same findings applies to the linter too; this lane never downloads one)'
29
+
30
+ function packstructInstalled(cwd) {
31
+ if (existsSync(path.join(cwd, 'node_modules', '.bin', 'packstruct'))) return 'local'
32
+ const probe = spawnSync('packstruct', ['--version'], { encoding: 'utf8' })
33
+ if (probe.error && probe.error.code === 'ENOENT') return null
34
+ return 'path'
35
+ }
36
+
37
+ function spawnPackstruct(cwd, args) {
38
+ const source = packstructInstalled(cwd)
39
+ if (!source) return { error: { code: 'ENOENT' } }
40
+ if (source === 'local') {
41
+ return spawnSync(path.join(cwd, 'node_modules', '.bin', 'packstruct'), args, { encoding: 'utf8', stdio: 'inherit' })
42
+ }
43
+ return spawnSync('packstruct', args, { encoding: 'utf8', stdio: 'inherit' })
44
+ }
45
+
46
+ function flagValue(argv, flag) {
47
+ const i = argv.indexOf(flag)
48
+ return i === -1 ? undefined : argv[i + 1]
49
+ }
50
+
51
+ function posArg(argv) {
52
+ return argv.find((a) => !a.startsWith('--') && a !== flagValue(argv, '--against'))
53
+ }
54
+
55
+ // Run the lint lane, return the process exit code (0 green / 1 findings /
56
+ // 2 setup refusal). The factory keeps its zero-dep law until the packs
57
+ // land: no packstruct dep is installed here, so today's invocation is the
58
+ // loud exit 2, never a silent skip.
59
+ export function runLintPacks(opts = {}) {
60
+ const cwd = opts.cwd || process.cwd()
61
+ const argv = opts.argv || []
62
+ const args = ['lint', posArg(argv) || 'packs']
63
+ if (argv.includes('--deep')) args.push('--deep')
64
+ if (opts.json) args.push('--json')
65
+ const against = flagValue(argv, '--against')
66
+ if (against !== undefined) args.push('--against', against)
67
+ process.stdout.write(`monoforge lint-packs: running packstruct over ${args[1]} (the repo's own install - never downloaded); ${args.join(' ')}\n`)
68
+ const res = spawnPackstruct(cwd, args)
69
+ if (res.error && res.error.code === 'ENOENT') {
70
+ console.error(PACKSTRUCT_FIX)
71
+ return 2
72
+ }
73
+ // Passthrough fidelity: the exit code IS the verdict.
74
+ return res.status ?? 1
75
+ }
76
+
77
+ export default { run: runLintPacks }
package/src/lock.mjs ADDED
@@ -0,0 +1,37 @@
1
+ // src/lock.mjs - forge lock: the final pass. The doctor must be clean
2
+ // (fails refuse the lock; warns carry with a note), then the archive is
3
+ // stamped with a checksum so the lock is verifiable rather than verbal.
4
+ import { execFileSync } from 'node:child_process'
5
+ import { existsSync, readFileSync, writeFileSync, rmSync, cpSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import doctor from './doctor.mjs'
8
+
9
+ export default async function lock(dir, opts = {}) {
10
+ const r = await doctor(dir, opts)
11
+ if (r.counts.fail > 0) {
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
+ }
14
+ let pkg
15
+ try { pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) } catch { pkg = {} }
16
+ // factory.json is the config-of-record: name/version come from it when the
17
+ // authored npm layer is not yet real (rank: package.json outranks factory.json
18
+ // only where the tool itself is versioned in npm; the factory config outranks
19
+ // the dir name).
20
+ let fcfg = {}
21
+ try { fcfg = JSON.parse(readFileSync(join(dir, 'factory.json'), 'utf8')) } catch { fcfg = {} }
22
+ const name = pkg.name || fcfg.name || dir.split('/').pop()
23
+ const version = pkg.version || fcfg.version || '0.9.0'
24
+ const out = opts.out || `${name}-${version}-lock.tar.gz`
25
+ const outPath = join(dir, '..', out)
26
+
27
+ // archive via a staging tree so the tar root is the versioned folder
28
+ const stage = join(dir, '..', `${name}-lockstage`)
29
+ rmSync(stage, { recursive: true, force: true })
30
+ const archiveDir = join(stage, `${name}-${version}`)
31
+ cpSync(dir, archiveDir, { recursive: true }) // includes .git: the lock is a resumable repo
32
+ execFileSync('tar', ['czf', outPath, '-C', stage, `${name}-${version}`])
33
+ rmSync(stage, { recursive: true, force: true })
34
+
35
+ const sha = execFileSync('sha256sum', [out], { cwd: join(dir, '..'), encoding: 'utf8' }).split(' ')[0]
36
+ return { ok: true, archive: out, sha: sha.slice(0, 16), doctor: r }
37
+ }