monoforge 0.0.0-stage → 0.9.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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/bin/forge.mjs +65 -0
  4. package/package.json +49 -4
  5. package/src/cut.mjs +244 -0
  6. package/src/doctor.mjs +230 -0
  7. package/src/index.mjs +4 -0
  8. package/src/lint-packs.mjs +77 -0
  9. package/src/lock.mjs +37 -0
  10. package/src/stamp.mjs +201 -0
  11. package/src/templates.mjs +133 -0
  12. package/templates/monoforge/AGENTS.md +30 -0
  13. package/templates/monoforge/CHANGELOG.md +19 -0
  14. package/templates/monoforge/DEPLOY.md +53 -0
  15. package/templates/monoforge/LICENSE +21 -0
  16. package/templates/monoforge/README.md +16 -0
  17. package/templates/monoforge/TEMPLATE.md +19 -0
  18. package/templates/monoforge/docs/Gemfile +5 -0
  19. package/templates/monoforge/docs/_config.yml +36 -0
  20. package/templates/monoforge/docs/_layouts/default.html +29 -0
  21. package/templates/monoforge/docs/assets/css/style.css +14 -0
  22. package/templates/monoforge/docs/freestruct.config.yml +7 -0
  23. package/templates/monoforge/docs/index.md +27 -0
  24. package/templates/monoforge/docs/search.md +28 -0
  25. package/templates/monoforge/functions/api/health.js +10 -0
  26. package/templates/monoforge/gitignore.tmpl +9 -0
  27. package/templates/monoforge/horcrux/HORCRUX.md +7 -0
  28. package/templates/monoforge/labs/.eyes/ledger.json +1 -0
  29. package/templates/monoforge/labs/.eyes/manifest.yml +5 -0
  30. package/templates/monoforge/labs/TASKS.md +11 -0
  31. package/templates/monoforge/scripts/build-docs.sh +12 -0
  32. package/templates/monoforge/scripts/check-docs-frontmatter.cjs +112 -0
  33. package/templates/monoforge/scripts/check-docs-links.cjs +81 -0
  34. package/templates/monoforge/scripts/check-docs-style.cjs +79 -0
  35. package/templates/monoforge/scripts/check-fiction-signatures.cjs +69 -0
  36. package/templates/monoforge/scripts/check-jekyll-filters.cjs +62 -0
  37. package/templates/monoforge/scripts/check-language.cjs +171 -0
  38. package/templates/monoforge/site/robots.txt +4 -0
  39. package/templates/monoforge/wrangler.toml +11 -0
  40. package/templates/monoforge-headless/.github/workflows/docs.yml +102 -0
  41. package/templates/monoforge-headless/.github/workflows/publish.yml +141 -0
  42. package/templates/monoforge-headless/.github/workflows/staging-ff-sync.yml +44 -0
  43. package/templates/monoforge-headless/.github/workflows/test.yml +21 -0
  44. package/templates/monoforge-headless/TEMPLATE.md +17 -0
