@fabrika/builder 0.9.0-dev.13 → 0.9.0-dev.14

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 (96) hide show
  1. package/BUILD-CONTRACT.md +9 -3
  2. package/README.md +39 -9
  3. package/cli/src/bin.ts +14 -1
  4. package/cli/src/build-review.ts +66 -0
  5. package/cli/src/build-status.ts +41 -3
  6. package/cli/src/catalog.ts +34 -2
  7. package/cli/src/commands/advance.ts +48 -6
  8. package/cli/src/commands/build.ts +152 -15
  9. package/cli/src/commands/design.ts +34 -0
  10. package/cli/src/commands/flows.ts +32 -0
  11. package/cli/src/commands/induce.ts +2 -2
  12. package/cli/src/commands/init.ts +7 -1
  13. package/cli/src/commands/next.ts +9 -2
  14. package/cli/src/context.ts +2 -1
  15. package/cli/src/contrast.ts +301 -0
  16. package/cli/src/daemon-client.ts +29 -3
  17. package/cli/src/design-review.ts +261 -0
  18. package/cli/src/flows.ts +162 -0
  19. package/cli/src/frontmatter.ts +32 -0
  20. package/cli/src/index.ts +10 -1
  21. package/cli/src/induce.ts +61 -3
  22. package/cli/src/issues.ts +15 -29
  23. package/cli/src/layout.ts +5 -2
  24. package/cli/src/packet.ts +36 -3
  25. package/cli/src/phase-state.ts +19 -1
  26. package/cli/src/verify.ts +50 -0
  27. package/daemon/src/handlers.ts +32 -6
  28. package/daemon/src/phases.ts +7 -109
  29. package/daemon/src/platform-source.ts +8 -0
  30. package/decisions/README.md +2 -2
  31. package/decisions/patterns/cf-contract-app.md +57 -0
  32. package/decisions/technologies/bun.md +2 -1
  33. package/decisions/technologies/cf-fabrika-contract.md +45 -0
  34. package/decisions/technologies/cloudflare.md +3 -1
  35. package/decisions/technologies/oblaka.md +1 -1
  36. package/decisions/technologies/opice.md +1 -1
  37. package/decisions/technologies/react.md +1 -1
  38. package/decisions/technologies/tailwind.md +5 -5
  39. package/decisions/technologies/zerops-fabrika-auth.md +1 -1
  40. package/decisions/technologies/zerops-platform.md +1 -1
  41. package/package.json +11 -8
  42. package/shared/approvals.ts +65 -0
  43. package/shared/derive.ts +189 -0
  44. package/shared/gate.ts +20 -0
  45. package/shared/index.ts +6 -1
  46. package/shared/phases.ts +22 -20
  47. package/skill/SKILL.md +25 -16
  48. package/skill/agents/build-orchestrator.md +28 -8
  49. package/skill/agents/flows-author.md +27 -13
  50. package/skill/agents/implementer.md +3 -1
  51. package/skill/agents/opice-skeleton-author.md +8 -7
  52. package/skill/gates/brief.jsx +26 -5
  53. package/skill/gates/review-grid.jsx +3 -8
  54. package/skill/gates/tech.jsx +3 -3
  55. package/stacks/README.md +8 -2
  56. package/stacks/cf-app.md +60 -0
  57. package/stacks/cf-fat.md +1 -0
  58. package/stacks/cf-internal-app.md +2 -2
  59. package/stacks/cf-lightweight.md +3 -2
  60. package/stacks/contember-app.md +1 -0
  61. package/stacks/content-site.md +1 -0
  62. package/stacks/zerops-app.md +1 -0
  63. package/types/cli/src/bin.d.ts +1 -1
  64. package/types/cli/src/build-review.d.ts +13 -0
  65. package/types/cli/src/build-status.d.ts +16 -1
  66. package/types/cli/src/catalog.d.ts +9 -0
  67. package/types/cli/src/commands/design.d.ts +1 -0
  68. package/types/cli/src/commands/flows.d.ts +1 -0
  69. package/types/cli/src/contrast.d.ts +59 -0
  70. package/types/cli/src/daemon-client.d.ts +13 -2
  71. package/types/cli/src/design-review.d.ts +54 -0
  72. package/types/cli/src/flows.d.ts +28 -0
  73. package/types/cli/src/frontmatter.d.ts +8 -0
  74. package/types/cli/src/index.d.ts +1 -1
  75. package/types/cli/src/induce.d.ts +3 -0
  76. package/types/cli/src/issues.d.ts +4 -0
  77. package/types/cli/src/packet.d.ts +9 -1
  78. package/types/cli/src/phase-state.d.ts +1 -1
  79. package/types/cli/src/verify.d.ts +18 -0
  80. package/types/daemon/src/phases.d.ts +4 -16
  81. package/types/daemon/src/platform-remote.d.ts +6 -2
  82. package/types/shared/approvals.d.ts +32 -0
  83. package/types/shared/derive.d.ts +41 -0
  84. package/types/shared/gate.d.ts +11 -0
  85. package/types/shared/index.d.ts +105 -65
  86. package/types/shared/phases.d.ts +7 -1
  87. package/ui/dist/assets/client.css +1 -1
  88. package/ui/dist/assets/client.vn7hykcn.js +120 -0
  89. package/ui/dist/index.html +1 -1
  90. package/cli/src/derive.ts +0 -105
  91. package/skill/gates/build.jsx +0 -20
  92. package/skill/gates/design.jsx +0 -22
  93. package/skill/gates/flows.jsx +0 -14
  94. package/skill/gates/vision.jsx +0 -27
  95. package/types/cli/src/derive.d.ts +0 -17
  96. package/ui/dist/assets/client.cemdw2n8.js +0 -214
