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