package/src/doctor.mjs ADDED
@@ -0,0 +1,230 @@
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
+ // Untracked scratch trees used to land in the battery through the walk
13
+ // (prestruct's beta false-positive class): a .gitignore at the root is the
14
+ // cheap truth about what is scratch, and scratch is by definition not
15
+ // shipped, so it never self-flags truth slots. Prefix/name matching covers
16
+ // the common classes (ignored dirs, trailing-slash dirs, *.log globs,
17
+ // top-level names); full glob semantics stay out of scope on purpose.
18
+ function gitignorePatterns(dir) {
19
+ try {
20
+ return readFileSync(join(dir, '.gitignore'), 'utf8').split('\n')
21
+ .map((l) => l.trim()).filter((l) => l && !l.startsWith('#') && !l.startsWith('!'))
22
+ .map((l) => l.replace(/\\/g, '/').replace(/\*+$/, '').replace(/\/+$/, ''))
23
+ .filter(Boolean)
24
+ }
25
+ catch { return [] }
26
+ }
27
+
28
+ function walkFiles(dir, skip = new Set(['.git', 'node_modules', 'docs/_site'])) {
29
+ const ignored = gitignorePatterns(dir)
30
+ const ignoreHit = (relp, name) =>
31
+ ignored.some((g) => relp === g || relp.startsWith(g + '/') || name === g || (g.includes('/') && name === g.split('/').pop()))
32
+ const out = []
33
+ const rec = (d, rel = '') => {
34
+ for (const f of readdirSync(d, { withFileTypes: true })) {
35
+ if (skip.has(f.name)) continue
36
+ const relp = rel ? rel + '/' + f.name : f.name
37
+ if (ignoreHit(relp, f.name)) continue
38
+ const p = join(d, f.name)
39
+ if (f.isDirectory()) rec(p, relp)
40
+ else out.push(p)
41
+ }
42
+ }
43
+ rec(dir)
44
+ return out
45
+ }
46
+
47
+ function gitClean(dir) {
48
+ try {
49
+ const out = execFileSync('git', ['status', '--porcelain'], { cwd: dir, encoding: 'utf8' })
50
+ return { dirty: out.trim().length > 0, detail: out.trim() }
51
+ } catch {
52
+ return { dirty: false, detail: '(not a git repo: skipped)' }
53
+ }
54
+ }
55
+
56
+ export default async function doctor(dir, opts = {}) {
57
+ const findings = []
58
+ const fail = (id, message) => findings.push({ level: 'fail', id, message })
59
+ const warn = (id, message) => findings.push({ level: 'warn', id, message })
60
+
61
+ // 1. git state (warn: dirty tree ships? no. but a lock needs clean)
62
+ const g = gitClean(dir)
63
+ if (g.dirty) warn('git-dirty', `uncommitted changes:\n${g.detail}`)
64
+
65
+ // 2. unfilled truth slots. Scoped by the stamp manifest when one
66
+ // exists (monoforge-scanned trees that merely document the FORGE-TODO
67
+ // convention never self-flag; prose ABOUT the law is not a slot).
68
+ const files = walkFiles(dir)
69
+ const manifestPath = join(dir, '.monoforge-stamp.json')
70
+ if (existsSync(manifestPath)) {
71
+ let manifest
72
+ try { manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
73
+ fail('stamp-manifest', `.monoforge-stamp.json is unparseable: ${e.message}`)
74
+ manifest = { files: [] }
75
+ }
76
+ for (const rel of manifest.files || []) {
77
+ const p = join(dir, rel)
78
+ if (!existsSync(p)) continue
79
+ if (!/\.(md|json|yml|toml|sh|html|txt)$/.test(p)) continue
80
+ let s
81
+ try { s = readFileSync(p, 'utf8') } catch { continue }
82
+ 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`)
84
+ // stamp-token pass (eyestruct dogfood, 2026-10-24): raw __X__ tokens
85
+ // are the truth-slot class wearing a different uniform; the same law
86
+ // applies (a shipped placeholder is a shipped lie).
87
+ 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`)
89
+ }
90
+ }
91
+
92
+ // 3. package.json sanity (when present)
93
+ const pkgPath = join(dir, 'package.json')
94
+ if (existsSync(pkgPath)) {
95
+ let pkg
96
+ try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) } catch (e) { fail('package-json', `unparseable: ${e.message}`); pkg = null }
97
+ if (pkg) {
98
+ if (pkg?.bin) {
99
+ 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)`)
101
+ }
102
+ }
103
+ if (pkg?.exports) {
104
+ for (const v of Object.values(pkg.exports)) {
105
+ 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)
107
+ }
108
+ }
109
+ for (const f of pkg.files || []) {
110
+ if (f.startsWith('!')) continue // negation: npm's exclude mechanism inside the whitelist, never a must-exist path (prestruct beta class #2)
111
+ const p3 = join(dir, f)
112
+ if (!existsSync(p3) && !f.includes('*')) fail('files-path', `files entry ${f} does not exist in the tree`)
113
+ }
114
+ if (!pkg.description || pkg.description.length < 10) warn('description', 'package.json description missing or too thin')
115
+ if ((pkg.engines?.node || '') < '>=20') warn('engines', 'engines.node floor not >=20 (house runtime floor)')
116
+ // 4. publish.yml refuses 0.x AND carries no publish token
117
+ const pub = join(dir, '.github', 'workflows', 'publish.yml')
118
+ if (existsSync(pub)) {
119
+ const w = readFileSync(pub, 'utf8')
120
+ // Two accepted shapes: the `startsWith(github.ref_name,'v0.')` job
121
+ // 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)')
123
+ // The family law (rule #3: the NPM_TOKEN bug was caught twice - in the
124
+ // live workflow and in the template - so it becomes a gate). A real
125
+ // `secrets.NPM_TOKEN` reference is a violation; a comment that merely
126
+ // names the removed line is not. Strip comment lines, then scan.
127
+ const codeLines = w.split('\n').filter((l) => !/^\s*#/.test(l)).join('\n')
128
+ 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')
130
+ }
131
+ }
132
+ // 5. npm test
133
+ if (pkg.scripts?.test) {
134
+ try {
135
+ execFileSync('npm', ['test', '--silent'], { cwd: dir, stdio: 'pipe' })
136
+ } catch {
137
+ fail('npm-test', 'npm test failed: the negative test is the product, not an optional extra')
138
+ }
139
+ } else warn('npm-test', 'no test script: nothing self-audits')
140
+ }
141
+ }
142
+
143
+ // 6. docs gates + dash law over md prose
144
+ const dirs = existsSync(join(dir, 'docs')) ? ['docs'] : []
145
+ for (const d of dirs) {
146
+ const gates = ['check-docs-frontmatter.cjs', 'check-docs-links.cjs', 'check-docs-style.cjs', 'check-language.cjs']
147
+ for (const g2 of gates) {
148
+ const gp = join(dir, 'scripts', g2)
149
+ if (!existsSync(gp)) { warn('docs-gate', `missing gate script scripts/${g2} (stamped repos always carry them)`); continue }
150
+ 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]}`) }
152
+ }
153
+ }
154
+ for (const p of files) {
155
+ if (!p.endsWith('.md')) continue
156
+ let s
157
+ try { s = readFileSync(p, 'utf8') } catch { continue }
158
+ if (/[\u2014\u2013]/.test(s)) {
159
+ 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)`)
161
+ }
162
+ }
163
+
164
+ // 7. the .eyes canon, when the tree docks it (monoforge#12 rider, the
165
+ // eyestruct DANGLING_ROW refusal scored as a doctor check; the canon is
166
+ // a second truth surface, so its rows must resolve exactly like bin /
167
+ // exports / files paths do above). A canon-free tree stays silent -
168
+ // the canon is opt-in; auditing nothing is never dressed up as a pass.
169
+ const canonCheck = (eyesHome) => {
170
+ const ledgerFile = join(dir, eyesHome, 'ledger.json')
171
+ const manifestFile = join(dir, eyesHome, 'manifest.yml')
172
+ if (existsSync(manifestFile)) {
173
+ let s
174
+ try { s = readFileSync(manifestFile, 'utf8') } catch {
175
+ fail('canon-pin', `${eyesHome}/manifest.yml is not readable`)
176
+ return
177
+ }
178
+ // The pin block parses in the family subset, and every seeded pin
179
+ // must have been replaced by a real reference: 'UNSET' markers are
180
+ // the unfilled truth-slot class wearing the canon's uniform.
181
+ const pin = {}
182
+ const m = s.match(/^pin:\s*\n((?:\s{2}.+\n?)+)?/m)
183
+ if (m && m[1]) {
184
+ for (const line of m[1].split('\n')) {
185
+ if (!line.trim()) continue
186
+ 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 }
188
+ pin[kv[1]] = kv[2].trim()
189
+ }
190
+ } else {
191
+ fail('canon-pin', `${eyesHome}/manifest.yml carries no pin block (the canon token the captures resolve)`)
192
+ }
193
+ for (const key of ['browser-image', 'renderer']) {
194
+ 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`)
197
+ }
198
+ }
199
+ if (!existsSync(ledgerFile)) return
200
+ let rows
201
+ try {
202
+ rows = JSON.parse(readFileSync(ledgerFile, 'utf8'))
203
+ } catch (e) {
204
+ fail('dangling-canon', `${eyesHome}/ledger.json does not parse (LEDGER_CORRUPT): the gate would refuse it loudly - the doctor refuses first`)
205
+ return
206
+ }
207
+ if (!Array.isArray(rows)) {
208
+ fail('dangling-canon', `${eyesHome}/ledger.json is not an array of rows (LEDGER_CORRUPT)`)
209
+ return
210
+ }
211
+ const refs = []
212
+ 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 }
214
+ if (typeof row.artifact === 'string') refs.push({ id: row.id, p: row.artifact })
215
+ if (Array.isArray(row.artifacts)) for (const a of row.artifacts) if (typeof a === 'string') refs.push({ id: row.id, p: a })
216
+ }
217
+ for (const { id, p } of refs) {
218
+ 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)`)
220
+ } 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)`)
222
+ }
223
+ }
224
+ }
225
+ canonCheck('labs/.eyes')
226
+ canonCheck('labs/.eyes-receipt')
227
+
228
+ const counts = { fail: findings.filter((f) => f.level === 'fail').length, warn: findings.filter((f) => f.level === 'warn').length }
229
+ return { dir, counts, findings, ok: counts.fail === 0 }
230
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ // src/index.mjs - programmatic surface: the three verbs of the factory.
2
+ export { default as stamp } from './stamp.mjs'
3
+ export { default as doctor } from './doctor.mjs'
4
+ export { default as lock } from './lock.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, 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
+ }
package/src/stamp.mjs ADDED
@@ -0,0 +1,201 @@
1
+ // src/stamp.mjs - monoforge new: stamp a fleet repo from template blocks.
2
+ // The config (factory.json) is validated HARD before anything is written:
3
+ // a half-specified repo is refused, never half-created.
4
+ //
5
+ // Coexistence (monoforge#4): a re-stamp over a tree this factory already
6
+ // stamped (it carries our receipt) overlays only the files still matching the
7
+ // factory's last emission. A template path the host has edited since - a
8
+ // crashtest.config.js, an AGENTS house-rules edit, a CI lane - is skipped by
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'
14
+ import { resolveTemplate, resolveChain, TEMPLATES } from './templates.mjs'
15
+
16
+ const ROOT = join(fileURLToPath(new URL('..', import.meta.url)))
17
+
18
+ export function readFactoryConfig(dir) {
19
+ 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` }
22
+ }
23
+ 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}` }
26
+ }
27
+ const required = ['name', 'species', 'pitch', 'description', 'siteDomain']
28
+ 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)' }
32
+ cfg.docsPath = typeof cfg.docsPath === 'string' && cfg.docsPath.trim() ? cfg.docsPath.trim() : `docs.creadev.org/${cfg.name}`
33
+ cfg.version = typeof cfg.version === 'string' && /^\d+\.\d+(\.\d+)?$/.test(cfg.version) ? cfg.version : '0.9.0'
34
+ cfg.docsHost = cfg.docsPath.split('/')[0]
35
+ return { ok: true, cfg }
36
+ }
37
+
38
+ const STAMP_TOOL = 'monoforge'
39
+
40
+ // One token convention for the whole template layer: __TOKENS__ map to the
41
+ // authored factory config. (Dogfood fix, eyestruct 2026-10-24: the first
42
+ // non-monoforge stamp left raw __NAME__/__PITCH__ tokens and mutated the
43
+ // stamp-tool attribution, because the old map spoke two conventions.)
44
+ export function tokenReplacements(cfg, stampDate) {
45
+ return [
46
+ ['__NAME__', cfg.name],
47
+ ['__SPECIES__', cfg.species],
48
+ ['__PITCH__', cfg.pitch],
49
+ ['__DESCRIPTION__', cfg.description],
50
+ ['__DESCRIPTION_LONG__', cfg.description],
51
+ ['__VERSION__', cfg.version],
52
+ ['__SITE_URL__', cfg.siteDomain],
53
+ ['__DOCS_URL__', cfg.docsPath],
54
+ ['__STAMP_DATE__', stampDate],
55
+ ['__STAMP_TOOL__', STAMP_TOOL],
56
+ ]
57
+ }
58
+
59
+ export const stampToolName = STAMP_TOOL
60
+
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
+ }
68
+
69
+ // The receipt path a stamped tree carries. Its presence is what makes a
70
+ // non-empty directory a RE-STAMP rather than a stray dir to refuse.
71
+ export const RECEIPT = '.monoforge-stamp.json'
72
+
73
+ export function readReceipt(dir) {
74
+ const p = join(dir, RECEIPT)
75
+ if (!existsSync(p)) return null
76
+ try {
77
+ const r = JSON.parse(readFileSync(p, 'utf8'))
78
+ return r && r.stampTool === STAMP_TOOL ? r : null
79
+ } catch { return null }
80
+ }
81
+
82
+ export default async function stamp(dir) {
83
+ const cfgRes = readFactoryConfig(dir)
84
+ if (!cfgRes.ok) return { ok: false, error: cfgRes.error }
85
+ const cfg = cfgRes.cfg
86
+
87
+ // A re-stamp overlays a tree this factory already stamped (it carries our
88
+ // receipt). Any OTHER non-empty directory is refused: never half-merge a
89
+ // stranger's content. The receipt's own identity is checked, so a re-stamp
90
+ // can never silently rewrite a repo that answers to a different name.
91
+ const receipt = readReceipt(dir)
92
+ const restamp = Boolean(receipt)
93
+ if (existsSync(dir)) {
94
+ const stray = readdirSync(dir).filter((f) => !['factory.json', '.git'].includes(f))
95
+ if (stray.length && !restamp) {
96
+ return { ok: false, error: `${dir} already contains ${stray.join(', ')} - run in an empty directory holding only factory.json` }
97
+ }
98
+ 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)` }
100
+ }
101
+ }
102
+ // Resolve the profile's chain (children first, parent wins on collision) and
103
+ // copy the composed file set. `factory.json.profile` selects the profile;
104
+ // it defaults to the full scaffold. An unknown profile refuses by name, the
105
+ // same law as a bad config.
106
+ const profile = typeof cfg.profile === 'string' && cfg.profile.trim() ? cfg.profile.trim() : 'monoforge'
107
+ if (!TEMPLATES[profile]) {
108
+ return { ok: false, error: `factory.json profile "${profile}" is not a known profile (known: ${Object.keys(TEMPLATES).join(', ')})` }
109
+ }
110
+ let resolved
111
+ try {
112
+ resolved = resolveTemplate(profile)
113
+ } catch (e) {
114
+ return { ok: false, error: `template resolution failed: ${e.message}` }
115
+ }
116
+ if (resolved.size === 0) return { ok: false, error: `profile "${profile}" resolved to no files - the scaffold is missing templates/${profile}/` }
117
+
118
+ mkdirSync(dir, { recursive: true })
119
+ // Coexistence: on a re-stamp, a template path whose on-disk bytes no longer
120
+ // match the receipt's recorded hash is host-authored (crashtest.config.js,
121
+ // scenario packs, an edited AGENTS/CI lane) - skip it, loudly, never bleed.
122
+ // New template paths are copied; pristine ones are refreshed in place.
123
+ const priorHashes = (restamp && receipt.hashes && typeof receipt.hashes === 'object') ? receipt.hashes : {}
124
+ const skipped = []
125
+ const copied = []
126
+ for (const [rel, src] of resolved) {
127
+ const dest = join(dir, rel)
128
+ const exists = existsSync(dest)
129
+ if (exists && restamp) {
130
+ const recorded = priorHashes[rel]
131
+ const onDisk = sha256(readFileSync(dest, 'utf8'))
132
+ if (recorded && onDisk !== recorded) { skipped.push(rel); continue }
133
+ }
134
+ mkdirSync(dirname(dest), { recursive: true })
135
+ copyFileSync(src, dest)
136
+ copied.push(rel)
137
+ }
138
+
139
+ const stampDate = new Date().toISOString().slice(0, 10)
140
+ const reps = tokenReplacements(cfg, stampDate)
141
+ const touched = []
142
+ let filled = 0
143
+ // Only files this stamp actually emitted are token-filled: a skipped
144
+ // host-authored file keeps its bytes verbatim (a re-stamp never rewrites
145
+ // the host's state, not even a stray token in it).
146
+ const walk = (d) => {
147
+ for (const f of readdirSync(d, { withFileTypes: true })) {
148
+ const p = join(d, f.name)
149
+ if (f.isDirectory()) { walk(p); continue }
150
+ const rel = relative(dir, p)
151
+ if (restamp && skipped.includes(rel)) continue
152
+ if (restamp && !copied.includes(rel) && rel !== 'gitignore.tmpl') continue
153
+ let s = readFileSync(p, 'utf8')
154
+ const before = s
155
+ for (const [tok, val] of reps) s = s.replaceAll(tok, val)
156
+ if (s !== before) { writeFileSync(p, s); filled++ }
157
+ touched.push(rel)
158
+ }
159
+ }
160
+ walk(dir)
161
+ // gitignore.tmpl -> .gitignore
162
+ const gi = join(dir, 'gitignore.tmpl')
163
+ if (existsSync(gi)) {
164
+ const giRel = '.gitignore'
165
+ if (!(restamp && priorHashes[giRel] && sha256(readFileSync(join(dir, giRel), 'utf8')) !== priorHashes[giRel])) {
166
+ writeFileSync(join(dir, giRel), readFileSync(gi, 'utf8'))
167
+ } else {
168
+ skipped.push(giRel)
169
+ }
170
+ rmSync(gi)
171
+ if (!touched.includes(giRel)) touched.push(giRel)
172
+ }
173
+ // receipt: the record of what the stamp actually emitted. `files` keeps its
174
+ // long-standing meaning - exactly the token-filled files - because the doctor
175
+ // scopes its truth-slot scan to them, so prose that merely DOCUMENTS the
176
+ // FORGE-TODO convention never self-flags. `hashes` is the new sibling: the
177
+ // sha256 of every path the stamp touched, as the factory LAST emitted it,
178
+ // which a later re-stamp reads to tell a pristine template file from a
179
+ // host-authored one.
180
+ const emitted = [...new Set([...touched, ...copied, ...skipped])].filter((rel) => existsSync(join(dir, rel)))
181
+ const hashes = {}
182
+ for (const rel of emitted) {
183
+ try { hashes[rel] = sha256(readFileSync(join(dir, rel), 'utf8')) } catch {}
184
+ }
185
+ // A skipped (host-authored) template path keeps the factory's LAST recorded
186
+ // emission hash - not its own bytes - so every future re-stamp still reads
187
+ // it as host-owned and leaves it alone. Overwriting with the host's bytes
188
+ // would make it look pristine next time and get clobbered.
189
+ for (const rel of skipped) {
190
+ if (priorHashes[rel]) hashes[rel] = priorHashes[rel]
191
+ }
192
+ writeFileSync(join(dir, RECEIPT), JSON.stringify({
193
+ stampTool: STAMP_TOOL,
194
+ name: cfg.name,
195
+ version: cfg.version,
196
+ date: stampDate,
197
+ files: touched,
198
+ hashes,
199
+ }, null, 2) + '\n')
200
+ return { ok: true, dir, filled, manifest: touched.length, skipped, restamp, cfg }
201
+ }