@@ -0,0 +1,162 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from 'fs'
2
+ import { join } from 'path'
3
+ import { GATE_APPROVE, GATE_CHANGES, GATE_VERDICT_ID } from '../../shared/gate'
4
+ import { literal } from './build-review'
5
+ import { extractFrontMatter, list, scalar } from './frontmatter'
6
+ import { readSkeletons } from './skeletons'
7
+
8
+ export const FLOWS_DIR = '.fabrika/architecture/flows'
9
+ export const FLOWS_REVIEW_PATH = '.fabrika/architecture/flows-review.jsx'
10
+
11
+ export interface Flow {
12
+ slug: string
13
+ /** Repository-relative. */
14
+ path: string
15
+ actor: string
16
+ goal: string
17
+ /** The screen the flow starts on; null when the front matter names none or an invalid one. */
18
+ route: string | null
19
+ /** The screens the flow moves to, valid routes only. */
20
+ leadsTo: string[]
21
+ /** What the reviewer must fix before the map can be trusted. */
22
+ problems: string[]
23
+ /** Only a regular file under a slug name is shown and mapped; a link could pull in any file on the machine. */
24
+ shown: boolean
25
+ }
26
+
27
+ // A route is a path: segments of URL-safe characters, `:name` parameters included. Anything else stays off the map.
28
+ const ROUTE = /^\/(?:[A-Za-z0-9._~:-]+(?:\/[A-Za-z0-9._~:-]+)*\/?)?$/
29
+ const SLUG = /^[a-z0-9][a-z0-9-]*$/
30
+
31
+ export function readFlows(repoRoot: string): Flow[] {
32
+ const dir = join(repoRoot, FLOWS_DIR)
33
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return []
34
+ const flows: Flow[] = []
35
+ for (const entry of readdirSync(dir).sort()) {
36
+ if (!entry.endsWith('.flow.md')) continue
37
+ const file = join(dir, entry)
38
+ const slug = entry.slice(0, -'.flow.md'.length)
39
+ const stat = lstatSync(file)
40
+ if (stat.isSymbolicLink() || !stat.isFile()) {
41
+ flows.push(unreadable(slug, 'not a regular file (a link or a directory); it is not read'))
42
+ continue
43
+ }
44
+ if (stat.size === 0) continue
45
+ flows.push(parseFlow(slug, readFileSync(file, 'utf8')))
46
+ }
47
+ return flows
48
+ }
49
+
50
+ function unreadable(slug: string, problem: string): Flow {
51
+ return { slug, path: `${FLOWS_DIR}/${slug}.flow.md`, actor: '', goal: '', route: null, leadsTo: [], problems: [problem], shown: false }
52
+ }
53
+
54
+ export function parseFlow(slug: string, raw: string): Flow {
55
+ const fm = extractFrontMatter(raw).body
56
+ const problems: string[] = []
57
+ const shown = SLUG.test(slug)
58
+ if (!shown) problems.push('rename the file to lowercase letters, digits and dashes; it is not mapped until then')
59
+ const rawRoute = scalar(fm['route'])
60
+ let route: string | null = null
61
+ if (rawRoute === undefined || rawRoute === '') problems.push('no `route:` in its front matter')
62
+ else if (!ROUTE.test(rawRoute)) problems.push(`\`route: ${rawRoute}\` is not a path`)
63
+ else route = rawRoute
64
+ const leadsTo: string[] = []
65
+ // The reader is flat: a block list (`leads_to:` then `- /x` lines) reads as empty, which must not pass silently.
66
+ if (fm['leads_to'] === '') problems.push('write `leads_to` on one line, as `[/a, /b]`')
67
+ for (const target of list(fm['leads_to'])) {
68
+ if (ROUTE.test(target)) leadsTo.push(target)
69
+ else problems.push(`\`leads_to\` entry \`${target}\` is not a path`)
70
+ }
71
+ return {
72
+ slug,
73
+ path: `${FLOWS_DIR}/${slug}.flow.md`,
74
+ actor: scalar(fm['actor']) ?? '',
75
+ goal: scalar(fm['goal']) ?? '',
76
+ route,
77
+ leadsTo,
78
+ problems,
79
+ shown,
80
+ }
81
+ }
82
+
83
+ /** Every screen on the map: each shown flow's start and every screen it leads to. */
84
+ export function mappedRoutes(flows: readonly Flow[]): Set<string> {
85
+ return new Set(flows.filter((flow) => flow.shown).flatMap((flow) => [...(flow.route ? [flow.route] : []), ...flow.leadsTo]))
86
+ }
87
+
88
+ /** The skeleton URLs on no screen of the map: a `:name` segment matches any one segment, and a trailing slash is ignored. */
89
+ export function unmappedUrls(flows: readonly Flow[], urls: readonly string[]): string[] {
90
+ const routes = [...mappedRoutes(flows)].map(segments)
91
+ return [...new Set(urls)].filter((url) => {
92
+ const path = segments(url.split(/[?#]/)[0] ?? url)
93
+ return !routes.some((route) => route.length === path.length && route.every((part, i) => part.startsWith(':') || part === path[i]))
94
+ }).sort()
95
+ }
96
+
97
+ function segments(path: string): string[] {
98
+ return path.split('/').filter((part) => part !== '')
99
+ }
100
+
101
+ /** The route check `next` and `advance` report from the skeletons phase on: the issues are induced from these urls. */
102
+ export function skeletonRouteWarnings(repoRoot: string): string[] {
103
+ const urls = readSkeletons(join(repoRoot, 'tests', 'browser')).flatMap((skeleton) => (skeleton.url ? [skeleton.url] : []))
104
+ return unmappedUrls(readFlows(repoRoot), urls).map((url) => `skeleton url ${url} is on no flow's route map (route or leads_to)`)
105
+ }
106
+
107
+ export function routeMapMermaid(flows: readonly Flow[]): string {
108
+ const ids = new Map<string, string>()
109
+ const id = (route: string): string => {
110
+ let found = ids.get(route)
111
+ if (found === undefined) {
112
+ found = `s${ids.size}`
113
+ ids.set(route, found)
114
+ }
115
+ return found
116
+ }
117
+ const edges: string[] = []
118
+ for (const flow of flows) {
119
+ if (!flow.route || !flow.shown) continue
120
+ const from = id(flow.route)
121
+ for (const target of flow.leadsTo) edges.push(` ${from} -->|${flow.slug}| ${id(target)}`)
122
+ }
123
+ for (const route of mappedRoutes(flows)) id(route)
124
+ // Routes and slugs were validated above, so neither can close a label.
125
+ const nodes = [...ids].map(([route, nodeId]) => ` ${nodeId}["${route}"]`)
126
+ return ['flowchart LR', ...nodes, ...edges].join('\n')
127
+ }
128
+
129
+ /** The flows gate's view, generated from the flow files so the map is the one they declare. */
130
+ export function renderFlowsReview(flows: readonly Flow[], now: Date): string {
131
+ const screens = mappedRoutes(flows).size
132
+ const problems = flows.flatMap((flow) => flow.problems.map((problem) => [flow.path, problem]))
133
+ const lines = [
134
+ `<Section title={${literal(`Flows review — ${flows.length} flows, ${screens} screens`)}}>`,
135
+ `\t<Note>{${
136
+ literal(
137
+ `Generated by \`fabrika builder flows review\` at ${now.toISOString()} from ${FLOWS_DIR}/*.flow.md: each arrow is a flow's \`leads_to\`, labelled with the flow.`,
138
+ )
139
+ }}</Note>`,
140
+ ]
141
+ if (screens > 0) lines.push(`\t<Mermaid>{${literal(routeMapMermaid(flows))}}</Mermaid>`)
142
+ lines.push(
143
+ `\t<Table headers={${literal(['Flow', 'Actor', 'Goal', 'Starts at', 'Leads to'])}} rows={${
144
+ literal(flows.map((flow) => [flow.slug, flow.actor, flow.goal, flow.route ?? '(none)', flow.leadsTo.join(', ') || '(none)']))
145
+ }} />`,
146
+ )
147
+ if (problems.length > 0) lines.push(`\t<Table headers={${literal(['Flow file', 'Problem'])}} rows={${literal(problems)}} />`)
148
+ for (const flow of flows) {
149
+ if (!flow.shown) continue
150
+ lines.push(
151
+ `\t<Item id={${literal(`flow-${flow.slug}`)}} label={${literal(`${flow.slug} — ${flow.route ?? 'no route'}`)}} badge="flow" badgeVariant="info">`,
152
+ `\t\t<Markdown file="${flow.path}" />`,
153
+ '\t</Item>',
154
+ )
155
+ }
156
+ lines.push(
157
+ `\t<UserInput id="flows-note" label="A missing screen, a wrong transition, or a missing step?" placeholder="write here…" multiline />`,
158
+ `\t<Choice id="${GATE_VERDICT_ID}" label="Verdict" required options={['${GATE_APPROVE}', '${GATE_CHANGES}']} />`,
159
+ '</Section>',
160
+ )
161
+ return lines.join('\n') + '\n'
162
+ }
@@ -0,0 +1,32 @@
1
+ /** The flat `key: value` front matter the builder's own Markdown files carry; lists are `[a, b]` on one line. */
2
+ export interface FrontMatter {
3
+ body: Record<string, string>
4
+ rest: string
5
+ }
6
+
7
+ export function extractFrontMatter(raw: string): FrontMatter {
8
+ // An editor's byte-order mark would otherwise hide the whole front matter.
9
+ const m = raw.replace(/^\uFEFF/, '').match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/)
10
+ if (!m) return { body: {}, rest: raw }
11
+ const body: Record<string, string> = {}
12
+ for (const line of (m[1] ?? '').split(/\r?\n/)) {
13
+ const kv = line.match(/^\s*([A-Za-z0-9_-]+)\s*:\s*(.*)$/)
14
+ if (kv && kv[1]) body[kv[1]] = (kv[2] ?? '').trim()
15
+ }
16
+ return { body, rest: (m[2] ?? '').trim() }
17
+ }
18
+
19
+ export function scalar(v: string | undefined): string | undefined {
20
+ if (v === undefined) return undefined
21
+ return v.replace(/^["']|["']$/g, '')
22
+ }
23
+
24
+ export function list(v: string | undefined): string[] {
25
+ if (!v) return []
26
+ const inner = v.replace(/^\[/, '').replace(/\]$/, '')
27
+ if (inner.trim() === '') return []
28
+ return inner
29
+ .split(',')
30
+ .map((s) => s.trim().replace(/^["']|["']$/g, ''))
31
+ .filter((s) => s.length > 0)
32
+ }
package/cli/src/index.ts CHANGED
@@ -1,3 +1,13 @@
1
+ export {
2
+ derivePhase,
3
+ type GateProbe,
4
+ isNonEmptyFile,
5
+ matchGlob,
6
+ offlineGateProbe,
7
+ type PhaseState,
8
+ producesSatisfied,
9
+ resolveReads,
10
+ } from '../../shared/derive'
1
11
  export { type Phase, PHASE_COUNT, PHASE_IDS, phaseById, type PhaseId, phaseIndex, PHASES } from '../../shared/phases'
2
12
  export { resolveCatalogRoot, resolveStackPointer, type StackPointer } from './catalog'
3
13
  export {
@@ -12,7 +22,6 @@ export {
12
22
  TEMP_DIR,
13
23
  WS_URL,
14
24
  } from './config'
15
- export { derivePhase, type GateProbe, isNonEmptyFile, matchGlob, offlineGateProbe, type PhaseState, producesSatisfied, resolveReads } from './derive'
16
25
  export {
17
26
  type AgentHost,
18
27
  injectAgentSupport,
package/cli/src/induce.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import { basename } from 'path'
1
2
  import type { StackPointer } from './catalog'
3
+ import { DESIGN_GATE, DESIGN_PATH, DESIGN_REVIEW_PATH } from './design-review'
2
4
  import type { Skeleton } from './skeletons'
3
5
 
4
6
  export interface InducedIssue {
@@ -7,6 +9,9 @@ export interface InducedIssue {
7
9
  satisfies: string[]
8
10
  dependsOn: string[]
9
11
  touches: string[]
12
+ verify: string[]
13
+ /** The review gate whose consumed verdict `build done` records instead of running a check. */
14
+ gate?: string
10
15
  body: string
11
16
  kind: 'foundation' | 'feature'
12
17
  }
@@ -14,6 +19,7 @@ export interface InducedIssue {
14
19
  const FOUNDATION_SCAFFOLD = 'ISSUE-001'
15
20
  const FOUNDATION_DATA = 'ISSUE-002'
16
21
  const FOUNDATION_AUTH = 'ISSUE-003'
22
+ const DESIGN_CHECKPOINT = 'ISSUE-004'
17
23
 
18
24
  export interface InduceOpts {
19
25
  stack?: StackPointer
@@ -42,6 +48,7 @@ export function induceIssues(skeletons: Skeleton[], opts: InduceOpts = {}): Indu
42
48
  satisfies: [],
43
49
  dependsOn: [],
44
50
  touches: ['app scaffold', 'routing', ...allUrls.map((u) => `route: ${u}`)],
51
+ verify: [],
45
52
  body: [
46
53
  ...stackRef,
47
54
  'Foundation. Scaffold the running app per the active stack preset — read its',
@@ -63,9 +70,11 @@ export function induceIssues(skeletons: Skeleton[], opts: InduceOpts = {}): Indu
63
70
  satisfies: [],
64
71
  dependsOn: [FOUNDATION_SCAFFOLD],
65
72
  touches: ['schema/migrations', ...allSeeds.map((s) => `seed: ${s}`)],
73
+ verify: [],
66
74
  body: [
67
75
  'Foundation. Define the schema (idempotent migrations) and one named',
68
- 'idempotent seed per `seeds:` value, keyed on stable ids.',
76
+ 'idempotent seed per `seeds:` value, keyed on stable ids, in the form the',
77
+ "stack preset's seed strategy names.",
69
78
  '',
70
79
  'Named seeds to provide (union of skeleton `seeds`):',
71
80
  ...allSeeds.map((s) => `- \`${s}\``),
@@ -81,6 +90,7 @@ export function induceIssues(skeletons: Skeleton[], opts: InduceOpts = {}): Indu
81
90
  satisfies: [],
82
91
  dependsOn: [FOUNDATION_SCAFFOLD],
83
92
  touches: ['auth', 'identities'],
93
+ verify: [],
84
94
  body: [
85
95
  'Foundation. Provide auth for every acting identity in the skeletons.',
86
96
  '',
@@ -90,11 +100,56 @@ export function induceIssues(skeletons: Skeleton[], opts: InduceOpts = {}): Indu
90
100
  })
