sdtk-spec-kit 0.4.11 → 0.4.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 (143) hide show
  1. package/README.md +353 -353
  2. package/assets/atlas/build_atlas.py +880 -880
  3. package/assets/atlas/doc_atlas_viewer_template.html +3796 -3796
  4. package/assets/atlas/vendor/mermaid.min.js +2029 -2029
  5. package/assets/keys/spec-entitlement-public.pem +9 -9
  6. package/assets/manifest/toolkit-bundle.manifest.json +496 -496
  7. package/assets/manifest/toolkit-bundle.sha256.txt +97 -97
  8. package/assets/toolkit/toolkit/AGENTS.md +157 -241
  9. package/assets/toolkit/toolkit/README.md +51 -51
  10. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +206 -206
  11. package/assets/toolkit/toolkit/install.ps1 +362 -362
  12. package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +95 -91
  13. package/assets/toolkit/toolkit/runtimes/codex/CODEX_TEMPLATE.md +70 -69
  14. package/assets/toolkit/toolkit/scripts/agents/run-claude-task.ps1 +332 -332
  15. package/assets/toolkit/toolkit/scripts/agents/run-codex-task.ps1 +618 -618
  16. package/assets/toolkit/toolkit/scripts/agents/validate-mailbox-formal-artifact.py +87 -87
  17. package/assets/toolkit/toolkit/scripts/generate-code-handoff.ps1 +317 -317
  18. package/assets/toolkit/toolkit/scripts/init-feature.ps1 +262 -262
  19. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +180 -180
  20. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +209 -209
  21. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +139 -139
  22. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +143 -143
  23. package/assets/toolkit/toolkit/sdtk-spec.config.json +28 -28
  24. package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +50 -50
  25. package/assets/toolkit/toolkit/session/SDTK_ACTIVE_BOOTSTRAP.md +46 -46
  26. package/assets/toolkit/toolkit/session/SDTK_AGENT_WORKING_RULES.md +48 -48
  27. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/SKILL.md +111 -111
  28. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/scripts/generate_api_design_detail.py +732 -732
  29. package/assets/toolkit/toolkit/skills/sdtk-api-doc/SKILL.md +79 -79
  30. package/assets/toolkit/toolkit/skills/sdtk-arch/SKILL.md +85 -85
  31. package/assets/toolkit/toolkit/skills/sdtk-ba/SKILL.md +46 -46
  32. package/assets/toolkit/toolkit/skills/sdtk-design-layout/SKILL.md +91 -91
  33. package/assets/toolkit/toolkit/skills/sdtk-design-layout/scripts/render_design_layout_images.py +246 -246
  34. package/assets/toolkit/toolkit/skills/sdtk-dev/SKILL.md +133 -133
  35. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/code-quality-reviewer.md +34 -34
  36. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/implementer.md +60 -60
  37. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/spec-reviewer.md +41 -41
  38. package/assets/toolkit/toolkit/skills/sdtk-dev-backend/SKILL.md +80 -80
  39. package/assets/toolkit/toolkit/skills/sdtk-dev-frontend/SKILL.md +80 -80
  40. package/assets/toolkit/toolkit/skills/sdtk-mailbox-dispatch/SKILL.md +73 -73
  41. package/assets/toolkit/toolkit/skills/sdtk-orchestrator/SKILL.md +176 -108
  42. package/assets/toolkit/toolkit/skills/sdtk-pm/SKILL.md +74 -74
  43. package/assets/toolkit/toolkit/skills/sdtk-qa/SKILL.md +75 -75
  44. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/SKILL.md +108 -107
  45. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/excel-image-export.md +51 -51
  46. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/figma-mcp.md +54 -54
  47. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/numbering-rules.md +28 -28
  48. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/renumber_flow_action_spec_global.py +136 -136
  49. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/validate_flow_action_spec_numbering.py +414 -414
  50. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/SKILL.md +110 -110
  51. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/scripts/validate_test_case_spec.py +97 -97
  52. package/assets/toolkit/toolkit/skills/skills.catalog.yaml +330 -330
  53. package/assets/toolkit/toolkit/skills-claude/api-design-spec/SKILL.md +116 -116
  54. package/assets/toolkit/toolkit/skills-claude/api-doc/SKILL.md +87 -87
  55. package/assets/toolkit/toolkit/skills-claude/arch/SKILL.md +59 -59
  56. package/assets/toolkit/toolkit/skills-claude/ba/SKILL.md +67 -67
  57. package/assets/toolkit/toolkit/skills-claude/design-layout/SKILL.md +91 -91
  58. package/assets/toolkit/toolkit/skills-claude/dev/SKILL.md +59 -59
  59. package/assets/toolkit/toolkit/skills-claude/dev-backend/SKILL.md +73 -73
  60. package/assets/toolkit/toolkit/skills-claude/dev-frontend/SKILL.md +73 -73
  61. package/assets/toolkit/toolkit/skills-claude/mailbox-dispatch/SKILL.md +73 -73
  62. package/assets/toolkit/toolkit/skills-claude/orchestrator/SKILL.md +88 -42
  63. package/assets/toolkit/toolkit/skills-claude/pm/SKILL.md +88 -88
  64. package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +58 -58
  65. package/assets/toolkit/toolkit/skills-claude/screen-design-spec/SKILL.md +113 -112
  66. package/assets/toolkit/toolkit/skills-claude/test-case-spec/SKILL.md +115 -115
  67. package/assets/toolkit/toolkit/templates/QUALITY_CHECKLIST.md +124 -124
  68. package/assets/toolkit/toolkit/templates/README.md +68 -68
  69. package/assets/toolkit/toolkit/templates/SHARED_PLANNING.md +81 -81
  70. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_CREATION_RULES.md +21 -21
  71. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_DETAIL_TEMPLATE.md +67 -67
  72. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_FLOWCHART_CREATION_RULES.md +468 -468
  73. package/assets/toolkit/toolkit/templates/docs/api/API_ENDPOINTS_TEMPLATE.md +229 -229
  74. package/assets/toolkit/toolkit/templates/docs/api/FEATURE_API_TEMPLATE.yaml +20 -20
  75. package/assets/toolkit/toolkit/templates/docs/api/FLOWCHART_CREATION_RULES.md +20 -20
  76. package/assets/toolkit/toolkit/templates/docs/api/YAML_CREATION_RULES.md +128 -128
  77. package/assets/toolkit/toolkit/templates/docs/api/feature_api_flow_list_TEMPLATE.txt +12 -12
  78. package/assets/toolkit/toolkit/templates/docs/architecture/ARCH_DESIGN_TEMPLATE.md +109 -109
  79. package/assets/toolkit/toolkit/templates/docs/database/DATABASE_SPEC_TEMPLATE.md +175 -175
  80. package/assets/toolkit/toolkit/templates/docs/design/DESIGN_LAYOUT_TEMPLATE.md +60 -60
  81. package/assets/toolkit/toolkit/templates/docs/dev/FEATURE_IMPL_PLAN_TEMPLATE.md +117 -117
  82. package/assets/toolkit/toolkit/templates/docs/dev/OPS_HANDOFF_CREATION_RULES.md +369 -369
  83. package/assets/toolkit/toolkit/templates/docs/discovery/REQUIREMENT_TEMPLATE.md +155 -155
  84. package/assets/toolkit/toolkit/templates/docs/product/BACKLOG_TEMPLATE.md +50 -50
  85. package/assets/toolkit/toolkit/templates/docs/product/CONDENSED_UPSTREAM_INPUT_TEMPLATE.md +276 -276
  86. package/assets/toolkit/toolkit/templates/docs/product/PRD_TEMPLATE.md +66 -66
  87. package/assets/toolkit/toolkit/templates/docs/product/PROJECT_INITIATION_TEMPLATE.md +98 -98
  88. package/assets/toolkit/toolkit/templates/docs/qa/CONTROLLER_ACCEPTANCE_TEMPLATE.md +90 -90
  89. package/assets/toolkit/toolkit/templates/docs/qa/QA_RELEASE_REPORT_TEMPLATE.md +162 -162
  90. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_CREATION_RULES.md +129 -129
  91. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_TEMPLATE.md +104 -104
  92. package/assets/toolkit/toolkit/templates/docs/specs/BA_SPEC_TEMPLATE.md +139 -139
  93. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_CREATION_RULES.md +220 -220
  94. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_TEMPLATE.md +197 -197
  95. package/assets/toolkit/toolkit/templates/handoffs/ARCH_TO_DEV.md +31 -31
  96. package/assets/toolkit/toolkit/templates/handoffs/BA_TO_ARCH.md +28 -28
  97. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE1_SPEC_REVIEW.md +26 -26
  98. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE2_CODE_QUALITY_REVIEW.md +20 -20
  99. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_QA.md +33 -33
  100. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_SDTK_CODE.md +60 -60
  101. package/assets/toolkit/toolkit/templates/handoffs/PM_TO_BA.md +30 -30
  102. package/assets/toolkit/toolkit/templates/handoffs/QA_RELEASE_DECISION.md +26 -26
  103. package/assets/toolkit/toolkit/templates/mailbox/AGENT_REPORT_TEMPLATE.md +63 -63
  104. package/assets/toolkit/toolkit/templates/mailbox/AGENT_TASK_TEMPLATE.md +76 -76
  105. package/bin/sdtk.js +15 -15
  106. package/package.json +48 -48
  107. package/src/commands/activate.js +94 -94
  108. package/src/commands/atlas.js +339 -339
  109. package/src/commands/auth.js +85 -85
  110. package/src/commands/entitlement.js +170 -170
  111. package/src/commands/generate.js +191 -170
  112. package/src/commands/help.js +248 -246
  113. package/src/commands/init.js +117 -117
  114. package/src/commands/project.js +51 -51
  115. package/src/commands/runtime.js +239 -239
  116. package/src/commands/update.js +11 -11
  117. package/src/index.js +68 -68
  118. package/src/lib/activation-state.js +68 -68
  119. package/src/lib/args.js +116 -116
  120. package/src/lib/atlas-config.js +200 -200
  121. package/src/lib/atlas-runner.js +435 -435
  122. package/src/lib/browser-open.js +39 -39
  123. package/src/lib/capabilities.js +89 -89
  124. package/src/lib/entitlements.js +245 -245
  125. package/src/lib/errors.js +41 -41
  126. package/src/lib/github-access.js +143 -143
  127. package/src/lib/legacy-auth-migration.js +56 -56
  128. package/src/lib/license-activation.js +386 -386
  129. package/src/lib/powershell.js +85 -85
  130. package/src/lib/premium-loader.js +124 -124
  131. package/src/lib/premium-packs.js +333 -333
  132. package/src/lib/premium-sync.js +235 -235
  133. package/src/lib/project-audit.js +332 -332
  134. package/src/lib/project-config.js +108 -108
  135. package/src/lib/project-ingest.js +450 -450
  136. package/src/lib/project-refresh.js +666 -666
  137. package/src/lib/project-target-guard.js +79 -79
  138. package/src/lib/requirement-analysis.js +14 -4
  139. package/src/lib/scope.js +83 -83
  140. package/src/lib/state.js +74 -74
  141. package/src/lib/suite-state.js +70 -70
  142. package/src/lib/toolkit-payload.js +99 -99
  143. package/src/lib/update.js +333 -333
