Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1026 wiersze
75KB

  1. # C64/C128 Dev Foundry - validation, resolution, rendering and generation.
  2. # Deterministic: no network access and no AI API needed. Requires PowerShell 7+ and git.
  3. Set-StrictMode -Version 1.0
  4. $ErrorActionPreference = 'Stop'
  5. $script:FoundryRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path
  6. $script:Stages = @('idea', 'target', 'first-release', 'details', 'toolchain', 'plan', 'destination', 'review')
  7. $script:StageQuestions = @{
  8. 'idea' = @('In a sentence or two, what should the program do and who is it for?', 'What is the smallest version that would already be useful or playable?')
  9. 'target' = @('Which machine and display: C64, C128 native 40-column, C128 native 80-column, or both C64 and C128?', 'PAL, NTSC or both?', 'Should it be tested on real hardware as well as VICE?')
  10. 'first-release' = @('What must the first release do, and what is explicitly out of scope?', 'How will we see that it works (observable success criteria)?')
  11. 'details' = @('Controls (keyboard, joystick port)?', 'Visuals and sound?', 'Saving/loading, file formats, disk drive or other peripherals?', 'Speed and memory limits that matter?')
  12. 'toolchain' = @('Any language or tool preference? (Otherwise the Foundry picks the simplest that fits and explains why.)', 'Build on Windows (default) or author/compile on the Commodore itself?')
  13. 'plan' = @('Does the proposed first milestone and its checks look right?')
  14. 'destination' = @('Where should the new project folder be created?')
  15. 'review' = @('Do you approve this spec for generation, or what should change?')
  16. }
  17. $script:DesignTopics = @('controls', 'visuals', 'sound', 'persistence', 'fileFormats', 'peripherals', 'budgets')
  18. # ---------------------------------------------------------------------------
  19. # Basics
  20. # ---------------------------------------------------------------------------
  21. function Get-FoundryRoot { $script:FoundryRoot }
  22. function Read-FoundryJson([string]$Path) {
  23. if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "File not found: $Path" }
  24. try { Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -AsHashtable -Depth 64 }
  25. catch { throw "Invalid JSON in ${Path}: $($_.Exception.Message)" }
  26. }
  27. function Get-FoundryCatalog { Read-FoundryJson (Join-Path $script:FoundryRoot 'catalog/recipes.json') }
  28. function Test-Blank($Value) { ($null -eq $Value) -or ($Value -is [string] -and [string]::IsNullOrWhiteSpace($Value)) }
  29. function Get-List($Value) { if ($null -eq $Value) { return }; foreach ($x in @($Value)) { $x } }
  30. function Get-Field($Object, [string]$Path) {
  31. $cur = $Object
  32. foreach ($part in $Path -split '\.') {
  33. if ($cur -is [System.Collections.IDictionary] -and $cur.Contains($part)) { $cur = $cur[$part] } else { return $null }
  34. }
  35. $cur
  36. }
  37. # ---------------------------------------------------------------------------
  38. # Validation
  39. # ---------------------------------------------------------------------------
  40. class FoundryIssues {
  41. [System.Collections.Generic.List[object]]$Items = [System.Collections.Generic.List[object]]::new()
  42. [void] Add([string]$stage, [string]$kind, [string]$path, [string]$message) {
  43. $this.Items.Add([pscustomobject]@{ Stage = $stage; Kind = $kind; Path = $path; Message = $message })
  44. }
  45. }
  46. function Test-FoundryBrief {
  47. <#
  48. .SYNOPSIS Validate a brief. Mode Draft reports what is still missing and where to resume;
  49. mode Approved requires a complete, approved, conflict-free brief.
  50. #>
  51. [CmdletBinding()]
  52. param(
  53. [Parameter(Mandatory)][hashtable]$Brief,
  54. [ValidateSet('Draft', 'Approved')][string]$Mode = 'Approved',
  55. [string]$BriefPath,
  56. [hashtable]$Catalog = (Get-FoundryCatalog)
  57. )
  58. $issues = [FoundryIssues]::new()
  59. $need = {
  60. param($stage, $path, $message)
  61. $issues.Add($stage, 'missing', $path, $message)
  62. }
  63. $err = { param($stage, $path, $message) $issues.Add($stage, 'error', $path, $message) }
  64. $conflict = { param($stage, $path, $message) $issues.Add($stage, 'conflict', $path, $message) }
  65. $warn = { param($stage, $path, $message) $issues.Add($stage, 'warning', $path, $message) }
  66. if ($Brief.schemaVersion -ne '1.0') { & $err 'idea' 'schemaVersion' "schemaVersion must be '1.0'." }
  67. # --- idea ---------------------------------------------------------------
  68. $p = $Brief.project
  69. if ($p -isnot [System.Collections.IDictionary]) { & $need 'idea' 'project' 'project section (name, slug, idea, summary, kind, smallestUsefulVersion) is missing.'; $p = @{} }
  70. foreach ($f in 'name', 'idea', 'summary', 'smallestUsefulVersion') { if (Test-Blank $p[$f]) { & $need 'idea' "project.$f" "project.$f is required." } }
  71. if (Test-Blank $p.slug) { & $need 'idea' 'project.slug' 'project.slug is required.' }
  72. elseif ($p.slug -cnotmatch '^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$') { & $err 'idea' 'project.slug' "project.slug '$($p.slug)' must be 3-50 lower-case letters, digits and dashes." }
  73. if ((-not (Test-Blank $p.name)) -and $p.name.Length -gt 60) { & $err 'idea' 'project.name' 'project.name must be 60 characters or fewer.' }
  74. if (Test-Blank $p.kind) { & $need 'idea' 'project.kind' 'project.kind is required.' }
  75. elseif ($p.kind -notin 'game', 'utility', 'demo', 'tool', 'education', 'other') { & $err 'idea' 'project.kind' "project.kind '$($p.kind)' must be game, utility, demo, tool, education or other." }
  76. # --- target -------------------------------------------------------------
  77. $targets = @(Get-List $Brief.targets)
  78. $targetIds = @()
  79. if ($targets.Count -eq 0) { & $need 'target' 'targets' 'At least one target (machine + display) is required.' }
  80. $i = 0
  81. foreach ($t in $targets) {
  82. $tp = "targets[$i]"; $i++
  83. if ($t -isnot [System.Collections.IDictionary]) { & $err 'target' $tp 'Each target must be an object.'; continue }
  84. if (Test-Blank $t.id) { & $need 'target' "$tp.id" 'Target id is required.' }
  85. elseif ($t.id -cnotmatch '^[a-z0-9][a-z0-9-]{0,23}$') { & $err 'target' "$tp.id" "Target id '$($t.id)' must be lower-case letters, digits and dashes (max 24)." }
  86. elseif ($t.id -in $targetIds) { & $err 'target' "$tp.id" "Duplicate target id '$($t.id)'." }
  87. else { $targetIds += $t.id }
  88. if (Test-Blank $t.platform) { & $need 'target' "$tp.platform" 'Target platform is required (c64, c128-native or c128-c64mode).' }
  89. elseif (-not $Catalog.platforms.Contains($t.platform)) { & $err 'target' "$tp.platform" "Unknown platform '$($t.platform)'. Use c64, c128-native or c128-c64mode." }
  90. if (Test-Blank $t.display) { & $need 'target' "$tp.display" 'Target display is required (vicii-40 or vdc-80).' }
  91. elseif (-not $Catalog.displays.Contains($t.display)) { & $err 'target' "$tp.display" "Unknown display '$($t.display)'. Use vicii-40 or vdc-80." }
  92. elseif ($Catalog.platforms.Contains("$($t.platform)") -and $t.display -notin $Catalog.platforms[$t.platform].displays) {
  93. & $conflict 'target' "$tp.display" ("Target '$($t.id)': display '$($t.display)' is not available on platform '$($t.platform)'. 80-column VDC output needs a C128 in native mode (platform c128-native). Ask the user which constraint to change: the machine/mode, or the 80-column requirement.")
  94. }
  95. if (Test-Blank $t.video) { & $need 'target' "$tp.video" 'Target video standard is required (pal, ntsc or pal-ntsc).' }
  96. elseif ($t.video -notin 'pal', 'ntsc', 'pal-ntsc') { & $err 'target' "$tp.video" "video must be pal, ntsc or pal-ntsc." }
  97. if (Test-Blank $t.expectedBehavior) { & $need 'target' "$tp.expectedBehavior" "Target '$($t.id)': describe the expected behavior on this target." }
  98. if ($t.disk) {
  99. if ((Test-Blank $t.disk.name) -or $t.disk.name -notmatch '^[^,]{1,16},[^,]{1,2}$') { & $err 'target' "$tp.disk.name" "disk.name must look like 'diskname,id' (name up to 16 chars, id 1-2 chars)." }
  100. if ($t.disk.format -and $t.disk.format -notin 'd64', 'd71', 'd81') { & $err 'target' "$tp.disk.format" 'disk.format must be d64, d71 or d81.' }
  101. foreach ($df in Get-List $t.disk.files) {
  102. if ((Test-Blank $df.source) -or (Test-Blank $df.name)) { & $err 'target' "$tp.disk.files" 'Each disk file needs source and name.' }
  103. elseif ($df.name.Length -gt 16) { & $err 'target' "$tp.disk.files" "Disk file name '$($df.name)' is longer than 16 characters." }
  104. }
  105. }
  106. if ($t.autostart -and $t.autostart -notin 'prg', 'disk') { & $err 'target' "$tp.autostart" 'autostart must be prg or disk.' }
  107. if ($t.autostart -eq 'disk' -and -not $t.disk) { & $err 'target' "$tp.autostart" "Target '$($t.id)' autostarts from disk but has no disk section." }
  108. }
  109. $platforms = @($targets | Where-Object { $_ -is [System.Collections.IDictionary] } | ForEach-Object { $_.platform })
  110. if ($targets.Count -gt 1) {
  111. $strategy = Get-Field $Brief 'dualTarget.strategy'
  112. if (Test-Blank $strategy) {
  113. & $need 'target' 'dualTarget.strategy' 'More than one target: record dualTarget.strategy (c64-mode-on-both, native-per-target or multi-display) and how each target behaves.'
  114. } elseif ($strategy -eq 'c64-mode-on-both') {
  115. if ('c128-native' -in $platforms) { & $conflict 'target' 'dualTarget.strategy' "Strategy 'c64-mode-on-both' runs the same C64 program on both machines, but a target uses platform 'c128-native'. Ask the user: keep one C64-mode program (use platform c128-c64mode), or build a native C128 version (strategy native-per-target)." }
  116. if (-not ('c64' -in $platforms -and 'c128-c64mode' -in $platforms)) { & $err 'target' 'targets' "Strategy 'c64-mode-on-both' needs one c64 target and one c128-c64mode target." }
  117. } elseif ($strategy -eq 'native-per-target') {
  118. if (-not ('c64' -in $platforms -and 'c128-native' -in $platforms)) { & $err 'target' 'targets' "Strategy 'native-per-target' needs a c64 target and a c128-native target." }
  119. } elseif ($strategy -eq 'multi-display') {
  120. if (@($platforms | Where-Object { $_ -ne 'c128-native' }).Count -gt 0) { & $err 'target' 'targets' "Strategy 'multi-display' is for one C128 native program with separate 40- and 80-column targets." }
  121. } else { & $err 'target' 'dualTarget.strategy' "Unknown dualTarget.strategy '$strategy'." }
  122. if (Test-Blank (Get-Field $Brief 'dualTarget.notes')) { & $need 'target' 'dualTarget.notes' 'Explain in dualTarget.notes what is shared and what differs between targets.' }
  123. }
  124. if ($Brief.testing -isnot [System.Collections.IDictionary]) { & $need 'target' 'testing' 'testing section (emulator, realHardware) is required.' }
  125. else {
  126. if ($Brief.testing.emulator -ne 'vice') { & $err 'target' 'testing.emulator' "testing.emulator must be 'vice' in version 1." }
  127. $rh = $Brief.testing.realHardware
  128. if ($rh -isnot [System.Collections.IDictionary] -or $rh.requested -isnot [bool]) { & $need 'target' 'testing.realHardware.requested' 'Say whether real-hardware testing is requested (true/false).' }
  129. elseif ($rh.requested -and (Test-Blank $rh.reason)) { & $need 'target' 'testing.realHardware.reason' 'Real hardware requested: record why (which requirement depends on it).' }
  130. }
  131. # --- first release --------------------------------------------------------
  132. $s = $Brief.scope
  133. if ($s -isnot [System.Collections.IDictionary]) { & $need 'first-release' 'scope' 'scope section (firstRelease, inScope, outOfScope) is required.' }
  134. else {
  135. if (Test-Blank $s.firstRelease) { & $need 'first-release' 'scope.firstRelease' 'Describe the first release.' }
  136. if (@(Get-List $s.inScope).Count -eq 0) { & $need 'first-release' 'scope.inScope' 'List what is in scope.' }
  137. if (@(Get-List $s.outOfScope).Count -eq 0) { & $need 'first-release' 'scope.outOfScope' 'List what is out of scope.' }
  138. }
  139. $reqIds = @()
  140. $reqs = @(Get-List $Brief.requirements)
  141. if ($reqs.Count -eq 0) { & $need 'first-release' 'requirements' 'At least one requirement with observable acceptance criteria is required.' }
  142. foreach ($r in $reqs) {
  143. if ((Test-Blank $r.id) -or $r.id -cnotmatch '^R\d+$') { & $err 'first-release' 'requirements' "Requirement id '$($r.id)' must look like R1, R2, ..."; continue }
  144. if ($r.id -in $reqIds) { & $err 'first-release' "requirements.$($r.id)" "Duplicate requirement id $($r.id)." }
  145. $reqIds += $r.id
  146. if ((Test-Blank $r.title) -or (Test-Blank $r.text)) { & $need 'first-release' "requirements.$($r.id)" "$($r.id) needs a title and text." }
  147. if ($r.priority -notin 'must', 'should', 'could') { & $err 'first-release' "requirements.$($r.id).priority" "$($r.id) priority must be must, should or could." }
  148. if (@(Get-List $r.acceptance).Count -eq 0) { & $need 'first-release' "requirements.$($r.id).acceptance" "$($r.id) needs at least one observable acceptance criterion." }
  149. }
  150. # --- details --------------------------------------------------------------
  151. $d = $Brief.design
  152. if ($d -isnot [System.Collections.IDictionary]) { & $need 'details' 'design' 'design section is required (controls, visuals, sound, persistence, fileFormats, peripherals, budgets).'; $d = @{} }
  153. foreach ($topic in $script:DesignTopics) {
  154. $entry = $d[$topic]
  155. if ($entry -isnot [System.Collections.IDictionary] -or (Test-Blank $entry.value)) { & $need 'details' "design.$topic" "design.$topic needs a value (use source 'n/a' with a short reason when it does not apply)." ; continue }
  156. if ($entry.source -notin 'user', 'default', 'n/a', 'open') { & $err 'details' "design.$topic.source" "design.$topic.source must be user, default, n/a or open." }
  157. if ($entry.source -eq 'open') {
  158. $listed = @(Get-List $Brief.openDecisions | Where-Object { $_.topic -eq $topic }).Count -gt 0
  159. if (-not $listed) { & $err 'details' "design.$topic" "design.$topic is marked open but no openDecisions entry has topic '$topic'." }
  160. }
  161. }
  162. $caps = @(Get-List $Brief.capabilities)
  163. foreach ($c in $caps) { if (-not $Catalog.capabilities.Contains("$c")) { & $err 'details' 'capabilities' "Unknown capability '$c'. Known: $($Catalog.capabilities.Keys -join ', ')." } }
  164. foreach ($a in Get-List $Brief.assumptions) {
  165. if ((Test-Blank $a.id) -or (Test-Blank $a.text)) { & $err 'details' 'assumptions' 'Each assumption needs id and text.' }
  166. elseif ($a.status -notin 'default', 'unverified', 'confirmed') { & $err 'details' "assumptions.$($a.id)" "Assumption $($a.id) status must be default, unverified or confirmed." }
  167. }
  168. foreach ($o in Get-List $Brief.openDecisions) {
  169. if ((Test-Blank $o.id) -or (Test-Blank $o.question) -or (Test-Blank $o.default)) { & $err 'details' 'openDecisions' 'Each open decision needs id, question and the default used until it is decided.' }
  170. elseif ($o.status -notin 'open', 'resolved') { & $err 'details' "openDecisions.$($o.id)" "Open decision $($o.id) status must be open or resolved." }
  171. }
  172. # --- toolchain ----------------------------------------------------------------
  173. $tc = $Brief.toolchain
  174. $buildLocation = $Brief.buildLocation
  175. if (Test-Blank $buildLocation) { & $need 'toolchain' 'buildLocation' "buildLocation is required (windows-cross or on-commodore)." }
  176. elseif ($buildLocation -notin 'windows-cross', 'on-commodore') { & $err 'toolchain' 'buildLocation' "buildLocation must be windows-cross or on-commodore." }
  177. if ($tc -isnot [System.Collections.IDictionary]) { & $need 'toolchain' 'toolchain' 'toolchain section (recipe, language, recommended, reasons, alternatives) is required.' }
  178. else {
  179. $recipe = $null; $lang = $null
  180. if (Test-Blank $tc.recipe) { & $need 'toolchain' 'toolchain.recipe' 'toolchain.recipe is required.' }
  181. elseif (-not $Catalog.recipes.Contains($tc.recipe)) { & $err 'toolchain' 'toolchain.recipe' "Unknown recipe '$($tc.recipe)'. Known: $($Catalog.recipes.Keys -join ', ')." }
  182. else { $recipe = $Catalog.recipes[$tc.recipe] }
  183. if (Test-Blank $tc.language) { & $need 'toolchain' 'toolchain.language' 'toolchain.language is required.' }
  184. elseif (-not $Catalog.languages.Contains($tc.language)) { & $err 'toolchain' 'toolchain.language' "Unknown language '$($tc.language)'. Known: $($Catalog.languages.Keys -join ', ')." }
  185. else { $lang = $Catalog.languages[$tc.language] }
  186. $override = $tc.override
  187. $byOverride = ($override -is [System.Collections.IDictionary]) -and (-not (Test-Blank $override.requestedLanguage)) -and $override.requestedLanguage -eq $tc.language
  188. $ask = if ($byOverride) {
  189. $rec = Get-Field $tc 'recommended.language'
  190. " This language is a user override. Ask the user which constraint to change: keep '$($tc.language)' and change the conflicting target/requirement, or drop the override and use the recommended '$rec'."
  191. } else { ' Ask the user which constraint to change.' }
  192. if ($lang) {
  193. foreach ($t in $targets) {
  194. if ($t -isnot [System.Collections.IDictionary] -or (Test-Blank $t.platform)) { continue }
  195. if ($t.platform -notin $lang.platforms) {
  196. & $conflict 'toolchain' 'toolchain.language' ("Language '$($tc.language)' ($($lang.title)) does not run on platform '$($t.platform)' (target '$($t.id)')." + $ask)
  197. }
  198. }
  199. foreach ($c in $caps) {
  200. if ($c -notin $lang.capabilities) {
  201. $by = @(Get-List $Brief.requirements | Where-Object { @(Get-List $_.capabilities) -contains $c } | ForEach-Object { $_.id }) -join ', '
  202. $reqNote = if ($by) { " (needed by $by)" } else { '' }
  203. & $conflict 'toolchain' 'capabilities' ("Required capability '$c'$reqNote is not provided by '$($tc.language)': $($lang.limits)" + $ask)
  204. }
  205. }
  206. }
  207. if ('vdc-80col' -in $caps -and -not ($targets | Where-Object { $_ -is [System.Collections.IDictionary] -and $_.display -eq 'vdc-80' })) {
  208. & $conflict 'target' 'capabilities' "Capability 'vdc-80col' is required but no target uses display 'vdc-80'. Ask the user which constraint to change: add a C128 native 80-column target, or drop the 80-column requirement."
  209. }
  210. if ($recipe -and $lang) {
  211. if ($tc.language -notin $recipe.languages) { & $conflict 'toolchain' 'toolchain.recipe' ("Recipe '$($tc.recipe)' does not support language '$($tc.language)' (supports: $($recipe.languages -join ', '))." + $ask) }
  212. if ($buildLocation -and $buildLocation -notin $recipe.buildLocations) {
  213. $alt = @($Catalog.recipes.Keys | Where-Object { $buildLocation -in $Catalog.recipes[$_].buildLocations -and $tc.language -in $Catalog.recipes[$_].languages })
  214. $altNote = if ($alt) { " Recipe(s) that fit: $($alt -join ', ')." } else { " No catalog recipe supports '$($tc.language)' with build location '$buildLocation'." }
  215. & $conflict 'toolchain' 'buildLocation' ("Recipe '$($tc.recipe)' does not support build location '$buildLocation'.$altNote Ask the user which constraint to change: the build location or the language.")
  216. }
  217. foreach ($t in $targets) {
  218. if ($t -isnot [System.Collections.IDictionary]) { continue }
  219. $combo = @($recipe.combos | Where-Object { $_.platform -eq $t.platform -and $_.display -eq $t.display -and $tc.language -in $_.languages })
  220. if ($combo.Count -eq 0 -and $t.platform -and $t.display -and $t.platform -in $lang.platforms) {
  221. & $conflict 'toolchain' 'toolchain.recipe' ("Recipe '$($tc.recipe)' has no configuration for '$($tc.language)' on $($t.platform)/$($t.display) (target '$($t.id)')." + $ask)
  222. } elseif ($combo.Count -gt 0 -and $combo[0].status -ne 'verified') {
  223. & $warn 'toolchain' 'toolchain.recipe' "Target '$($t.id)': $($tc.recipe) on $($t.platform)/$($t.display) with $($tc.language) has no verified starter yet; the generated docs include a validation plan."
  224. }
  225. }
  226. }
  227. if ($tc.recommended -isnot [System.Collections.IDictionary] -or (Test-Blank $tc.recommended.recipe) -or (Test-Blank $tc.recommended.language)) { & $need 'toolchain' 'toolchain.recommended' "Record the Foundry's default recommendation (recommended.recipe and recommended.language)." }
  228. if (@(Get-List $tc.reasons).Count -eq 0) { & $need 'toolchain' 'toolchain.reasons' 'Explain the language choice in plain English (toolchain.reasons).' }
  229. if (@(Get-List $tc.alternatives).Count -eq 0) { & $need 'toolchain' 'toolchain.alternatives' 'List meaningful alternatives and why they were not chosen.' }
  230. if ($override -is [System.Collections.IDictionary]) {
  231. if ((Test-Blank $override.requestedLanguage) -or (Test-Blank $override.reason)) { & $err 'toolchain' 'toolchain.override' 'An override needs requestedLanguage and reason.' }
  232. elseif (-not $byOverride) { & $err 'toolchain' 'toolchain.override' "The user requested '$($override.requestedLanguage)' but toolchain.language is '$($tc.language)'. An approved override takes precedence: set toolchain.language to the requested language, or record that the user withdrew the override." }
  233. } elseif ($tc.recommended -is [System.Collections.IDictionary] -and $tc.recommended.language -and $tc.language -and $tc.recommended.language -ne $tc.language) {
  234. & $err 'toolchain' 'toolchain.language' "toolchain.language differs from the recommendation but no override is recorded."
  235. }
  236. }
  237. if ($buildLocation -eq 'on-commodore') {
  238. $oc = $Brief.onCommodore
  239. if ($oc -isnot [System.Collections.IDictionary]) { & $need 'toolchain' 'onCommodore' 'On-Commodore build: describe targetTool, transfer method and diskFormat.' }
  240. else {
  241. foreach ($f in 'targetTool', 'transfer') { if (Test-Blank $oc[$f]) { & $need 'toolchain' "onCommodore.$f" "onCommodore.$f is required." } }
  242. if ($oc.diskFormat -notin 'd64', 'd71', 'd81') { & $err 'toolchain' 'onCommodore.diskFormat' 'onCommodore.diskFormat must be d64, d71 or d81.' }
  243. }
  244. }
  245. # --- plan -----------------------------------------------------------------
  246. $st = $Brief.starter
  247. if ($st -isnot [System.Collections.IDictionary]) { & $need 'plan' 'starter' 'starter section (screenTitle, expectedScreen) is required.' }
  248. else {
  249. if (Test-Blank $st.screenTitle) { & $need 'plan' 'starter.screenTitle' 'starter.screenTitle (text shown on the first screen row) is required.' }
  250. elseif ($st.screenTitle -cnotmatch "^[A-Z0-9 .,:!?()+\-*/=#%&<>]{1,38}$") { & $err 'plan' 'starter.screenTitle' "starter.screenTitle must be 1-38 characters of A-Z, 0-9, space and simple punctuation (no quotes); got '$($st.screenTitle)'." }
  251. if (Test-Blank $st.expectedScreen) { & $need 'plan' 'starter.expectedScreen' 'Describe what the starter screen shows (starter.expectedScreen).' }
  252. foreach ($sc in Get-List $st.smokeChecks) {
  253. if ($null -eq $sc.row -or $null -eq $sc.col -or (Test-Blank $sc.text)) { & $err 'plan' 'starter.smokeChecks' 'Each smoke check needs row, col and text.' }
  254. elseif ($sc.text -cnotmatch "^[A-Za-z0-9 .,:!?()+\-*/=#%&<>]{1,80}$") { & $err 'plan' 'starter.smokeChecks' "Smoke check text '$($sc.text)' has unsupported characters." }
  255. foreach ($tid in Get-List $sc.targets) { if ($tid -notin $targetIds) { & $err 'plan' 'starter.smokeChecks' "Smoke check refers to unknown target '$tid'." } }
  256. }
  257. if ($st.filesDir) {
  258. if (-not $BriefPath) { & $warn 'plan' 'starter.filesDir' 'starter.filesDir is set but the brief path is unknown; cannot check it.' }
  259. else {
  260. $fd = Join-Path (Split-Path -Parent $BriefPath) $st.filesDir
  261. if (-not (Test-Path -LiteralPath $fd -PathType Container)) { & $err 'plan' 'starter.filesDir' "starter.filesDir '$($st.filesDir)' does not exist next to the brief." }
  262. }
  263. }
  264. }
  265. $ms = @(Get-List $Brief.milestones)
  266. if ($ms.Count -eq 0) { & $need 'plan' 'milestones' 'At least one milestone (M1, M2, ...) is required. M0 (starter) is added automatically.' }
  267. $covered = @()
  268. $msIds = @()
  269. foreach ($m in $ms) {
  270. if ((Test-Blank $m.id) -or $m.id -cnotmatch '^M[1-9]\d*$') { & $err 'plan' 'milestones' "Milestone id '$($m.id)' must be M1, M2, ... (M0 is generated)."; continue }
  271. if ($m.id -in $msIds) { & $err 'plan' "milestones.$($m.id)" "Duplicate milestone $($m.id)." }
  272. $msIds += $m.id
  273. if ((Test-Blank $m.title) -or (Test-Blank $m.goal)) { & $need 'plan' "milestones.$($m.id)" "$($m.id) needs title and goal." }
  274. $tasks = @(Get-List $m.tasks)
  275. if ($tasks.Count -eq 0) { & $need 'plan' "milestones.$($m.id).tasks" "$($m.id) needs at least one task." }
  276. foreach ($t in $tasks) {
  277. if ((Test-Blank $t.id) -or (Test-Blank $t.text) -or (Test-Blank $t.outcome) -or (Test-Blank $t.check)) { & $need 'plan' "milestones.$($m.id).tasks" "Every task in $($m.id) needs id, text, outcome (buildable result) and check (how completion is verified)." }
  278. $refs = @(Get-List $t.requirements)
  279. if ($refs.Count -eq 0) { & $err 'plan' "milestones.$($m.id).tasks" "Task $($t.id) must link to at least one requirement." }
  280. foreach ($rid in $refs) { if ($rid -notin $reqIds) { & $err 'plan' "milestones.$($m.id).tasks" "Task $($t.id) refers to unknown requirement '$rid'." } else { $covered += $rid } }
  281. }
  282. $tests = @(Get-List $m.manualTests)
  283. if ($tests.Count -eq 0) { & $need 'plan' "milestones.$($m.id).manualTests" "$($m.id) needs at least one manual test." }
  284. foreach ($mt in $tests) {
  285. if ((Test-Blank $mt.id) -or (Test-Blank $mt.setup) -or @(Get-List $mt.steps).Count -eq 0 -or @(Get-List $mt.expected).Count -eq 0) { & $need 'plan' "milestones.$($m.id).manualTests" "Manual test $($mt.id) in $($m.id) needs id, setup, steps and expected observations." }
  286. $tt = if ($mt.target) { $mt.target } else { 'all' }
  287. if ($tt -ne 'all' -and $tt -ne 'real-hardware' -and $tt -notin $targetIds) { & $err 'plan' "milestones.$($m.id).manualTests" "Manual test $($mt.id) targets unknown target '$tt'." }
  288. }
  289. }
  290. foreach ($rid in @(Get-List (Get-Field $Brief 'starter.requirements'))) { if ($rid -notin $reqIds) { & $err 'plan' 'starter.requirements' "starter.requirements refers to unknown requirement '$rid'." } else { $covered += $rid } }
  291. foreach ($rid in $reqIds) { if ($rid -notin $covered -and $ms.Count -gt 0) { & $err 'plan' 'milestones' "Requirement $rid is not linked to any milestone task." } }
  292. # --- destination ------------------------------------------------------------
  293. if (Test-Blank $Brief.destination) { & $need 'destination' 'destination' 'destination (folder for the new project) is required.' }
  294. else {
  295. try { $null = Resolve-FoundryDestination $Brief.destination } catch { & $err 'destination' 'destination' $_.Exception.Message }
  296. }
  297. # --- review -----------------------------------------------------------------
  298. if ($Mode -eq 'Approved') {
  299. if ($Brief.status -ne 'approved') { & $need 'review' 'status' "status must be 'approved' (the user approved the spec) before generation." }
  300. if ((Test-Blank (Get-Field $Brief 'approval.approvedBy')) -or (Test-Blank (Get-Field $Brief 'approval.approvedOn'))) { & $need 'review' 'approval' 'Record approval.approvedBy and approval.approvedOn.' }
  301. } elseif ($Brief.status -notin 'draft', 'approved') { & $err 'review' 'status' "status must be 'draft' or 'approved'." }
  302. # --- summary ----------------------------------------------------------------
  303. $items = $issues.Items
  304. $blocking = @($items | Where-Object { $_.Kind -in 'error', 'conflict' -or ($Mode -eq 'Approved' -and $_.Kind -eq 'missing') })
  305. $missingStages = @($items | Where-Object { $_.Kind -eq 'missing' } | ForEach-Object { $_.Stage } | Select-Object -Unique)
  306. $resume = $script:Stages | Where-Object { $_ -in $missingStages } | Select-Object -First 1
  307. if (-not $resume) {
  308. $problemStages = @($items | Where-Object { $_.Kind -in 'error', 'conflict' } | ForEach-Object { $_.Stage } | Select-Object -Unique)
  309. $resume = $script:Stages | Where-Object { $_ -in $problemStages } | Select-Object -First 1
  310. }
  311. if (-not $resume) { $resume = if ($Brief.status -eq 'approved') { 'generate' } else { 'review' } }
  312. $questions = @(Get-List (Get-Field $Brief 'interview.openQuestions'))
  313. if ($script:StageQuestions.Contains($resume)) { $questions += $script:StageQuestions[$resume] }
  314. [pscustomobject]@{
  315. Valid = ($blocking.Count -eq 0)
  316. Mode = $Mode
  317. Errors = @($items | Where-Object Kind -eq 'error')
  318. Conflicts = @($items | Where-Object Kind -eq 'conflict')
  319. Missing = @($items | Where-Object Kind -eq 'missing')
  320. Warnings = @($items | Where-Object Kind -eq 'warning')
  321. ResumeStage = $resume
  322. NextQuestions = $questions
  323. }
  324. }
  325. function Format-FoundryValidation($Result) {
  326. $lines = @()
  327. $lines += "Validation ($($Result.Mode)): " + $(if ($Result.Valid) { 'OK' } else { 'NOT READY' })
  328. foreach ($c in $Result.Conflicts) { $lines += " CONFLICT [$($c.Path)] $($c.Message)" }
  329. foreach ($e in $Result.Errors) { $lines += " ERROR [$($e.Path)] $($e.Message)" }
  330. foreach ($m in $Result.Missing) { $lines += " MISSING [$($m.Stage)] $($m.Message)" }
  331. foreach ($w in $Result.Warnings) { $lines += " WARNING [$($w.Path)] $($w.Message)" }
  332. $lines += "Resume interview at stage: $($Result.ResumeStage)"
  333. if ($Result.ResumeStage -notin 'generate') {
  334. $lines += 'Next questions:'
  335. foreach ($q in $Result.NextQuestions) { $lines += " - $q" }
  336. }
  337. $lines -join [Environment]::NewLine
  338. }
  339. # ---------------------------------------------------------------------------
  340. # Destination handling
  341. # ---------------------------------------------------------------------------
  342. function Resolve-FoundryDestination([string]$Destination) {
  343. if (Test-Blank $Destination) { throw 'Destination is empty.' }
  344. $raw = [Environment]::ExpandEnvironmentVariables($Destination)
  345. if ($raw.IndexOfAny([char[]]'<>"|?*') -ge 0) { throw "Destination '$Destination' contains a character Windows does not allow in paths (< > "" | ? *)." }
  346. # Check the name as written: Windows path normalization silently drops trailing dots and spaces.
  347. $rawLeaf = ($raw.TrimEnd('\', '/') -split '[\\/]')[-1]
  348. if ($rawLeaf -match '[. ]$') { throw "Destination folder name '$rawLeaf' ends with a dot or space, which Windows does not keep." }
  349. $full = if ([IO.Path]::IsPathRooted($raw)) { [IO.Path]::GetFullPath($raw) } else { [IO.Path]::GetFullPath((Join-Path $script:FoundryRoot $raw)) }
  350. $full = $full.TrimEnd('\', '/')
  351. $leaf = Split-Path $full -Leaf
  352. if ((Test-Blank $leaf) -or $leaf -match '[. ]$') { throw "Destination folder name '$leaf' is empty or ends with a dot or space." }
  353. if ($leaf -match '^(CON|PRN|AUX|NUL|COM\d|LPT\d)(\..*)?$') { throw "Destination folder name '$leaf' is reserved on Windows." }
  354. $root = $script:FoundryRoot.TrimEnd('\', '/')
  355. if ($full -eq $root -or $full.StartsWith($root + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) {
  356. throw "Destination '$full' is inside the Foundry repository. Generate projects into their own folder outside the Foundry."
  357. }
  358. $full
  359. }
  360. function Get-DestinationState([string]$Path) {
  361. if (-not (Test-Path -LiteralPath $Path)) { return 'absent' }
  362. if (Test-Path -LiteralPath $Path -PathType Leaf) { return 'file' }
  363. if (@(Get-ChildItem -LiteralPath $Path -Force).Count -eq 0) { return 'empty' }
  364. if (Test-Path -LiteralPath (Join-Path $Path '.git')) { return 'git-repo' }
  365. 'non-empty'
  366. }
  367. # ---------------------------------------------------------------------------
  368. # Resolution: brief + catalog -> concrete build/run/smoke configuration
  369. # ---------------------------------------------------------------------------
  370. function Get-ProgramName([hashtable]$Brief) {
  371. $n = ($Brief.project.slug -replace '-', '')
  372. if ($n.Length -gt 16) { $n = $n.Substring(0, 16) }
  373. $n
  374. }
  375. function Resolve-FoundryProject([hashtable]$Brief, [hashtable]$Catalog = (Get-FoundryCatalog)) {
  376. $recipe = $Catalog.recipes[$Brief.toolchain.recipe]
  377. $langId = $Brief.toolchain.language
  378. $lang = $Catalog.languages[$langId]
  379. $slug = $Brief.project.slug
  380. $isAsm = $langId -eq 'asm-ca65'
  381. $sameProgram = (Get-Field $Brief 'dualTarget.strategy') -eq 'c64-mode-on-both'
  382. $onboard = $Brief.buildLocation -eq 'on-commodore'
  383. $programName = if ($Brief.onCommodore -and $Brief.onCommodore.programName) { $Brief.onCommodore.programName } else { Get-ProgramName $Brief }
  384. $transferImage = "build/transfer/$slug.$(if ($Brief.onCommodore -and $Brief.onCommodore.diskFormat) { $Brief.onCommodore.diskFormat } else { 'd64' })"
  385. $smokeChecks = @(Get-List $Brief.starter.smokeChecks)
  386. if ($smokeChecks.Count -eq 0) {
  387. $smokeChecks = @(
  388. @{ row = 0; col = 0; text = $Brief.starter.screenTitle; description = 'Title on row 0' },
  389. @{ row = 2; col = 0; text = 'STARTER OK'; description = "'STARTER OK' on row 2" }
  390. )
  391. }
  392. # Emulator options a capability needs on every target (for example a 1351 mouse in control port 1).
  393. $capEmuArgs = @(); $capEmuNotes = @()
  394. foreach ($c in Get-List $Brief.capabilities) {
  395. $ce = if ($Catalog.Contains('capabilityEmulator')) { $Catalog.capabilityEmulator["$c"] } else { $null }
  396. if ($ce) { $capEmuArgs += @($ce.args); if ($ce.note) { $capEmuNotes += "${c}: $($ce.note)" } }
  397. }
  398. # Source files a capability brings along (for example the 1351 mouse reader), when the language and every platform fit.
  399. $capFiles = foreach ($c in Get-List $Brief.capabilities) {
  400. $cf = if ($Catalog.Contains('capabilityFiles')) { $Catalog.capabilityFiles["$c"] } else { $null }
  401. if (-not $cf) { continue }
  402. $fits = ($langId -in @($cf.languages)) -and -not @(Get-List $Brief.targets | Where-Object { $_.platform -notin @($cf.platforms) })
  403. if ($fits) { [ordered]@{ capability = "$c"; dir = $cf.dir; note = $cf.note } }
  404. else { [ordered]@{ capability = "$c"; dir = $null; note = "Not added automatically (it is for $(@($cf.languages) -join '/') on $(@($cf.platforms) -join '/'); see the Foundry's templates/$($cf.dir) for the method). $($cf.note)" } }
  405. }
  406. $toolUse = [ordered]@{}
  407. $addUse = { param($tool, $what) if (-not $toolUse.Contains($tool)) { $toolUse[$tool] = [System.Collections.Generic.List[string]]::new() }; if ($what -notin $toolUse[$tool]) { $toolUse[$tool].Add($what) } }
  408. $targets = foreach ($t in Get-List $Brief.targets) {
  409. $combo = @($recipe.combos | Where-Object { $_.platform -eq $t.platform -and $_.display -eq $t.display -and $langId -in $_.languages })[0]
  410. $artifact = if ($t.artifact) { $t.artifact } elseif ($sameProgram) { "build/$slug.prg" } elseif (@($Brief.targets).Count -eq 1) { "build/$slug.prg" } else { "build/$slug-$($t.id).prg" }
  411. $base = [IO.Path]::ChangeExtension($artifact, $null).TrimEnd('.')
  412. $build = switch ($recipe.buildKind) {
  413. 'cc65' {
  414. $defines = @("FOUNDRY_TARGET_$(($t.id -replace '-', '_').ToUpperInvariant())")
  415. if ($t.display -eq 'vdc-80') { $defines += 'FOUNDRY_VDC80' }
  416. [ordered]@{ kind = 'cc65'; cc65Target = $combo.cc65Target; config = $(if ($isAsm) { "$($combo.cc65Target)-asm.cfg" } else { $null }); defines = $defines; sourceDirs = @('src'); labels = "$base.lbl"; map = "$base.map" }
  417. }
  418. 'petcat' { [ordered]@{ kind = 'petcat'; dialect = $combo.dialect; source = 'src/main.bas' } }
  419. default { [ordered]@{ kind = 'none' } }
  420. }
  421. $disk = $null
  422. $autostart = 'prg'
  423. if ($t.disk) {
  424. $files = foreach ($f in Get-List $t.disk.files) {
  425. $src = if ($f.source -eq '$artifact') { $artifact } else { $f.source }
  426. [ordered]@{ source = $src; name = $f.name; type = $(if ($f.type) { $f.type } else { 'prg' }); convert = $f.convert; lineEndings = $(if ($f.lineEndings) { $f.lineEndings } else { 'cr' }) }
  427. }
  428. $disk = [ordered]@{ image = $(if ($t.disk.image) { $t.disk.image } else { "build/$slug-$($t.id).$(if ($t.disk.format) { $t.disk.format } else { 'd64' })" }); format = $(if ($t.disk.format) { $t.disk.format } else { 'd64' }); name = $t.disk.name; files = @($files) }
  429. $autostart = if ($t.autostart) { $t.autostart } else { 'prg' }
  430. } elseif ($onboard -and $recipe.buildKind -eq 'petcat') {
  431. # On-Commodore BASIC: the smoke test uses the same load-and-run procedure as a person,
  432. # autostarting the transfer disk that tools/to-commodore.ps1 produces.
  433. $disk = [ordered]@{ image = $transferImage; format = $(if ($Brief.onCommodore.diskFormat) { $Brief.onCommodore.diskFormat } else { 'd64' }); name = "$programName,fd"; files = @([ordered]@{ source = $artifact; name = $programName; type = 'prg'; convert = $null; lineEndings = 'keep' }) }
  434. $autostart = 'disk'
  435. }
  436. $smoke = $null
  437. if ($recipe.buildKind -ne 'none' -and $combo.status -eq 'verified') {
  438. $ready = if ($recipe.buildKind -eq 'cc65') { [ordered]@{ kind = 'exec'; symbol = $(if ($isAsm) { 'smoke_ready' } else { '_smoke_ready' }); address = $null } }
  439. else { [ordered]@{ kind = 'store'; symbol = $null; address = $(if ($combo.dialect -eq '70') { '0BFF' } else { '02A7' }) } }
  440. $dumps = @(); $checks = @()
  441. $enc = $lang.screenEncoding
  442. if ($t.display -eq 'vicii-40') {
  443. $dumps += [ordered]@{ name = 'screen'; symbol = $null; address = '0400'; length = 1000 }
  444. foreach ($sc in $smokeChecks) {
  445. if (@(Get-List $sc.targets).Count -gt 0 -and $t.id -notin $sc.targets) { continue }
  446. $checks += [ordered]@{ dump = 'screen'; offset = ([int]$sc.row * 40 + [int]$sc.col); text = $sc.text; encoding = $enc; bytes = $null; description = $(if ($sc.description) { $sc.description } else { "Row $($sc.row): '$($sc.text)'" }) }
  447. }
  448. } elseif ($recipe.buildKind -eq 'cc65' -and -not $isAsm) {
  449. $dumps += [ordered]@{ name = 'probe'; symbol = '_smoke_probe'; address = $null; length = 320 }
  450. foreach ($sc in $smokeChecks) {
  451. if (@(Get-List $sc.targets).Count -gt 0 -and $t.id -notin $sc.targets) { continue }
  452. if ([int]$sc.row -ge 4) { continue }
  453. $checks += [ordered]@{ dump = 'probe'; offset = ([int]$sc.row * 80 + [int]$sc.col); text = $sc.text; encoding = $enc; bytes = $null; description = $(if ($sc.description) { $sc.description } else { "VDC row $($sc.row): '$($sc.text)'" }) }
  454. }
  455. }
  456. if ($t.platform -eq 'c128-native') {
  457. $dumps += [ordered]@{ name = 'mode'; symbol = $null; address = '00D7'; length = 1 }
  458. $checks += [ordered]@{ dump = 'mode'; offset = 0; text = $null; encoding = $null; bytes = $(if ($t.display -eq 'vdc-80') { '80' } else { '00' }); description = $(if ($t.display -eq 'vdc-80') { 'C128 MODE flag $D7 = $80 (80-column screen active)' } else { 'C128 MODE flag $D7 = $00 (40-column screen active)' }) }
  459. } else {
  460. $dumps += [ordered]@{ name = 'vector'; symbol = $null; address = 'FFFC'; length = 2 }
  461. $checks += [ordered]@{ dump = 'vector'; offset = 0; text = $null; encoding = $null; bytes = 'E2 FC'; description = 'C64 KERNAL reset vector at $FFFC (machine is in C64 mode)' }
  462. }
  463. $limit = if ($t.smokeLimitCycles) { [int]$t.smokeLimitCycles } elseif ($autostart -eq 'disk') { 80000000 } else { 30000000 }
  464. $smoke = [ordered]@{ ready = $ready; limitCycles = $limit; dumps = $dumps; checks = $checks; expectedScreen = $Brief.starter.expectedScreen }
  465. }
  466. # tool usage notes for check-prereqs
  467. foreach ($tool in $recipe.tools) {
  468. if ($tool -eq 'c1541' -and $onboard) { & $addUse $tool "transfer disk (tools/to-commodore.ps1, tools/from-commodore.ps1)" ; continue }
  469. & $addUse $tool "build of target $($t.id) (tools/build.ps1)"
  470. }
  471. if ($disk) { & $addUse 'c1541' "disk image for target $($t.id)" }
  472. & $addUse $combo.emulator "run and smoke test of target $($t.id) (tools/run.ps1, tools/smoke.ps1)"
  473. [ordered]@{
  474. id = $t.id; name = $(if ($t.name) { $t.name } else { "$($Catalog.platforms[$t.platform].title), $($Catalog.displays[$t.display])" })
  475. platform = $t.platform; display = $t.display; video = $(if ($t.video -eq 'ntsc') { 'ntsc' } else { 'pal' }); videoSupport = $t.video
  476. artifact = $artifact; expectedBehavior = $t.expectedBehavior
  477. build = $build; disk = $disk
  478. emulator = [ordered]@{ binary = $combo.emulator; args = @($combo.emulatorArgs) + @($capEmuArgs); autostart = $autostart; notes = @($capEmuNotes) }
  479. smoke = $smoke
  480. recipeStatus = $combo.status
  481. validationPlan = @(Get-List $combo.validationPlan)
  482. }
  483. }
  484. $tools = foreach ($id in $toolUse.Keys) {
  485. $c = $Catalog.tools[$id]
  486. [ordered]@{ id = $id; executable = $c.executable; package = $c.package; purpose = $c.purpose; verifiedVersion = $c.verifiedVersion; versionArgs = @($c.versionArgs); envVar = $c.envVar; searchPaths = @($c.searchPaths); install = $c.install; docs = @($c.docs); requiredFor = @($toolUse[$id]) }
  487. }
  488. $onCommodore = $null
  489. if ($onboard) {
  490. $oc = $recipe.onCommodore
  491. $onCommodore = [ordered]@{
  492. kind = $(if ($recipe.buildKind -eq 'petcat') { 'basic' } else { 'files' })
  493. programName = $programName
  494. dialect = $(if ($recipe.buildKind -eq 'petcat') { @($targets)[0].build.dialect } else { $null })
  495. source = $(if ($recipe.buildKind -eq 'petcat') { 'src/main.bas' } else { $null })
  496. image = $transferImage
  497. diskName = "$programName,fd"
  498. diskFormat = $(if ($Brief.onCommodore.diskFormat) { $Brief.onCommodore.diskFormat } else { 'd64' })
  499. files = $(if ($recipe.buildKind -eq 'petcat') { @() } else { @([ordered]@{ source = 'src/STARTER.TXT'; name = 'starter'; type = 'seq'; convert = 'ascii-to-petscii'; lineEndings = 'cr' }) })
  500. returnFiles = $(if ($recipe.buildKind -eq 'petcat') { @() } else { @([ordered]@{ name = $programName; type = 'prg'; dest = "build/$programName.prg" }) })
  501. loadCommand = $(if ($recipe.buildKind -eq 'petcat') { "LOAD`"$($programName.ToUpperInvariant())`",8 then RUN" } else { 'Load your assembler, then load the source file STARTER from drive 8' })
  502. targetTool = $Brief.onCommodore.targetTool
  503. transfer = $Brief.onCommodore.transfer
  504. hostToTarget = $oc.hostToTarget
  505. targetToHost = $oc.targetToHost
  506. }
  507. # The transfer disk needs c1541 even when no target has its own disk.
  508. if (-not ($tools | Where-Object { $_.id -eq 'c1541' })) {
  509. $c = $Catalog.tools['c1541']
  510. $tools = @($tools) + [ordered]@{ id = 'c1541'; executable = $c.executable; package = $c.package; purpose = $c.purpose; verifiedVersion = $c.verifiedVersion; versionArgs = @($c.versionArgs); envVar = $c.envVar; searchPaths = @($c.searchPaths); install = $c.install; docs = @($c.docs); requiredFor = @('transfer disk (tools/to-commodore.ps1, tools/from-commodore.ps1)') }
  511. }
  512. }
  513. [ordered]@{
  514. _note = 'Generated by the C64/C128 Dev Foundry from the approved brief and catalog. tools/*.ps1 read this section; edit it (and docs/toolchain.md) together if the build changes.'
  515. recipe = $Brief.toolchain.recipe
  516. recipeTitle = $recipe.title
  517. language = $langId
  518. languageTitle = $lang.title
  519. starter = $recipe.starters[$langId]
  520. capabilityFiles = @($capFiles)
  521. tools = @($tools)
  522. targets = @($targets)
  523. onCommodore = $onCommodore
  524. catalogVerifiedOn = $Catalog.verifiedOn
  525. catalogVerifiedWith = $Catalog.verifiedWith
  526. sources = @($recipe.sources)
  527. }
  528. }
  529. # ---------------------------------------------------------------------------
  530. # Templates
  531. # ---------------------------------------------------------------------------
  532. function Expand-FoundryTemplate([string]$Text, [hashtable]$Vars, [string]$Name = 'template') {
  533. $missing = [System.Collections.Generic.List[string]]::new()
  534. $out = [regex]::Replace($Text, '\{\{([A-Z0-9_]+)\}\}', {
  535. param($m)
  536. $key = $m.Groups[1].Value
  537. if ($Vars.ContainsKey($key)) { return [string]$Vars[$key] }
  538. $missing.Add($key); return $m.Value
  539. })
  540. if ($missing.Count) { throw "Template '$Name' uses unknown placeholder(s): $(($missing | Select-Object -Unique) -join ', ')" }
  541. $out
  542. }
  543. function Find-UnresolvedPlaceholders([string]$Directory) {
  544. $textExt = '.md', '.json', '.c', '.h', '.s', '.bas', '.txt', '.ps1', '.gitignore', '.gitattributes', '.cfg', '.inc'
  545. Get-ChildItem -LiteralPath $Directory -Recurse -File -Force |
  546. Where-Object { $_.FullName -notmatch '[\\/]\.git[\\/]' -and ($_.Extension -in $textExt -or $_.Name -in '.gitignore', '.gitattributes') } |
  547. ForEach-Object {
  548. $hits = Select-String -LiteralPath $_.FullName -Pattern '\{\{[A-Z0-9_]+\}\}' -AllMatches
  549. foreach ($h in $hits) { [pscustomobject]@{ File = $_.FullName.Substring($Directory.Length + 1); Line = $h.LineNumber; Text = $h.Line.Trim() } }
  550. }
  551. }
  552. function ConvertTo-MdCell([string]$Text) { if ($null -eq $Text) { '' } else { ($Text -replace '\|', '\|' -replace '\r?\n', ' ') } }
  553. function Get-TargetLabel([hashtable]$Catalog, $t) { "$($t.id) ($($Catalog.platforms[$t.platform].title), $($t.display))" }
  554. function New-DocVariables([hashtable]$Brief, $Resolved, [hashtable]$Catalog, [string]$Destination) {
  555. $nl = "`n"
  556. $p = $Brief.project
  557. $targets = @($Resolved.targets)
  558. $firstTarget = $targets[0]
  559. $v = @{}
  560. $v.PROJECT_NAME = $p.name
  561. $v.PROJECT_SLUG = $p.slug
  562. $v.PROJECT_SUMMARY = $p.summary
  563. $v.PROJECT_IDEA = $p.idea
  564. $v.SMALLEST_VERSION = $p.smallestUsefulVersion
  565. $v.PROJECT_KIND = $p.kind
  566. $v.SCREEN_TITLE = $Brief.starter.screenTitle
  567. $v.SCREEN_TITLE_LOWER = $Brief.starter.screenTitle.ToLowerInvariant()
  568. $v.PROJECT_NAME_LOWER = ($p.name.ToLowerInvariant() -replace '[^a-z0-9 .,:!?()+\-*/=#%&<>]', '')
  569. $v.GENERATED_ON = (Get-Date -Format 'yyyy-MM-dd')
  570. $v.APPROVED_BY = $Brief.approval.approvedBy
  571. $v.APPROVED_ON = $Brief.approval.approvedOn
  572. $v.LANGUAGE_TITLE = $Resolved.languageTitle
  573. $v.RECIPE_TITLE = $Resolved.recipeTitle
  574. $v.RECIPE_ID = $Resolved.recipe
  575. $v.BUILD_LOCATION = $(if ($Brief.buildLocation -eq 'on-commodore') { 'On the Commodore (repository kept on the Windows host)' } else { 'Windows cross-development' })
  576. $v.FIRST_TARGET = $firstTarget.id
  577. $v.EXPECTED_SCREEN = $Brief.starter.expectedScreen
  578. $v.FIRST_RELEASE = $Brief.scope.firstRelease
  579. $v.HANDOFF_MESSAGE = 'Read AGENTS.md and follow it. Build and verify the starter (milestone M0) first, then implement the next milestone one task at a time, reporting after each task what changed, which checks ran, and exactly how I should verify it.'
  580. # Targets table
  581. $rows = @('| Target | Machine / mode | Display | Video | Artifact | Expected behavior |', '|---|---|---|---|---|---|')
  582. foreach ($t in $targets) {
  583. $rows += "| ``$($t.id)`` | $($Catalog.platforms[$t.platform].title) | $(ConvertTo-MdCell $Catalog.displays[$t.display]) | $($t.videoSupport) | ``$($t.artifact)`` | $(ConvertTo-MdCell $t.expectedBehavior) |"
  584. }
  585. $v.TARGETS_TABLE = $rows -join $nl
  586. $dual = $Brief.dualTarget
  587. $v.DUAL_TARGET = if ($dual -and $dual.strategy) {
  588. $desc = switch ($dual.strategy) {
  589. 'c64-mode-on-both' { 'One C64 program. The C128 runs it in C64 mode (GO 64, or hold the Commodore key at power-on); no native C128 build.' }
  590. 'native-per-target' { 'Separate builds from shared source: a C64 program and a native C128 program.' }
  591. 'multi-display' { 'One native C128 program with separate 40-column and 80-column targets that are verified independently.' }
  592. }
  593. "**Strategy:** ``$($dual.strategy)`` - $desc$nl$nl$($dual.notes)"
  594. } else { 'Single target.' }
  595. $displayNotes = foreach ($t in $targets) {
  596. switch ($t.display) {
  597. 'vicii-40' { "- ``$($t.id)``: VIC-II 40x25 screen. Screen RAM at `$0400 by default. $(if ($t.platform -eq 'c128-native') { 'On a C128 this is the 40-column (composite/RF) output; the 40/80 DISPLAY key must be up, or the program switches with videomode().' } else { '' })" }
  598. 'vdc-80' { "- ``$($t.id)``: VDC 80x25 text screen on the C128 RGBI output. Not memory-mapped: all screen access goes through `$D600/`$D601. 40/80 DISPLAY key down (VICE: -80col). In VICE the 80-column output appears in its own window." }
  599. }
  600. }
  601. $v.DISPLAY_NOTES = $displayNotes -join $nl
  602. # Scope
  603. $v.IN_SCOPE = @(Get-List $Brief.scope.inScope | ForEach-Object { "- $_" }) -join $nl
  604. $v.OUT_OF_SCOPE = @(Get-List $Brief.scope.outOfScope | ForEach-Object { "- $_" }) -join $nl
  605. # Requirements
  606. $req = foreach ($r in Get-List $Brief.requirements) {
  607. $caps = @(Get-List $r.capabilities)
  608. $lines = @("### $($r.id) - $($r.title) ($($r.priority))", '', $r.text, '', 'Acceptance criteria:')
  609. $n = 0
  610. foreach ($a in Get-List $r.acceptance) { $n++; $lines += "- [$($r.id).$n] $a" }
  611. if ($caps.Count) { $lines += ''; $lines += "Capabilities: $($caps -join ', ')" }
  612. $lines -join $nl
  613. }
  614. $v.REQUIREMENTS = $req -join ($nl + $nl)
  615. # Design decisions
  616. $labels = @{ controls = 'Controls'; visuals = 'Visuals'; sound = 'Sound'; persistence = 'Persistence (save/load)'; fileFormats = 'File formats'; peripherals = 'Peripherals'; budgets = 'Timing and memory budgets' }
  617. $srcLabel = @{ user = 'decided by user'; default = 'practical default'; 'n/a' = 'not applicable'; open = 'UNRESOLVED' }
  618. $design = @('| Topic | Decision | Source |', '|---|---|---|')
  619. foreach ($topic in $script:DesignTopics) {
  620. $e = $Brief.design[$topic]
  621. $design += "| $($labels[$topic]) | $(ConvertTo-MdCell $e.value) | $($srcLabel[$e.source]) |"
  622. }
  623. foreach ($o in Get-List $Brief.design.other) { $design += "| $(ConvertTo-MdCell $o.topic) | $(ConvertTo-MdCell $o.value) | $($srcLabel[$o.source]) |" }
  624. $v.DESIGN_TABLE = $design -join $nl
  625. $v.CAPABILITIES = if (@(Get-List $Brief.capabilities).Count) { @(Get-List $Brief.capabilities | ForEach-Object { "- ``$_``: $($Catalog.capabilities[$_])" }) -join $nl } else { '- (none beyond plain text output)' }
  626. $v.ASSUMPTIONS = if (@(Get-List $Brief.assumptions).Count) {
  627. (@('| ID | Assumption | Status |', '|---|---|---|') + @(Get-List $Brief.assumptions | ForEach-Object { "| $($_.id) | $(ConvertTo-MdCell $_.text) | $($_.status) |" })) -join $nl
  628. } else { '- None recorded.' }
  629. $v.OPEN_DECISIONS = if (@(Get-List $Brief.openDecisions).Count) {
  630. (@('| ID | Question | Default until decided | Status |', '|---|---|---|---|') + @(Get-List $Brief.openDecisions | ForEach-Object { "| $($_.id) | $(ConvertTo-MdCell $_.question) | $(ConvertTo-MdCell $_.default) | $($_.status) |" })) -join $nl
  631. } else { '- None. Every decision in this spec is settled.' }
  632. $rh = $Brief.testing.realHardware
  633. $v.REAL_HARDWARE = if ($rh.requested) { "Requested. Reason: $($rh.reason)" } else { 'Not requested for this release. VICE is the reference environment; real-hardware steps in docs/manual-tests.md are optional.' }
  634. # Toolchain
  635. $tc = $Brief.toolchain
  636. $v.TOOLCHAIN_REASONS = @(Get-List $tc.reasons | ForEach-Object { "- $_" }) -join $nl
  637. $v.TOOLCHAIN_ALTERNATIVES = (@('| Alternative | Why not chosen |', '|---|---|') + @(Get-List $tc.alternatives | ForEach-Object { "| $(ConvertTo-MdCell $_.option) | $(ConvertTo-MdCell $_.whyNot) |" })) -join $nl
  638. $v.TOOLCHAIN_RECOMMENDED = "``$($tc.recommended.recipe)`` / ``$($tc.recommended.language)`` ($($Catalog.languages[$tc.recommended.language].title))"
  639. $v.TOOLCHAIN_OVERRIDE = if ($tc.override -and $tc.override.requestedLanguage) {
  640. "**User override (approved):** the user asked for ``$($tc.override.requestedLanguage)`` instead of the recommendation. Reason given: $($tc.override.reason) The override is compatible with every target and required capability, so it takes precedence."
  641. } else { 'No user override. The recommended language is used.' }
  642. $v.TOOLCHAIN_VERIFY = if (@(Get-List $tc.assumptionsToVerify).Count) { @(Get-List $tc.assumptionsToVerify | ForEach-Object { "- [ ] $_" }) -join $nl } else { '- [ ] None beyond the starter verification below.' }
  643. $toolRows = @('| Tool | Purpose | Verified version | Install source | First command if missing | Override variable |', '|---|---|---|---|---|---|')
  644. foreach ($t in $Resolved.tools) { $toolRows += "| ``$($t.executable)`` | $(ConvertTo-MdCell $t.purpose) | $($t.verifiedVersion) | $($t.install.source) | $(ConvertTo-MdCell $t.install.firstCommand) | ``$($t.envVar)`` |" }
  645. $v.TOOLS_TABLE = $toolRows -join $nl
  646. $cmdRows = foreach ($t in $targets) {
  647. $b = $t.build
  648. $buildCmd = switch ($b.kind) {
  649. 'cc65' { "cl65 -t $($b.cc65Target) -g $(if ($b.config) { "-C $($b.config) -u __EXEHDR__" } else { '-O' }) $(($b.defines | ForEach-Object { "-D $_" }) -join ' ') -I src -o $($t.artifact) -Ln $($b.labels) -m $($b.map) src/*.c src/*.s" }
  650. 'petcat' { "petcat -w$($b.dialect) -f -o $($t.artifact) -- $($b.source)" }
  651. default { '(built on the Commodore - see On-Commodore workflow)' }
  652. }
  653. $emuArgs = (@(if ($t.video -eq 'ntsc') { '-ntsc' } else { '-pal' }) + @($t.emulator.args)) -join ' '
  654. $runFile = if ($t.emulator.autostart -eq 'disk') { $t.disk.image } else { $t.artifact }
  655. $lines = @("### Target ``$($t.id)``", '', "- Status: **$($t.recipeStatus)** starter configuration ($($Resolved.recipe), $($t.platform)/$($t.display), $($Resolved.language))",
  656. "- Build (what tools/build.ps1 runs): ``$buildCmd``")
  657. if ($t.disk) { $lines += "- Disk image: ``$($t.disk.image)`` ($($t.disk.format), header ``$($t.disk.name)``), files: $((@($t.disk.files) | ForEach-Object { "$($_.name) ($($_.type))" }) -join ', ')" }
  658. $lines += "- Emulator: ``$($t.emulator.binary) $emuArgs -autostart $runFile``"
  659. foreach ($note in @(Get-List $t.emulator.notes)) { $lines += "- Emulator note - $note" }
  660. foreach ($cf in @(Get-List $Resolved.capabilityFiles)) { $lines += "- Capability $($cf.capability) - $($cf.note)" }
  661. if ($t.smoke) {
  662. $readyText = if ($t.smoke.ready.symbol) { '`' + $t.smoke.ready.symbol + '`' } else { 'its marker store to $' + $t.smoke.ready.address }
  663. $lines += "- Smoke test: ``pwsh -File tools/smoke.ps1 -Target $($t.id)``. It runs VICE headless for $($t.smoke.limitCycles) cycles, saves memory when the program reaches $readyText, and checks:"
  664. foreach ($c in $t.smoke.checks) { $lines += " - $($c.description)" }
  665. if ($t.display -eq 'vdc-80' -and -not ($t.smoke.checks | Where-Object { $_.text })) { $lines += ' - (80-column text is not readable from CPU memory in this recipe: inspect build/smoke/' + $t.id + '/screen.png)' }
  666. } else {
  667. $lines += '- Smoke test: none automated. Verification is manual (docs/manual-tests.md, M0).'
  668. }
  669. if (@($t.validationPlan).Count) {
  670. $lines += ''; $lines += 'Validation plan (no verified starter yet for this configuration):'
  671. $n = 0; foreach ($s in $t.validationPlan) { $n++; $lines += "$n. $s" }
  672. }
  673. $lines -join $nl
  674. }
  675. $v.TARGET_COMMANDS = $cmdRows -join ($nl + $nl)
  676. $vw = $Resolved.catalogVerifiedWith
  677. $v.CATALOG_VERIFIED = "Starter configurations marked verified were exercised by the Foundry's automated checks on $($Resolved.catalogVerifiedOn) with $($vw.cc65), $($vw.vice), $($vw.powershell) on $($vw.os)."
  678. $v.SOURCES = ($Resolved.sources + @($Resolved.tools | ForEach-Object { $_.install.source }) | Select-Object -Unique | ForEach-Object { "- $_" }) -join $nl
  679. if ($Resolved.onCommodore) {
  680. $oc = $Resolved.onCommodore
  681. $v.ON_COMMODORE = @(
  682. '## On-Commodore workflow', '',
  683. 'The Git repository stays on the Windows host. Authoring (and, for compiled languages, building) happens on the Commodore or in VICE; disk images carry the work back and forth.', '',
  684. "- Target-side tool: $($oc.targetTool)",
  685. "- Transfer method: $($oc.transfer)",
  686. "- Disk format: ``$($oc.diskFormat)``, transfer image ``$($oc.image)`` (header ``$($oc.diskName)``)",
  687. "- Program file on disk: ``$($oc.programName)``", '',
  688. '### Host to Commodore', '', $oc.hostToTarget, '',
  689. '```powershell', 'pwsh -File tools/to-commodore.ps1', '```', '',
  690. "Then on the Commodore (VICE: attach the image to drive 8): ``$($oc.loadCommand)``.", '',
  691. '### Commodore to host', '', $oc.targetToHost, '',
  692. '```powershell', 'pwsh -File tools/from-commodore.ps1', 'git diff', '```', '',
  693. 'Never edit the same program on both sides at once: pull the Commodore copy back (and commit) before editing on the host, and run to-commodore.ps1 before editing on the Commodore.'
  694. ) -join $nl
  695. } else { $v.ON_COMMODORE = '' }
  696. # Milestones
  697. $m0 = @{ id = 'M0'; title = 'Starter builds and runs'; goal = 'Prove the toolchain, emulator configuration and smoke test work before any feature work.'
  698. tasks = @(@{ id = 'M0.1'; text = 'Run tools/check-prereqs.ps1, then tools/smoke.ps1 for every target.'; requirements = @(Get-List $Brief.starter.requirements); outcome = "Starter artifact(s) built: $((@($targets | ForEach-Object { $_.artifact }) | Select-Object -Unique) -join ', ')"; check = 'tools/smoke.ps1 exits 0 (or every target without automation is verified by hand), and the user confirms the M0 manual test.' }) }
  699. $milestones = @($m0) + @(Get-List $Brief.milestones)
  700. $ml = foreach ($m in $milestones) {
  701. $reqs = @($m.tasks | ForEach-Object { Get-List $_.requirements } | Select-Object -Unique)
  702. $lines = @("## $($m.id) - $($m.title)", '', "Goal: $($m.goal)", '', "Requirements: $(if ($reqs.Count) { $reqs -join ', ' } else { '(foundation)' })", '', '| Task | Description | Requirements | Buildable outcome | Completion check |', '|---|---|---|---|---|')
  703. foreach ($t in $m.tasks) { $lines += "| $($t.id) | $(ConvertTo-MdCell $t.text) | $(@(Get-List $t.requirements) -join ', ') | $(ConvertTo-MdCell $t.outcome) | $(ConvertTo-MdCell $t.check) |" }
  704. $lines += ''; $lines += "Manual verification: see docs/manual-tests.md section $($m.id)."
  705. $lines -join $nl
  706. }
  707. $v.MILESTONES = $ml -join ($nl + $nl)
  708. $v.NEXT_MILESTONE = if (@(Get-List $Brief.milestones).Count) { "$($Brief.milestones[0].id) - $($Brief.milestones[0].title)" } else { 'none' }
  709. # Manual tests
  710. $mt = @()
  711. $mt += '## M0 - Starter builds and runs'
  712. foreach ($t in $targets) {
  713. $runFile = if ($t.emulator.autostart -eq 'disk') { $t.disk.image } else { $t.artifact }
  714. $mt += ''
  715. $mt += "### MT0-$($t.id): starter on $(Get-TargetLabel $Catalog $t)"
  716. $mt += ''
  717. $mt += "Setup: prerequisites installed (``pwsh -File tools/check-prereqs.ps1`` reports no missing tools)."
  718. $mt += ''
  719. $mt += 'Steps:'
  720. if ($t.build.kind -eq 'none') {
  721. $mt += '1. Run `pwsh -File tools/to-commodore.ps1` and attach the transfer image to drive 8.'
  722. $mt += "2. Follow the validation plan in docs/toolchain.md for target ``$($t.id)``: load the assembler, assemble src/STARTER.TXT, save and run it."
  723. } else {
  724. $mt += "1. Run ``pwsh -File tools/smoke.ps1 -Target $($t.id)``$(if ($t.smoke) { ' and note the result.' } else { '.' })"
  725. $mt += "2. Run ``pwsh -File tools/run.ps1 -Target $($t.id)`` (VICE starts and autostarts ``$runFile``)."
  726. if ($t.display -eq 'vdc-80') { $mt += '3. Look at the VDC (80-column) window. If VICE shows only one window, use View > Show VDC window / switch to the VDC display.' }
  727. }
  728. $mt += ''
  729. $mt += 'Expected:'
  730. if ($t.smoke) { $mt += "- tools/smoke.ps1 prints ``[PASS] $($t.id)``; screenshot in build/smoke/$($t.id)/." }
  731. $mt += "- $($Brief.starter.expectedScreen)"
  732. $mt += "- $($t.expectedBehavior)"
  733. }
  734. foreach ($m in Get-List $Brief.milestones) {
  735. $mt += ''; $mt += "## $($m.id) - $($m.title)"
  736. foreach ($test in Get-List $m.manualTests) {
  737. $tt = if ($test.target) { $test.target } else { 'all' }
  738. $applies = if ($tt -eq 'all') { @($targets | ForEach-Object { $_.id }) } else { @($tt) }
  739. foreach ($tid in $applies) {
  740. $title = if ($tid -eq 'real-hardware') { 'real hardware' } else { $tid }
  741. $mt += ''; $mt += "### $($test.id)$(if ($applies.Count -gt 1) { "-$tid" }): $($test.title) ($title)"
  742. $mt += ''; $mt += "Setup: $($test.setup)"
  743. if ($tid -ne 'real-hardware') {
  744. $t = $targets | Where-Object { $_.id -eq $tid }
  745. $mt += "Start: ``pwsh -File tools/run.ps1 -Target $tid``"
  746. }
  747. $mt += ''; $mt += 'Steps:'
  748. $n = 0; foreach ($s in Get-List $test.steps) { $n++; $mt += "$n. $s" }
  749. $mt += ''; $mt += 'Expected:'
  750. foreach ($e in Get-List $test.expected) { $mt += "- $e" }
  751. if ($test.requirements) { $mt += ''; $mt += "Verifies: $(@(Get-List $test.requirements) -join ', ')" }
  752. }
  753. }
  754. }
  755. $mt += ''; $mt += '## Real hardware'
  756. $mt += ''
  757. if ($rh.requested) { $mt += "Real-hardware verification is **required** for this project: $($rh.reason)" } else { $mt += 'Optional for this release. Use these steps when hardware is available.' }
  758. $mt += ''
  759. $mt += '1. Build: `pwsh -File tools/build.ps1`.'
  760. $mt += '2. Get the program onto a disk the machine can read, for example: copy the .prg (or .d64) to an SD2IEC/Pi1541/1541 Ultimate SD card; or write the .d64 to a real floppy with a ZoomFloppy/XUM1541 and OpenCBM (`d64copy build\<image>.d64 8`).'
  761. $mt += "3. On the machine: ``LOAD`"*`",8`` then ``RUN`` (a C128 in native mode can also use ``RUN`"name`"``). For C64-mode targets on a C128, enter C64 mode first (``GO 64``, then ``Y``)."
  762. $mt += '4. Repeat the manual tests for the current milestone and note any difference from VICE (timing, colours, display artefacts, disk speed) in docs/verification-status.md.'
  763. $v.MANUAL_TESTS = $mt -join $nl
  764. # Verification status
  765. $vs = @('| Item | Automated check | Manual verification by user |', '|---|---|---|')
  766. foreach ($m in $milestones) {
  767. foreach ($t in $m.tasks) { $vs += "| $($t.id) $(ConvertTo-MdCell $t.text) | not run | pending |" }
  768. }
  769. $v.VERIFICATION_TABLE = $vs -join $nl
  770. $v.TARGET_LIST = (@($targets | ForEach-Object { "``$($_.id)``" })) -join ', '
  771. $v.TOOL_LIST = (@($Resolved.tools | ForEach-Object { $_.executable }) + 'PowerShell 7', 'git') -join ', '
  772. $v.DESTINATION = $Destination
  773. $v.ON_COMMODORE_README = if ($Resolved.onCommodore) { @('', '## Working on the Commodore', '', "This project is authored on the Commodore. Move work with ``pwsh -File tools/to-commodore.ps1`` (host to disk image) and ``pwsh -File tools/from-commodore.ps1`` (disk image to host). Details: docs/toolchain.md, On-Commodore workflow.") -join $nl } else { '' }
  774. $v.ON_COMMODORE_AGENTS = if ($Resolved.onCommodore) { @('', '## On-Commodore projects', '', '- The source of truth is the repository, but the user may edit the program on the Commodore. Before you edit `' + $Resolved.onCommodore.source + '`, ask whether there is newer work on the transfer disk, and if so have them run `pwsh -File tools/from-commodore.ps1` first.', '- After you change source, run `pwsh -File tools/to-commodore.ps1` so the user can load the new version on the machine, and say so in your report.') -join $nl } else { '' }
  775. $v
  776. }
  777. # ---------------------------------------------------------------------------
  778. # Generation
  779. # ---------------------------------------------------------------------------
  780. function Copy-TemplateTree([string]$From, [string]$To, [hashtable]$Vars) {
  781. if (-not (Test-Path -LiteralPath $From)) { return }
  782. foreach ($f in Get-ChildItem -LiteralPath $From -Recurse -File -Force) {
  783. if ($f.Name -eq 'starter.json') { continue }
  784. $rel = $f.FullName.Substring($From.Length + 1)
  785. if ($rel.EndsWith('.tmpl')) {
  786. $rel = $rel.Substring(0, $rel.Length - 5)
  787. $dest = Join-Path $To $rel
  788. New-Item -ItemType Directory -Force -Path (Split-Path $dest -Parent) | Out-Null
  789. $text = Expand-FoundryTemplate (Get-Content -LiteralPath $f.FullName -Raw) $Vars $rel
  790. [IO.File]::WriteAllText($dest, $text, [Text.UTF8Encoding]::new($false))
  791. } else {
  792. $dest = Join-Path $To $rel
  793. New-Item -ItemType Directory -Force -Path (Split-Path $dest -Parent) | Out-Null
  794. Copy-Item -LiteralPath $f.FullName -Destination $dest -Force
  795. }
  796. }
  797. }
  798. function Remove-StaleStaging([string]$Parent, [string]$Leaf) {
  799. if (-not (Test-Path -LiteralPath $Parent)) { return @() }
  800. $removed = @()
  801. foreach ($d in Get-ChildItem -LiteralPath $Parent -Directory -Force -Filter ".$Leaf.foundry-staging-*") {
  802. Remove-Item -LiteralPath $d.FullName -Recurse -Force
  803. $removed += $d.FullName
  804. }
  805. $removed
  806. }
  807. function Invoke-Git([string]$Dir, [string[]]$GitArgs, [switch]$AllowFail) {
  808. $out = & git -C $Dir @GitArgs 2>&1 | ForEach-Object { "$_" }
  809. if ($LASTEXITCODE -ne 0 -and -not $AllowFail) { throw "git $($GitArgs -join ' ') failed: $($out -join ' ')" }
  810. , @($out)
  811. }
  812. function New-FoundryProject {
  813. <#
  814. .SYNOPSIS Generate a handoff repository from an approved brief.
  815. #>
  816. [CmdletBinding()]
  817. param(
  818. [Parameter(Mandatory)][string]$BriefPath,
  819. [string]$Destination,
  820. [switch]$SkipVerify,
  821. [string]$FailAfterStep # test hook: simulate an interruption after the named step
  822. )
  823. $catalog = Get-FoundryCatalog
  824. $BriefPath = (Resolve-Path -LiteralPath $BriefPath).ProviderPath
  825. $brief = Read-FoundryJson $BriefPath
  826. if ($Destination) { $brief.destination = $Destination }
  827. # 1. Validate inputs
  828. $validation = Test-FoundryBrief -Brief $brief -Mode Approved -BriefPath $BriefPath -Catalog $catalog
  829. if (-not $validation.Valid) { throw ("The brief is not ready for generation.`n" + (Format-FoundryValidation $validation)) }
  830. if (-not (Get-Command git -ErrorAction SilentlyContinue)) { throw 'git was not found on PATH. Install it first: winget install --id Git.Git -e' }
  831. # 2. Validate destination
  832. $dest = Resolve-FoundryDestination $brief.destination
  833. $state = Get-DestinationState $dest
  834. switch ($state) {
  835. 'file' { throw "Destination '$dest' is an existing file. Nothing was written." }
  836. 'git-repo' { throw "Destination '$dest' already contains a Git repository. The Foundry never overwrites an existing project; choose another folder. Nothing was written." }
  837. 'non-empty' { throw "Destination '$dest' already exists and is not empty. The Foundry never overwrites existing work; choose another folder or move the existing one yourself. Nothing was written." }
  838. }
  839. $parent = Split-Path $dest -Parent
  840. $leaf = Split-Path $dest -Leaf
  841. New-Item -ItemType Directory -Force -Path $parent | Out-Null
  842. $stale = Remove-StaleStaging $parent $leaf
  843. $staging = Join-Path $parent (".$leaf.foundry-staging-" + (Get-Date -Format 'yyyyMMddHHmmss') + '-' + [Guid]::NewGuid().ToString('N').Substring(0, 6))
  844. $published = $false
  845. $resolved = Resolve-FoundryProject $brief $catalog
  846. $step = { param($name) if ($FailAfterStep -eq $name) { throw "Simulated interruption after step '$name' (test hook)." } }
  847. try {
  848. New-Item -ItemType Directory -Path $staging | Out-Null
  849. $vars = New-DocVariables $brief $resolved $catalog $dest
  850. $tpl = Join-Path $script:FoundryRoot 'templates'
  851. # 3. Common files and docs
  852. Copy-TemplateTree (Join-Path $tpl 'repo') $staging $vars
  853. # Knowledge Engine: one skill file serves the Foundry and every generated project.
  854. Copy-TemplateTree (Join-Path $script:FoundryRoot 'skills/knowledge-management') (Join-Path $staging 'skills/knowledge-management') $vars
  855. if (-not $resolved.onCommodore) {
  856. Remove-Item -LiteralPath (Join-Path $staging 'tools/to-commodore.ps1'), (Join-Path $staging 'tools/from-commodore.ps1') -Force
  857. }
  858. & $step 'templates'
  859. # 4. Starter source: recipe default, then project-specific files on top
  860. $starterDir = Join-Path $tpl "starters/$($resolved.starter)"
  861. $manifest = Join-Path $starterDir 'starter.json'
  862. if (Test-Path -LiteralPath $manifest) {
  863. foreach ($inc in (Read-FoundryJson $manifest).include) { Copy-TemplateTree (Join-Path $tpl "starters/$inc") $staging $vars }
  864. }
  865. Copy-TemplateTree $starterDir $staging $vars
  866. foreach ($cf in @(Get-List $resolved.capabilityFiles | Where-Object { $_.dir })) { Copy-TemplateTree (Join-Path $tpl $cf.dir) $staging $vars }
  867. if ($brief.starter.filesDir) {
  868. $filesDir = (Resolve-Path -LiteralPath (Join-Path (Split-Path $BriefPath -Parent) $brief.starter.filesDir)).ProviderPath
  869. Copy-TemplateTree $filesDir $staging $vars
  870. }
  871. foreach ($dir in 'src', 'fixtures') { New-Item -ItemType Directory -Force -Path (Join-Path $staging $dir) | Out-Null }
  872. if (-not (Get-ChildItem -LiteralPath (Join-Path $staging 'fixtures') -Force)) {
  873. Set-Content -LiteralPath (Join-Path $staging 'fixtures/README.md') -Value "# Fixtures`n`nSample inputs for tests go here. Files in this folder are stored byte-for-byte (see .gitattributes)."
  874. }
  875. # 5. project.json = approved brief + resolved configuration
  876. $project = [ordered]@{}
  877. foreach ($k in $brief.Keys) { $project[$k] = $brief[$k] }
  878. $project.destination = $dest
  879. $project.generated = [ordered]@{ by = 'C64/C128 Dev Foundry'; foundryVersion = '1.0'; on = (Get-Date -Format 'yyyy-MM-dd'); fromBrief = (Split-Path $BriefPath -Leaf); foundryRoot = $script:FoundryRoot }
  880. $project.resolved = $resolved
  881. [IO.File]::WriteAllText((Join-Path $staging 'project.json'), ($project | ConvertTo-Json -Depth 64), [Text.UTF8Encoding]::new($false))
  882. & $step 'files'
  883. # 6. Template completeness
  884. $unresolved = @(Find-UnresolvedPlaceholders $staging)
  885. if ($unresolved.Count) { throw ("Unresolved template placeholders:`n" + (($unresolved | ForEach-Object { " $($_.File):$($_.Line) $($_.Text)" }) -join "`n")) }
  886. # 7. Git
  887. Invoke-Git $staging @('init', '-q', '-b', 'main') | Out-Null
  888. Invoke-Git $staging @('add', '-A') | Out-Null
  889. $name = (Invoke-Git $staging @('config', 'user.name') -AllowFail) -join ''
  890. $email = (Invoke-Git $staging @('config', 'user.email') -AllowFail) -join ''
  891. $committed = $false
  892. if ($name -and $email) {
  893. Invoke-Git $staging @('commit', '-q', '--no-verify', '-m', "Initial handoff from the C64/C128 Dev Foundry`n`nApproved spec: $($brief.project.name). Starter (milestone M0) plus implementation docs.") | Out-Null
  894. $committed = $true
  895. }
  896. & $step 'git'
  897. # 8. Publish
  898. if ($state -eq 'empty') { Remove-Item -LiteralPath $dest -Force }
  899. Move-Item -LiteralPath $staging -Destination $dest
  900. $published = $true
  901. } finally {
  902. if (-not $published -and (Test-Path -LiteralPath $staging)) { Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue }
  903. if (-not $published -and $state -eq 'empty' -and -not (Test-Path -LiteralPath $dest)) { New-Item -ItemType Directory -Path $dest | Out-Null }
  904. }
  905. # 9. Starter verification in the published repo
  906. $verification = [ordered]@{ status = 'skipped'; exitCode = $null; output = @() }
  907. if (-not $SkipVerify) {
  908. $out = & pwsh -NoProfile -File (Join-Path $dest 'tools/smoke.ps1') 2>&1 | ForEach-Object { "$_" }
  909. $code = $LASTEXITCODE
  910. $verification.exitCode = $code
  911. $verification.output = @($out)
  912. $verification.status = switch ($code) { 0 { 'passed' } 1 { 'failed' } 2 { 'not run: missing tool' } 3 { 'manual verification only' } default { "unknown (exit $code)" } }
  913. }
  914. [pscustomobject]@{
  915. Destination = $dest
  916. Committed = $committed
  917. StaleRemoved = @($stale)
  918. Warnings = @($validation.Warnings | ForEach-Object { $_.Message })
  919. Verification = $verification
  920. HandoffMessage = $vars.HANDOFF_MESSAGE
  921. Targets = @($resolved.targets | ForEach-Object { [pscustomobject]@{ Id = $_.id; Artifact = $_.artifact; Status = $_.recipeStatus } })
  922. }
  923. }
  924. function Format-FoundrySpecPreview {
  925. <#
  926. .SYNOPSIS Markdown summary of a brief for the user to approve before generation (interview step 4).
  927. #>
  928. param([Parameter(Mandatory)][hashtable]$Brief, [string]$BriefPath, [hashtable]$Catalog = (Get-FoundryCatalog))
  929. $check = Test-FoundryBrief -Brief $Brief -Mode Draft -BriefPath $BriefPath -Catalog $Catalog
  930. $blocking = @($check.Missing | Where-Object { $_.Stage -ne 'review' }) + @($check.Errors) + @($check.Conflicts)
  931. if ($blocking.Count) { throw ("The brief is not complete enough to preview.`n" + (Format-FoundryValidation $check)) }
  932. $resolved = Resolve-FoundryProject $Brief $Catalog
  933. $dest = Resolve-FoundryDestination $Brief.destination
  934. $v = New-DocVariables $Brief $resolved $Catalog $dest
  935. $m1 = @(Get-List $Brief.milestones)[0]
  936. $lines = @(
  937. "# Proposed spec: $($Brief.project.name)", '',
  938. $Brief.project.summary, '',
  939. "**Smallest useful version:** $($Brief.project.smallestUsefulVersion)", '',
  940. '## Scope', '', "**First release:** $($Brief.scope.firstRelease)", '', '**In scope**', $v.IN_SCOPE, '', '**Out of scope**', $v.OUT_OF_SCOPE, '',
  941. '## Target and toolchain', '', $v.TARGETS_TABLE, '', $v.DUAL_TARGET, '',
  942. "- Language: **$($resolved.languageTitle)** via $($resolved.recipeTitle)",
  943. "- Build location: $($v.BUILD_LOCATION)",
  944. "- Testing: VICE; real hardware: $($v.REAL_HARDWARE)",
  945. "- $($v.TOOLCHAIN_OVERRIDE)", '', 'Why:', $v.TOOLCHAIN_REASONS, '',
  946. (($resolved.targets | ForEach-Object { "- Starter for ``$($_.id)``: **$($_.recipeStatus)** configuration$(if (@($_.validationPlan).Count) { ' (validation plan included)' })" }) -join "`n"), '',
  947. '## Design decisions', '', $v.DESIGN_TABLE, '',
  948. '## Assumptions', '', $v.ASSUMPTIONS, '',
  949. '## Unresolved decisions', '', $v.OPEN_DECISIONS, '',
  950. '## Acceptance checks', ''
  951. )
  952. foreach ($r in @(Get-List $Brief.requirements)) {
  953. $lines += "- **$($r.id) $($r.title)** ($($r.priority)): " + ((@(Get-List $r.acceptance)) -join '; ')
  954. }
  955. $lines += @('', '## First milestone', '', "M0 (automatic): the starter builds and passes the smoke test. Expected screen: $($Brief.starter.expectedScreen)", '')
  956. if ($m1) {
  957. $lines += "$($m1.id) - $($m1.title): $($m1.goal)"
  958. foreach ($t in @(Get-List $m1.tasks)) { $lines += "- $($t.id): $($t.text) (done when: $($t.check))" }
  959. }
  960. $lines += @('', '## Destination', '', "``$dest`` ($(Get-DestinationState $dest))", '', 'Reply "approve" to generate the project, or tell me what to change.')
  961. $lines -join "`n"
  962. }
  963. Export-ModuleMember -Function Format-FoundrySpecPreview, Get-FoundryRoot, Read-FoundryJson, Get-FoundryCatalog, Test-FoundryBrief, Format-FoundryValidation, Resolve-FoundryDestination, Get-DestinationState, Resolve-FoundryProject, Expand-FoundryTemplate, Find-UnresolvedPlaceholders, New-FoundryProject

Powered by TurnKey Linux.