91
101
  }
92
102
 
103
+ issues.push({
104
+ id: DESIGN_CHECKPOINT,
105
+ kind: 'foundation',
106
+ goal: 'Design checkpoint: theme the running application and get the design gate reviewed.',
107
+ satisfies: [],
108
+ dependsOn: issues.map((i) => i.id),
109
+ touches: ['theme stylesheet'],
110
+ verify: [],
111
+ gate: DESIGN_GATE,
112
+ body: [
113
+ 'Foundation. The design is reviewed on the real application, not on drawings:',
114
+ "the screens are the kit's components with the seeded data.",
115
+ '',
116
+ "1. Theme through the kit's tokens only: override `--fui-*` custom properties in the",
117
+ " SPA's own stylesheet, imported after `@fabrika/ui/styles.css` (the `fabrika-app`",
118
+ ' skill\'s `spa.md`, "Theming"). Never restyle a `.fui-` class. On a stack without',
119
+ " `@fabrika/ui`, theme that stack's own tokens the same way.",
120
+ ' Propose two or three variants: each a stylesheet beside it with only the `:root`',
121
+ " (and `:root[data-theme='dark']`) overrides. Copy one into the imported stylesheet.",
122
+ '2. Record the decisions in `' + DESIGN_PATH + '`: front matter',
123
+ ' `stylesheet: <repository-relative path>` naming the imported stylesheet and',
124
+ " `variants: [<path>, <path>]` naming the variants, then each variant's idea and",
125
+ ' its overridden tokens.',
126
+ '3. Start the application with its seeds and publish its address:',
127
+ ' `fabrika builder preview --url=<local url>`.',
128
+ '4. `fabrika builder design review` writes the gate view `' + DESIGN_REVIEW_PATH + '`:',
129
+ " each variant side by side (swatches, overrides, the WCAG contrast of the kit's text",
130
+ ' and focus pairs), a required choice between them, and the routes below. The preview',
131
+ ' shows only the imported stylesheet. Raise every pair below AA, in each variant and',
132
+ ' in the imported stylesheet, then',
133
+ ' `fabrika builder gate open ' + DESIGN_GATE + ' --view ' + DESIGN_REVIEW_PATH + ' && fabrika builder gate wait`.',
134
+ '5. The feedback names the chosen variant. On "Request changes", first make the',
135
+ " requested changes in that variant's file. Copy its overrides into the imported",
136
+ ' stylesheet and run `design review` again; the view must say the stylesheet declares',
137
+ ' that variant. Re-open the gate on "Request changes", or when the variant differs',
138
+ ' from what the preview showed, so the screens are reviewed with it.',
139
+ '6. `fabrika builder build done ' + DESIGN_CHECKPOINT + "` records the gate's verdict. It refuses a pair",
140
+ ' below AA unless the reviewer accepts it: then pass `--waive-contrast`.',
141
+ '',
142
+ 'Screens to review (skeleton `url` metadata):',
143
+ ...(allUrls.length ? allUrls.map((u) => `- \`${u}\``) : ['- (none declared)']),
144
+ ].join('\n'),
145
+ })
146
+
93
147
  let n = 101