@@ -1,618 +1,618 @@
1
- param(
2
- [Parameter(Mandatory = $true)] [string] $RepoRoot,
3
- [Parameter(Mandatory = $true)] [string] $TaskFile,
4
- [Parameter(Mandatory = $true)] [string] $ReportFile,
5
- [string] $LogFile = '',
6
- [string] $Model = '',
7
- [switch] $FullAuto,
8
- [switch] $DryRun
9
- )
10
-
11
- $ErrorActionPreference = 'Stop'
12
- $Utf8NoBom = [System.Text.UTF8Encoding]::new($false)
13
- $ReviewPhases = @('controller-dev-review', 'qa-review', 'controller-acceptance')
14
- $ReadOnlyPermissionMode = 'read-only'
15
- $WritablePermissionMode = 'workspace-write-approved'
16
- $NotRequiredApprovalStatus = 'not-required'
17
- $HumanApprovedStatus = 'human-approved'
18
- $DefaultImplementationWatchdogSeconds = 35 * 60
19
-
20
- function Get-TaskBulletValue([string[]] $Lines, [string] $Heading) {
21
- for ($i = 0; $i -lt $Lines.Length; $i++) {
22
- if ($Lines[$i].Trim() -eq $Heading) {
23
- for ($j = $i + 1; $j -lt $Lines.Length; $j++) {
24
- $candidate = $Lines[$j].Trim()
25
- if (-not $candidate) { continue }
26
- if ($candidate.StartsWith('- ')) {
27
- return $candidate.Substring(2).Trim()
28
- }
29
- break
30
- }
31
- }
32
- }
33
- return ''
34
- }
35
-
36
-
37
- function Get-TaskListValues([string[]] $Lines, [string] $Heading) {
38
- $values = New-Object System.Collections.Generic.List[string]
39
- $foundHeading = $false
40
- for ($i = 0; $i -lt $Lines.Length; $i++) {
41
- $trimmed = $Lines[$i].Trim()
42
- if (-not $foundHeading) {
43
- if ($trimmed -eq $Heading) {
44
- $foundHeading = $true
45
- }
46
- continue
47
- }
48
-
49
- if (-not $trimmed) {
50
- if ($values.Count -gt 0) { break }
51
- continue
52
- }
53
-
54
- $headingMatch = [regex]::Match($trimmed, '^[A-Za-z].*:$')
55
- if ($headingMatch.Success) { break }
56
-
57
- $listMatch = [regex]::Match($trimmed, '^(?:-|\d+\.)\s+(?<value>.+)$')
58
- if ($listMatch.Success) {
59
- $values.Add($listMatch.Groups['value'].Value.Trim())
60
- continue
61
- }
62
-
63
- if ($values.Count -gt 0) { break }
64
- }
65
- return $values.ToArray()
66
- }
67
-
68
- function Resolve-RepoPath([string] $RepoRootPath, [string] $CandidatePath) {
69
- if ([string]::IsNullOrWhiteSpace($CandidatePath)) { return '' }
70
- if ([System.IO.Path]::IsPathRooted($CandidatePath)) { return $CandidatePath }
71
- return Join-Path $RepoRootPath $CandidatePath
72
- }
73
-
74
- function Append-FileText([string] $Path, [string] $Text) {
75
- if ([string]::IsNullOrWhiteSpace($Text)) { return }
76
- [System.IO.File]::AppendAllText($Path, [Environment]::NewLine + $Text, $Utf8NoBom)
77
- }
78
-
79
- function Normalize-TaskValue([string] $Value, [string] $Default = '') {
80
- if ([string]::IsNullOrWhiteSpace($Value)) { return $Default }
81
- return $Value.Trim()
82
- }
83
-
84
-
85
- function Convert-ToBulletBlock([string[]] $Items) {
86
- if ($null -eq $Items -or $Items.Count -eq 0) {
87
- return '- (none declared)'
88
- }
89
- return (($Items | ForEach-Object { "- $_" }) -join [Environment]::NewLine)
90
- }
91
-
92
- function New-BoundedExecutionPrompt([string[]] $TaskLines) {
93
- $phase = Normalize-TaskValue (Get-TaskBulletValue $TaskLines 'Phase:') 'other'
94
- $objective = Normalize-TaskValue (Get-TaskBulletValue $TaskLines 'Objective:') 'n/a'
95
- $boundaryMode = Normalize-TaskValue (Get-TaskBulletValue $TaskLines 'Boundary Mode:') 'n/a'
96
- $inputs = Get-TaskListValues $TaskLines 'Inputs:'
97
- $includeBoundary = Get-TaskListValues $TaskLines 'Include Boundary:'
98
- $excludeBoundary = Get-TaskListValues $TaskLines 'Exclude Boundary:'
99
- $verification = Get-TaskListValues $TaskLines 'Required Verification:'
100
- $taskBody = [string]($TaskLines | Out-String)
101
-
102
- $envelope = @"
103
- [MAILBOX BOUNDED EXECUTION MODE]
104
- You are running under controller-enforced bounded execution mode.
105
-
106
- Phase: $phase
107
- Objective: $objective
108
- Boundary Mode: $boundaryMode
109
-
110
- Execution Discipline:
111
- 1. Read every listed input first and treat the `Inputs:` section as the authoritative starting source set.
112
- 2. Do not run broad repo-wide or directory-wide discovery before you have read the listed inputs.
113
- 3. Only inspect additional files when they are directly required to modify an included path or execute a required verification command.
114
- 4. Any additional inspection must stay inside the include boundary and must not cross the exclude boundary.
115
- 5. Do not mine `governance/ai/reviews/shared/` or similar directories for examples unless a specific file is already listed in `Inputs:`.
116
- 6. If the listed inputs are insufficient, stop and report the exact missing dependency instead of broad scanning.
117
- 7. Deliver the bounded patch and formal artifact before optional example-hunting or style exploration.
118
-
119
- Authoritative Inputs:
120
- $(Convert-ToBulletBlock $inputs)
121
-
122
- Include Boundary:
123
- $(Convert-ToBulletBlock $includeBoundary)
124
-
125
- Exclude Boundary:
126
- $(Convert-ToBulletBlock $excludeBoundary)
127
-
128
- Required Verification:
129
- $(Convert-ToBulletBlock $verification)
130
-
131
- [ORIGINAL TASK PACKET]
132
- "@
133
-
134
- return $envelope.TrimEnd() + [Environment]::NewLine + [Environment]::NewLine + $taskBody
135
- }
136
-
137
- function Test-PlaceholderValue([string] $Value) {
138
- $normalized = Normalize-TaskValue $Value
139
- if ([string]::IsNullOrWhiteSpace($normalized)) { return $true }
140
- return @('n/a', 'na', 'none', 'not-applicable') -contains $normalized.ToLowerInvariant()
141
- }
142
-
143
- function New-PermissionAuditBlock(
144
- [string] $DeclaredPermission,
145
- [string] $EffectiveMode,
146
- [string] $ApprovalStatus,
147
- [string] $ApprovedBy,
148
- [string] $ApprovalReason,
149
- [string] $ApprovedScope,
150
- [string] $ApprovalReference,
151
- [string] $DecisionSummary
152
- ) {
153
- return @"
154
- [MAILBOX EXECUTION PERMISSION AUDIT]
155
- - Declared Execution Permission: $DeclaredPermission
156
- - Effective Runtime Permission Mode: $EffectiveMode
157
- - Permission Approval Status: $ApprovalStatus
158
- - Approved By: $ApprovedBy
159
- - Approval Reason: $ApprovalReason
160
- - Approved Writable Scope: $ApprovedScope
161
- - Approval Reference: $ApprovalReference
162
- - Launcher Decision Summary: $DecisionSummary
163
- "@.TrimEnd()
164
- }
165
-
166
- function New-PartialFailureCloseoutBlock(
167
- [string] $CloseoutReason,
168
- [string] $StallBudgetSource,
169
- [int] $WatchdogSeconds,
170
- [string] $RuntimeExitCode,
171
- [string] $ReportStateBeforeCloseout,
172
- [string] $LogPath,
173
- [string] $CloseoutAuthorship,
174
- [string] $WatchdogReached
175
- ) {
176
- return @"
177
- [MAILBOX PARTIAL FAILURE CLOSEOUT]
178
- - Closeout Reason: $CloseoutReason
179
- - Stall Budget Source: $StallBudgetSource
180
- - Effective Stall Budget Seconds: $WatchdogSeconds
181
- - Runtime Exit Code: $RuntimeExitCode
182
- - Runtime Report State Before Closeout: $ReportStateBeforeCloseout
183
- - Raw Log Path: $LogPath
184
- - Watchdog Timeout Reached: $WatchdogReached
185
- - Launcher Authored Closeout Report: $CloseoutAuthorship
186
- - Controller Fallback Recommended: yes
187
- "@.TrimEnd()
188
- }
189
-
190
- function Write-PermissionFailure(
191
- [string] $ReportPath,
192
- [string] $LogPath,
193
- [string] $AuditBlock,
194
- [string] $Message
195
- ) {
196
- Append-FileText $ReportPath $AuditBlock
197
- Append-FileText $ReportPath "[MAILBOX PERMISSION VALIDATION] failed: $Message"
198
- if ($LogPath) {
199
- Append-FileText $LogPath $AuditBlock
200
- Append-FileText $LogPath "[MAILBOX PERMISSION VALIDATION] failed: $Message"
201
- }
202
- throw $Message
203
- }
204
-
205
- function Invoke-PhaseArtifactValidation([string[]] $TaskLines, [string] $RepoRootPath, [string] $ReportPath, [string] $LogPath, [string] $ValidatorPath) {
206
- $phase = Get-TaskBulletValue $TaskLines 'Phase:'
207
- if ($ReviewPhases -notcontains $phase) { return }
208
-
209
- $artifactValue = Get-TaskBulletValue $TaskLines 'Primary Formal Artifact:'
210
- if ([string]::IsNullOrWhiteSpace($artifactValue)) { return }
211
- if (-not (Test-Path $ValidatorPath)) { return }
212
-
213
- $artifactPath = Resolve-RepoPath $RepoRootPath $artifactValue
214
- if (-not (Test-Path $artifactPath)) {
215
- $skip = "[MAILBOX PHASE VALIDATION] skipped: primary formal artifact not found at $artifactPath"
216
- Append-FileText $ReportPath $skip
217
- if ($LogPath) { Append-FileText $LogPath $skip }
218
- return
219
- }
220
-
221
- $validationOutput = (& python $ValidatorPath --phase $phase --artifact $artifactPath 2>&1 | Out-String).TrimEnd()
222
- $validationBlock = "[MAILBOX PHASE VALIDATION]`n$validationOutput"
223
- Append-FileText $ReportPath $validationBlock
224
- if ($LogPath) { Append-FileText $LogPath $validationBlock }
225
-
226
- if ($LASTEXITCODE -ne 0) {
227
- throw "Mailbox phase artifact validation failed for $artifactPath"
228
- }
229
- }
230
-
231
- function Get-StallBudgetSeconds([string] $Phase, [string] $RawValue) {
232
- $normalized = Normalize-TaskValue $RawValue
233
- if (-not [string]::IsNullOrWhiteSpace($normalized)) {
234
- $match = [regex]::Match($normalized.ToLowerInvariant(), '(?<value>\d+)\s*(?<unit>seconds?|secs?|sec|minutes?|mins?|min|hours?|hrs?|hr|h)')
235
- if ($match.Success) {
236
- $value = [int]$match.Groups['value'].Value
237
- $unit = $match.Groups['unit'].Value
238
- switch -Regex ($unit) {
239
- '^sec' { return [Math]::Max($value, 1) }
240
- '^second' { return [Math]::Max($value, 1) }
241
- '^min' { return [Math]::Max($value * 60, 1) }
242
- '^minute' { return [Math]::Max($value * 60, 1) }
243
- '^hr$|^hrs$|^hour|^h$' { return [Math]::Max($value * 3600, 1) }
244
- }
245
- }
246
- }
247
- if ($Phase -eq 'implementation') { return $DefaultImplementationWatchdogSeconds }
248
- return 0
249
- }
250
-
251
- function Get-StallBudgetSource([string] $RawValue, [int] $Seconds) {
252
- $normalized = Normalize-TaskValue $RawValue
253
- if (-not [string]::IsNullOrWhiteSpace($normalized)) {
254
- return $normalized
255
- }
256
- if ($Seconds -gt 0) {
257
- return "defaulted to $Seconds seconds because no parseable stall budget was provided"
258
- }
259
- return 'n/a'
260
- }
261
-
262
- function Get-ReportState([string] $Path) {
263
- if (-not (Test-Path $Path)) { return 'missing' }
264
- $info = Get-Item $Path
265
- if ($info.Length -le 0) { return 'empty' }
266
- return 'present'
267
- }
268
-
269
- function Get-GitCommandOutput([string] $RepoRootPath, [string[]] $Arguments) {
270
- $previousErrorActionPreference = $ErrorActionPreference
271
- try {
272
- $ErrorActionPreference = 'Continue'
273
- $result = (& git -C $RepoRootPath @Arguments 2>&1 | Out-String).TrimEnd()
274
- } finally {
275
- $ErrorActionPreference = $previousErrorActionPreference
276
- }
277
- if ([string]::IsNullOrWhiteSpace($result)) { return '(empty)' }
278
- return $result
279
- }
280
-
281
- function New-GitTruthBlock([string] $RepoRootPath) {
282
- $status = Get-GitCommandOutput $RepoRootPath @('status', '--short', '--untracked-files=all')
283
- $diff = Get-GitCommandOutput $RepoRootPath @('diff', '--name-only')
284
- $cached = Get-GitCommandOutput $RepoRootPath @('diff', '--cached', '--name-only')
285
- $head = Get-GitCommandOutput $RepoRootPath @('rev-parse', 'HEAD')
286
- $branch = Get-GitCommandOutput $RepoRootPath @('branch', '--show-current')
287
- return @"
288
- 10. Git Truth
289
- - git status --short --untracked-files=all -> $status
290
- - git diff --name-only -> $diff
291
- - git diff --cached --name-only -> $cached
292
- - git rev-parse HEAD -> $head
293
- - git branch --show-current -> $branch
294
- "@.TrimEnd()
295
- }
296
-
297
- function Stop-ProcessTree([int] $ProcessId) {
298
- $children = @(Get-CimInstance Win32_Process -Filter "ParentProcessId=$ProcessId" -ErrorAction SilentlyContinue)
299
- foreach ($child in $children) {
300
- Stop-ProcessTree -ProcessId $child.ProcessId
301
- }
302
- Stop-Process -Id $ProcessId -Force -ErrorAction SilentlyContinue
303
- }
304
-
305
- function Convert-ToCmdQuoted([string] $Value) {
306
- return '"' + ($Value -replace '"', '""') + '"'
307
- }
308
-
309
- function Invoke-CodexProcessWithWatchdog(
310
- [string] $RepoRootPath,
311
- [string] $PromptPath,
312
- [string] $ReportPath,
313
- [string] $LogPath,
314
- [string] $ModelName,
315
- [bool] $UseWorkspaceWrite,
316
- [int] $WatchdogSeconds
317
- ) {
318
- $runnerScriptPath = Join-Path ([System.IO.Path]::GetTempPath()) ("sdtk-mailbox-codex-" + [guid]::NewGuid().ToString('N') + '.cmd')
319
- $commandParts = @(
320
- 'codex',
321
- 'exec',
322
- '-c',
323
- (Convert-ToCmdQuoted 'mcp_servers={}'),
324
- '-c',
325
- (Convert-ToCmdQuoted 'model_reasoning_effort="medium"'),
326
- '-C',
327
- (Convert-ToCmdQuoted $RepoRootPath),
328
- '--output-last-message',
329
- (Convert-ToCmdQuoted $ReportPath)
330
- )
331
- if ($UseWorkspaceWrite) {
332
- $commandParts += '--full-auto'
333
- } else {
334
- $commandParts += @('--sandbox', 'read-only')
335
- }
336
- if ($ModelName) {
337
- $commandParts += @('--model', (Convert-ToCmdQuoted $ModelName))
338
- }
339
- $commandParts += '-'
340
-
341
- $commandLine = ($commandParts -join ' ') + ' < ' + (Convert-ToCmdQuoted $PromptPath)
342
- if ($LogPath) {
343
- $commandLine += ' > ' + (Convert-ToCmdQuoted $LogPath) + ' 2>&1'
344
- }
345
-
346
- $embedded = "@echo off`r`nsetlocal`r`n$commandLine`r`nexit /b %ERRORLEVEL%`r`n"
347
- [System.IO.File]::WriteAllText($runnerScriptPath, $embedded, $Utf8NoBom)
348
-
349
- $process = Start-Process -FilePath 'cmd.exe' -ArgumentList @('/d', '/c', $runnerScriptPath) -WorkingDirectory $RepoRootPath -PassThru -WindowStyle Hidden
350
-
351
- $timedOut = $false
352
- try {
353
- if ($WatchdogSeconds -gt 0) {
354
- if (-not $process.WaitForExit($WatchdogSeconds * 1000)) {
355
- $timedOut = $true
356
- Stop-ProcessTree -ProcessId $process.Id
357
- }
358
- }
359
- if (-not $timedOut) {
360
- $process.WaitForExit()
361
- }
362
- return [pscustomobject]@{
363
- TimedOut = $timedOut
364
- ExitCode = if ($timedOut) { -1 } else { $process.ExitCode }
365
- }
366
- } finally {
367
- Remove-Item $runnerScriptPath -Force -ErrorAction SilentlyContinue
368
- }
369
- }
370
-
371
- function Write-StructuredPartialFailureReport(
372
- [string] $RepoRootPath,
373
- [string] $ReportPath,
374
- [string] $LogPath,
375
- [string] $CloseoutReason,
376
- [string] $RuntimeExitCode,
377
- [string] $ReportStateBeforeCloseout,
378
- [string] $PermissionAuditBlock,
379
- [string] $PartialFailureBlock,
380
- [string] $BoundaryMode,
381
- [string] $IssueCloseoutMode,
382
- [string] $DecisionRequested,
383
- [string] $Phase,
384
- [string] $PrimaryFormalArtifact,
385
- [string] $WatchdogReached
386
- ) {
387
- $gitTruthBlock = New-GitTruthBlock $RepoRootPath
388
- $repoBranch = Get-GitCommandOutput $RepoRootPath @('branch', '--show-current')
389
- $reportText = @"
390
- # MAILBOX PARTIAL FAILURE REPORT
391
- 1. Metadata
392
- - Worker: Codex mailbox launcher
393
- - Runtime: codex
394
- - Phase: $Phase
395
- - Repo / Branch: $RepoRootPath | $repoBranch
396
- - Decision Requested: $DecisionRequested
397
- - Issue Closeout Mode: $IssueCloseoutMode
398
- - Runtime Outcome (completed | stalled | fallback-used): stalled
399
- 2. Short Summary
400
- - Launcher emitted a controller-usable partial-failure blocker report because the external Codex run did not reach a normal closeout path.
401
- 3. Exact Files Changed
402
- - none confirmed
403
- 4. Carryover Findings Resolution
404
- - no tracked diff from the stalled runtime was accepted
405
- 5. Formal Artifact Truth
406
- - primary formal artifact path: $PrimaryFormalArtifact
407
- - written by agent or controller fallback: launcher-authored transient blocker report only
408
- - fallback reason when controller authored the artifact: $CloseoutReason
409
- 6. Execution Permission Audit
410
- - see launcher audit block below
411
- 7. Phase Artifact Validation
412
- - skipped: implementation partial-failure closeout does not run review-phase artifact validation
413
- 8. Exact Verification Results
414
- - codex mailbox launch -> $CloseoutReason
415
- - runtime report state before closeout -> $ReportStateBeforeCloseout
416
- - raw log path -> $LogPath
417
- 9. Boundary Truth
418
- - included surfaces actually touched -> no tracked diff accepted from the stalled runtime
419
- - excluded surfaces not touched -> not fully verifiable from the stalled runtime; controller fallback required before promotion
420
- - formal artifacts created -> transient mailbox blocker report only ($ReportPath)
421
- - boundary mode actually executed -> $BoundaryMode
422
- - parent issue status after this batch (`DONE` | `IN_PROGRESS`) -> IN_PROGRESS
423
- $gitTruthBlock
424
- 11. Fallback Truth
425
- - fallback trigger reached or not -> yes
426
- - fallback path used or not -> launcher-authored partial-failure closeout only
427
- - stalled runtime diff accepted: yes or no -> no
428
- - watchdog timeout reached: yes or no -> $WatchdogReached
429
- - launcher-authored partial-failure closeout emitted: yes or no -> yes
430
- - raw log path -> $LogPath
431
- - raw runtime report state before closeout -> $ReportStateBeforeCloseout
432
- 12. Blockers / Open Questions
433
- - external Codex run ended without a usable normal closeout path; controller must review the blocker report and choose a bounded fallback or rerun
434
- 13. Ready State
435
- - not ready
436
- - reason -> $CloseoutReason
437
- - next step -> choose controller fallback, native fallback, or a rerun with a new run id after reviewing the raw log
438
- $PartialFailureBlock
439
- $PermissionAuditBlock
440
- "@
441
- [System.IO.File]::WriteAllText($ReportPath, $reportText.TrimEnd() + [Environment]::NewLine, $Utf8NoBom)
442
- if ($LogPath) {
443
- Append-FileText $LogPath $PartialFailureBlock
444
- Append-FileText $LogPath $PermissionAuditBlock
445
- }
446
- }
447
-
448
- if (-not (Test-Path $RepoRoot)) { throw "RepoRoot not found: $RepoRoot" }
449
- if (-not (Test-Path $TaskFile)) { throw "TaskFile not found: $TaskFile" }
450
-
451
- $taskLines = Get-Content $TaskFile -Encoding UTF8
452
- $prompt = New-BoundedExecutionPrompt $taskLines
453
- $phase = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Phase:')
454
- $permissionMode = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Execution Permission:') $ReadOnlyPermissionMode
455
- $approvalStatus = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Permission Approval Status:') $NotRequiredApprovalStatus
456
- $approvedBy = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approved By:') 'n/a'
457
- $approvalReason = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approval Reason:') 'n/a'
458
- $approvedScope = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approved Writable Scope:') 'n/a'
459
- $approvalReference = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approval Reference:') 'n/a'
460
- $issueCloseoutMode = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Issue Closeout Mode:') 'phase-only'
461
- $decisionRequested = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Decision Requested:') 'n/a'
462
- $boundaryMode = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Boundary Mode:') 'n/a'
463
- $primaryFormalArtifact = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Primary Formal Artifact:') 'n/a'
464
- $stallBudgetValue = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Runtime Stall Budget / Fallback Trigger:')
465
- New-Item -ItemType Directory -Force -Path ([System.IO.Path]::GetDirectoryName($ReportFile)) | Out-Null
466
- if ($LogFile) {
467
- New-Item -ItemType Directory -Force -Path ([System.IO.Path]::GetDirectoryName($LogFile)) | Out-Null
468
- }
469
-
470
- $cliArgs = @('exec', '-c', 'mcp_servers={}', '-c', 'model_reasoning_effort="medium"', '-C', $RepoRoot, '--output-last-message', $ReportFile)
471
- $useWorkspaceWrite = $false
472
- $effectiveMode = $ReadOnlyPermissionMode
473
- $decisionSummary = ''
474
- $approvalFieldsArePlaceholder = (Test-PlaceholderValue $approvedBy) -and (Test-PlaceholderValue $approvalReason) -and (Test-PlaceholderValue $approvedScope)
475
-
476
- if ($ReviewPhases -contains $phase) {
477
- if ($permissionMode -ne $ReadOnlyPermissionMode) {
478
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'review phase attempted writable permission and was rejected before launch'
479
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Review-phase mailbox runs must declare 'Execution Permission: read-only'."
480
- }
481
- if ($approvalStatus -ne $NotRequiredApprovalStatus -or -not $approvalFieldsArePlaceholder) {
482
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'review phase approval metadata was inconsistent for a read-only run'
483
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Read-only review phases must use 'Permission Approval Status: not-required' and leave writable approval fields as 'n/a'."
484
- }
485
- $decisionSummary = 'review phase forced explicit read-only sandbox'
486
- } elseif ($phase -eq 'implementation') {
487
- if ($permissionMode -eq $WritablePermissionMode) {
488
- if ($approvalStatus -ne $HumanApprovedStatus) {
489
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'writable implementation requested without human-approved status'
490
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Writable implementation runs require 'Permission Approval Status: human-approved'."
491
- }
492
- if ((Test-PlaceholderValue $approvedBy) -or (Test-PlaceholderValue $approvalReason) -or (Test-PlaceholderValue $approvedScope)) {
493
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'writable implementation requested without complete approval metadata'
494
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message 'Writable implementation runs require Approved By, Approval Reason, and Approved Writable Scope.'
495
- }
496
- $useWorkspaceWrite = $true
497
- $effectiveMode = 'workspace-write'
498
- $decisionSummary = 'writable Codex implementation run approved and enabled from task-packet approval record'
499
- } elseif ($permissionMode -eq $ReadOnlyPermissionMode) {
500
- if ($approvalStatus -ne $NotRequiredApprovalStatus -or -not $approvalFieldsArePlaceholder) {
501
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'read-only implementation run carried contradictory writable approval metadata'
502
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Read-only implementation runs must use 'Permission Approval Status: not-required' and leave writable approval fields as 'n/a'."
503
- }
504
- $decisionSummary = 'implementation run remained read-only because no writable approval was declared'
505
- } else {
506
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'unknown execution permission rejected before launch'
507
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Unknown execution permission mode '$permissionMode'."
508
- }
509
- } else {
510
- if ($permissionMode -ne $ReadOnlyPermissionMode) {
511
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'non-implementation phase attempted writable permission and was rejected before launch'
512
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message 'Only implementation-phase mailbox runs may request writable execution.'
513
- }
514
- if ($approvalStatus -ne $NotRequiredApprovalStatus -or -not $approvalFieldsArePlaceholder) {
515
- $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'non-implementation phase approval metadata was inconsistent for a read-only run'
516
- Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Non-implementation read-only runs must use 'Permission Approval Status: not-required' and leave writable approval fields as 'n/a'."
517
- }
518
- $decisionSummary = 'non-implementation phase forced explicit read-only sandbox'
519
- }
520
-
521
- if ($FullAuto -and -not $useWorkspaceWrite) {
522
- $decisionSummary += '; ignored manual -FullAuto override because the task packet did not authorize writable execution'
523
- }
524
-
525
- $watchdogSeconds = Get-StallBudgetSeconds -Phase $phase -RawValue $stallBudgetValue
526
- $stallBudgetSource = Get-StallBudgetSource -RawValue $stallBudgetValue -Seconds $watchdogSeconds
527
- $permissionAuditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $effectiveMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary $decisionSummary
528
-
529
- if ($useWorkspaceWrite) {
530
- $cliArgs += '--full-auto'
531
- } else {
532
- $cliArgs += @('--sandbox', 'read-only')
533
- }
534
- if ($Model) { $cliArgs += @('--model', $Model) }
535
- $cliArgs += '-'
536
-
537
- if ($DryRun) {
538
- [pscustomobject]@{
539
- Cli = 'codex'
540
- RepoRoot = $RepoRoot
541
- TaskFile = $TaskFile
542
- ReportFile = $ReportFile
543
- LogFile = $LogFile
544
- Args = $cliArgs
545
- DeclaredExecutionPermission = $permissionMode
546
- EffectiveRuntimePermissionMode = $effectiveMode
547
- PermissionApprovalStatus = $approvalStatus
548
- ApprovedBy = $approvedBy
549
- ApprovalReason = $approvalReason
550
- ApprovedWritableScope = $approvedScope
551
- ApprovalReference = $approvalReference
552
- LauncherDecisionSummary = $decisionSummary
553
- RuntimeStallBudget = $stallBudgetValue
554
- EffectiveWatchdogSeconds = $watchdogSeconds
555
- PromptLength = $prompt.Length
556
- PromptPreview = if ($prompt.Length -gt 2000) { $prompt.Substring(0, 2000) } else { $prompt }
557
- } | ConvertTo-Json -Depth 4
558
- exit 0
559
- }
560
-
561
- $promptPath = Join-Path ([System.IO.Path]::GetTempPath()) ("sdtk-mailbox-prompt-" + [guid]::NewGuid().ToString('N') + '.md')
562
- [System.IO.File]::WriteAllText($promptPath, $prompt, $Utf8NoBom)
563
- try {
564
- $processResult = Invoke-CodexProcessWithWatchdog -RepoRootPath $RepoRoot -PromptPath $promptPath -ReportPath $ReportFile -LogPath $LogFile -ModelName $Model -UseWorkspaceWrite:$useWorkspaceWrite -WatchdogSeconds $watchdogSeconds
565
- $reportStateBeforeCloseout = Get-ReportState $ReportFile
566
- $runtimeExitCode = if ($processResult.TimedOut) { 'timed-out' } else { [string]$processResult.ExitCode }
567
- $needsPartialFailureCloseout = $processResult.TimedOut -or $processResult.ExitCode -ne 0 -or $reportStateBeforeCloseout -ne 'present'
568
-
569
- if ($needsPartialFailureCloseout) {
570
- if ($processResult.TimedOut) {
571
- $closeoutReason = "launcher watchdog terminated the external Codex run after $watchdogSeconds second(s) before a usable normal closeout path was reached"
572
- $watchdogReached = 'yes'
573
- } elseif ($reportStateBeforeCloseout -ne 'present') {
574
- $closeoutReason = "external Codex run exited with code $runtimeExitCode without writing a usable runtime report"
575
- $watchdogReached = 'no'
576
- } else {
577
- $closeoutReason = "external Codex run exited with code $runtimeExitCode and requires controller review before the batch can proceed"
578
- $watchdogReached = 'no'
579
- }
580
-
581
- $partialFailureBlock = New-PartialFailureCloseoutBlock -CloseoutReason $closeoutReason -StallBudgetSource $stallBudgetSource -WatchdogSeconds $watchdogSeconds -RuntimeExitCode $runtimeExitCode -ReportStateBeforeCloseout $reportStateBeforeCloseout -LogPath $(if ($LogFile) { $LogFile } else { 'n/a' }) -CloseoutAuthorship $(if ($reportStateBeforeCloseout -eq 'present') { 'no' } else { 'yes' }) -WatchdogReached $watchdogReached
582
-
583
- if ($reportStateBeforeCloseout -eq 'present') {
584
- Append-FileText $ReportFile $partialFailureBlock
585
- Append-FileText $ReportFile $permissionAuditBlock
586
- if ($LogFile) {
587
- Append-FileText $LogFile $partialFailureBlock
588
- Append-FileText $LogFile $permissionAuditBlock
589
- }
590
- } else {
591
- Write-StructuredPartialFailureReport -RepoRootPath $RepoRoot -ReportPath $ReportFile -LogPath $LogFile -CloseoutReason $closeoutReason -RuntimeExitCode $runtimeExitCode -ReportStateBeforeCloseout $reportStateBeforeCloseout -PermissionAuditBlock $permissionAuditBlock -PartialFailureBlock $partialFailureBlock -BoundaryMode $boundaryMode -IssueCloseoutMode $issueCloseoutMode -DecisionRequested $decisionRequested -Phase $phase -PrimaryFormalArtifact $primaryFormalArtifact -WatchdogReached $watchdogReached
592
- }
593
-
594
- if ($processResult.TimedOut) {
595
- Write-Error $closeoutReason
596
- exit 124
597
- }
598
-
599
- if ($processResult.ExitCode -ne 0) {
600
- Write-Error $closeoutReason
601
- exit $processResult.ExitCode
602
- }
603
-
604
- Write-Error $closeoutReason
605
- exit 3
606
- }
607
-
608
- Append-FileText $ReportFile $permissionAuditBlock
609
- if ($LogFile) {
610
- Append-FileText $LogFile $permissionAuditBlock
611
- }
612
-
613
- $validatorPath = Join-Path $RepoRoot 'products/sdtk-spec/toolkit/scripts/agents/validate-mailbox-formal-artifact.py'
614
- Invoke-PhaseArtifactValidation -TaskLines $taskLines -RepoRootPath $RepoRoot -ReportPath $ReportFile -LogPath $LogFile -ValidatorPath $validatorPath
615
- Write-Host "Codex report written to: $ReportFile"
616
- } finally {
617
- Remove-Item $promptPath -Force -ErrorAction SilentlyContinue
618
- }
1
+ param(
2
+ [Parameter(Mandatory = $true)] [string] $RepoRoot,
3
+ [Parameter(Mandatory = $true)] [string] $TaskFile,
4
+ [Parameter(Mandatory = $true)] [string] $ReportFile,
5
+ [string] $LogFile = '',
6
+ [string] $Model = '',
7
+ [switch] $FullAuto,
8
+ [switch] $DryRun
9
+ )
10
+
11
+ $ErrorActionPreference = 'Stop'
12
+ $Utf8NoBom = [System.Text.UTF8Encoding]::new($false)
13
+ $ReviewPhases = @('controller-dev-review', 'qa-review', 'controller-acceptance')
14
+ $ReadOnlyPermissionMode = 'read-only'
15
+ $WritablePermissionMode = 'workspace-write-approved'
16
+ $NotRequiredApprovalStatus = 'not-required'
17
+ $HumanApprovedStatus = 'human-approved'
18
+ $DefaultImplementationWatchdogSeconds = 35 * 60
19
+
20
+ function Get-TaskBulletValue([string[]] $Lines, [string] $Heading) {
21
+ for ($i = 0; $i -lt $Lines.Length; $i++) {
22
+ if ($Lines[$i].Trim() -eq $Heading) {
23
+ for ($j = $i + 1; $j -lt $Lines.Length; $j++) {
24
+ $candidate = $Lines[$j].Trim()
25
+ if (-not $candidate) { continue }
26
+ if ($candidate.StartsWith('- ')) {
27
+ return $candidate.Substring(2).Trim()
28
+ }
29
+ break
30
+ }
31
+ }
32
+ }
33
+ return ''
34
+ }
35
+
36
+
37
+ function Get-TaskListValues([string[]] $Lines, [string] $Heading) {
38
+ $values = New-Object System.Collections.Generic.List[string]
39
+ $foundHeading = $false
40
+ for ($i = 0; $i -lt $Lines.Length; $i++) {
41
+ $trimmed = $Lines[$i].Trim()
42
+ if (-not $foundHeading) {
43
+ if ($trimmed -eq $Heading) {
44
+ $foundHeading = $true
45
+ }
46
+ continue
47
+ }
48
+
49
+ if (-not $trimmed) {
50
+ if ($values.Count -gt 0) { break }
51
+ continue
52
+ }
53
+
54
+ $headingMatch = [regex]::Match($trimmed, '^[A-Za-z].*:$')
55
+ if ($headingMatch.Success) { break }
56
+
57
+ $listMatch = [regex]::Match($trimmed, '^(?:-|\d+\.)\s+(?<value>.+)$')
58
+ if ($listMatch.Success) {
59
+ $values.Add($listMatch.Groups['value'].Value.Trim())
60
+ continue
61
+ }
62
+
63
+ if ($values.Count -gt 0) { break }
64
+ }
65
+ return $values.ToArray()
66
+ }
67
+
68
+ function Resolve-RepoPath([string] $RepoRootPath, [string] $CandidatePath) {
69
+ if ([string]::IsNullOrWhiteSpace($CandidatePath)) { return '' }
70
+ if ([System.IO.Path]::IsPathRooted($CandidatePath)) { return $CandidatePath }
71
+ return Join-Path $RepoRootPath $CandidatePath
72
+ }
73
+
74
+ function Append-FileText([string] $Path, [string] $Text) {
75
+ if ([string]::IsNullOrWhiteSpace($Text)) { return }
76
+ [System.IO.File]::AppendAllText($Path, [Environment]::NewLine + $Text, $Utf8NoBom)
77
+ }
78
+
79
+ function Normalize-TaskValue([string] $Value, [string] $Default = '') {
80
+ if ([string]::IsNullOrWhiteSpace($Value)) { return $Default }
81
+ return $Value.Trim()
82
+ }
83
+
84
+
85
+ function Convert-ToBulletBlock([string[]] $Items) {
86
+ if ($null -eq $Items -or $Items.Count -eq 0) {
87
+ return '- (none declared)'
88
+ }
89
+ return (($Items | ForEach-Object { "- $_" }) -join [Environment]::NewLine)
90
+ }
91
+
92
+ function New-BoundedExecutionPrompt([string[]] $TaskLines) {
93
+ $phase = Normalize-TaskValue (Get-TaskBulletValue $TaskLines 'Phase:') 'other'
94
+ $objective = Normalize-TaskValue (Get-TaskBulletValue $TaskLines 'Objective:') 'n/a'
95
+ $boundaryMode = Normalize-TaskValue (Get-TaskBulletValue $TaskLines 'Boundary Mode:') 'n/a'
96
+ $inputs = Get-TaskListValues $TaskLines 'Inputs:'
97
+ $includeBoundary = Get-TaskListValues $TaskLines 'Include Boundary:'
98
+ $excludeBoundary = Get-TaskListValues $TaskLines 'Exclude Boundary:'
99
+ $verification = Get-TaskListValues $TaskLines 'Required Verification:'
100
+ $taskBody = [string]($TaskLines | Out-String)
101
+
102
+ $envelope = @"
103
+ [MAILBOX BOUNDED EXECUTION MODE]
104
+ You are running under controller-enforced bounded execution mode.
105
+
106
+ Phase: $phase
107
+ Objective: $objective
108
+ Boundary Mode: $boundaryMode
109
+
110
+ Execution Discipline:
111
+ 1. Read every listed input first and treat the `Inputs:` section as the authoritative starting source set.
112
+ 2. Do not run broad repo-wide or directory-wide discovery before you have read the listed inputs.
113
+ 3. Only inspect additional files when they are directly required to modify an included path or execute a required verification command.
114
+ 4. Any additional inspection must stay inside the include boundary and must not cross the exclude boundary.
115
+ 5. Do not mine `governance/ai/reviews/shared/` or similar directories for examples unless a specific file is already listed in `Inputs:`.
116
+ 6. If the listed inputs are insufficient, stop and report the exact missing dependency instead of broad scanning.
117
+ 7. Deliver the bounded patch and formal artifact before optional example-hunting or style exploration.
118
+
119
+ Authoritative Inputs:
120
+ $(Convert-ToBulletBlock $inputs)
121
+
122
+ Include Boundary:
123
+ $(Convert-ToBulletBlock $includeBoundary)
124
+
125
+ Exclude Boundary:
126
+ $(Convert-ToBulletBlock $excludeBoundary)
127
+
128
+ Required Verification:
129
+ $(Convert-ToBulletBlock $verification)
130
+
131
+ [ORIGINAL TASK PACKET]
132
+ "@
133
+
134
+ return $envelope.TrimEnd() + [Environment]::NewLine + [Environment]::NewLine + $taskBody
135
+ }
136
+
137
+ function Test-PlaceholderValue([string] $Value) {
138
+ $normalized = Normalize-TaskValue $Value
139
+ if ([string]::IsNullOrWhiteSpace($normalized)) { return $true }
140
+ return @('n/a', 'na', 'none', 'not-applicable') -contains $normalized.ToLowerInvariant()
141
+ }
142
+
143
+ function New-PermissionAuditBlock(
144
+ [string] $DeclaredPermission,
145
+ [string] $EffectiveMode,
146
+ [string] $ApprovalStatus,
147
+ [string] $ApprovedBy,
148
+ [string] $ApprovalReason,
149
+ [string] $ApprovedScope,
150
+ [string] $ApprovalReference,
151
+ [string] $DecisionSummary
152
+ ) {
153
+ return @"
154
+ [MAILBOX EXECUTION PERMISSION AUDIT]
155
+ - Declared Execution Permission: $DeclaredPermission
156
+ - Effective Runtime Permission Mode: $EffectiveMode
157
+ - Permission Approval Status: $ApprovalStatus
158
+ - Approved By: $ApprovedBy
159
+ - Approval Reason: $ApprovalReason
160
+ - Approved Writable Scope: $ApprovedScope
161
+ - Approval Reference: $ApprovalReference
162
+ - Launcher Decision Summary: $DecisionSummary
163
+ "@.TrimEnd()
164
+ }
165
+
166
+ function New-PartialFailureCloseoutBlock(
167
+ [string] $CloseoutReason,
168
+ [string] $StallBudgetSource,
169
+ [int] $WatchdogSeconds,
170
+ [string] $RuntimeExitCode,
171
+ [string] $ReportStateBeforeCloseout,
172
+ [string] $LogPath,
173
+ [string] $CloseoutAuthorship,
174
+ [string] $WatchdogReached
175
+ ) {
176
+ return @"
177
+ [MAILBOX PARTIAL FAILURE CLOSEOUT]
178
+ - Closeout Reason: $CloseoutReason
179
+ - Stall Budget Source: $StallBudgetSource
180
+ - Effective Stall Budget Seconds: $WatchdogSeconds
181
+ - Runtime Exit Code: $RuntimeExitCode
182
+ - Runtime Report State Before Closeout: $ReportStateBeforeCloseout
183
+ - Raw Log Path: $LogPath
184
+ - Watchdog Timeout Reached: $WatchdogReached
185
+ - Launcher Authored Closeout Report: $CloseoutAuthorship
186
+ - Controller Fallback Recommended: yes
187
+ "@.TrimEnd()
188
+ }
189
+
190
+ function Write-PermissionFailure(
191
+ [string] $ReportPath,
192
+ [string] $LogPath,
193
+ [string] $AuditBlock,
194
+ [string] $Message
195
+ ) {
196
+ Append-FileText $ReportPath $AuditBlock
197
+ Append-FileText $ReportPath "[MAILBOX PERMISSION VALIDATION] failed: $Message"
198
+ if ($LogPath) {
199
+ Append-FileText $LogPath $AuditBlock
200
+ Append-FileText $LogPath "[MAILBOX PERMISSION VALIDATION] failed: $Message"
201
+ }
202
+ throw $Message
203
+ }
204
+
205
+ function Invoke-PhaseArtifactValidation([string[]] $TaskLines, [string] $RepoRootPath, [string] $ReportPath, [string] $LogPath, [string] $ValidatorPath) {
206
+ $phase = Get-TaskBulletValue $TaskLines 'Phase:'
207
+ if ($ReviewPhases -notcontains $phase) { return }
208
+
209
+ $artifactValue = Get-TaskBulletValue $TaskLines 'Primary Formal Artifact:'
210
+ if ([string]::IsNullOrWhiteSpace($artifactValue)) { return }
211
+ if (-not (Test-Path $ValidatorPath)) { return }
212
+
213
+ $artifactPath = Resolve-RepoPath $RepoRootPath $artifactValue
214
+ if (-not (Test-Path $artifactPath)) {
215
+ $skip = "[MAILBOX PHASE VALIDATION] skipped: primary formal artifact not found at $artifactPath"
216
+ Append-FileText $ReportPath $skip
217
+ if ($LogPath) { Append-FileText $LogPath $skip }
218
+ return
219
+ }
220
+
221
+ $validationOutput = (& python $ValidatorPath --phase $phase --artifact $artifactPath 2>&1 | Out-String).TrimEnd()
222
+ $validationBlock = "[MAILBOX PHASE VALIDATION]`n$validationOutput"
223
+ Append-FileText $ReportPath $validationBlock
224
+ if ($LogPath) { Append-FileText $LogPath $validationBlock }
225
+
226
+ if ($LASTEXITCODE -ne 0) {
227
+ throw "Mailbox phase artifact validation failed for $artifactPath"
228
+ }
229
+ }
230
+
231
+ function Get-StallBudgetSeconds([string] $Phase, [string] $RawValue) {
232
+ $normalized = Normalize-TaskValue $RawValue
233
+ if (-not [string]::IsNullOrWhiteSpace($normalized)) {
234
+ $match = [regex]::Match($normalized.ToLowerInvariant(), '(?<value>\d+)\s*(?<unit>seconds?|secs?|sec|minutes?|mins?|min|hours?|hrs?|hr|h)')
235
+ if ($match.Success) {
236
+ $value = [int]$match.Groups['value'].Value
237
+ $unit = $match.Groups['unit'].Value
238
+ switch -Regex ($unit) {
239
+ '^sec' { return [Math]::Max($value, 1) }
240
+ '^second' { return [Math]::Max($value, 1) }
241
+ '^min' { return [Math]::Max($value * 60, 1) }
242
+ '^minute' { return [Math]::Max($value * 60, 1) }
243
+ '^hr$|^hrs$|^hour|^h$' { return [Math]::Max($value * 3600, 1) }
244
+ }
245
+ }
246
+ }
247
+ if ($Phase -eq 'implementation') { return $DefaultImplementationWatchdogSeconds }
248
+ return 0
249
+ }
250
+
251
+ function Get-StallBudgetSource([string] $RawValue, [int] $Seconds) {
252
+ $normalized = Normalize-TaskValue $RawValue
253
+ if (-not [string]::IsNullOrWhiteSpace($normalized)) {
254
+ return $normalized
255
+ }
256
+ if ($Seconds -gt 0) {
257
+ return "defaulted to $Seconds seconds because no parseable stall budget was provided"
258
+ }
259
+ return 'n/a'
260
+ }
261
+
262
+ function Get-ReportState([string] $Path) {
263
+ if (-not (Test-Path $Path)) { return 'missing' }
264
+ $info = Get-Item $Path
265
+ if ($info.Length -le 0) { return 'empty' }
266
+ return 'present'
267
+ }
268
+
269
+ function Get-GitCommandOutput([string] $RepoRootPath, [string[]] $Arguments) {
270
+ $previousErrorActionPreference = $ErrorActionPreference
271
+ try {
272
+ $ErrorActionPreference = 'Continue'
273
+ $result = (& git -C $RepoRootPath @Arguments 2>&1 | Out-String).TrimEnd()
274
+ } finally {
275
+ $ErrorActionPreference = $previousErrorActionPreference
276
+ }
277
+ if ([string]::IsNullOrWhiteSpace($result)) { return '(empty)' }
278
+ return $result
279
+ }
280
+
281
+ function New-GitTruthBlock([string] $RepoRootPath) {
282
+ $status = Get-GitCommandOutput $RepoRootPath @('status', '--short', '--untracked-files=all')
283
+ $diff = Get-GitCommandOutput $RepoRootPath @('diff', '--name-only')
284
+ $cached = Get-GitCommandOutput $RepoRootPath @('diff', '--cached', '--name-only')
285
+ $head = Get-GitCommandOutput $RepoRootPath @('rev-parse', 'HEAD')
286
+ $branch = Get-GitCommandOutput $RepoRootPath @('branch', '--show-current')
287
+ return @"
288
+ 10. Git Truth
289
+ - git status --short --untracked-files=all -> $status
290
+ - git diff --name-only -> $diff
291
+ - git diff --cached --name-only -> $cached
292
+ - git rev-parse HEAD -> $head
293
+ - git branch --show-current -> $branch
294
+ "@.TrimEnd()
295
+ }
296
+
297
+ function Stop-ProcessTree([int] $ProcessId) {
298
+ $children = @(Get-CimInstance Win32_Process -Filter "ParentProcessId=$ProcessId" -ErrorAction SilentlyContinue)
299
+ foreach ($child in $children) {
300
+ Stop-ProcessTree -ProcessId $child.ProcessId
301
+ }
302
+ Stop-Process -Id $ProcessId -Force -ErrorAction SilentlyContinue
303
+ }
304
+
305
+ function Convert-ToCmdQuoted([string] $Value) {
306
+ return '"' + ($Value -replace '"', '""') + '"'
307
+ }
308
+
309
+ function Invoke-CodexProcessWithWatchdog(
310
+ [string] $RepoRootPath,
311
+ [string] $PromptPath,
312
+ [string] $ReportPath,
313
+ [string] $LogPath,
314
+ [string] $ModelName,
315
+ [bool] $UseWorkspaceWrite,
316
+ [int] $WatchdogSeconds
317
+ ) {
318
+ $runnerScriptPath = Join-Path ([System.IO.Path]::GetTempPath()) ("sdtk-mailbox-codex-" + [guid]::NewGuid().ToString('N') + '.cmd')
319
+ $commandParts = @(
320
+ 'codex',
321
+ 'exec',
322
+ '-c',
323
+ (Convert-ToCmdQuoted 'mcp_servers={}'),
324
+ '-c',
325
+ (Convert-ToCmdQuoted 'model_reasoning_effort="medium"'),
326
+ '-C',
327
+ (Convert-ToCmdQuoted $RepoRootPath),
328
+ '--output-last-message',
329
+ (Convert-ToCmdQuoted $ReportPath)
330
+ )
331
+ if ($UseWorkspaceWrite) {
332
+ $commandParts += '--full-auto'
333
+ } else {
334
+ $commandParts += @('--sandbox', 'read-only')
335
+ }
336
+ if ($ModelName) {
337
+ $commandParts += @('--model', (Convert-ToCmdQuoted $ModelName))
338
+ }
339
+ $commandParts += '-'
340
+
341
+ $commandLine = ($commandParts -join ' ') + ' < ' + (Convert-ToCmdQuoted $PromptPath)
342
+ if ($LogPath) {
343
+ $commandLine += ' > ' + (Convert-ToCmdQuoted $LogPath) + ' 2>&1'
344
+ }
345
+
346
+ $embedded = "@echo off`r`nsetlocal`r`n$commandLine`r`nexit /b %ERRORLEVEL%`r`n"
347
+ [System.IO.File]::WriteAllText($runnerScriptPath, $embedded, $Utf8NoBom)
348
+
349
+ $process = Start-Process -FilePath 'cmd.exe' -ArgumentList @('/d', '/c', $runnerScriptPath) -WorkingDirectory $RepoRootPath -PassThru -WindowStyle Hidden
350
+
351
+ $timedOut = $false
352
+ try {
353
+ if ($WatchdogSeconds -gt 0) {
354
+ if (-not $process.WaitForExit($WatchdogSeconds * 1000)) {
355
+ $timedOut = $true
356
+ Stop-ProcessTree -ProcessId $process.Id
357
+ }
358
+ }
359
+ if (-not $timedOut) {
360
+ $process.WaitForExit()
361
+ }
362
+ return [pscustomobject]@{
363
+ TimedOut = $timedOut
364
+ ExitCode = if ($timedOut) { -1 } else { $process.ExitCode }
365
+ }
366
+ } finally {
367
+ Remove-Item $runnerScriptPath -Force -ErrorAction SilentlyContinue
368
+ }
369
+ }
370
+
371
+ function Write-StructuredPartialFailureReport(
372
+ [string] $RepoRootPath,
373
+ [string] $ReportPath,
374
+ [string] $LogPath,
375
+ [string] $CloseoutReason,
376
+ [string] $RuntimeExitCode,
377
+ [string] $ReportStateBeforeCloseout,
378
+ [string] $PermissionAuditBlock,
379
+ [string] $PartialFailureBlock,
380
+ [string] $BoundaryMode,
381
+ [string] $IssueCloseoutMode,
382
+ [string] $DecisionRequested,
383
+ [string] $Phase,
384
+ [string] $PrimaryFormalArtifact,
385
+ [string] $WatchdogReached
386
+ ) {
387
+ $gitTruthBlock = New-GitTruthBlock $RepoRootPath
388
+ $repoBranch = Get-GitCommandOutput $RepoRootPath @('branch', '--show-current')
389
+ $reportText = @"
390
+ # MAILBOX PARTIAL FAILURE REPORT
391
+ 1. Metadata
392
+ - Worker: Codex mailbox launcher
393
+ - Runtime: codex
394
+ - Phase: $Phase
395
+ - Repo / Branch: $RepoRootPath | $repoBranch
396
+ - Decision Requested: $DecisionRequested
397
+ - Issue Closeout Mode: $IssueCloseoutMode
398
+ - Runtime Outcome (completed | stalled | fallback-used): stalled
399
+ 2. Short Summary
400
+ - Launcher emitted a controller-usable partial-failure blocker report because the external Codex run did not reach a normal closeout path.
401
+ 3. Exact Files Changed
402
+ - none confirmed
403
+ 4. Carryover Findings Resolution
404
+ - no tracked diff from the stalled runtime was accepted
405
+ 5. Formal Artifact Truth
406
+ - primary formal artifact path: $PrimaryFormalArtifact
407
+ - written by agent or controller fallback: launcher-authored transient blocker report only
408
+ - fallback reason when controller authored the artifact: $CloseoutReason
409
+ 6. Execution Permission Audit
410
+ - see launcher audit block below
411
+ 7. Phase Artifact Validation
412
+ - skipped: implementation partial-failure closeout does not run review-phase artifact validation
413
+ 8. Exact Verification Results
414
+ - codex mailbox launch -> $CloseoutReason
415
+ - runtime report state before closeout -> $ReportStateBeforeCloseout
416
+ - raw log path -> $LogPath
417
+ 9. Boundary Truth
418
+ - included surfaces actually touched -> no tracked diff accepted from the stalled runtime
419
+ - excluded surfaces not touched -> not fully verifiable from the stalled runtime; controller fallback required before promotion
420
+ - formal artifacts created -> transient mailbox blocker report only ($ReportPath)
421
+ - boundary mode actually executed -> $BoundaryMode
422
+ - parent issue status after this batch (`DONE` | `IN_PROGRESS`) -> IN_PROGRESS
423
+ $gitTruthBlock
424
+ 11. Fallback Truth
425
+ - fallback trigger reached or not -> yes
426
+ - fallback path used or not -> launcher-authored partial-failure closeout only
427
+ - stalled runtime diff accepted: yes or no -> no
428
+ - watchdog timeout reached: yes or no -> $WatchdogReached
429
+ - launcher-authored partial-failure closeout emitted: yes or no -> yes
430
+ - raw log path -> $LogPath
431
+ - raw runtime report state before closeout -> $ReportStateBeforeCloseout
432
+ 12. Blockers / Open Questions
433
+ - external Codex run ended without a usable normal closeout path; controller must review the blocker report and choose a bounded fallback or rerun
434
+ 13. Ready State
435
+ - not ready
436
+ - reason -> $CloseoutReason
437
+ - next step -> choose controller fallback, native fallback, or a rerun with a new run id after reviewing the raw log
438
+ $PartialFailureBlock
439
+ $PermissionAuditBlock
440
+ "@
441
+ [System.IO.File]::WriteAllText($ReportPath, $reportText.TrimEnd() + [Environment]::NewLine, $Utf8NoBom)
442
+ if ($LogPath) {
443
+ Append-FileText $LogPath $PartialFailureBlock
444
+ Append-FileText $LogPath $PermissionAuditBlock
445
+ }
446
+ }
447
+
448
+ if (-not (Test-Path $RepoRoot)) { throw "RepoRoot not found: $RepoRoot" }
449
+ if (-not (Test-Path $TaskFile)) { throw "TaskFile not found: $TaskFile" }
450
+
451
+ $taskLines = Get-Content $TaskFile -Encoding UTF8
452
+ $prompt = New-BoundedExecutionPrompt $taskLines
453
+ $phase = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Phase:')
454
+ $permissionMode = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Execution Permission:') $ReadOnlyPermissionMode
455
+ $approvalStatus = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Permission Approval Status:') $NotRequiredApprovalStatus
456
+ $approvedBy = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approved By:') 'n/a'
457
+ $approvalReason = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approval Reason:') 'n/a'
458
+ $approvedScope = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approved Writable Scope:') 'n/a'
459
+ $approvalReference = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Approval Reference:') 'n/a'
460
+ $issueCloseoutMode = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Issue Closeout Mode:') 'phase-only'
461
+ $decisionRequested = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Decision Requested:') 'n/a'
462
+ $boundaryMode = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Boundary Mode:') 'n/a'
463
+ $primaryFormalArtifact = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Primary Formal Artifact:') 'n/a'
464
+ $stallBudgetValue = Normalize-TaskValue (Get-TaskBulletValue $taskLines 'Runtime Stall Budget / Fallback Trigger:')
465
+ New-Item -ItemType Directory -Force -Path ([System.IO.Path]::GetDirectoryName($ReportFile)) | Out-Null
466
+ if ($LogFile) {
467
+ New-Item -ItemType Directory -Force -Path ([System.IO.Path]::GetDirectoryName($LogFile)) | Out-Null
468
+ }
469
+
470
+ $cliArgs = @('exec', '-c', 'mcp_servers={}', '-c', 'model_reasoning_effort="medium"', '-C', $RepoRoot, '--output-last-message', $ReportFile)
471
+ $useWorkspaceWrite = $false
472
+ $effectiveMode = $ReadOnlyPermissionMode
473
+ $decisionSummary = ''
474
+ $approvalFieldsArePlaceholder = (Test-PlaceholderValue $approvedBy) -and (Test-PlaceholderValue $approvalReason) -and (Test-PlaceholderValue $approvedScope)
475
+
476
+ if ($ReviewPhases -contains $phase) {
477
+ if ($permissionMode -ne $ReadOnlyPermissionMode) {
478
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'review phase attempted writable permission and was rejected before launch'
479
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Review-phase mailbox runs must declare 'Execution Permission: read-only'."
480
+ }
481
+ if ($approvalStatus -ne $NotRequiredApprovalStatus -or -not $approvalFieldsArePlaceholder) {
482
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'review phase approval metadata was inconsistent for a read-only run'
483
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Read-only review phases must use 'Permission Approval Status: not-required' and leave writable approval fields as 'n/a'."
484
+ }
485
+ $decisionSummary = 'review phase forced explicit read-only sandbox'
486
+ } elseif ($phase -eq 'implementation') {
487
+ if ($permissionMode -eq $WritablePermissionMode) {
488
+ if ($approvalStatus -ne $HumanApprovedStatus) {
489
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'writable implementation requested without human-approved status'
490
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Writable implementation runs require 'Permission Approval Status: human-approved'."
491
+ }
492
+ if ((Test-PlaceholderValue $approvedBy) -or (Test-PlaceholderValue $approvalReason) -or (Test-PlaceholderValue $approvedScope)) {
493
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'writable implementation requested without complete approval metadata'
494
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message 'Writable implementation runs require Approved By, Approval Reason, and Approved Writable Scope.'
495
+ }
496
+ $useWorkspaceWrite = $true
497
+ $effectiveMode = 'workspace-write'
498
+ $decisionSummary = 'writable Codex implementation run approved and enabled from task-packet approval record'
499
+ } elseif ($permissionMode -eq $ReadOnlyPermissionMode) {
500
+ if ($approvalStatus -ne $NotRequiredApprovalStatus -or -not $approvalFieldsArePlaceholder) {
501
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'read-only implementation run carried contradictory writable approval metadata'
502
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Read-only implementation runs must use 'Permission Approval Status: not-required' and leave writable approval fields as 'n/a'."
503
+ }
504
+ $decisionSummary = 'implementation run remained read-only because no writable approval was declared'
505
+ } else {
506
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'unknown execution permission rejected before launch'
507
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Unknown execution permission mode '$permissionMode'."
508
+ }
509
+ } else {
510
+ if ($permissionMode -ne $ReadOnlyPermissionMode) {
511
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'non-implementation phase attempted writable permission and was rejected before launch'
512
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message 'Only implementation-phase mailbox runs may request writable execution.'
513
+ }
514
+ if ($approvalStatus -ne $NotRequiredApprovalStatus -or -not $approvalFieldsArePlaceholder) {
515
+ $auditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $ReadOnlyPermissionMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary 'non-implementation phase approval metadata was inconsistent for a read-only run'
516
+ Write-PermissionFailure -ReportPath $ReportFile -LogPath $LogFile -AuditBlock $auditBlock -Message "Non-implementation read-only runs must use 'Permission Approval Status: not-required' and leave writable approval fields as 'n/a'."
517
+ }
518
+ $decisionSummary = 'non-implementation phase forced explicit read-only sandbox'
519
+ }
520
+
521
+ if ($FullAuto -and -not $useWorkspaceWrite) {
522
+ $decisionSummary += '; ignored manual -FullAuto override because the task packet did not authorize writable execution'
523
+ }
524
+
525
+ $watchdogSeconds = Get-StallBudgetSeconds -Phase $phase -RawValue $stallBudgetValue
526
+ $stallBudgetSource = Get-StallBudgetSource -RawValue $stallBudgetValue -Seconds $watchdogSeconds
527
+ $permissionAuditBlock = New-PermissionAuditBlock -DeclaredPermission $permissionMode -EffectiveMode $effectiveMode -ApprovalStatus $approvalStatus -ApprovedBy $approvedBy -ApprovalReason $approvalReason -ApprovedScope $approvedScope -ApprovalReference $approvalReference -DecisionSummary $decisionSummary
528
+
529
+ if ($useWorkspaceWrite) {
530
+ $cliArgs += '--full-auto'
531
+ } else {
532
+ $cliArgs += @('--sandbox', 'read-only')
533
+ }
534
+ if ($Model) { $cliArgs += @('--model', $Model) }
535
+ $cliArgs += '-'
536
+
537
+ if ($DryRun) {
538
+ [pscustomobject]@{
539
+ Cli = 'codex'
540
+ RepoRoot = $RepoRoot
541
+ TaskFile = $TaskFile
542
+ ReportFile = $ReportFile
543
+ LogFile = $LogFile
544
+ Args = $cliArgs
545
+ DeclaredExecutionPermission = $permissionMode
546
+ EffectiveRuntimePermissionMode = $effectiveMode
547
+ PermissionApprovalStatus = $approvalStatus
548
+ ApprovedBy = $approvedBy
549
+ ApprovalReason = $approvalReason
550
+ ApprovedWritableScope = $approvedScope
551
+ ApprovalReference = $approvalReference
552
+ LauncherDecisionSummary = $decisionSummary
553
+ RuntimeStallBudget = $stallBudgetValue
554
+ EffectiveWatchdogSeconds = $watchdogSeconds
555
+ PromptLength = $prompt.Length
556
+ PromptPreview = if ($prompt.Length -gt 2000) { $prompt.Substring(0, 2000) } else { $prompt }
557
+ } | ConvertTo-Json -Depth 4
558
+ exit 0
559
+ }
560
+
561
+ $promptPath = Join-Path ([System.IO.Path]::GetTempPath()) ("sdtk-mailbox-prompt-" + [guid]::NewGuid().ToString('N') + '.md')
562
+ [System.IO.File]::WriteAllText($promptPath, $prompt, $Utf8NoBom)
563
+ try {
564
+ $processResult = Invoke-CodexProcessWithWatchdog -RepoRootPath $RepoRoot -PromptPath $promptPath -ReportPath $ReportFile -LogPath $LogFile -ModelName $Model -UseWorkspaceWrite:$useWorkspaceWrite -WatchdogSeconds $watchdogSeconds
565
+ $reportStateBeforeCloseout = Get-ReportState $ReportFile
566
+ $runtimeExitCode = if ($processResult.TimedOut) { 'timed-out' } else { [string]$processResult.ExitCode }
567
+ $needsPartialFailureCloseout = $processResult.TimedOut -or $processResult.ExitCode -ne 0 -or $reportStateBeforeCloseout -ne 'present'
568
+
569
+ if ($needsPartialFailureCloseout) {
570
+ if ($processResult.TimedOut) {
571
+ $closeoutReason = "launcher watchdog terminated the external Codex run after $watchdogSeconds second(s) before a usable normal closeout path was reached"
572
+ $watchdogReached = 'yes'
573
+ } elseif ($reportStateBeforeCloseout -ne 'present') {
574
+ $closeoutReason = "external Codex run exited with code $runtimeExitCode without writing a usable runtime report"
575
+ $watchdogReached = 'no'
576
+ } else {
577
+ $closeoutReason = "external Codex run exited with code $runtimeExitCode and requires controller review before the batch can proceed"
578
+ $watchdogReached = 'no'
579
+ }
580
+
581
+ $partialFailureBlock = New-PartialFailureCloseoutBlock -CloseoutReason $closeoutReason -StallBudgetSource $stallBudgetSource -WatchdogSeconds $watchdogSeconds -RuntimeExitCode $runtimeExitCode -ReportStateBeforeCloseout $reportStateBeforeCloseout -LogPath $(if ($LogFile) { $LogFile } else { 'n/a' }) -CloseoutAuthorship $(if ($reportStateBeforeCloseout -eq 'present') { 'no' } else { 'yes' }) -WatchdogReached $watchdogReached
582
+
583
+ if ($reportStateBeforeCloseout -eq 'present') {
584
+ Append-FileText $ReportFile $partialFailureBlock
585
+ Append-FileText $ReportFile $permissionAuditBlock
586
+ if ($LogFile) {
587
+ Append-FileText $LogFile $partialFailureBlock
588
+ Append-FileText $LogFile $permissionAuditBlock
589
+ }
590
+ } else {
591
+ Write-StructuredPartialFailureReport -RepoRootPath $RepoRoot -ReportPath $ReportFile -LogPath $LogFile -CloseoutReason $closeoutReason -RuntimeExitCode $runtimeExitCode -ReportStateBeforeCloseout $reportStateBeforeCloseout -PermissionAuditBlock $permissionAuditBlock -PartialFailureBlock $partialFailureBlock -BoundaryMode $boundaryMode -IssueCloseoutMode $issueCloseoutMode -DecisionRequested $decisionRequested -Phase $phase -PrimaryFormalArtifact $primaryFormalArtifact -WatchdogReached $watchdogReached
592
+ }
593
+
594
+ if ($processResult.TimedOut) {
595
+ Write-Error $closeoutReason
596
+ exit 124
597
+ }
598
+
599
+ if ($processResult.ExitCode -ne 0) {
600
+ Write-Error $closeoutReason
601
+ exit $processResult.ExitCode
602
+ }
603
+
604
+ Write-Error $closeoutReason
605
+ exit 3
606
+ }
607
+
608
+ Append-FileText $ReportFile $permissionAuditBlock
609
+ if ($LogFile) {
610
+ Append-FileText $LogFile $permissionAuditBlock
611
+ }
612
+
613
+ $validatorPath = Join-Path $RepoRoot 'products/sdtk-spec/toolkit/scripts/agents/validate-mailbox-formal-artifact.py'
614
+ Invoke-PhaseArtifactValidation -TaskLines $taskLines -RepoRootPath $RepoRoot -ReportPath $ReportFile -LogPath $LogFile -ValidatorPath $validatorPath
615
+ Write-Host "Codex report written to: $ReportFile"
616
+ } finally {
617
+ Remove-Item $promptPath -Force -ErrorAction SilentlyContinue
618
+ }