@t275005746/gse 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/.gse/releases/public-github-release-v0.1.2.md +49 -0
  2. package/.gse/releases/public-registry-publication-npm.md +49 -49
  3. package/.gse/state.json +148 -26
  4. package/CHANGELOG.md +52 -8
  5. package/README.md +13 -6
  6. package/README.zh-CN.md +13 -6
  7. package/SKILL.md +32 -12
  8. package/assets/templates/dispatch-packet.md +22 -14
  9. package/assets/templates/evidence.md +11 -5
  10. package/assets/templates/role-fallback-packet.md +49 -0
  11. package/package.json +18 -10
  12. package/references/agent-roles.md +41 -20
  13. package/references/commands.md +75 -45
  14. package/references/drift-audit.md +2 -1
  15. package/references/evidence-taxonomy.md +46 -9
  16. package/references/file-ownership.md +17 -13
  17. package/references/final-form-roadmap.md +203 -0
  18. package/references/final-readiness.md +3 -3
  19. package/references/host-adapters.md +38 -10
  20. package/references/learning-system.md +24 -8
  21. package/references/maintenance-cadence.md +51 -0
  22. package/references/project-guards.md +52 -0
  23. package/references/quality-gates.md +18 -11
  24. package/references/role-dispatch-fallback.md +54 -0
  25. package/references/tool-adapters.md +13 -3
  26. package/scripts/audit-close-gate-hardening.mjs +188 -0
  27. package/scripts/audit-close-gate.mjs +219 -33
  28. package/scripts/audit-command-execution.mjs +30 -17
  29. package/scripts/audit-commands.mjs +7 -5
  30. package/scripts/audit-completion-plan-drill.mjs +271 -0
  31. package/scripts/audit-completion-readiness.mjs +9 -6
  32. package/scripts/audit-continue-preflight.mjs +318 -0
  33. package/scripts/audit-evidence-levels.mjs +217 -0
  34. package/scripts/audit-evidence-review-queue.mjs +206 -0
  35. package/scripts/audit-final-acceptance-packet.mjs +9 -9
  36. package/scripts/audit-final-form-progress-report.mjs +19 -18
  37. package/scripts/audit-final-form-roadmap.mjs +157 -0
  38. package/scripts/audit-final-form-stale-copy.mjs +2 -2
  39. package/scripts/audit-final-readiness.mjs +3 -3
  40. package/scripts/audit-fresh-session-readiness.mjs +1 -1
  41. package/scripts/audit-host-capabilities.mjs +237 -0
  42. package/scripts/audit-installed-sync.mjs +203 -0
  43. package/scripts/audit-learning-drift.mjs +292 -0
  44. package/scripts/audit-learning-promotion.mjs +351 -0
  45. package/scripts/audit-learning-system.mjs +24 -14
  46. package/scripts/audit-local-final-form-completion.mjs +11 -10
  47. package/scripts/audit-maintenance-cadence.mjs +139 -0
  48. package/scripts/audit-maintenance-snapshot.mjs +181 -0
  49. package/scripts/audit-npm-package-metadata.mjs +8 -2
  50. package/scripts/audit-npm-publish-dry-run.mjs +10 -4
  51. package/scripts/audit-npm-tarball-install.mjs +9 -3
  52. package/scripts/audit-owner-external-gate-kit.mjs +12 -11
  53. package/scripts/audit-project-guards.mjs +189 -0
  54. package/scripts/audit-project.mjs +14 -11
  55. package/scripts/audit-public-acceptance-handoff.mjs +10 -10
  56. package/scripts/audit-public-acceptance-readiness.mjs +6 -6
  57. package/scripts/audit-public-release-checklist.mjs +17 -15
  58. package/scripts/audit-release-bundle.mjs +13 -11
  59. package/scripts/audit-release-owner-action-plan-drill.mjs +5 -4
  60. package/scripts/audit-release-owner-action-plan.mjs +10 -10
  61. package/scripts/audit-release-status-manifest.mjs +4 -4
  62. package/scripts/audit-roadmap-consistency.mjs +11 -7
  63. package/scripts/audit-role-dispatch-fallback.mjs +212 -0
  64. package/scripts/audit-session-sync.mjs +127 -0
  65. package/scripts/audit-state-freshness.mjs +6 -5
  66. package/scripts/audit-state-repair.mjs +360 -0
  67. package/scripts/audit-target-hardening-drills.mjs +518 -0
  68. package/scripts/audit-tool-fallback-policy.mjs +180 -0
  69. package/scripts/audit-ui-browser-evidence-policy.mjs +191 -0
  70. package/scripts/audit-validation-profiles.mjs +6 -4
  71. package/scripts/backfill-evidence-levels.mjs +98 -0
  72. package/scripts/check-encoding.mjs +72 -0
  73. package/scripts/generate-continue-packet.mjs +1487 -0
  74. package/scripts/generate-final-acceptance-packet.mjs +23 -8
  75. package/scripts/generate-final-form-progress-report.mjs +25 -23
  76. package/scripts/generate-host-runtime-evidence-handoff.mjs +23 -16
  77. package/scripts/generate-maintenance-snapshot.mjs +216 -0
  78. package/scripts/generate-public-acceptance-handoff.mjs +26 -14
  79. package/scripts/generate-release-owner-action-plan.mjs +4 -3
  80. package/scripts/generate-release-status-manifest.mjs +4 -3
  81. package/scripts/init-project.mjs +144 -63
  82. package/scripts/record-learning.mjs +37 -8
  83. package/scripts/record-session-sync.mjs +87 -0
  84. package/scripts/run-gse-command.mjs +79 -47
  85. package/scripts/run-validation-profile.mjs +24 -5
  86. package/scripts/validate-gse.mjs +262 -9