94
148
  for (const s of skeletons) {
95
149
  const deps = [FOUNDATION_SCAFFOLD]
96
150
  if (s.seeds.length && allSeeds.length) deps.push(FOUNDATION_DATA)
97
151
  if (s.roles.length && allRoles.length) deps.push(FOUNDATION_AUTH)
152
+ deps.push(DESIGN_CHECKPOINT)
98
153
 
99
154
  const satisfies = [s.feature ?? s.name, ...s.invariants]
100
155
 
@@ -105,6 +160,7 @@ export function induceIssues(skeletons: Skeleton[], opts: InduceOpts = {}): Indu
105
160
  satisfies: uniq(satisfies),
106
161
  dependsOn: deps,
107
162
  touches: uniq([s.url ? `route: ${s.url}` : 'feature route/UI', ...s.seeds.map((sd) => `seed: ${sd}`)]),
163
+ verify: [relTest(s.file)],
108
164
  body: [
109
165
  `Feature slice satisfying the scenario **${s.name}**` + (s.feature ? ` (\`${s.feature}\`)` : '') + '.',
110
166
  '',
@@ -132,14 +188,16 @@ export function renderIssue(issue: InducedIssue): string {
132
188
  `satisfies: [${issue.satisfies.map(q).join(', ')}]`,
133
189
  `depends_on: [${issue.dependsOn.map(q).join(', ')}]`,
134
190
  `touches: [${issue.touches.map(q).join(', ')}]`,
191
+ `verify: [${issue.verify.map(q).join(', ')}]`,
192
+ ...(issue.gate ? [`gate: ${issue.gate}`] : []),
135
193
  '---',
136
194
  ].join('\n')
137
195
  return `${fm}\n\n# ${issue.id} — ${issue.goal}\n\n${issue.body}\n`
138
196
  }
139
197
 
198
+ // readSkeletons reads only the top level of the repository's tests/browser/.
140
199
  function relTest(file: string): string {
141
- const i = file.indexOf('tests/browser/')
142
- return i !== -1 ? file.slice(i) : file
200
+ return `tests/browser/${basename(file)}`
143
201
  }
144
202
 
145
203
  function uniq<T>(xs: T[]): T[] {
package/cli/src/issues.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { existsSync, readdirSync, readFileSync, statSync } from 'fs'
2
2
  import { basename, join } from 'path'
3
+ import { BuilderCliError } from './errors'
4
+ import { extractFrontMatter, list, scalar } from './frontmatter'
3
5
 
4
6
  export interface Issue {
5
7
  id: string
@@ -8,6 +10,10 @@ export interface Issue {
8
10
  satisfies: string[]
9
11
  dependsOn: string[]
10
12
  touches: string[]
13
+ /** Repository-relative acceptance files `build done` runs; empty for an issue whose check the driver names. */
14
+ verify: string[]
15
+ /** A review gate whose verdict `build done` records instead of running a check. */
16
+ gate?: string
11
17
  body: string
12
18
  }
13
19
 
@@ -28,6 +34,7 @@ export function readIssues(fabrikaDir: string): Issue[] {
28
34
  export function parseIssue(path: string): Issue {
29
35
  const raw = readFileSync(path, 'utf-8')
30
36
  const fm = extractFrontMatter(raw)
37
+ const gate = gateName(path, fm.body['gate'])
31
38
  return {
32
39
  id: basename(path).replace(/\.md$/i, ''),
33
40
  path,
@@ -35,6 +42,8 @@ export function parseIssue(path: string): Issue {
35
42
  satisfies: list(fm.body['satisfies']),
36
43
  dependsOn: list(fm.body['depends_on']),
37
44
  touches: list(fm.body['touches']),
45
+ verify: list(fm.body['verify']),
46
+ ...(gate ? { gate } : {}),
38
47
  body: fm.rest,
39
48
  }
40
49
  }
@@ -43,33 +52,10 @@ export function isReady(issue: Issue, knownIds: Set<string>): boolean {
43
52
  return issue.dependsOn.every((dep) => knownIds.has(dep))
44
53
  }
45
54
 
46
- interface FrontMatter {
47
- body: Record<string, string>
48
- rest: string
49
- }
50
-
51
- function extractFrontMatter(raw: string): FrontMatter {
52
- const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/)
53
- if (!m) return { body: {}, rest: raw }
54
- const body: Record<string, string> = {}
55
- for (const line of (m[1] ?? '').split(/\r?\n/)) {
56
- const kv = line.match(/^\s*([A-Za-z0-9_-]+)\s*:\s*(.*)$/)
57
- if (kv && kv[1]) body[kv[1]] = (kv[2] ?? '').trim()
58
- }
59
- return { body, rest: (m[2] ?? '').trim() }
60
- }
61
-
62
- function scalar(v: string | undefined): string | undefined {
63
- if (v === undefined) return undefined
64
- return v.replace(/^["']|["']$/g, '')
65
- }
66
-
67
- function list(v: string | undefined): string[] {
68
- if (!v) return []
69
- const inner = v.replace(/^\[/, '').replace(/\]$/, '')
70
- if (inner.trim() === '') return []
71
- return inner
72
- .split(',')
73
- .map((s) => s.trim().replace(/^["']|["']$/g, ''))
74
- .filter((s) => s.length > 0)
55
+ // The name reaches a daemon URL; an issue that names an invalid one is refused, never read as ungated.
56
+ function gateName(path: string, v: string | undefined): string | undefined {
57
+ const name = scalar(v)
58
+ if (!name) return undefined
59
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new BuilderCliError(`${path}: "${name}" is not a gate name (lowercase letters, digits and dashes).`)
60
+ return name
75
61
  }
package/cli/src/layout.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
2
2
  import { join, resolve } from 'node:path'
3
3
  import { type BuilderProjectConfig, parseBuilderProjectConfig } from '../../shared'
4
+ import { writeApprovals } from '../../shared/approvals'
5
+ import { DEFAULT_PROFILE } from './catalog'
4
6
  import { FABRIKA_DIRNAME, hashRepoPath } from './config'
5
7
  import { BuilderCliError } from './errors'
6
8
 
@@ -10,7 +12,6 @@ export const LAYER_DIRS = [
10
12
  'architecture',
11
13
  'architecture/flows',
12
14
  'architecture/spec',
13
- 'pages',
14
15
  'issues',
15
16
  ]
16
17
 
@@ -55,7 +56,7 @@ export function scaffold(
55
56
  ): InitResult {
56
57
  const root = resolve(repoRoot)
57
58
  const fdir = fabrikaDir(root)
58
- const profile = opts.profile ?? 'cf-lightweight'
59
+ const profile = opts.profile ?? DEFAULT_PROFILE
59
60
  const createdDirs: string[] = []
60
61
 
61
62
  const alreadyInitialized = isInitialized(root)
@@ -88,6 +89,8 @@ export function scaffold(
88
89
  createdAt: new Date().toISOString(),
89
90
  }
90
91
  writeFileSync(configPath(root), JSON.stringify(config, null, 2) + '\n')
92
+ // A new project keeps approvals from its first gate; one without the file is judged by its reviews alone.
93
+ writeApprovals(root, {})
91
94
  createdConfig = true
92
95
  }
93
96
 
package/cli/src/packet.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { join } from 'node:path'
2
2
  import type { BuilderProjectConnection } from '../../shared'
3
+ import type { PhaseState } from '../../shared/derive'
3
4
  import { PHASE_COUNT, phaseById, type PhaseId, phaseIndex } from '../../shared/phases'
4
- import { resolveStackPointer, type StackPointer } from './catalog'
5
- import type { PhaseState } from './derive'
5
+ import { resolveStackPointer, type StackPointer, unsupportedProfileNote } from './catalog'
6
6
 
7
7
  export interface RenderOpts {
8
8
  profile?: string
9
9
  connection?: BuilderProjectConnection
10
+ /** Skeleton urls off the flows' route map (`skeletonRouteWarnings`). */
11
+ routeWarnings?: string[]
10
12
  }
11
13
 
12
14
  const CHECK = '✓' // ✓
@@ -20,6 +22,18 @@ export function renderPacket(state: PhaseState, opts: RenderOpts = {}): string {
20
22
  const completedSuffix = done ? ` (${done})` : ''
21
23
  lines.push(`## Phase ${phase.number}/${PHASE_COUNT} - ${phase.title}${completedSuffix}`)
22
24
 
25
+ // Only an explicit "Request changes": sessions saved before verdicts existed read as `none` for every gate.
26
+ const overruled = state.completed.filter((id) => state.verdicts[id] === 'changes')
27
+ if (overruled.length > 0) {
28
+ lines.push(`Review: advanced over requested changes: ${overruled.join(', ')}`)
29
+ }
30
+ if (state.unverified.length > 0) {
31
+ lines.push(`Review: not checked (daemon down), assumed reviewed: ${state.unverified.join(', ')} - run \`fabrika builder ensure-daemon\``)
32
+ }
33
+ if (state.stale.length > 0) {
34
+ lines.push(`Stale: approved earlier, but its inputs changed since: ${state.stale.join(', ')} - re-open the gate for a new review`)
35
+ }
36
+
23
37
  const reads = state.reads.length > 0 ? state.reads.join(', ') : phase.reads.join(', ')
24
38
  lines.push(`Read: ${reads}`)
25
39
 
@@ -28,18 +42,25 @@ export function renderPacket(state: PhaseState, opts: RenderOpts = {}): string {
28
42
  }
29
43
 
30
44
  lines.push(`Goal: ${phase.goal}`)
45
+ for (const warning of opts.routeWarnings ?? []) lines.push(`Routes: warning: ${warning}`)
31
46
 
32
47
  if (phase.skills) lines.push(`Skills: ${phase.skills.join(', ')}`)
33
48
 
34
49
  if (phase.gate) {
35
50
  const view = phase.gateView ?? `${phase.id}.jsx`
36
- lines.push(`Gate: fabrika builder gate open ${phase.id} --view ${view} && fabrika builder gate wait`)
51
+ const write = phase.gateViewCommand ? `${phase.gateViewCommand} && ` : ''
52
+ lines.push(`Gate: ${write}fabrika builder gate open ${phase.id} --view ${view} && fabrika builder gate wait`)
53
+ } else if (phase.reviewedAt) {
54
+ lines.push(`Gate: (none - reviewed at the ${phase.reviewedAt} gate, with the next phase's output)`)
37
55
  } else {
38
56
  lines.push(`Gate: (none - deterministic compile step; review optional)`)
39
57
  }
40
58
 
41
59
  if (phase.id === 'build') {
42
60
  lines.push(`After OK: fabrika builder build (apply agents/build-orchestrator.md in the main session)`)
61
+ } else if (!phase.gate) {
62
+ // Nothing to approve: the phase completes as soon as its files exist, and `advance` would judge the next one.
63
+ lines.push(`After OK: fabrika builder next`)
43
64
  } else {
44
65
  lines.push(`After OK: fabrika builder advance && fabrika builder next`)
45
66
  }
@@ -61,6 +82,7 @@ function stackPointerLines(profile: string): string[] {
61
82
  return [
62
83
  `Stack: ${profile} -> ${p.stackFile}`,
63
84
  ` read it, then resolve its \`decisions:\` ids under ${p.decisionsDir}/ (curated reference + live \`sources\` — verify against current APIs)`,
85
+ ...(p.support === 'unsupported' ? [` warning: ${unsupportedProfileNote(profile)}`] : []),
64
86
  ]
65
87
  }
66
88
 
@@ -73,9 +95,15 @@ export interface PacketJson {
73
95
  produces: string[]
74
96
  gate: boolean
75
97
  gateView: string | null
98
+ gateViewCommand: string | null
99
+ /** An ungated phase whose output this later phase's gate reviews. */
100
+ reviewedAt: PhaseId | null
76
101
  skills: string[]
77
102
  completed: PhaseId[]
78
103
  satisfied: boolean
104
+ verdicts: PhaseState['verdicts']
105
+ unverified: PhaseId[]
106
+ stale: string[]
79
107
  stack: StackPointer | null
80
108
  platform: ReturnType<typeof connectionContext> | null
81
109
  }
@@ -92,9 +120,14 @@ export function packetJson(state: PhaseState, opts: RenderOpts = {}): PacketJson
92
120
  produces: state.produces,
93
121
  gate: phase.gate,
94
122
  gateView: phase.gateView ?? null,
123
+ gateViewCommand: phase.gateViewCommand ?? null,
124
+ reviewedAt: phase.reviewedAt ?? null,
95
125
  skills: phase.skills ?? [],
96
126
  completed: state.completed,
97
127
  satisfied: state.satisfied,
128
+ verdicts: state.verdicts,
129
+ unverified: state.unverified,
130
+ stale: state.stale,
98
131
  stack: phase.catalog && opts.profile ? resolveStackPointer(opts.profile) : null,
99
132
  }
100
133
  }
@@ -1,5 +1,7 @@
1
+ import { type Approvals, readApprovals, writeApprovals } from '../../shared/approvals'
2
+ import { derivePhase, offlineGateProbe, phaseInputs, type PhaseState } from '../../shared/derive'
3
+ import { phaseById, type PhaseId } from '../../shared/phases'
1
4
  import { fetchPhase } from './daemon-client'
2
- import { derivePhase, offlineGateProbe, type PhaseState } from './derive'
3
5
 
4
6
  export interface ResolvedPhase {
5
7
  state: PhaseState
@@ -13,7 +15,23 @@ export async function resolvePhaseState(
13
15
  ): Promise<ResolvedPhase> {
14
16
  const fromDaemon = await fetchPhase(fabrikaDir, sessionId)
15
17
  if (fromDaemon) {
18
+ adoptApprovals(repoRoot, fromDaemon.completed)
16
19
  return { state: fromDaemon, source: 'daemon' }
17
20
  }
18
21
  return { state: derivePhase(repoRoot, offlineGateProbe), source: 'offline' }
19
22
  }
23
+
24
+ /**
25
+ * A project initialized before approvals existed records the gated phases the daemon judged reviewed, over their files
26
+ * now. Without the daemon it then derives the same phase, instead of refusing gates that were reviewed.
27
+ */
28
+ function adoptApprovals(repoRoot: string, completed: readonly PhaseId[]): void {
29
+ if (readApprovals(repoRoot) !== null) return
30
+ const at = new Date().toISOString()
31
+ const approvals: Approvals = {}
32
+ for (const id of completed) {
33
+ const phase = phaseById(id)
34
+ if (phase.gate) approvals[id] = { at, inputs: phaseInputs(repoRoot, phase) }
35
+ }
36
+ writeApprovals(repoRoot, approvals)
37
+ }
@@ -0,0 +1,50 @@
1
+ import type { BuildEvidence } from './build-status'
2
+
3
+ /** What an issue's check runs: its acceptance files under `bun test`, or the command the driver names. */
4
+ export type Verification = { kind: 'files'; files: string[] } | { kind: 'command'; command: string }
5
+
6
+ export function verificationCommand(verification: Verification): string[] {
7
+ // `bun test` reads a bare argument as a name filter; a `./` path names exactly that file.
8
+ return verification.kind === 'files'
9
+ ? [process.execPath, 'test', ...verification.files.map((file) => `./${file}`)]
10
+ : ['sh', '-c', verification.command]
11
+ }
12
+
13
+ export function describeVerification(verification: Verification): string {
14
+ return verification.kind === 'files' ? `bun test ${verification.files.join(' ')}` : verification.command
15
+ }
16
+
17
+ /** Runs the check in the repository with the driver's terminal attached, and returns what happened. */
18
+ export async function runVerification(repoRoot: string, verification: Verification, now: () => Date = () => new Date()): Promise<BuildEvidence> {
19
+ const started = performance.now()
20
+ const exitCode = await runCommand(repoRoot, verificationCommand(verification))
21
+ const durationMs = Math.round(performance.now() - started)
22
+ return { command: describeVerification(verification), exitCode, durationMs, at: now().toISOString(), ...gitState(repoRoot) }
23
+ }
24
+
25
+ async function runCommand(repoRoot: string, command: string[]): Promise<number> {
26
+ try {
27
+ return await Bun.spawn(command, { cwd: repoRoot, stdin: 'ignore', stdout: 'inherit', stderr: 'inherit' }).exited
28
+ } catch {
29
+ console.error(`[fabrika] could not start \`${command[0]}\``)
30
+ return 127
31
+ }
32
+ }
33
+
34
+ /** `commit` is null before the first commit and outside git; `dirty` is true whenever git cannot tell. */
35
+ export function gitState(repoRoot: string): { commit: string | null; dirty: boolean } {
36
+ if (git(repoRoot, ['rev-parse', '--is-inside-work-tree'])?.trim() !== 'true') return { commit: null, dirty: false }
37
+ const head = git(repoRoot, ['rev-parse', '--verify', '--quiet', 'HEAD'])?.trim()
38
+ // Only the application's own tree counts; the builder's state under .fabrika/ changes with every record.
39
+ const status = git(repoRoot, ['status', '--porcelain', '--untracked-files=all', '--', '.', ':!.fabrika'])
40
+ return { commit: head ? head : null, dirty: status === null || status.trim().length > 0 }
41
+ }
42
+
43
+ function git(cwd: string, args: string[]): string | null {
44
+ try {
45
+ const proc = Bun.spawnSync(['git', ...args], { cwd, stdout: 'pipe', stderr: 'ignore' })
46
+ return proc.exitCode === 0 ? proc.stdout.toString() : null
47
+ } catch {
48
+ return null
49
+ }
50
+ }