@@ -0,0 +1,518 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { spawnSync } from 'node:child_process'
6
+
7
+ const args = process.argv.slice(2)
8
+
9
+ function readArg(name, fallback = null) {
10
+ const index = args.indexOf(name)
11
+ if (index === -1) return fallback
12
+ return args[index + 1] ?? fallback
13
+ }
14
+
15
+ function readAllArgs(name) {
16
+ const values = []
17
+ for (let index = 0; index < args.length; index += 1) {
18
+ if (args[index] === name && args[index + 1]) values.push(args[index + 1])
19
+ }
20
+ return values
21
+ }
22
+
23
+ const root = path.resolve(readArg('--root', path.join(import.meta.dirname, '..')))
24
+ const jsonOnly = args.includes('--json')
25
+ const strictWarnings = args.includes('--strict-warnings')
26
+
27
+ function run(script, commandArgs, options = {}) {
28
+ const result = spawnSync(process.execPath, [path.join(root, 'scripts', script), ...commandArgs], {
29
+ cwd: root,
30
+ encoding: 'utf8',
31
+ windowsHide: true,
32
+ ...options,
33
+ })
34
+ const stdout = (result.stdout ?? '').trim()
35
+ let parsed = null
36
+ try {
37
+ parsed = JSON.parse(stdout)
38
+ } catch {
39
+ parsed = null
40
+ }
41
+ return {
42
+ script,
43
+ command: [process.execPath, path.join(root, 'scripts', script), ...commandArgs].join(' '),
44
+ status: result.status ?? 1,
45
+ stdout,
46
+ stderr: (result.stderr ?? '').trim(),
47
+ parsed,
48
+ }
49
+ }
50
+
51
+ function check(id, label, status, evidence, recommendation = '') {
52
+ return { id, label, status, evidence, recommendation }
53
+ }
54
+
55
+ function parseTargets() {
56
+ const explicitTargets = readAllArgs('--target')
57
+ const namedTargets = [
58
+ { id: 'aion', root: readArg('--aion-target', process.env.GSE_AION_TARGET || null) },
59
+ { id: 'museflow', root: readArg('--museflow-target', process.env.GSE_MUSEFLOW_TARGET || null) },
60
+ ].filter((item) => item.root)
61
+ const explicit = explicitTargets.map((target, index) => ({
62
+ id: `target-${index + 1}`,
63
+ root: target,
64
+ }))
65
+ return [...namedTargets, ...explicit].map((item) => ({
66
+ ...item,
67
+ root: path.resolve(item.root),
68
+ }))
69
+ }
70
+
71
+ function statusFromRun(runResult) {
72
+ if (!runResult.parsed) return runResult.status === 0 ? 'passed' : 'failed'
73
+ const summaryStatus = runResult.parsed.summary?.status
74
+ if (summaryStatus === 'failed' || summaryStatus === 'not-ready') return 'failed'
75
+ if (summaryStatus === 'warning' || summaryStatus === 'ready-with-warnings') return 'warning'
76
+ if ((runResult.parsed.summary?.failed ?? 0) > 0) return 'failed'
77
+ if ((runResult.parsed.summary?.warnings ?? 0) > 0) return 'warning'
78
+ return runResult.status === 0 ? 'passed' : 'failed'
79
+ }
80
+
81
+ function evidenceFromRun(runResult) {
82
+ const summary = runResult.parsed?.summary
83
+ if (!summary) return runResult.stderr || runResult.stdout.slice(0, 160) || `exit:${runResult.status}`
84
+ const parts = []
85
+ if (summary.status) parts.push(`status:${summary.status}`)
86
+ if (Number.isFinite(summary.passed) && Number.isFinite(summary.total)) parts.push(`checks:${summary.passed}/${summary.total}`)
87
+ if (Number.isFinite(summary.warnings)) parts.push(`warnings:${summary.warnings}`)
88
+ if (Number.isFinite(summary.failed)) parts.push(`failed:${summary.failed}`)
89
+ if (Number.isFinite(summary.blockedGates)) parts.push(`blockedGates:${summary.blockedGates}`)
90
+ if (Number.isFinite(summary.highUnenforced)) parts.push(`highUnenforced:${summary.highUnenforced}`)
91
+ return parts.join(', ') || `exit:${runResult.status}`
92
+ }
93
+
94
+ function compactText(value, limit = 180) {
95
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
96
+ if (text.length <= limit) return text
97
+ return text.slice(0, limit - 3) + '...'
98
+ }
99
+
100
+ function warningChecks(runResult) {
101
+ return (runResult.parsed?.checks ?? [])
102
+ .filter((item) => item.status === 'warning' || item.status === 'failed')
103
+ .map((item) => ({
104
+ id: item.id,
105
+ label: item.label,
106
+ status: item.status,
107
+ evidence: compactText(item.evidence),
108
+ recommendation: compactText(item.recommendation),
109
+ }))
110
+ }
111
+
112
+ function repairIssues(runResult) {
113
+ return (runResult.parsed?.repairActions ?? [])
114
+ .map((item) => ({
115
+ id: item.id,
116
+ label: item.problem,
117
+ status: item.severity === 'hard' ? 'failed' : 'warning',
118
+ evidence: item.targetPath,
119
+ recommendation: compactText(item.command),
120
+ }))
121
+ }
122
+
123
+ function uniqueIssues(items, limit = 8) {
124
+ const seen = new Set()
125
+ const result = []
126
+ for (const item of items) {
127
+ const key = `${item.id}:${item.label}:${item.evidence}`
128
+ if (seen.has(key)) continue
129
+ seen.add(key)
130
+ result.push(item)
131
+ if (result.length >= limit) break
132
+ }
133
+ return result
134
+ }
135
+
136
+ function classifyTargetAdoption({ hasHardFailure, hasWarnings, topLocalIssues }) {
137
+ if (hasHardFailure) return 'target-hard-failure'
138
+ if (topLocalIssues.length > 0) return 'target-local-adoption-hygiene'
139
+ if (hasWarnings) return 'gse-ready-with-soft-warnings'
140
+ return 'gse-ready'
141
+ }
142
+
143
+ function hasDirtyGseIssue(topLocalIssues) {
144
+ return topLocalIssues.some((item) => {
145
+ const id = String(item.id ?? '')
146
+ const evidence = String(item.evidence ?? '').toLowerCase()
147
+ if (id.startsWith('SR')) return false
148
+ return (
149
+ id === 'TPD09' ||
150
+ id === 'CG08' ||
151
+ evidence.includes('.gse/') ||
152
+ evidence.includes('.gse\\')
153
+ )
154
+ })
155
+ }
156
+
157
+ function hasDirtyTargetWorktreeIssue(topLocalIssues) {
158
+ return topLocalIssues.some((item) => {
159
+ const id = String(item.id ?? '')
160
+ const label = String(item.label ?? '').toLowerCase()
161
+ const evidence = String(item.evidence ?? '').toLowerCase()
162
+ return (
163
+ id === 'CG11' ||
164
+ label.includes('worktree') ||
165
+ evidence.includes('staged') ||
166
+ evidence.includes('unstaged') ||
167
+ evidence.includes('untracked') ||
168
+ evidence.includes('conflict')
169
+ )
170
+ })
171
+ }
172
+
173
+ function hasStateRepairIssue(topLocalIssues) {
174
+ return topLocalIssues.some((item) => String(item.id ?? '').startsWith('SR'))
175
+ }
176
+
177
+ function buildRepairPlan({ topLocalIssues, stateRepairSummary }) {
178
+ const dirtyGse = hasDirtyGseIssue(topLocalIssues)
179
+ const dirtyTargetWorktree = hasDirtyTargetWorktreeIssue(topLocalIssues)
180
+ const stateRepairAdvised = hasStateRepairIssue(topLocalIssues) || (stateRepairSummary.actions ?? 0) > 0
181
+ const repairBlockedByDirtyWorktree = dirtyGse || dirtyTargetWorktree
182
+ const steps = []
183
+ if (dirtyTargetWorktree) {
184
+ steps.push({
185
+ id: 'resolve-worktree-ownership',
186
+ status: 'required-first',
187
+ action: 'Review current target worktree ownership, finish or exclude unrelated target-session changes, and stage/commit only the active slice before repair.',
188
+ })
189
+ } else if (dirtyGse) {
190
+ steps.push({
191
+ id: 'resolve-gse-worktree-ownership',
192
+ status: 'required-first',
193
+ action: 'Review current .gse worktree ownership, finish or exclude unrelated target-session changes, and stage/commit only the active slice before repair.',
194
+ })
195
+ }
196
+ if (stateRepairAdvised) {
197
+ steps.push({
198
+ id: 'compact-state-risks',
199
+ status: repairBlockedByDirtyWorktree ? 'blocked-until-worktree-owned' : 'ready',
200
+ action: 'Run `/gse repair --execute` only after the target worktree and .gse state are owned and reversible backup output is acceptable.',
201
+ })
202
+ }
203
+ if (!steps.length) {
204
+ steps.push({
205
+ id: 'no-repair-required',
206
+ status: 'ready',
207
+ action: 'No target adoption repair step is required before normal continuation.',
208
+ })
209
+ }
210
+ return {
211
+ repairBlockedByDirtyGse: dirtyGse && stateRepairAdvised,
212
+ repairBlockedByDirtyWorktree: repairBlockedByDirtyWorktree && stateRepairAdvised,
213
+ stateRepairAdvised,
214
+ dirtyGseWorktree: dirtyGse,
215
+ dirtyTargetWorktree,
216
+ steps,
217
+ }
218
+ }
219
+
220
+ function buildRecommendedNextActions(topLocalIssues, repairPlan) {
221
+ const actions = []
222
+ for (const step of repairPlan.steps) {
223
+ if (step.id === 'no-repair-required') continue
224
+ actions.push(step.action)
225
+ }
226
+ for (const issue of uniqueIssues(topLocalIssues, 8)) {
227
+ if (!issue.recommendation) continue
228
+ if (repairPlan.repairBlockedByDirtyWorktree && String(issue.id ?? '').startsWith('SR')) continue
229
+ actions.push(issue.recommendation)
230
+ }
231
+ return [...new Set(actions)].slice(0, 6)
232
+ }
233
+
234
+ function buildTargetAdoptionSummary(commandRuns, checks) {
235
+ const failed = checks.filter((item) => item.status === 'failed')
236
+ const warnings = checks.filter((item) => item.status === 'warning')
237
+ const continueSummary = commandRuns.continue.parsed?.summary ?? {}
238
+ const stateRepairSummary = commandRuns.stateRepair.parsed?.summary ?? {}
239
+ const portableContinueUsable =
240
+ commandRuns.continue.status === 0 &&
241
+ (continueSummary.failedHardChecks ?? 0) === 0 &&
242
+ (continueSummary.blockedGates ?? 0) === 0
243
+ const activeRiskCount = continueSummary.activeRiskCount ?? continueSummary.riskCount ?? null
244
+ const topLocalIssues = uniqueIssues([
245
+ ...repairIssues(commandRuns.stateRepair),
246
+ ...warningChecks(commandRuns.doctor),
247
+ ...warningChecks(commandRuns.close),
248
+ ...warningChecks(commandRuns.hostCapabilities),
249
+ ...warningChecks(commandRuns.learningDrift),
250
+ ])
251
+ const repairPlan = buildRepairPlan({ topLocalIssues, stateRepairSummary })
252
+ const recommendedNextActions = buildRecommendedNextActions(topLocalIssues, repairPlan)
253
+ const hasHardFailure = failed.length > 0 || (stateRepairSummary.hard ?? 0) > 0
254
+ const hasWarnings = warnings.length > 0 || (stateRepairSummary.warnings ?? 0) > 0
255
+ return {
256
+ classification: classifyTargetAdoption({ hasHardFailure, hasWarnings, topLocalIssues }),
257
+ gseCoreGap: false,
258
+ coreGapAssessment: 'not-assessed-by-target-drill',
259
+ portableContinueUsable,
260
+ hostNativeSlashCommand: 'not-proven',
261
+ longPromptRisk: portableContinueUsable
262
+ ? Number.isFinite(activeRiskCount) && activeRiskCount > 20
263
+ ? 'risk-dump-needs-compaction'
264
+ : 'low'
265
+ : 'unknown',
266
+ activeRiskCount,
267
+ stateRepairStatus: stateRepairSummary.status ?? 'unknown',
268
+ topLocalIssues,
269
+ repairPlan,
270
+ recommendedNextActions,
271
+ limits: [
272
+ 'This classifies target-project adoption hygiene, not product readiness.',
273
+ 'gseCoreGap=false means this target drill did not find or claim a GSE core gap; full core-gap coverage belongs to GSE self audits.',
274
+ 'Portable /gse continue success does not prove host-native slash-command support.',
275
+ 'Warnings should be fixed before claiming a target project is fully GSE-ready, but they do not block normal continuation unless project policy says so.',
276
+ ],
277
+ }
278
+ }
279
+
280
+ function validateAdoptionSummary(target) {
281
+ const summary = target.adoptionSummary
282
+ const allowedClassifications = new Set([
283
+ 'gse-ready',
284
+ 'gse-ready-with-soft-warnings',
285
+ 'target-local-adoption-hygiene',
286
+ 'target-hard-failure',
287
+ ])
288
+ const failures = []
289
+ if (!summary || typeof summary !== 'object') failures.push('missing adoptionSummary')
290
+ if (summary && !allowedClassifications.has(summary.classification)) failures.push('invalid classification')
291
+ if (summary && typeof summary.gseCoreGap !== 'boolean') failures.push('gseCoreGap is not boolean')
292
+ if (summary && summary.coreGapAssessment !== 'not-assessed-by-target-drill') failures.push('coreGapAssessment boundary is missing')
293
+ if (summary && typeof summary.portableContinueUsable !== 'boolean') failures.push('portableContinueUsable is not boolean')
294
+ if (summary && !Array.isArray(summary.topLocalIssues)) failures.push('topLocalIssues is not an array')
295
+ if (summary && !summary.repairPlan) failures.push('missing repairPlan')
296
+ if (summary?.repairPlan && typeof summary.repairPlan.repairBlockedByDirtyGse !== 'boolean') failures.push('repairPlan.repairBlockedByDirtyGse is not boolean')
297
+ if (summary?.repairPlan && typeof summary.repairPlan.repairBlockedByDirtyWorktree !== 'boolean') failures.push('repairPlan.repairBlockedByDirtyWorktree is not boolean')
298
+ if (summary?.repairPlan && typeof summary.repairPlan.dirtyTargetWorktree !== 'boolean') failures.push('repairPlan.dirtyTargetWorktree is not boolean')
299
+ if (summary?.repairPlan && !Array.isArray(summary.repairPlan.steps)) failures.push('repairPlan.steps is not an array')
300
+ if (summary && !Array.isArray(summary.recommendedNextActions)) failures.push('recommendedNextActions is not an array')
301
+ if (summary?.repairPlan?.repairBlockedByDirtyWorktree) {
302
+ const firstAction = String(summary.recommendedNextActions?.[0] ?? '')
303
+ if (!firstAction.includes('worktree ownership')) failures.push('dirty repair plan does not prioritize worktree ownership')
304
+ }
305
+ if (summary?.classification === 'target-local-adoption-hygiene' && summary.topLocalIssues.length === 0) {
306
+ failures.push('local hygiene classification has no local issues')
307
+ }
308
+ return check(
309
+ `${target.id}-adoption-summary`,
310
+ 'target adoption summary is structured and separates soft warnings from local hygiene',
311
+ failures.length === 0 ? 'passed' : 'failed',
312
+ failures.length === 0
313
+ ? `classification:${summary.classification}, portableContinueUsable:${summary.portableContinueUsable}, gseCoreGap:${summary.gseCoreGap}`
314
+ : failures.join('; '),
315
+ 'Keep adoptionSummary machine-readable so project adoption reports do not overstate GSE core gaps.',
316
+ )
317
+ }
318
+
319
+ function createFixture(label, options = {}) {
320
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `gse-hardening-${label}-`))
321
+ const init = run('init-project.mjs', ['--target', dir, '--mode', 'enterprise', '--json'])
322
+ fs.mkdirSync(path.join(dir, 'docs'), { recursive: true })
323
+ fs.writeFileSync(path.join(dir, 'docs', 'productization-architecture.md'), `# ${label} Productization\n`, 'utf8')
324
+
325
+ const statePath = path.join(dir, '.gse', 'state.json')
326
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'))
327
+ state.canonicalPlan = 'docs/productization-architecture.md'
328
+ state.phase = 'verify'
329
+ state.currentSlice = {
330
+ id: `${label}-hardening-fixture`,
331
+ outcome: `${label} hardening fixture.`,
332
+ status: 'verified',
333
+ nextAction: 'Continue target hardening drill.',
334
+ }
335
+ state.lastEvidence = '.gse/evidence/2026-07-09.md'
336
+ state.residualRisks = options.committedRepair
337
+ ? Array.from({ length: 8 }, (_, index) => `Committed fixture residual risk ${index + 1} that should be compacted only after worktree ownership is resolved.`)
338
+ : []
339
+ fs.writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n', 'utf8')
340
+ fs.appendFileSync(path.join(dir, '.gse', 'README.md'), '\nCanonical plan: `docs/productization-architecture.md`.\n', 'utf8')
341
+ fs.writeFileSync(path.join(dir, '.gse', 'evidence', '2026-07-09.md'), '# Evidence\n\nFixture hardening evidence.\n', 'utf8')
342
+ fs.writeFileSync(path.join(dir, '.gse', 'evidence', 'index.jsonl'), JSON.stringify({
343
+ date: '2026-07-09',
344
+ recordType: 'slice',
345
+ status: 'verified',
346
+ evidenceLevel: 'verified-unit',
347
+ requiredEvidenceLevel: 'verified-unit',
348
+ summary: `${label} hardening fixture evidence.`,
349
+ evidenceFile: '.gse/evidence/2026-07-09.md',
350
+ commands: ['node scripts/audit-target-hardening-drills.mjs --self-test'],
351
+ nextAction: 'Continue target hardening drill.',
352
+ }) + '\n', 'utf8')
353
+ spawnSync('git', ['init'], { cwd: dir, encoding: 'utf8', windowsHide: true })
354
+ spawnSync('git', ['config', 'user.email', 'gse-fixture@example.local'], { cwd: dir, encoding: 'utf8', windowsHide: true })
355
+ spawnSync('git', ['config', 'user.name', 'GSE Fixture'], { cwd: dir, encoding: 'utf8', windowsHide: true })
356
+ spawnSync('git', ['add', '.'], { cwd: dir, encoding: 'utf8', windowsHide: true })
357
+ spawnSync('git', ['commit', '-m', 'fixture'], { cwd: dir, encoding: 'utf8', windowsHide: true })
358
+ if (options.dirtyRepair || options.dirtyProductRepair) {
359
+ state.residualRisks = Array.from({ length: 8 }, (_, index) => `Fixture residual risk ${index + 1} that should be compacted after worktree ownership is resolved.`)
360
+ fs.writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n', 'utf8')
361
+ }
362
+ if (options.dirtyProductRepair) {
363
+ fs.mkdirSync(path.join(dir, 'src'), { recursive: true })
364
+ fs.writeFileSync(path.join(dir, 'src', 'active-slice.js'), 'export const activeSlice = true\n', 'utf8')
365
+ }
366
+ return { dir, init }
367
+ }
368
+
369
+ function auditTarget(target) {
370
+ const commandRuns = {
371
+ doctor: run('audit-target-project.mjs', ['--root', root, '--target', target.root, '--json']),
372
+ continue: run('run-gse-command.mjs', ['--root', root, '--target', target.root, '--command', '/gse continue', '--json', '--compact']),
373
+ close: run('audit-close-gate.mjs', ['--target', target.root, '--json']),
374
+ hostCapabilities: run('audit-host-capabilities.mjs', ['--root', root, '--target', target.root, '--json']),
375
+ learningDrift: run('audit-learning-drift.mjs', ['--root', root, '--target', target.root, '--json']),
376
+ stateRepair: run('audit-state-repair.mjs', ['--root', root, '--target', target.root, '--json']),
377
+ }
378
+ const checks = [
379
+ check(`${target.id}-doctor`, 'target project doctor has no hard failures', statusFromRun(commandRuns.doctor), evidenceFromRun(commandRuns.doctor), 'Repair target .gse adoption drift before claiming GSE-ready status.'),
380
+ check(`${target.id}-continue`, '/gse continue hard preflight returns a usable packet', statusFromRun(commandRuns.continue), evidenceFromRun(commandRuns.continue), 'Repair hard preflight failures before implementation starts.'),
381
+ check(`${target.id}-close`, 'close gate exposes close readiness and ownership state', statusFromRun(commandRuns.close), evidenceFromRun(commandRuns.close), 'Resolve close-gate failures before claiming the slice complete.'),
382
+ check(`${target.id}-host`, 'host capability records are audited with claim boundaries', statusFromRun(commandRuns.hostCapabilities), evidenceFromRun(commandRuns.hostCapabilities), 'Record missing host capability facts or keep unknown/external-required boundaries explicit.'),
383
+ check(`${target.id}-learning`, 'learning drift is audited for promoted guard candidates', statusFromRun(commandRuns.learningDrift), evidenceFromRun(commandRuns.learningDrift), 'Promote high-severity learning drift into guards, gates, or scripts before close.'),
384
+ ]
385
+ const adoptionSummary = buildTargetAdoptionSummary(commandRuns, checks)
386
+ checks.push(validateAdoptionSummary({ id: target.id, adoptionSummary }))
387
+ const failed = checks.filter((item) => item.status === 'failed')
388
+ const warnings = checks.filter((item) => item.status === 'warning')
389
+ return {
390
+ id: target.id,
391
+ root: target.root,
392
+ status: failed.length > 0 ? 'failed' : warnings.length > 0 ? 'warning' : 'passed',
393
+ adoptionSummary,
394
+ checks,
395
+ commands: Object.values(commandRuns).map((item) => item.command),
396
+ summaries: Object.fromEntries(Object.entries(commandRuns).map(([key, value]) => [key, value.parsed?.summary ?? { exit: value.status }])),
397
+ }
398
+ }
399
+
400
+ function runConfiguredTargets() {
401
+ const targets = parseTargets()
402
+ if (targets.length === 0) return null
403
+ return {
404
+ targets,
405
+ cleanup: () => {},
406
+ }
407
+ }
408
+
409
+ function runSelfTestTargets() {
410
+ const primary = createFixture('primary')
411
+ const secondary = createFixture('secondary', { dirtyRepair: true })
412
+ const dirtyProduct = createFixture('dirty-product', { dirtyProductRepair: true })
413
+ const committedRepairDirtyProduct = createFixture('committed-repair-dirty-product', { committedRepair: true })
414
+ fs.mkdirSync(path.join(committedRepairDirtyProduct.dir, 'src'), { recursive: true })
415
+ fs.writeFileSync(path.join(committedRepairDirtyProduct.dir, 'src', 'active-slice.js'), 'export const activeSlice = true\n', 'utf8')
416
+ return {
417
+ targets: [
418
+ { id: 'fixture-primary', root: primary.dir },
419
+ { id: 'fixture-secondary', root: secondary.dir },
420
+ { id: 'fixture-dirty-product', root: dirtyProduct.dir },
421
+ { id: 'fixture-committed-repair-dirty-product', root: committedRepairDirtyProduct.dir },
422
+ ],
423
+ cleanup: () => {
424
+ fs.rmSync(primary.dir, { recursive: true, force: true })
425
+ fs.rmSync(secondary.dir, { recursive: true, force: true })
426
+ fs.rmSync(dirtyProduct.dir, { recursive: true, force: true })
427
+ fs.rmSync(committedRepairDirtyProduct.dir, { recursive: true, force: true })
428
+ },
429
+ }
430
+ }
431
+
432
+ function buildReport() {
433
+ const configured = runConfiguredTargets()
434
+ const targetSet = configured ?? runSelfTestTargets()
435
+ try {
436
+ const reports = targetSet.targets.map(auditTarget)
437
+ const checks = reports.flatMap((report) => report.checks)
438
+ const hardFailures = checks.filter((item) => item.status === 'failed')
439
+ const warnings = checks.filter((item) => item.status === 'warning')
440
+ const passed = checks.filter((item) => item.status === 'passed').length
441
+ const failed = hardFailures.length
442
+ const warningCount = warnings.length
443
+ const status = failed > 0 || (strictWarnings && warningCount > 0) ? 'failed' : warningCount > 0 ? 'warning' : 'passed'
444
+ return {
445
+ root,
446
+ generatedAt: new Date().toISOString(),
447
+ summary: {
448
+ status,
449
+ mode: configured ? 'configured-targets' : 'self-test',
450
+ passed,
451
+ warnings: warningCount,
452
+ failed,
453
+ hardFailures: failed,
454
+ total: checks.length,
455
+ targets: reports.length,
456
+ },
457
+ workflows: {
458
+ targetHardeningDrills: status === 'failed' ? 'failed' : 'verified',
459
+ closeGateHardening: hardFailures.length === 0 ? 'verified' : 'failed',
460
+ hostCapabilityBoundaries: hardFailures.length === 0 ? 'verified' : 'failed',
461
+ learningDriftCoverage: hardFailures.length === 0 ? 'verified' : 'failed',
462
+ targetAdoptionHygieneSummary: hardFailures.length === 0 ? 'verified' : 'failed',
463
+ },
464
+ targets: reports,
465
+ checks,
466
+ limits: [
467
+ 'Target hardening drills are read-only for target projects.',
468
+ 'They run GSE doctor, /gse continue, close gate, host capability audit, and learning drift audit.',
469
+ 'Warnings mean the project can continue only if the current slice accepts that residual risk; hard failures must be fixed before close.',
470
+ 'This drill does not run product tests, browser smokes, CI, or native host slash-command invocation.',
471
+ ],
472
+ }
473
+ } finally {
474
+ targetSet.cleanup()
475
+ }
476
+ }
477
+
478
+ function renderMarkdown(report) {
479
+ const lines = []
480
+ lines.push('# GSE Target Hardening Drills')
481
+ lines.push('')
482
+ lines.push('Generated: ' + report.generatedAt)
483
+ lines.push('Root: ' + report.root)
484
+ lines.push('')
485
+ lines.push('## Summary')
486
+ lines.push('')
487
+ lines.push('- Status: ' + report.summary.status)
488
+ lines.push('- Mode: ' + report.summary.mode)
489
+ lines.push('- Targets: ' + report.summary.targets)
490
+ lines.push('- Checks: ' + report.summary.passed + ' passed, ' + report.summary.warnings + ' warnings, ' + report.summary.hardFailures + ' hard failures, ' + report.summary.total + ' total')
491
+ lines.push('')
492
+ lines.push('## Targets')
493
+ lines.push('')
494
+ for (const target of report.targets) {
495
+ lines.push('- ' + target.id + ': ' + target.status + ' at ' + target.root)
496
+ lines.push(' - Classification: ' + target.adoptionSummary.classification)
497
+ lines.push(' - Portable continue usable: ' + target.adoptionSummary.portableContinueUsable)
498
+ lines.push(' - Long prompt risk: ' + target.adoptionSummary.longPromptRisk)
499
+ }
500
+ lines.push('')
501
+ lines.push('## Checks')
502
+ lines.push('')
503
+ for (const item of report.checks) {
504
+ const marker = item.status === 'passed' ? '[x]' : item.status === 'warning' ? '[!]' : '[ ]'
505
+ lines.push('- ' + marker + ' ' + item.id + ' ' + item.label + ': ' + item.evidence)
506
+ }
507
+ lines.push('')
508
+ lines.push('## Limits')
509
+ lines.push('')
510
+ for (const item of report.limits) lines.push('- ' + item)
511
+ return lines.join('\n') + '\n'
512
+ }
513
+
514
+ const report = buildReport()
515
+ if (jsonOnly) console.log(JSON.stringify(report, null, 2))
516
+ else console.log(renderMarkdown(report))
517
+
518
+ if (report.summary.status === 'failed') process.exit(1)