safeword 0.78.2 → 0.78.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/codex-plugin/hooks.json +5 -5
- package/codex-plugin/skills/bdd/references/SCENARIOS.md +3 -0
- package/codex-plugin/skills/bdd/references/TDD.md +11 -5
- package/codex-plugin/skills/closeout/SKILL.md +24 -16
- package/codex-plugin/skills/finish-review/SKILL.md +4 -3
- package/codex-plugin/skills/lint/SKILL.md +1 -1
- package/codex-plugin/skills/review-spec/SKILL.md +5 -1
- package/codex-plugin/skills/self-review/SKILL.md +2 -2
- package/codex-plugin/skills/ticket-system/SKILL.md +3 -0
- package/dist/{architecture-N5ZC4CDU.js → architecture-TCSDEFKH.js} +9 -9
- package/dist/{architecture-document-UBA5UT4J.js → architecture-document-L2ADWVMV.js} +6 -6
- package/dist/{architecture-monorepo-E4JUYJGV.js → architecture-monorepo-NKOQZBEY.js} +4 -4
- package/dist/{boundary-HLJILY7R.js → boundary-QP2H7C46.js} +6 -6
- package/dist/{chunk-NOTBZCKG.js → chunk-2XR7J5WL.js} +93 -42
- package/dist/chunk-2XR7J5WL.js.map +1 -0
- package/dist/{chunk-4CZS4YJV.js → chunk-3OKZ3X4O.js} +3 -3
- package/dist/{chunk-GZ36UZJG.js → chunk-73TABQRT.js} +10 -10
- package/dist/{chunk-4CKCRZDO.js → chunk-7ULZND56.js} +2 -2
- package/dist/{chunk-34NCOTP5.js → chunk-7XELS325.js} +2 -2
- package/dist/{chunk-USPVNZ63.js → chunk-BZWO3BVD.js} +11 -7
- package/dist/chunk-BZWO3BVD.js.map +1 -0
- package/dist/{chunk-BQTC6YGN.js → chunk-D5ENZR6N.js} +2 -2
- package/dist/{chunk-SME5SU3O.js → chunk-DBXX5K74.js} +258 -48
- package/dist/chunk-DBXX5K74.js.map +1 -0
- package/dist/{chunk-V63TSN3C.js → chunk-FOYGZ4MK.js} +31 -10
- package/dist/chunk-FOYGZ4MK.js.map +1 -0
- package/dist/{chunk-ZRV7TOCX.js → chunk-G5AFQXXW.js} +2 -2
- package/dist/{chunk-AXAGJLMP.js → chunk-G757F3EU.js} +4 -4
- package/dist/{chunk-KXHVFCDT.js → chunk-GFDINP7M.js} +153 -27
- package/dist/chunk-GFDINP7M.js.map +1 -0
- package/dist/{chunk-S2T356DA.js → chunk-HF3DXZEA.js} +7 -10
- package/dist/chunk-HF3DXZEA.js.map +1 -0
- package/dist/{chunk-NSZGI7HK.js → chunk-HNCUIXDY.js} +9 -9
- package/dist/{chunk-NSZGI7HK.js.map → chunk-HNCUIXDY.js.map} +1 -1
- package/dist/{chunk-BSOUMHMQ.js → chunk-IPTM5VE7.js} +101 -1094
- package/dist/chunk-IPTM5VE7.js.map +1 -0
- package/dist/chunk-JBOLNV2L.js +21 -0
- package/dist/chunk-JBOLNV2L.js.map +1 -0
- package/dist/chunk-JSR3HXFT.js +1231 -0
- package/dist/chunk-JSR3HXFT.js.map +1 -0
- package/dist/{chunk-BAVDDAN3.js → chunk-KS2ESRQL.js} +9 -9
- package/dist/chunk-LFC6CMMX.js +136 -0
- package/dist/chunk-LFC6CMMX.js.map +1 -0
- package/dist/{chunk-QTG2EXFT.js → chunk-LUNHU6Z3.js} +2 -2
- package/dist/{chunk-QTG2EXFT.js.map → chunk-LUNHU6Z3.js.map} +1 -1
- package/dist/{chunk-WVDRXD67.js → chunk-MLBZFB5A.js} +1 -1
- package/dist/chunk-MLBZFB5A.js.map +1 -0
- package/dist/{chunk-KFVEPQ7X.js → chunk-MVFHTUQ3.js} +2 -2
- package/dist/{chunk-TJ627SKI.js → chunk-O3GZ77F7.js} +15 -1
- package/dist/chunk-O3GZ77F7.js.map +1 -0
- package/dist/{chunk-Q5KLE6ZF.js → chunk-OKPRQGFG.js} +2 -2
- package/dist/{chunk-QUDIOBHP.js → chunk-PD7ZXRHV.js} +139 -18
- package/dist/chunk-PD7ZXRHV.js.map +1 -0
- package/dist/chunk-QAHJSG53.js +30 -0
- package/dist/chunk-QAHJSG53.js.map +1 -0
- package/dist/{chunk-3SOJBMM6.js → chunk-R6BSRNU4.js} +6 -6
- package/dist/{chunk-3SOJBMM6.js.map → chunk-R6BSRNU4.js.map} +1 -1
- package/dist/{chunk-J7UDLLTK.js → chunk-RQ7RZYNB.js} +39 -25
- package/dist/chunk-RQ7RZYNB.js.map +1 -0
- package/dist/{chunk-664YNAMR.js → chunk-RTFPKJJV.js} +5 -5
- package/dist/{chunk-GKR44BCH.js → chunk-RVDXBHUG.js} +2 -2
- package/dist/chunk-THLEVFEX.js +22 -0
- package/dist/chunk-THLEVFEX.js.map +1 -0
- package/dist/{chunk-A7Z27COA.js → chunk-VFWAZLEF.js} +3 -3
- package/dist/{chunk-I4KBHRZW.js → chunk-VJUPD7JI.js} +7 -7
- package/dist/{chunk-3EJNDIAO.js → chunk-VZ5B2SIO.js} +2 -2
- package/dist/chunk-WAMQTZAH.js +19 -0
- package/dist/chunk-WAMQTZAH.js.map +1 -0
- package/dist/{chunk-FDHJ63FZ.js → chunk-WVA4Q6BX.js} +1 -1
- package/dist/{chunk-FDHJ63FZ.js.map → chunk-WVA4Q6BX.js.map} +1 -1
- package/dist/{chunk-AV5LTEME.js → chunk-YZ5JGDOV.js} +30 -134
- package/dist/chunk-YZ5JGDOV.js.map +1 -0
- package/dist/{cleanup-X556LNWM.js → cleanup-JNLZ7AXA.js} +9 -9
- package/dist/{cleanup-command-RV2Q7G72.js → cleanup-command-MFAYNYRW.js} +15 -15
- package/dist/cli.js +152 -109
- package/dist/cli.js.map +1 -1
- package/dist/{clients-HP23HRN2.js → clients-7AJBKEWF.js} +2 -2
- package/dist/codex-bootstrap-KFNUS63Y.js +252 -0
- package/dist/codex-bootstrap-KFNUS63Y.js.map +1 -0
- package/dist/{codex-hook-IPX3PDXX.js → codex-hook-TNMYVOR7.js} +57 -49
- package/dist/codex-hook-TNMYVOR7.js.map +1 -0
- package/dist/{codify-J5ZLJ3HK.js → codify-RBWBRXQO.js} +11 -8
- package/dist/codify-RBWBRXQO.js.map +1 -0
- package/dist/{commands-L4AINARC.js → commands-4UXHBZFD.js} +127 -71
- package/dist/commands-4UXHBZFD.js.map +1 -0
- package/dist/{config-LUSJAK6B.js → config-GS7BTZJD.js} +2 -2
- package/dist/{configured-paths-SPQ5XWOM.js → configured-paths-CREUDQF3.js} +4 -4
- package/dist/contract-42CIWIWV.js +8 -0
- package/dist/{coordinator-SA75UB3C.js → coordinator-WOPGWDXK.js} +231 -144
- package/dist/coordinator-WOPGWDXK.js.map +1 -0
- package/dist/corpus-CAFYEMBO.js +15 -0
- package/dist/{doctor-DSC36R4U.js → doctor-AZP5D7QP.js} +21 -21
- package/dist/{feature-directories-VOHVV26X.js → feature-directories-6TLM7Y4H.js} +6 -6
- package/dist/{finalization-7SMLMVLV.js → finalization-AQT3SOP7.js} +4 -4
- package/dist/{gh-cli-ZMO7D2KE.js → gh-cli-XCQT5ST7.js} +2 -2
- package/dist/{github-rest-KGKS4V2H.js → github-rest-CXFJ2NFF.js} +2 -2
- package/dist/index.js +2 -2
- package/dist/{job-CDADLJDF.js → job-4POTQJZK.js} +20 -21
- package/dist/job-4POTQJZK.js.map +1 -0
- package/dist/{learning-sync-6BTHM6ZC.js → learning-sync-QVXBOP6J.js} +4 -4
- package/dist/{legacy-global-guidance-2JL4Y5EB.js → legacy-global-guidance-CPGUUNJI.js} +5 -5
- package/dist/{lint-gherkin-COSHVS6Z.js → lint-gherkin-LZ45NG4A.js} +7 -7
- package/dist/{operations-XVRQSLJG.js → operations-ODOA5CDG.js} +18 -16
- package/dist/{output-3LB2OEHN.js → output-QTZCFLAY.js} +2 -2
- package/dist/{packet-5WT5M3OS.js → packet-5G6RT2EW.js} +2 -2
- package/dist/presets/typescript/index.js +2 -2
- package/dist/{profile-UMKQ5JVO.js → profile-QGLZNLRU.js} +7 -7
- package/dist/{prompt-GWYDFMLO.js → prompt-UCTSCXSS.js} +2 -2
- package/dist/remove-UQPEXXNP.js +23 -0
- package/dist/{retro-IFSVU5KS.js → retro-ELKR6GHF.js} +8 -8
- package/dist/{retro-draft-spool-4S3TCHWL.js → retro-draft-spool-M75BTT32.js} +2 -2
- package/dist/{retro-extract-OSBFAXLU.js → retro-extract-RA6THOC4.js} +2 -2
- package/dist/{review-pr-6S2352CK.js → review-pr-MN6QESAJ.js} +2 -2
- package/dist/{review-pr-publication-CGHCRRUI.js → review-pr-publication-6AVOGWR2.js} +2 -2
- package/dist/{run-5JESKXUR.js → run-JFDGRAH2.js} +4 -4
- package/dist/{self-report-VPHBPPSJ.js → self-report-5APRPB5P.js} +2 -2
- package/dist/status-ATFG6Q3K.js +21 -0
- package/dist/{status-EX4L3ELO.js → status-HIQSP3F5.js} +21 -21
- package/dist/{sync-config-O7J7IDGE.js → sync-config-XPAJKBRO.js} +5 -5
- package/dist/{sync-tracker-U2GYOFUO.js → sync-tracker-3E5BWX73.js} +6 -6
- package/dist/{test-execution-6LIPMBIH.js → test-execution-VDECX7TO.js} +8 -7
- package/dist/{test-execution-6LIPMBIH.js.map → test-execution-VDECX7TO.js.map} +1 -1
- package/dist/{test-plan-VASHZXJ7.js → test-plan-2L7A7UZV.js} +7 -6
- package/dist/{test-plan-VASHZXJ7.js.map → test-plan-2L7A7UZV.js.map} +1 -1
- package/dist/{ticket-new-3YXDIWPC.js → ticket-new-HZKNZ5GO.js} +11 -11
- package/dist/ticket-new-HZKNZ5GO.js.map +1 -0
- package/dist/{ticket-sync-LLUBXZ2R.js → ticket-sync-4QJD3KOL.js} +5 -5
- package/dist/{tracker-map-HR4MBYG5.js → tracker-map-CFMFIEER.js} +2 -2
- package/dist/{tracker-sync-YDICZN66.js → tracker-sync-MOPJE6M7.js} +2 -2
- package/package.json +1 -1
- package/templates/SAFEWORD.md +2 -2
- package/templates/commands/lint.md +1 -1
- package/templates/scripts/closeout-cleanup.ts +127 -31
- package/templates/skills/bdd/SCENARIOS.md +3 -0
- package/templates/skills/bdd/TDD.md +11 -5
- package/templates/skills/closeout/SKILL.md +25 -17
- package/templates/skills/finish-review/SKILL.md +4 -3
- package/templates/skills/lint/SKILL.md +1 -1
- package/templates/skills/review-spec/SKILL.md +5 -1
- package/templates/skills/self-review/SKILL.md +2 -2
- package/templates/skills/ticket-system/SKILL.md +3 -0
- package/dist/chunk-6S7CTKGC.js +0 -128
- package/dist/chunk-6S7CTKGC.js.map +0 -1
- package/dist/chunk-AV5LTEME.js.map +0 -1
- package/dist/chunk-BSOUMHMQ.js.map +0 -1
- package/dist/chunk-J7UDLLTK.js.map +0 -1
- package/dist/chunk-KXHVFCDT.js.map +0 -1
- package/dist/chunk-NOTBZCKG.js.map +0 -1
- package/dist/chunk-QUDIOBHP.js.map +0 -1
- package/dist/chunk-S2T356DA.js.map +0 -1
- package/dist/chunk-SME5SU3O.js.map +0 -1
- package/dist/chunk-TJ627SKI.js.map +0 -1
- package/dist/chunk-USPVNZ63.js.map +0 -1
- package/dist/chunk-V63TSN3C.js.map +0 -1
- package/dist/chunk-WRUXO3WA.js +0 -48
- package/dist/chunk-WRUXO3WA.js.map +0 -1
- package/dist/chunk-WVDRXD67.js.map +0 -1
- package/dist/codex-bootstrap-MGY2D6HU.js +0 -178
- package/dist/codex-bootstrap-MGY2D6HU.js.map +0 -1
- package/dist/codex-hook-IPX3PDXX.js.map +0 -1
- package/dist/codify-J5ZLJ3HK.js.map +0 -1
- package/dist/commands-L4AINARC.js.map +0 -1
- package/dist/contract-KEZY6YC3.js +0 -8
- package/dist/coordinator-SA75UB3C.js.map +0 -1
- package/dist/corpus-PPOBTF4J.js +0 -15
- package/dist/job-CDADLJDF.js.map +0 -1
- package/dist/remove-E6HGNHOU.js +0 -22
- package/dist/status-7VIGNTUI.js +0 -21
- package/dist/ticket-new-3YXDIWPC.js.map +0 -1
- /package/dist/{architecture-N5ZC4CDU.js.map → architecture-TCSDEFKH.js.map} +0 -0
- /package/dist/{architecture-document-UBA5UT4J.js.map → architecture-document-L2ADWVMV.js.map} +0 -0
- /package/dist/{architecture-monorepo-E4JUYJGV.js.map → architecture-monorepo-NKOQZBEY.js.map} +0 -0
- /package/dist/{boundary-HLJILY7R.js.map → boundary-QP2H7C46.js.map} +0 -0
- /package/dist/{chunk-4CZS4YJV.js.map → chunk-3OKZ3X4O.js.map} +0 -0
- /package/dist/{chunk-GZ36UZJG.js.map → chunk-73TABQRT.js.map} +0 -0
- /package/dist/{chunk-4CKCRZDO.js.map → chunk-7ULZND56.js.map} +0 -0
- /package/dist/{chunk-34NCOTP5.js.map → chunk-7XELS325.js.map} +0 -0
- /package/dist/{chunk-BQTC6YGN.js.map → chunk-D5ENZR6N.js.map} +0 -0
- /package/dist/{chunk-ZRV7TOCX.js.map → chunk-G5AFQXXW.js.map} +0 -0
- /package/dist/{chunk-AXAGJLMP.js.map → chunk-G757F3EU.js.map} +0 -0
- /package/dist/{chunk-BAVDDAN3.js.map → chunk-KS2ESRQL.js.map} +0 -0
- /package/dist/{chunk-KFVEPQ7X.js.map → chunk-MVFHTUQ3.js.map} +0 -0
- /package/dist/{chunk-Q5KLE6ZF.js.map → chunk-OKPRQGFG.js.map} +0 -0
- /package/dist/{chunk-664YNAMR.js.map → chunk-RTFPKJJV.js.map} +0 -0
- /package/dist/{chunk-GKR44BCH.js.map → chunk-RVDXBHUG.js.map} +0 -0
- /package/dist/{chunk-A7Z27COA.js.map → chunk-VFWAZLEF.js.map} +0 -0
- /package/dist/{chunk-I4KBHRZW.js.map → chunk-VJUPD7JI.js.map} +0 -0
- /package/dist/{chunk-3EJNDIAO.js.map → chunk-VZ5B2SIO.js.map} +0 -0
- /package/dist/{cleanup-X556LNWM.js.map → cleanup-JNLZ7AXA.js.map} +0 -0
- /package/dist/{cleanup-command-RV2Q7G72.js.map → cleanup-command-MFAYNYRW.js.map} +0 -0
- /package/dist/{clients-HP23HRN2.js.map → clients-7AJBKEWF.js.map} +0 -0
- /package/dist/{config-LUSJAK6B.js.map → config-GS7BTZJD.js.map} +0 -0
- /package/dist/{configured-paths-SPQ5XWOM.js.map → configured-paths-CREUDQF3.js.map} +0 -0
- /package/dist/{contract-KEZY6YC3.js.map → contract-42CIWIWV.js.map} +0 -0
- /package/dist/{corpus-PPOBTF4J.js.map → corpus-CAFYEMBO.js.map} +0 -0
- /package/dist/{doctor-DSC36R4U.js.map → doctor-AZP5D7QP.js.map} +0 -0
- /package/dist/{feature-directories-VOHVV26X.js.map → feature-directories-6TLM7Y4H.js.map} +0 -0
- /package/dist/{finalization-7SMLMVLV.js.map → finalization-AQT3SOP7.js.map} +0 -0
- /package/dist/{gh-cli-ZMO7D2KE.js.map → gh-cli-XCQT5ST7.js.map} +0 -0
- /package/dist/{github-rest-KGKS4V2H.js.map → github-rest-CXFJ2NFF.js.map} +0 -0
- /package/dist/{learning-sync-6BTHM6ZC.js.map → learning-sync-QVXBOP6J.js.map} +0 -0
- /package/dist/{legacy-global-guidance-2JL4Y5EB.js.map → legacy-global-guidance-CPGUUNJI.js.map} +0 -0
- /package/dist/{lint-gherkin-COSHVS6Z.js.map → lint-gherkin-LZ45NG4A.js.map} +0 -0
- /package/dist/{operations-XVRQSLJG.js.map → operations-ODOA5CDG.js.map} +0 -0
- /package/dist/{output-3LB2OEHN.js.map → output-QTZCFLAY.js.map} +0 -0
- /package/dist/{packet-5WT5M3OS.js.map → packet-5G6RT2EW.js.map} +0 -0
- /package/dist/{profile-UMKQ5JVO.js.map → profile-QGLZNLRU.js.map} +0 -0
- /package/dist/{prompt-GWYDFMLO.js.map → prompt-UCTSCXSS.js.map} +0 -0
- /package/dist/{remove-E6HGNHOU.js.map → remove-UQPEXXNP.js.map} +0 -0
- /package/dist/{retro-IFSVU5KS.js.map → retro-ELKR6GHF.js.map} +0 -0
- /package/dist/{retro-draft-spool-4S3TCHWL.js.map → retro-draft-spool-M75BTT32.js.map} +0 -0
- /package/dist/{retro-extract-OSBFAXLU.js.map → retro-extract-RA6THOC4.js.map} +0 -0
- /package/dist/{review-pr-6S2352CK.js.map → review-pr-MN6QESAJ.js.map} +0 -0
- /package/dist/{review-pr-publication-CGHCRRUI.js.map → review-pr-publication-6AVOGWR2.js.map} +0 -0
- /package/dist/{run-5JESKXUR.js.map → run-JFDGRAH2.js.map} +0 -0
- /package/dist/{self-report-VPHBPPSJ.js.map → self-report-5APRPB5P.js.map} +0 -0
- /package/dist/{status-7VIGNTUI.js.map → status-ATFG6Q3K.js.map} +0 -0
- /package/dist/{status-EX4L3ELO.js.map → status-HIQSP3F5.js.map} +0 -0
- /package/dist/{sync-config-O7J7IDGE.js.map → sync-config-XPAJKBRO.js.map} +0 -0
- /package/dist/{sync-tracker-U2GYOFUO.js.map → sync-tracker-3E5BWX73.js.map} +0 -0
- /package/dist/{ticket-sync-LLUBXZ2R.js.map → ticket-sync-4QJD3KOL.js.map} +0 -0
- /package/dist/{tracker-map-HR4MBYG5.js.map → tracker-map-CFMFIEER.js.map} +0 -0
- /package/dist/{tracker-sync-YDICZN66.js.map → tracker-sync-MOPJE6M7.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/remove.ts","../src/cli-protocol/file-effects.ts","../src/cli-protocol/reconciliation.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport nodePath from 'node:path';\n\nimport { diffFileSnapshots } from '../cli-protocol/file-effects.js';\nimport type { CliPlan } from '../cli-protocol/plan.js';\nimport { isPlanIdentity, malformedPlanIdentity, toWirePlan } from '../cli-protocol/plan.js';\nimport {\n applyReconciliation,\n createReconciliationPlan,\n effectsForReconciliation,\n} from '../cli-protocol/reconciliation.js';\nimport { type CliResult, createResult } from '../cli-protocol/result.js';\nimport type { ReconcileResult } from '../reconcile.js';\nimport { ReconcileExecutionError } from '../reconcile.js';\nimport type { SafewordSchema } from '../schema.js';\nimport type { DependencyInstallResult } from '../utils/install.js';\nimport { uninstallDependencies } from '../utils/install.js';\n\nexport interface RemoveOptions {\n readonly full?: boolean;\n readonly yes?: boolean;\n readonly plan?: string;\n readonly schema?: SafewordSchema;\n}\n\nconst PACKAGE_MANAGER_FILES = [\n 'package.json',\n 'bun.lock',\n 'bun.lockb',\n 'package-lock.json',\n 'pnpm-lock.yaml',\n 'yarn.lock',\n] as const;\n\nfunction snapshotPackageFiles(cwd: string): ReadonlyMap<string, string> {\n const snapshot = new Map<string, string>();\n for (const target of PACKAGE_MANAGER_FILES) {\n const path = nodePath.join(cwd, target);\n if (existsSync(path)) snapshot.set(target, readFileSync(path).toString('base64'));\n }\n return snapshot;\n}\n\nfunction combinedFileEffects(\n ...groups: readonly (readonly { kind: string; target: string }[])[]\n): { kind: string; target: string }[] {\n const effects = new Map<string, { kind: string; target: string }>();\n for (const effect of groups.flat()) effects.set(`${effect.kind}\\0${effect.target}`, effect);\n return effects.values().toArray();\n}\n\nfunction confirmationRequired(plan: CliPlan, full: boolean): CliResult {\n const fullFlag = full ? ' --full' : '';\n return createResult({\n state: 'action_required',\n findings: [\n {\n code: 'CONFIRMATION_REQUIRED',\n message: 'Review and confirm the exact removal plan.',\n severity: 'warning',\n },\n ],\n nextActions: [\n {\n command: `safeword remove${fullFlag} --yes --plan ${plan.id}`,\n mutates: true,\n requiresHuman: true,\n },\n ],\n data: { plan: toWirePlan(plan) },\n });\n}\n\nfunction stalePlan(plan: CliPlan): CliResult {\n return createResult({\n state: 'action_required',\n findings: [\n {\n code: 'PLAN_STALE',\n message: 'The project changed after this removal plan was created.',\n severity: 'warning',\n },\n ],\n nextActions: [{ command: 'safeword remove', mutates: false, requiresHuman: true }],\n data: { plan: toWirePlan(plan) },\n });\n}\n\nfunction packageUninstallFailure(\n applied: ReconcileResult,\n packageRemoval: DependencyInstallResult,\n mode: 'uninstall' | 'uninstall-full',\n packageFileEffects: readonly { kind: string; target: string }[],\n): CliResult {\n const completed = effectsForReconciliation(applied, mode);\n const files = combinedFileEffects(completed.files, packageFileEffects);\n return createResult({\n state: 'failed',\n changed: completed.destructive.length > 0 || files.length > 0,\n effects: {\n ...completed,\n files,\n network: packageRemoval.attempted\n ? [\n {\n kind: 'package-registry',\n target: packageRemoval.command ?? 'Safeword packages',\n operation: 'uninstall-failed',\n },\n ]\n : [],\n },\n errors: [\n {\n code: 'PACKAGE_UNINSTALL_FAILED',\n message: packageRemoval.error ?? 'Safeword package removal failed.',\n retryable: true,\n },\n ],\n recovery: [\n {\n command: packageRemoval.command ?? 'safeword remove --full',\n description: 'Complete the package removal, then re-run Safeword status.',\n requiresHuman: true,\n },\n ],\n });\n}\n\nasync function applyRemoval(\n cwd: string,\n mode: 'uninstall' | 'uninstall-full',\n full: boolean,\n schema?: SafewordSchema,\n): Promise<CliResult> {\n const applied = await applyReconciliation(cwd, mode, schema);\n const packageFilesBefore = snapshotPackageFiles(cwd);\n const packageRemoval = full\n ? uninstallDependencies(cwd, applied.packagesToRemove, { report: false })\n : { attempted: false, installed: false };\n const packageFileEffects = diffFileSnapshots(packageFilesBefore, snapshotPackageFiles(cwd));\n if (packageRemoval.attempted && !packageRemoval.installed) {\n return packageUninstallFailure(applied, packageRemoval, mode, packageFileEffects);\n }\n const completed = effectsForReconciliation(applied, mode);\n const packageEffects = packageRemoval.installed\n ? applied.packagesToRemove.map(target => ({ kind: 'remove', target }))\n : [];\n const files = combinedFileEffects(completed.files, packageFileEffects);\n return createResult({\n state:\n completed.destructive.length === 0 && packageEffects.length === 0 && files.length === 0\n ? 'healthy'\n : 'changed',\n effects: {\n ...completed,\n files,\n packages: packageEffects,\n network: packageRemoval.installed\n ? packageEffects.map(effect => ({\n kind: 'package-registry',\n target: effect.target,\n operation: 'uninstall',\n }))\n : [],\n },\n data: { removed: applied.removed },\n });\n}\n\nfunction partialRemovalEffects(\n removeError: unknown,\n): (Partial<CliResult['effects']> & Pick<CliResult['effects'], 'destructive'>) | undefined {\n if (!(removeError instanceof ReconcileExecutionError)) return undefined;\n return {\n files: [\n ...removeError.partial.created.map(target => ({ kind: 'create', target })),\n ...removeError.partial.updated.map(target => ({ kind: 'update', target })),\n ],\n packages: [],\n configuration: [],\n network: [],\n destructive: removeError.partial.removed.map(target => ({\n kind: 'remove',\n target,\n })),\n };\n}\n\nfunction hasPartialRemovalEffects(partial: ReturnType<typeof partialRemovalEffects>): boolean {\n return (partial?.destructive.length ?? 0) !== 0 || (partial?.files?.length ?? 0) !== 0;\n}\n\nexport async function removeProject(cwd: string, options: RemoveOptions): Promise<CliResult> {\n if (options.plan !== undefined && !isPlanIdentity(options.plan)) {\n return malformedPlanIdentity('remove');\n }\n if (!existsSync(nodePath.join(cwd, '.safeword'))) {\n return createResult({\n state: 'healthy',\n findings: [\n {\n code: 'PROJECT_NOT_CONFIGURED',\n message: 'Safeword is not configured; there is nothing to remove.',\n severity: 'info',\n },\n ],\n data: { removed: [] },\n });\n }\n const mode = options.full === true ? 'uninstall-full' : 'uninstall';\n try {\n const { plan } = await createReconciliationPlan(cwd, mode, options.schema);\n if (options.yes !== true || options.plan === undefined) {\n return confirmationRequired(plan, options.full === true);\n }\n if (options.plan !== plan.id) return stalePlan(plan);\n return await applyRemoval(cwd, mode, options.full === true, options.schema);\n } catch (removeError) {\n const partial = partialRemovalEffects(removeError);\n return createResult({\n state: 'failed',\n changed: hasPartialRemovalEffects(partial),\n effects: partial,\n errors: [\n {\n code: 'REMOVE_FAILED',\n message: removeError instanceof Error ? removeError.message : String(removeError),\n retryable: true,\n },\n ],\n recovery: [\n {\n command: 'safeword status --verbose',\n description: 'Inspect the effects that completed before retrying.',\n requiresHuman: true,\n },\n ],\n });\n }\n}\n","import type { Effect } from './result.js';\n\nexport function diffFileSnapshots(\n before: ReadonlyMap<string, string>,\n after: ReadonlyMap<string, string>,\n): Effect[] {\n const effects: Effect[] = [];\n for (const [target, content] of after) {\n const previous = before.get(target);\n if (previous === undefined) effects.push({ kind: 'create', target });\n else if (previous !== content) effects.push({ kind: 'update', target });\n }\n for (const target of before.keys()) {\n if (!after.has(target)) effects.push({ kind: 'delete', target });\n }\n return effects;\n}\n","import { createHash } from 'node:crypto';\nimport type { Stats } from 'node:fs';\nimport { lstatSync, readdirSync, readFileSync, readlinkSync } from 'node:fs';\nimport nodePath from 'node:path';\n\nimport { type Action, reconcile, type ReconcileResult } from '../reconcile.js';\nimport { type ProjectContext, SAFEWORD_SCHEMA, type SafewordSchema } from '../schema.js';\nimport { createProjectContext } from '../utils/context.js';\nimport { type CliPlan, createPlan } from './plan.js';\nimport type { Effects } from './result.js';\n\ntype PlanMode = 'install' | 'upgrade' | 'uninstall' | 'uninstall-full';\ntype ReadFileForDigest = (path: string) => Buffer;\n\nconst PACKAGE_MANAGER_INPUTS = [\n 'package.json',\n 'bun.lock',\n 'bun.lockb',\n 'package-lock.json',\n 'pnpm-lock.yaml',\n 'yarn.lock',\n 'pyproject.toml',\n 'uv.lock',\n 'poetry.lock',\n 'Pipfile',\n 'Pipfile.lock',\n] as const;\n\nconst readFileForDigest: ReadFileForDigest = path => readFileSync(path);\n\nfunction actionTargets(action: Action): string[] {\n return action.type === 'chmod' ? action.paths : [action.path];\n}\n\nfunction filesystemFailureToken(error: unknown): string {\n const code = (error as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR' ? 'missing' : `error:${code ?? 'unknown'}`;\n}\n\nfunction hashField(hash: ReturnType<typeof createHash>, tag: string, value: string | Buffer): void {\n const bytes = typeof value === 'string' ? Buffer.from(value) : value;\n const length = Buffer.allocUnsafe(8);\n length.writeBigUInt64BE(BigInt(bytes.length));\n hash.update(tag);\n hash.update(Buffer.from([0]));\n hash.update(length);\n hash.update(bytes);\n}\n\nfunction filesystemNodeType(stat: Stats): string {\n if (stat.isSymbolicLink()) return 'link';\n if (stat.isDirectory()) return 'directory';\n if (stat.isFile()) return 'file';\n return 'other';\n}\n\nfunction hashPath(\n hash: ReturnType<typeof createHash>,\n absolutePath: string,\n relativePath: string,\n readFile: ReadFileForDigest,\n): void {\n try {\n const stat = lstatSync(absolutePath);\n hashField(hash, 'node-type', filesystemNodeType(stat));\n hashField(hash, 'relative-path', relativePath);\n hashField(hash, 'mode', stat.mode.toString());\n if (stat.isSymbolicLink()) hashField(hash, 'link-target', readlinkSync(absolutePath));\n if (stat.isDirectory()) {\n const entries = readdirSync(absolutePath).toSorted((left, right) =>\n left.localeCompare(right),\n );\n for (const name of entries) {\n hashPath(\n hash,\n nodePath.join(absolutePath, name),\n nodePath.join(relativePath, name),\n readFile,\n );\n }\n } else if (stat.isFile()) {\n // Exact bytes intentionally bind plan consent more strongly than\n // size/mtime metadata, which can be preserved across content changes.\n hashField(hash, 'file-content', readFile(absolutePath));\n }\n } catch (error) {\n hashField(hash, 'node-type', 'error');\n hashField(hash, 'relative-path', relativePath);\n hashField(hash, 'error', filesystemFailureToken(error));\n }\n}\n\nexport function preconditionDigest(\n cwd: string,\n actions: readonly Action[],\n readFile: ReadFileForDigest = readFileForDigest,\n): string {\n return preconditionDigestForPaths(\n cwd,\n actions.flatMap(action => actionTargets(action)),\n readFile,\n );\n}\n\nexport function preconditionDigestForPaths(\n cwd: string,\n paths: readonly string[],\n readFile: ReadFileForDigest = readFileForDigest,\n): string {\n const hash = createHash('sha256');\n const targets = [...new Set(paths)].toSorted((left, right) => left.localeCompare(right));\n for (const target of targets) {\n hashField(hash, 'target', target);\n hashPath(hash, nodePath.join(cwd, target), target, readFile);\n }\n return hash.digest('hex');\n}\n\nexport function effectsForReconciliation(result: ReconcileResult, mode: PlanMode): Effects {\n const created = result.created.map(target => ({ kind: 'create', target }));\n const updated = result.updated.map(target => ({ kind: 'update', target }));\n const removed = result.removed.map(target => ({ kind: 'remove', target }));\n const installing = mode === 'install' || mode === 'upgrade';\n const packageNames = installing ? result.packagesToInstall : result.packagesToRemove;\n const plannedPackageNames = result.applied ? [] : packageNames;\n const packageEffects = plannedPackageNames.map(target => ({\n kind: installing ? 'install' : 'remove',\n target,\n }));\n return {\n files: [...created, ...updated],\n packages: packageEffects,\n configuration: [],\n network: installing\n ? plannedPackageNames.map(target => ({\n kind: 'package-registry',\n target,\n operation: 'install',\n }))\n : [],\n destructive: removed,\n };\n}\n\nexport interface ReconciliationPlan {\n readonly plan: CliPlan;\n readonly dryRun: ReconcileResult;\n}\n\nexport async function createReconciliationPlan(\n cwd: string,\n mode: PlanMode,\n schema: SafewordSchema = SAFEWORD_SCHEMA,\n context: ProjectContext = createProjectContext(cwd),\n): Promise<ReconciliationPlan> {\n const dryRun = await reconcile(schema, mode, context, { dryRun: true });\n const effects = effectsForReconciliation(dryRun, mode);\n return {\n dryRun,\n plan: createPlan({\n command: mode === 'install' || mode === 'upgrade' ? 'setup' : 'remove',\n preconditionDigest: preconditionDigestForPaths(cwd, [\n ...dryRun.actions.flatMap(action => actionTargets(action)),\n ...PACKAGE_MANAGER_INPUTS,\n ]),\n effects,\n requiresConfirmation: mode !== 'install' && mode !== 'upgrade',\n verification: [{ description: 'Re-run safeword status' }],\n }),\n };\n}\n\nexport async function applyReconciliation(\n cwd: string,\n mode: Exclude<PlanMode, 'upgrade'>,\n schema: SafewordSchema = SAFEWORD_SCHEMA,\n): Promise<ReconcileResult> {\n return reconcile(schema, mode, createProjectContext(cwd));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,gBAAAA,qBAAoB;AACzC,OAAOC,eAAc;;;ACCd,SAAS,kBACd,QACA,OACU;AACV,QAAM,UAAoB,CAAC;AAC3B,aAAW,CAAC,QAAQ,OAAO,KAAK,OAAO;AACrC,UAAM,WAAW,OAAO,IAAI,MAAM;AAClC,QAAI,aAAa,OAAW,SAAQ,KAAK,EAAE,MAAM,UAAU,OAAO,CAAC;AAAA,aAC1D,aAAa,QAAS,SAAQ,KAAK,EAAE,MAAM,UAAU,OAAO,CAAC;AAAA,EACxE;AACA,aAAW,UAAU,OAAO,KAAK,GAAG;AAClC,QAAI,CAAC,MAAM,IAAI,MAAM,EAAG,SAAQ,KAAK,EAAE,MAAM,UAAU,OAAO,CAAC;AAAA,EACjE;AACA,SAAO;AACT;;;AChBA,SAAS,kBAAkB;AAE3B,SAAS,WAAW,aAAa,cAAc,oBAAoB;AACnE,OAAO,cAAc;AAWrB,IAAM,yBAAyB;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ACtD,aAAO,qBAAqB,MAAM,QAAQ,SAAS,IAAI;AAAA,IACzD;AACA,QAAI,QAAQ,SAAS,KAAK,GAAI,QAAO,UAAU,IAAI;AACnD,WAAO,MAAM,aAAa,KAAK,MAAM,QAAQ,SAAS,MAAM,QAAQ,MAAM;AAAA,EAC5E,SAAS,aAAa;AACpB,UAAM,UAAU,sBAAsB,WAAW;AACjD,WAAO,aAAa;AAAA,MAClB,OAAO;AAAA,MACP,SAAS,yBAAyB,OAAO;AAAA,MACzC,SAAS;AAAA,MACT,QAAQ;AAAA,QACN;AAAA,UACE,MAAM;AAAA,UACN,SAAS,uBAAuB,QAAQ,YAAY,UAAU,OAAO,WAAW;AAAA,UAChF,WAAW;AAAA,QACb;AAAA,MACF;AAAA,MACA,UAAU;AAAA,QACR;AAAA,UACE,SAAS;AAAA,UACT,aAAa;AAAA,UACb,eAAe;AAAA,QACjB;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["readFileSync","nodePath","nodePath","readFileSync"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/health.ts","../src/claude-plugin/delivery-schema.ts","../src/utils/architecture-records.ts","../src/utils/glossary.ts","../src/utils/validation.ts","../src/utils/personas.ts","../src/utils/ticket-index-warnings.ts","../src/codex-plugin/delivery-schema.ts","../src/lifecycle/schema.ts","../src/lifecycle/cursor.ts"],"sourcesContent":["/**\n * Config-health verification core (ticket 3293WH).\n *\n * Shared by typed status and setup convergence so mutating commands can prove\n * their own postcondition at exit. Deliberately network-free: a postcondition\n * check must not depend on the registry being reachable.\n *\n * Uses reconcile() with dryRun to detect missing files and configuration\n * issues.\n */\n\nimport { readdirSync } from 'node:fs';\nimport nodePath from 'node:path';\n\nimport {\n detectUnanchoredPhaseState,\n type PhaseAnchorScope,\n} from '../templates/hooks/lib/phase-provenance.js';\nimport { schemaForClaudeDelivery } from './claude-plugin/delivery-schema.js';\nimport { hasImportLinterScaffoldTarget } from './packs/python/files.js';\nimport { getMissingPythonToolDependencies } from './packs/python/setup.js';\nimport { getMissingPacks } from './packs/registry.js';\nimport type { ProjectType } from './packs/types.js';\nimport { typescriptPackages } from './packs/typescript/files.js';\nimport { reconcile } from './reconcile.js';\nimport { BDD_LANE_FILE_PATHS, BDD_LANE_SCRIPT, type SafewordSchema } from './schema.js';\nimport { inspectTicketIndexConflicts, readTickets } from './ticket-sync/index.js';\nimport { listArchitectureRecords } from './utils/architecture-records.js';\nimport {\n type ConfiguredPathKey,\n defaultConfiguredPath,\n readConfiguredDocumentationSources,\n readConfiguredPath,\n resolveConfiguredPath,\n resolveTicketsDirectory,\n} from './utils/configured-paths.js';\nimport { createProjectContext } from './utils/context.js';\nimport {\n createPhaseAnchorEnvironment,\n findFeatureSourcePath,\n hasDefaultExecutableFeatureFiles,\n} from './utils/feature-source.js';\nimport { readFrontmatterScalar } from './utils/frontmatter.js';\nimport { exists, isDirectory, readFileSafe, readJson } from './utils/fs.js';\nimport { FeatureParseError, findFeatureLineageIssues } from './utils/gherkin-feature.js';\nimport { parseGlossary, validateGlossary } from './utils/glossary.js';\nimport { header, info, listItem, success, warn } from './utils/output.js';\nimport { parsePersonas, validatePersonas } from './utils/personas.js';\nimport { toRepoRelativePath } from './utils/repo-path.js';\nimport {\n buildCoverageReport,\n buildCoverageReportFromFeature,\n buildSurfaceCoverageReportFromFeature,\n type CoverageReport,\n findMixedCriteriaJtbds,\n findRulesMissingRejectionPaths,\n isRuleId,\n type SurfaceCoverageReport,\n} from './utils/scenario-coverage.js';\nimport { buildIndexConflictListMessage } from './utils/ticket-index-warnings.js';\nimport { formatTicketReference } from './utils/ticket-reference.js';\nimport { findDanglingDependencies, findTicketsInCycles } from './utils/ticket-relations.js';\nimport { VERSION } from './version.js';\n\n/**\n * Check for missing files from write actions\n * @param cwd\n * @param actions\n */\nfunction findMissingFiles(cwd: string, actions: { type: string; path: string }[]): string[] {\n const issues: string[] = [];\n for (const action of actions) {\n if (action.type === 'write' && !exists(nodePath.join(cwd, action.path))) {\n issues.push(`Missing: ${action.path}`);\n }\n }\n return issues;\n}\n\nfunction missingClaudeSettingsIssues(cwd: string, schema: SafewordSchema): string[] {\n const required = '.claude/settings.json' in schema.jsonMerges;\n return required && !exists(nodePath.join(cwd, '.claude', 'settings.json'))\n ? ['Missing: .claude/settings.json']\n : [];\n}\n\n// Persona and glossary content validation stays separate because their parsers\n// and diagnostics differ. Their configured-path lifecycle is shared with the\n// other user-authored project-knowledge files below. The parallel lookup and\n// validation paths were assessed in ticket XEP59N; combining their different\n// matching and diagnostic rules would cost clarity.\n\n/**\n * Validate personas.md when present, routing through any configured\n * `paths.personas` override. Returns one issue string per persona\n * validation error, formatted as `personas.md:LINE: MESSAGE`.\n *\n * Two failure modes:\n * - Default location absent → no issue (scaffold is optional until JTBDs\n * reference personas).\n * - Configured override set but file absent → loud failure (user opted\n * in; typo would otherwise silently strand persona references). Ticket\n * K7N2QM.\n */\ntype ConfiguredKnowledgeFileKey = Extract<\n ConfiguredPathKey,\n 'glossary' | 'principles' | 'personas' | 'surfaces'\n>;\n\nconst PATH_ONLY_KNOWLEDGE_KEYS = ['principles', 'surfaces'] as const;\nconst CONFIGURED_KNOWLEDGE_KEYS: readonly ConfiguredKnowledgeFileKey[] = [\n 'personas',\n 'principles',\n 'surfaces',\n 'glossary',\n];\n\n/** Factual configured-file health shared by user-authored project knowledge. */\nfunction findConfiguredKnowledgeIssues(cwd: string, key: ConfiguredKnowledgeFileKey): string[] {\n const override = readConfiguredPath(cwd, key);\n if (override === undefined) return [];\n const configuredPath = resolveConfiguredPath(cwd, key);\n if (isDirectory(configuredPath)) return [`${key}-path: ${override}: not a file`];\n if (exists(configuredPath)) return [];\n return [`${key}-path: ${override}: file not found`];\n}\n\n/** Non-destructively identify a default knowledge file stranded by an override. */\nfunction findConfiguredKnowledgeAdvisories(cwd: string, key: ConfiguredKnowledgeFileKey): string[] {\n const override = readConfiguredPath(cwd, key);\n if (override === undefined) return [];\n const defaultPath = defaultConfiguredPath(cwd, key);\n if (!exists(defaultPath)) return [];\n return [\n `${nodePath.relative(cwd, defaultPath)} exists but paths.${key} points to ${override} — legacy file is orphaned. Consider removing.`,\n ];\n}\n\nfunction findPersonaIssues(cwd: string): string[] {\n const configuredIssues = findConfiguredKnowledgeIssues(cwd, 'personas');\n if (configuredIssues.length > 0) return configuredIssues;\n const filePath = resolveConfiguredPath(cwd, 'personas');\n const content = readFileSafe(filePath);\n\n if (content === undefined) return [];\n\n const errors = validatePersonas(parsePersonas(content));\n return errors.map(error => `personas.md:${error.line}: ${error.message}`);\n}\n\n/**\n * Both-namespace-roots advisory (ticket 9MMWS7): both `.project/` and\n * `.safeword-project/` present means a migration was left half-finished (or\n * the dirs were created independently). Zero-exit nudge naming the finishing\n * action; silent on any single root — declining migration is never a nag.\n */\nfunction findNamespaceAdvisories(cwd: string): string[] {\n if (\n isDirectory(nodePath.join(cwd, '.project')) &&\n isDirectory(nodePath.join(cwd, '.safeword-project'))\n ) {\n return [\n 'Both .project/ and .safeword-project/ exist — safeword reads .project/. Run `safeword project install` to merge them automatically; authored collisions are archived under .safeword/namespace-migration-conflicts-v1/.',\n ];\n }\n return [];\n}\n\n/**\n * Validate glossary.md when present, routing through any configured\n * `paths.glossary` override. Returns one issue string per glossary\n * validation error, formatted as `glossary.md:LINE: MESSAGE`. Same two\n * failure modes as {@link findPersonaIssues} — absent default is silent\n * (scaffold is optional), configured-but-missing fails loudly (ticket\n * YR6C49, mirrors K7N2QM).\n */\nfunction findGlossaryIssues(cwd: string): string[] {\n const configuredIssues = findConfiguredKnowledgeIssues(cwd, 'glossary');\n if (configuredIssues.length > 0) return configuredIssues;\n const filePath = resolveConfiguredPath(cwd, 'glossary');\n const content = readFileSafe(filePath);\n\n if (content === undefined) return [];\n\n const errors = validateGlossary(parseGlossary(content));\n return errors.map(error => `glossary.md:${error.line}: ${error.message}`);\n}\n\n/**\n * Cucumber-harness misalignment advisories (ticket 56JCFZ, TB3.AC1+AC2).\n * Persistent and zero-exit — the setup-time notice alone is ignorable:\n * - Host harness detected, safeword's lane absent, `paths.*` unset → name\n * the harness and the exact config lines to add. Silent once set.\n * - Host harness AND safeword's starter lane both present (a repo bitten by\n * pre-56JCFZ scaffolding) → enumerate the leftover lane surface, derived\n * from the schema constants so the list can't drift. Never edits/deletes.\n */\nfunction findCucumberHarnessAdvisories(\n cwd: string,\n // Detection already ran once for this invocation (createProjectContext →\n // detectProjectType); reuse it instead of re-sweeping the filesystem.\n { existingCucumberHarness, scaffoldBddLane }: ProjectType,\n): string[] {\n if (existingCucumberHarness === undefined) return [];\n\n if (scaffoldBddLane) {\n return [buildLeftoverLaneAdvisory(cwd, existingCucumberHarness)];\n }\n\n // paths.features alone silences this: the readers consume only the\n // features directory. paths.steps matters only to the scaffolded runner\n // (relocated TypeScript steps), which a host-harness repo isn't using.\n if (readConfiguredPath(cwd, 'features') !== undefined || hasDefaultExecutableFeatureFiles(cwd)) {\n return [];\n }\n return [\n `Detected a cucumber harness (${existingCucumberHarness}) but paths.features is not set in .safeword/config.json — project codify, project lint-gherkin, and doctor cannot see your suite. Add e.g. \"paths\": { \"features\": \"tests/behaviors\", \"steps\": \"tests/steps\" } (paths.steps only matters when the scaffolded runner reads relocated TypeScript steps).`,\n ];\n}\n\n/** Enumerate the starter-lane leftovers (files/deps/script) from schema constants. */\nfunction buildLeftoverLaneAdvisory(cwd: string, evidence: string): string {\n const leftovers: string[] = BDD_LANE_FILE_PATHS.filter(filePath =>\n exists(nodePath.join(cwd, filePath)),\n );\n\n const manifest = readPackageJsonSafe(cwd);\n const developmentDependencies = manifest?.devDependencies ?? {};\n leftovers.push(\n ...typescriptPackages.conditional.scaffoldBddLane.filter(dependency =>\n Object.hasOwn(developmentDependencies, dependency),\n ),\n );\n if (typeof manifest?.scripts?.[BDD_LANE_SCRIPT] === 'string') {\n leftovers.push(`\"${BDD_LANE_SCRIPT}\" script`);\n }\n\n return `Duplicate BDD lane: a cucumber harness (${evidence}) coexists with safeword's starter lane. Leftover scaffold: ${leftovers.join(', ')}. Safeword never removes these — if the host harness is the real suite, delete the leftovers and set paths.features / paths.steps in .safeword/config.json so safeword reads it.`;\n}\n\ninterface PackageJsonManifest {\n scripts?: Record<string, unknown>;\n devDependencies?: Record<string, string>;\n}\n\nfunction readPackageJsonSafe(cwd: string): PackageJsonManifest | undefined {\n return readJson(nodePath.join(cwd, 'package.json')) as PackageJsonManifest | undefined;\n}\n\nfunction findDocumentationSourceIssues(cwd: string): string[] {\n return readConfiguredDocumentationSources(cwd).flatMap(source => {\n if (source.type !== 'local') return [];\n return exists(source.resolvedPath)\n ? []\n : [`docs-source: ${source.path}: file or directory not found`];\n });\n}\n\n/** Ticket folder names under the tickets root (excluding `completed/`), or\n * empty when the root is missing/unreadable. */\nfunction listTicketIds(ticketsRoot: string): string[] {\n try {\n return readdirSync(ticketsRoot, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && entry.name !== 'completed')\n .map(entry => entry.name);\n } catch {\n return [];\n }\n}\n\n/**\n * Surface architecture-claim mismatches as non-blocking advisories (ticket\n * K4BWTQ). Structural only — no prose extraction (YR6C49 ruling): when an\n * in-progress ticket's impl-plan.md Design alignment section carries content\n * (not `skip:`) but the resolved `paths.architecture` location does not\n * exist, the claim cannot be honoring anything recorded. Zero-exit.\n */\nfunction findArchitectureAdvisories(cwd: string): string[] {\n const ticketsRoot = resolveTicketsDirectory(cwd);\n const ticketIds = listTicketIds(ticketsRoot);\n\n const resolved = resolveConfiguredPath(cwd, 'architecture');\n if (listArchitectureRecords(resolved).kind !== 'absent') return [];\n\n return ticketIds.flatMap(ticketId => {\n const ticketDirectory = nodePath.join(ticketsRoot, ticketId);\n const ticketContent = readFileSafe(nodePath.join(ticketDirectory, 'ticket.md'));\n if (ticketContent === undefined || !isInProgress(ticketContent)) return [];\n const implPlan = readFileSafe(nodePath.join(ticketDirectory, 'impl-plan.md'));\n if (implPlan === undefined) return [];\n if (!archAlignmentHasContent(implPlan)) return [];\n return [\n `${ticketId}: impl-plan.md Design alignment claims alignment, but no architecture record exists at ${resolved} — record the decision or mark the section skip:`,\n ];\n });\n}\n\n/** Whether the impl plan's canonical or legacy alignment section carries real content\n * (non-empty, not a `skip:` annotation). */\nfunction archAlignmentHasContent(implPlanContent: string): boolean {\n let isInSection = false;\n const body: string[] = [];\n for (const raw of implPlanContent.split('\\n')) {\n const line = raw.trim();\n if (line.startsWith('## ')) {\n const heading = line.slice(3).trim().toLowerCase();\n isInSection = heading === 'design alignment' || heading === 'arch alignment';\n continue;\n }\n // Principle alignment is the structured Markdown table in this shared\n // section. Architecture claims are the remaining prose below it.\n if (isInSection && line !== '' && !line.startsWith('|')) body.push(line);\n }\n if (body.length === 0) return false;\n return !(body.length === 1 && (body[0] ?? '').toLowerCase().startsWith('skip:'));\n}\n\n/**\n * Surface scenario-lineage coverage gaps as non-blocking advisories (ticket\n * XT1FFM). Scoped to `status: in_progress` tickets that carry a spec.md —\n * which excludes done predecessors whose pre-scheme scenarios are the\n * out-of-scope migration case (epic DZ2NM5/D5), and keeps the report focused\n * on the work the developer is actually building. Each in-progress ticket's\n * feature source or legacy (spec.md, test-definitions.md) pair is cross-referenced\n * into uncovered ACs, stale AC refs, and orphan scenarios. Coverage gaps stay\n * zero-exit advisories; invalid Gherkin is a health issue because the source\n * cannot be read.\n */\ninterface CoverageDiagnostics {\n issues: string[];\n advisories: string[];\n}\n\nfunction emptyCoverageDiagnostics(): CoverageDiagnostics {\n return { issues: [], advisories: [] };\n}\n\nfunction findCoverageDiagnostics(cwd: string): CoverageDiagnostics {\n const ticketsRoot = resolveTicketsDirectory(cwd);\n const all = emptyCoverageDiagnostics();\n const configuredFeatures = readConfiguredPath(cwd, 'features');\n const anchorEnvironment = createPhaseAnchorEnvironment(cwd, configuredFeatures);\n for (const ticketId of listTicketIds(ticketsRoot)) {\n const ticketDiagnostics = coverageDiagnosticsForTicket(cwd, ticketsRoot, ticketId);\n all.issues.push(...ticketDiagnostics.issues);\n all.advisories.push(...ticketDiagnostics.advisories);\n const anchorAdvisory = phaseAnchorAdvisoryForTicket(\n cwd,\n ticketsRoot,\n ticketId,\n anchorEnvironment,\n );\n if (anchorAdvisory !== undefined) all.advisories.push(anchorAdvisory);\n }\n return all;\n}\n\n/**\n * Phase-anchor advisory (issue #824, epic #808; HGYGND artifact-path grammar):\n * an in-progress feature ticket whose current phase carries no valid\n * `phase_anchors` entry gets a zero-exit nudge — the at-rest view of the\n * anchor substrate, verified against the working tree (a filesystem reader is\n * injected, so existence + shape are checked, not just format). Advisory only:\n * enforcement belongs to the deliverable-boundary gate (#810). Hex-shaped\n * legacy anchors are grandfathered by the detector and never re-litigated.\n */\nfunction phaseAnchorAdvisoryForTicket(\n cwd: string,\n ticketsRoot: string,\n ticketId: string,\n anchorEnvironment: Omit<PhaseAnchorScope, 'ticketPath'>,\n): string | undefined {\n const content = readFileSafe(nodePath.join(ticketsRoot, ticketId, 'ticket.md'));\n if (content === undefined || !isInProgress(content)) return undefined;\n const ticketDirectory = nodePath.join(ticketsRoot, ticketId);\n const ticketPath = toRepoRelativePath(cwd, ticketDirectory);\n const scope = { ticketPath, ...anchorEnvironment };\n const verdict = detectUnanchoredPhaseState(content, scope, relpath =>\n readFileSafe(nodePath.join(cwd, relpath)),\n );\n if (verdict.kind !== 'unanchored') return undefined;\n return `${formatCoverageTicketLabel(ticketId, content)}: ${verdict.reason} The anchor is the exited phase's artifact — boundary checks verify it against the tree.`;\n}\n\n/** Build coverage advisories for one ticket, or none if it is not an\n * in-progress, spec-bearing ticket. */\nfunction coverageDiagnosticsForTicket(\n cwd: string,\n ticketsRoot: string,\n ticketId: string,\n): CoverageDiagnostics {\n const ticketDirectory = nodePath.join(ticketsRoot, ticketId);\n const ticketContent = readFileSafe(nodePath.join(ticketDirectory, 'ticket.md'));\n if (ticketContent === undefined || !isInProgress(ticketContent))\n return emptyCoverageDiagnostics();\n\n const specContent = readFileSafe(nodePath.join(ticketDirectory, 'spec.md'));\n if (specContent === undefined) return emptyCoverageDiagnostics();\n\n const featureSource = readFeatureSource(cwd, ticketId);\n try {\n const report =\n featureSource === undefined\n ? buildCoverageReport(\n specContent,\n readFileSafe(nodePath.join(ticketDirectory, 'test-definitions.md')),\n )\n : buildCoverageReportFromFeature(specContent, featureSource.content);\n const surfaceReport =\n featureSource === undefined\n ? undefined\n : buildSurfaceCoverageReportFromFeature(specContent, featureSource.content);\n const lineageIssues =\n featureSource === undefined\n ? []\n : formatFeatureLineageIssues(cwd, ticketId, featureSource, ticketContent);\n const ruleTier = ruleTierDiagnostics(ticketId, specContent, featureSource, ticketContent);\n return {\n issues: [...lineageIssues, ...ruleTier.issues],\n advisories: [\n ...formatCoverageReport(ticketId, report, ticketContent),\n ...ruleTier.advisories,\n ...formatSurfaceCoverageReport(ticketId, surfaceReport, ticketContent),\n ],\n };\n } catch (parseError: unknown) {\n if (parseError instanceof FeatureParseError && featureSource !== undefined) {\n return {\n issues: [\n `${formatCoverageTicketLabel(ticketId, ticketContent)}: ${nodePath.relative(cwd, featureSource.path)}: invalid Gherkin feature: ${parseError.message}`,\n ],\n advisories: [],\n };\n }\n throw parseError;\n }\n}\n\n/** Rule-tier findings for one ticket: mixed-criteria JTBDs (issues) and\n * numbered rules missing a rejection-path scenario (advisories). */\nfunction ruleTierDiagnostics(\n ticketId: string,\n specContent: string,\n featureSource: FeatureSource | undefined,\n ticketContent: string,\n): CoverageDiagnostics {\n const label = formatCoverageTicketLabel(ticketId, ticketContent);\n return {\n issues: findMixedCriteriaJtbds(specContent).map(\n jtbd =>\n `${label}: JTBD ${jtbd} declares both Acceptance Criteria and numbered Rules; keep one criteria kind per job — convert one set or split the job`,\n ),\n advisories:\n featureSource === undefined\n ? []\n : findRulesMissingRejectionPaths(specContent, featureSource.content).map(\n ruleId =>\n `${label}: numbered rule ${ruleId} has no example of the rule being broken — add a @rejection-tagged scenario under it`,\n ),\n };\n}\n\nfunction formatFeatureLineageIssues(\n cwd: string,\n ticketId: string,\n featureSource: FeatureSource,\n ticketContent: string,\n): string[] {\n const label = formatCoverageTicketLabel(ticketId, ticketContent);\n const relativePath = nodePath.relative(cwd, featureSource.path);\n return findFeatureLineageIssues(featureSource.content).map(\n issue => `${label}: ${relativePath}: ${issue}`,\n );\n}\n\ninterface FeatureSource {\n path: string;\n content: string;\n}\n\nfunction readFeatureSource(cwd: string, ticketFolder: string): FeatureSource | undefined {\n const featurePath = findFeatureSourcePath(cwd, ticketFolder);\n const content = featurePath === undefined ? undefined : readFileSafe(featurePath);\n return featurePath === undefined || content === undefined\n ? undefined\n : { path: featurePath, content };\n}\n\n/** Whether a ticket.md's frontmatter declares `status: in_progress`. */\nfunction isInProgress(ticketContent: string): boolean {\n const lines = ticketContent.split('\\n');\n if (lines[0]?.trim() !== '---') return false;\n for (let index = 1; index < lines.length; index += 1) {\n const line = (lines[index] ?? '').trim();\n if (line === '---') return false;\n if (line === 'status: in_progress') return true;\n }\n return false;\n}\n\n/** Render a coverage report into one advisory string per finding. */\nfunction formatCoverageReport(\n ticketId: string,\n report: CoverageReport,\n ticketContent: string,\n): string[] {\n const ticketLabel = formatCoverageTicketLabel(ticketId, ticketContent);\n return [\n ...report.uncovered.map(id =>\n isRuleId(id)\n ? `${ticketLabel}: numbered rule ${id} has no scenario illustrating it (uncovered) — add a scenario tagged @${id}`\n : `${ticketLabel}: acceptance criterion ${id} has no scenario (uncovered)`,\n ),\n ...report.stale.map(reference =>\n isRuleId(reference)\n ? `${ticketLabel}: scenario ref ${reference} matches no numbered rule under its JTBD (stale ref) — retag to a declared rule or declare it in spec.md`\n : `${ticketLabel}: scenario ref ${reference} matches no AC under its JTBD (stale ref)`,\n ),\n ...report.orphan.map(reference =>\n isRuleId(reference)\n ? `${ticketLabel}: scenario ref ${reference} names no JTBD in spec.md (orphan) — fix the tag's JTBD id or add that JTBD to spec.md`\n : `${ticketLabel}: scenario ref ${reference} names no JTBD in spec.md (orphan)`,\n ),\n ];\n}\n\nfunction formatSurfaceCoverageReport(\n ticketId: string,\n report: SurfaceCoverageReport | undefined,\n ticketContent: string,\n): string[] {\n if (report === undefined) return [];\n const ticketLabel = formatCoverageTicketLabel(ticketId, ticketContent);\n return [\n ...report.missing.map(\n surface =>\n `${ticketLabel}: affected surface ${surface.name} has no @surface.* scenario tag (uncovered surface)`,\n ),\n ...report.stale.map(\n slug =>\n `${ticketLabel}: scenario surface tag @surface.${slug} is not listed under spec.md ## Surfaces Affected (stale surface)`,\n ),\n ];\n}\n\nfunction formatCoverageTicketLabel(ticketId: string, ticketContent?: string): string {\n const id = readFrontmatterScalar(ticketContent, 'id');\n const slug = readFrontmatterScalar(ticketContent, 'slug');\n if (id !== undefined && slug !== undefined) return formatTicketReference(id, slug);\n\n const dashIndex = ticketId.indexOf('-');\n return dashIndex === -1\n ? ticketId\n : formatTicketReference(ticketId.slice(0, dashIndex), ticketId.slice(dashIndex + 1));\n}\n\nfunction ticketReferenceOf(id: string, labelById: ReadonlyMap<string, string>): string {\n const title = labelById.get(id);\n return title === undefined ? id : formatTicketReference(id, title);\n}\n\n/**\n * Warn-only checks (dangling + cycle) over one directed relation field —\n * depends_on (soft, AKZJXC) and blocked_on (hard, MBGQ89). Generic over the edge\n * set; only the field name and cycle wording differ.\n */\nfunction relationAdvisoriesFor(\n nodes: { id: string; dependsOn: string[] }[],\n danglingField: string,\n cycleLabel: string,\n labelById: ReadonlyMap<string, string>,\n): string[] {\n const dangling = findDanglingDependencies(nodes).map(\n ({ from, missing }) =>\n `${ticketReferenceOf(from, labelById)}: ${danglingField} ${missing} — no such ticket (dangling ref)`,\n );\n const cyclic = findTicketsInCycles(nodes);\n const cycle =\n cyclic.length > 0\n ? [\n `${cycleLabel} cycle among: ${cyclic.map(id => ticketReferenceOf(id, labelById)).join(', ')} (break the loop)`,\n ]\n : [];\n return [...dangling, ...cycle];\n}\n\n/**\n * Surface structured-relation problems as non-blocking advisories (ticket\n * AKZJXC): a `depends_on` pointing at a ticket absent from the corpus (dangling\n * ref), and dependency cycles (A→B→A). Warn-only — a target may live on another\n * branch or in completed/, and a cycle is a planning smell, not a config fault.\n * Reads the full corpus (active + completed) so cross-status edges resolve.\n * Zero-exit.\n */\nfunction findRelationAdvisories(cwd: string): string[] {\n const ticketsDirectory = resolveTicketsDirectory(cwd);\n let entries;\n try {\n const { active, completed } = readTickets(ticketsDirectory);\n entries = [...active, ...completed];\n } catch {\n return [];\n }\n\n const labelById = new Map(entries.map(entry => [entry.id, entry.title]));\n const statusById = new Map(entries.map(entry => [entry.id, entry.status]));\n\n // MBGQ89: a blocked_on_override is stale once every listed blocker is `done`\n // (done auto-unblocks, so the override no longer does anything — clean it up).\n const staleOverrides = entries\n .filter(\n entry =>\n entry.blockedOnOverride !== undefined &&\n entry.blockedOn.length > 0 &&\n entry.blockedOn.every(id => statusById.get(id) === 'done'),\n )\n .map(\n entry =>\n `${ticketReferenceOf(entry.id, labelById)}: blocked_on_override is stale — every blocker is done; remove it`,\n );\n\n return [\n ...relationAdvisoriesFor(\n entries.map(entry => ({ id: entry.id, dependsOn: entry.dependsOn })),\n 'depends_on',\n 'dependency',\n labelById,\n ),\n ...relationAdvisoriesFor(\n entries.map(entry => ({ id: entry.id, dependsOn: entry.blockedOn })),\n 'blocked_on',\n 'blocked_on',\n labelById,\n ),\n ...staleOverrides,\n ];\n}\n\n/**\n * Check for missing text patch markers\n * @param cwd\n * @param actions\n */\nfunction findMissingPatches(\n cwd: string,\n actions: { type: string; path: string; definition?: { marker: string } }[],\n): string[] {\n const issues: string[] = [];\n for (const action of actions) {\n if (action.type !== 'text-patch') continue;\n\n const fullPath = nodePath.join(cwd, action.path);\n if (exists(fullPath)) {\n const content = readFileSafe(fullPath) ?? '';\n if (action.definition && !content.includes(action.definition.marker)) {\n issues.push(`${action.path} missing safeword link`);\n }\n } else {\n issues.push(`${action.path} file missing`);\n }\n }\n return issues;\n}\n\nexport interface HealthStatus {\n configured: boolean;\n projectVersion: string | undefined;\n cliVersion: string;\n updateAvailable: boolean;\n latestVersion: string | undefined;\n issues: string[];\n /**\n * Non-blocking diagnostics — reported to the user but do NOT gate\n * non-zero exit. Use for situations where safeword's operation is\n * unaffected but a cleanup or attention is warranted (e.g., legacy\n * default-location file orphaned by a configured `paths.*` override).\n */\n advisories: string[];\n missingPackages: string[];\n missingPacks: string[];\n missingPythonTools: string[];\n}\n\n/**\n * Check project configuration health using reconcile dryRun\n * @param cwd\n */\nexport interface CheckHealthOptions {\n /**\n * When true, package/pack installation state is excluded from the health\n * result — `missingPackages` and `missingPacks` come back empty regardless\n * of what is on disk. Used by the setup/upgrade self-verify when install was\n * deliberately skipped (`SAFEWORD_SKIP_INSTALL`): a command that was told not\n * to install must not then fault itself for absent packages. Config-file\n * health (missing files, broken patches, persona/glossary) is still checked.\n * Standalone `check` leaves this false so the diagnostic reports the truth.\n */\n skipPackageChecks?: boolean;\n /** Schema view used by the mutating command whose postcondition is being checked. */\n schema?: SafewordSchema;\n}\n\nfunction findMissingPythonToolDeclarations(\n cwd: string,\n context: ReturnType<typeof createProjectContext>,\n): string[] {\n if (!context.languages?.python) return [];\n return getMissingPythonToolDependencies(cwd, hasImportLinterScaffoldTarget(cwd));\n}\n\nexport async function checkHealth(\n cwd: string,\n options: CheckHealthOptions = {},\n): Promise<HealthStatus> {\n const safewordDirectory = nodePath.join(cwd, '.safeword');\n\n // Check if configured\n if (!exists(safewordDirectory)) {\n return {\n configured: false,\n projectVersion: undefined,\n cliVersion: VERSION,\n updateAvailable: false,\n latestVersion: undefined,\n issues: [],\n advisories: [],\n missingPackages: [],\n missingPacks: [],\n missingPythonTools: [],\n };\n }\n\n // Read project version\n const versionPath = nodePath.join(safewordDirectory, 'version');\n const projectVersion = readFileSafe(versionPath)?.trim() ?? undefined;\n\n // Use reconcile with dryRun to detect issues\n const ctx = createProjectContext(cwd);\n const healthSchema = options.schema ?? schemaForClaudeDelivery(cwd);\n const result = await reconcile(healthSchema, 'upgrade', ctx, {\n dryRun: true,\n });\n\n // Collect issues from write actions and text patches\n // Filter out chmod (paths[] instead of path) and json-merge/unmerge (incompatible definition)\n const actionsWithPath = result.actions.filter(\n (\n a,\n ): a is Exclude<\n (typeof result.actions)[number],\n { type: 'chmod' } | { type: 'json-merge' } | { type: 'json-unmerge' }\n > => a.type !== 'chmod' && a.type !== 'json-merge' && a.type !== 'json-unmerge',\n );\n const issues: string[] = [\n ...findMissingFiles(cwd, actionsWithPath),\n ...findMissingPatches(cwd, actionsWithPath),\n ...findPersonaIssues(cwd),\n ...PATH_ONLY_KNOWLEDGE_KEYS.flatMap(key => findConfiguredKnowledgeIssues(cwd, key)),\n ...findGlossaryIssues(cwd),\n ...findDocumentationSourceIssues(cwd),\n ...missingClaudeSettingsIssues(cwd, healthSchema),\n ];\n\n // Check for missing language packs (unless install was deliberately skipped)\n const missingPacks = options.skipPackageChecks ? [] : getMissingPacks(cwd);\n const missingPythonTools = findMissingPythonToolDeclarations(cwd, ctx);\n const coverageDiagnostics = findCoverageDiagnostics(cwd);\n const ticketIndexConflicts = inspectTicketIndexConflicts(cwd);\n issues.push(...coverageDiagnostics.issues);\n\n return {\n configured: true,\n projectVersion,\n cliVersion: VERSION,\n updateAvailable: false,\n latestVersion: undefined,\n issues,\n advisories: [\n ...(ticketIndexConflicts.length === 0\n ? []\n : [buildIndexConflictListMessage(ticketIndexConflicts)]),\n ...findNamespaceAdvisories(cwd),\n ...CONFIGURED_KNOWLEDGE_KEYS.flatMap(key => findConfiguredKnowledgeAdvisories(cwd, key)),\n ...findCucumberHarnessAdvisories(cwd, ctx.projectType),\n ...coverageDiagnostics.advisories,\n ...findRelationAdvisories(cwd),\n ...findArchitectureAdvisories(cwd),\n ],\n missingPackages: options.skipPackageChecks ? [] : result.packagesToInstall,\n missingPacks,\n missingPythonTools,\n };\n}\n\nexport interface ReportHealthOptions {\n /**\n * Replaces the default `Run \\`safeword install\\` …` instruction on every\n * failure branch. Used by the post-upgrade self-verify (ticket 3293WH\n * AC5): reconciliation telling the user to run `safeword install` as the fix is\n * a contradiction — an issue the reconcile just ran couldn't fix won't be\n * fixed by running it again.\n */\n repairHint?: string;\n}\n\ninterface FailureSection {\n title: string;\n lines: string[];\n render: (line: string) => void;\n defaultHint: string;\n}\n\n/** The highest-priority failure section to report, or undefined when healthy.\n * Packs first (explains missing files), then packages, then issues. */\nfunction firstFailureSection(health: HealthStatus): FailureSection | undefined {\n if (health.missingPacks.length > 0) {\n return {\n title: 'Missing Language Packs',\n lines: health.missingPacks.map(pack => `${pack} pack not installed`),\n render: listItem,\n defaultHint: 'Run `safeword install` to install missing packs',\n };\n }\n if (health.missingPackages.length > 0) {\n return {\n title: 'Missing Packages',\n lines: health.missingPackages,\n render: listItem,\n defaultHint: 'Run `safeword install` to install missing packages',\n };\n }\n if (health.missingPythonTools.length > 0) {\n return {\n title: 'Missing Python Tools',\n lines: health.missingPythonTools,\n render: listItem,\n defaultHint: 'Run `safeword install` to declare missing Python tools',\n };\n }\n if (health.issues.length > 0) {\n return {\n title: 'Issues Found',\n lines: health.issues,\n render: warn,\n defaultHint: 'Run `safeword install` to repair configuration',\n };\n }\n return undefined;\n}\n\n/**\n * Report issues or success\n * @param health\n * @param options\n * @returns true if there are issues requiring attention\n */\nexport function reportHealthSummary(\n health: HealthStatus,\n options: ReportHealthOptions = {},\n): boolean {\n // Advisories first: non-blocking diagnostics that must surface even when\n // issues exist (the failure branch below returns early). Ticket 9MMWS7\n // exposed the old ordering, which silently swallowed advisories on any\n // unhealthy project.\n if (health.advisories.length > 0) {\n header('Advisories');\n for (const advisory of health.advisories) {\n warn(advisory);\n }\n }\n\n const failure = firstFailureSection(health);\n if (failure === undefined) {\n success('\\nConfiguration is healthy');\n return false;\n }\n\n header(failure.title);\n for (const line of failure.lines) {\n failure.render(line);\n }\n info(`\\n${options.repairHint ?? failure.defaultHint}`);\n return true;\n}\n","import { SAFEWORD_SCHEMA, type SafewordSchema } from '../schema.js';\nimport { legacyObservationIsEmpty, observeClaudeLegacy } from './legacy-classifier.js';\nimport { hasLegacyClaudePluginMode, readClaudePluginMode } from './migration-state.js';\n\nfunction withoutLegacyClaude<T>(values: Record<string, T>): Record<string, T> {\n return Object.fromEntries(\n Object.entries(values).filter(([path]) => !path.startsWith('.claude/')),\n );\n}\n\n/** Select the project schema for native versus retained legacy Claude delivery. */\nexport function schemaForClaudeDelivery(cwd: string): SafewordSchema {\n const legacyPluginMode = hasLegacyClaudePluginMode(cwd);\n const nativePluginMode = readClaudePluginMode(cwd) !== undefined;\n if (\n !legacyPluginMode &&\n !nativePluginMode &&\n !legacyObservationIsEmpty(observeClaudeLegacy(cwd))\n ) {\n return SAFEWORD_SCHEMA;\n }\n return {\n ...SAFEWORD_SCHEMA,\n ownedDirs: SAFEWORD_SCHEMA.ownedDirs.filter(path => !path.startsWith('.claude')),\n sharedDirs: SAFEWORD_SCHEMA.sharedDirs.filter(path => !path.startsWith('.claude')),\n deprecatedFiles: SAFEWORD_SCHEMA.deprecatedFiles.filter(path => !path.startsWith('.claude/')),\n deprecatedDirs: SAFEWORD_SCHEMA.deprecatedDirs.filter(path => !path.startsWith('.claude')),\n ownedFiles: withoutLegacyClaude(SAFEWORD_SCHEMA.ownedFiles),\n managedFiles: withoutLegacyClaude(SAFEWORD_SCHEMA.managedFiles),\n jsonMerges: withoutLegacyClaude(SAFEWORD_SCHEMA.jsonMerges),\n };\n}\n","/**\n * Lists a project's architecture records (ticket K4BWTQ).\n *\n * The resolved `paths.architecture` location may be a single markdown file\n * (the architecture record itself) or a directory of ADRs — each top-level\n * `.md` file except README.md, accept-any naming, no recursion. See the\n * M6D315 replan for why this reuses `paths.architecture` instead of a\n * separate ADR-location field.\n */\n\nimport { readdirSync, statSync } from 'node:fs';\nimport nodePath from 'node:path';\n\ntype ArchitectureLocationKind = 'file' | 'directory' | 'absent';\n\nexport interface ArchitectureRecords {\n kind: ArchitectureLocationKind;\n /** Absolute paths of the record files; empty when none exist. */\n records: string[];\n}\n\nexport function listArchitectureRecords(resolvedPath: string): ArchitectureRecords {\n // try/catch in addition to throwIfNoEntry: statSync still throws ENOTDIR\n // when a path *component* is a file (nodejs/node#56993) — reachable here\n // via a misconfigured paths.architecture; treat it as absent, not a crash.\n let stats;\n try {\n stats = statSync(resolvedPath, { throwIfNoEntry: false });\n } catch {\n return { kind: 'absent', records: [] };\n }\n if (stats?.isFile()) {\n return { kind: 'file', records: [resolvedPath] };\n }\n if (stats?.isDirectory()) {\n const records = readdirSync(resolvedPath, { withFileTypes: true })\n .filter(entry => entry.isFile() && entry.name.endsWith('.md') && entry.name !== 'README.md')\n .map(entry => nodePath.join(resolvedPath, entry.name));\n return { kind: 'directory', records };\n }\n return { kind: 'absent', records: [] };\n}\n","/**\n * Glossary file model — parsing, validation, and lookup.\n *\n * Project-level glossary lives at the resolved namespace root (or the\n * path configured at `paths.glossary` in `.safeword/config.json`). Each\n * entry is a level-2 markdown block with a `## Term` header, a required\n * `**Definition:**` line, and optional `**Used in:**`, `**Example:**`,\n * `**Do not confuse with:**`, and `**Aliases:**` lines.\n *\n * Schema is intentionally lenient — unknown `**Field:**` lines are\n * tolerated for forward-compat, and the arcade-prototype\n * `**Used in**:` (colon outside the bold) variant parses identically\n * to `**Used in:**`. The required schema is just `## Term` + Definition;\n * everything else evolves per-team.\n *\n * See ticket YR6C49 for the full spec.\n */\n\nimport { readFileSync } from 'node:fs';\n\nimport { resolveConfiguredPath } from './configured-paths.js';\nimport { computeSkipMask, stripInlineComments } from './markdown-sections.js';\nimport { findDuplicates, groupByLine } from './validation.js';\n\n/**\n * A parsed glossary entry — name + Definition (required), plus any\n * optional fields the entry authored. Aliases is always present\n * (possibly empty) so callers can iterate without an optional-chain.\n */\nexport interface ParsedGlossaryEntry {\n name: string;\n definition: string;\n usedIn?: string;\n example?: string;\n doNotConfuseWith?: string;\n aliases: string[];\n /** 1-indexed line number of the `## ` header. */\n lineNumber: number;\n}\n\n/** A validation error with a 1-indexed line reference into the source content. */\nexport interface GlossaryValidationError {\n line: number;\n message: string;\n}\n\n/**\n * Result of resolving a glossary reference against the parsed entries.\n *\n * Discriminated union — `match` is guaranteed when `status === 'valid'`;\n * `suggestion` is only meaningful when `status === 'unknown'`. Callers\n * narrow on `status` without optional chaining.\n */\nexport type GlossaryReferenceResult =\n { status: 'valid'; match: ParsedGlossaryEntry } | { status: 'unknown'; suggestion?: string };\n\n/**\n * Resolve a glossary reference against the on-disk glossary file.\n *\n * Reads from `paths.glossary` in `.safeword/config.json` when configured;\n * falls back to the namespace-root default otherwise. Degrades\n * gracefully on a missing or unreadable file — returns\n * `{ status: 'unknown' }` rather than throwing, regardless of whether the\n * resolved path is the default or a configured override. The loud signal\n * on configured-but-missing lives in `safeword doctor`, not here — keep\n * this lookup cheap and side-effect-free (mirrors\n * `validatePersonaReference`, ticket K7N2QM).\n */\nexport function validateGlossaryReference(cwd: string, input: string): GlossaryReferenceResult {\n let content: string;\n try {\n const filePath = resolveConfiguredPath(cwd, 'glossary');\n content = readFileSync(filePath, 'utf8');\n } catch {\n return { status: 'unknown' };\n }\n return lookupGlossaryReference(parseGlossary(content), input);\n}\n\n/**\n * Look up a glossary reference against parsed entries.\n *\n * Match priority: exact term name → exact alias → casing-mismatch\n * suggestion → unknown. Pure — no I/O.\n */\nexport function lookupGlossaryReference(\n entries: readonly ParsedGlossaryEntry[],\n input: string,\n): GlossaryReferenceResult {\n if (input.length === 0) return { status: 'unknown' };\n\n for (const entry of entries) {\n if (entry.name === input || entry.aliases.includes(input)) {\n return { status: 'valid', match: entry };\n }\n }\n\n // Casing-mismatch detection — suggest the canonical spelling when the\n // only difference is case (on a term name or an alias).\n const lowered = input.toLowerCase();\n for (const entry of entries) {\n if (entry.name.toLowerCase() === lowered) {\n return { status: 'unknown', suggestion: entry.name };\n }\n const aliasMatch = entry.aliases.find(alias => alias.toLowerCase() === lowered);\n if (aliasMatch !== undefined) {\n return { status: 'unknown', suggestion: entry.name };\n }\n }\n\n return { status: 'unknown' };\n}\n\n/**\n * Group alias → header line numbers across all entries. Unlike\n * {@link groupByLine} (one key per entry), each entry contributes one key\n * per declared alias.\n */\nfunction groupAliasesByLine(entries: readonly ParsedGlossaryEntry[]): Map<string, number[]> {\n const grouped = new Map<string, number[]>();\n for (const entry of entries) {\n addEntryAliasesToGroup(entry, grouped);\n }\n return grouped;\n}\n\nfunction addEntryAliasesToGroup(entry: ParsedGlossaryEntry, grouped: Map<string, number[]>): void {\n for (const alias of entry.aliases) {\n if (alias.length === 0) continue;\n const lines = grouped.get(alias) ?? [];\n lines.push(entry.lineNumber);\n grouped.set(alias, lines);\n }\n}\n\n/**\n * Flag aliases that collide with a declared term name. Lookup must\n * resolve a string to exactly one term; an alias that shadows a real\n * term name is ambiguous. A self-alias (alias equal to its own term's\n * name) is harmless redundancy and not flagged.\n */\nfunction findAliasShadowingTerms(\n entries: readonly ParsedGlossaryEntry[],\n): GlossaryValidationError[] {\n const termLines = new Map<string, number>();\n for (const entry of entries) {\n if (entry.name.length > 0 && !termLines.has(entry.name)) {\n termLines.set(entry.name, entry.lineNumber);\n }\n }\n const errors: GlossaryValidationError[] = [];\n for (const entry of entries) {\n for (const alias of entry.aliases) {\n const termLine = termLines.get(alias);\n if (termLine !== undefined && termLine !== entry.lineNumber) {\n errors.push({\n line: entry.lineNumber,\n message: `alias \"${alias}\" shadows term defined at line ${termLine}`,\n });\n }\n }\n }\n return errors;\n}\n\n/**\n * Validate parsed glossary entries. Returns a list of\n * {@link GlossaryValidationError} with 1-indexed line numbers; empty list\n * means the file is well-formed.\n *\n * Checks (each independent, all errors collected — never throws):\n * - Every entry has a non-empty term name.\n * - Every entry has a non-empty `**Definition:**`.\n * - Term names are unique within the file.\n * - Aliases are unique across all terms.\n * - No alias shadows a declared term name (ambiguous lookup).\n */\nexport function validateGlossary(\n entries: readonly ParsedGlossaryEntry[],\n): GlossaryValidationError[] {\n const errors: GlossaryValidationError[] = [];\n for (const entry of entries) {\n if (entry.name.length === 0) {\n errors.push({ line: entry.lineNumber, message: 'header is missing term name' });\n }\n if (entry.definition.trim().length === 0) {\n const label = entry.name.length === 0 ? 'entry' : `\"${entry.name}\"`;\n errors.push({ line: entry.lineNumber, message: `${label} is missing Definition` });\n }\n }\n errors.push(\n ...findDuplicates(\n groupByLine(entries, entry => entry.name),\n 'term',\n ),\n ...findDuplicates(groupAliasesByLine(entries), 'alias'),\n ...findAliasShadowingTerms(entries),\n );\n return errors;\n}\n\n/**\n * The string-valued fields a `**Field:**` line can populate. Aliases is\n * excluded — it parses to an array and does not accumulate across lines.\n */\ntype StringFieldKey = 'definition' | 'usedIn' | 'example' | 'doNotConfuseWith';\n\n/**\n * Maps a `**Field:**` prefix to the corresponding property on\n * `ParsedGlossaryEntry`. Lookup is by exact-prefix; unknown prefixes are\n * silently ignored (forward-compat per ticket scope).\n */\nconst FIELD_PROPERTY_MAP: ReadonlyMap<string, StringFieldKey> = new Map([\n ['**Definition:**', 'definition'],\n ['**Used in:**', 'usedIn'],\n ['**Example:**', 'example'],\n ['**Do not confuse with:**', 'doNotConfuseWith'],\n]);\n\n/**\n * Normalize the colon-outside variant `**Foo**:` to the canonical\n * colon-inside form `**Foo:**` so a single prefix lookup table covers\n * both. Arcade's prototype glossary mixes both conventions on adjacent\n * lines — the parser must tolerate either.\n *\n * Bounded: only inspects the leading `**...**:` segment; no backtracking.\n */\nfunction normalizeFieldColon(line: string): string {\n if (!line.startsWith('**')) return line;\n const closeBold = line.indexOf('**', 2);\n if (closeBold === -1) return line;\n if (line.charAt(closeBold + 2) !== ':') return line;\n // Splice: `<prefix>**` + `:**` + `<rest after `**:`>` →\n // `**Foo**: bar` becomes `**Foo:** bar`.\n return `${line.slice(0, closeBold)}:**${line.slice(closeBold + 3)}`;\n}\n\n/**\n * If the line begins with one of the known `**Field:**` prefixes, return\n * the property + value to assign. Otherwise return undefined.\n */\nfunction parseFieldLine(line: string): { property: StringFieldKey; value: string } | undefined {\n const normalized = normalizeFieldColon(line);\n for (const [prefix, property] of FIELD_PROPERTY_MAP) {\n if (normalized.startsWith(prefix)) {\n return { property, value: normalized.slice(prefix.length).trim() };\n }\n }\n return undefined;\n}\n\n/**\n * Whether a line looks like a `**Field:**` declaration (known or not).\n * Used to terminate continuation accumulation on an unknown field line\n * so it isn't swallowed into the previous field's value. Accepts the\n * colon-outside variant via normalization first.\n */\nfunction looksLikeFieldDeclaration(line: string): boolean {\n const normalized = normalizeFieldColon(line);\n if (!normalized.startsWith('**')) return false;\n // Require non-empty content between the opening `**` and the `:**` close.\n return normalized.indexOf(':**') > 2;\n}\n\n/**\n * Parse the comma-separated alias list from a `**Aliases:** foo, bar` line.\n * Empty trailing-whitespace yields an empty list. Returns undefined when\n * the line isn't an Aliases line.\n */\nfunction parseAliasLine(line: string): string[] | undefined {\n if (!line.startsWith('**Aliases:**')) return undefined;\n const raw = line.slice('**Aliases:**'.length).trim();\n return raw.length === 0 ? [] : raw.split(',').map(part => part.trim());\n}\n\n/**\n * Outcome of applying one line to the active entry:\n * - `field` — a string field was set; the caller accumulates continuation\n * lines into `field`.\n * - `aliases` — the aliases line was consumed; stop accumulating.\n * - `none` — no known prefix matched; the line is a continuation candidate.\n */\ntype LineOutcome =\n { kind: 'field'; field: StringFieldKey } | { kind: 'aliases' } | { kind: 'none' };\n\n/**\n * Apply a recognized field/alias line to the active entry. Unknown\n * `**Field:**` lines are tolerated per ticket scope (returns `none`).\n */\nfunction applyLineToEntry(line: string, entry: ParsedGlossaryEntry): LineOutcome {\n const aliases = parseAliasLine(line);\n if (aliases !== undefined) {\n entry.aliases = aliases;\n return { kind: 'aliases' };\n }\n const field = parseFieldLine(line);\n if (field) {\n entry[field.property] = field.value;\n return { kind: 'field', field: field.property };\n }\n return { kind: 'none' };\n}\n\n/**\n * Append a continuation line to the active string field, soft-wrap style:\n * single space between the existing text and the trimmed continuation.\n */\nfunction appendContinuation(entry: ParsedGlossaryEntry, field: StringFieldKey, line: string): void {\n const existing = entry[field] ?? '';\n const addition = line.trim();\n entry[field] = existing.length === 0 ? addition : `${existing} ${addition}`;\n}\n\n/**\n * Apply one body line (a line within a `## Term` block) to the active\n * entry and return the field that should accumulate subsequent\n * continuation lines. A blank line, an aliases line, or an unknown\n * `**Field:**` declaration resets accumulation (returns undefined).\n */\nfunction consumeBodyLine(\n line: string,\n entry: ParsedGlossaryEntry,\n activeField: StringFieldKey | undefined,\n): StringFieldKey | undefined {\n if (line.trim().length === 0) return undefined;\n const outcome = applyLineToEntry(line, entry);\n if (outcome.kind === 'field') return outcome.field;\n if (outcome.kind === 'aliases' || looksLikeFieldDeclaration(line)) return undefined;\n if (activeField !== undefined) appendContinuation(entry, activeField, line);\n return activeField;\n}\n\n/**\n * If the line is a level-2 header (`## Name`, or a bare/empty `##`),\n * return the (possibly empty) term name with inline comments stripped.\n * Returns undefined for non-header lines. An empty name is surfaced as a\n * validation error downstream, not dropped here — so the bad line still\n * produces an entry the validator can point at.\n */\nfunction parseTermHeader(line: string): string | undefined {\n if (line === '##') return '';\n if (line.startsWith('## ')) return stripInlineComments(line.slice(3)).trim();\n return undefined;\n}\n\n/**\n * Parse glossary entries from markdown content.\n *\n * Walks lines once, tracking the active `## Term` block. Skip-mask hides\n * fenced code and block HTML comments. Inline HTML comments are stripped\n * from header text before name extraction. Known `**Field:**` lines (plus\n * the arcade colon-outside variant) populate the matching property on the\n * active entry; unknown `**Field:**` lines are silently tolerated. Pure\n * — no I/O.\n */\nexport function parseGlossary(content: string): ParsedGlossaryEntry[] {\n const lines = content.split('\\n');\n const skip = computeSkipMask(lines);\n const entries: ParsedGlossaryEntry[] = [];\n let current: ParsedGlossaryEntry | undefined;\n // The field currently accumulating continuation lines. Reset on a blank\n // line, a new `## ` header, or an aliases line.\n let activeField: StringFieldKey | undefined;\n\n for (const [index, line] of lines.entries()) {\n if (skip[index] === true) continue;\n const headerName = parseTermHeader(line);\n if (headerName !== undefined) {\n if (current) entries.push(current);\n current = {\n name: headerName,\n definition: '',\n aliases: [],\n lineNumber: index + 1,\n };\n activeField = undefined;\n continue;\n }\n if (!current) continue;\n activeField = consumeBodyLine(line, current, activeField);\n }\n\n if (current) entries.push(current);\n return entries;\n}\n","/**\n * Shared validation helpers for the `## `-block file models (personas,\n * glossary). Both group parsed entries by a key and flag duplicates with a\n * uniform `duplicate <kind> \"<value>\" (also at line <others>)` message.\n * Extracted per ticket JZXVKN (Rule of Three, after WQ4RH3's skip-mask lift).\n */\n\n/** A validation finding with a 1-indexed line reference into the source. */\nexport interface ValidationIssue {\n line: number;\n message: string;\n}\n\n/**\n * Group entries by a derived key → the 1-indexed header line numbers that\n * produced it. Empty keys are skipped. Works for any parsed entry carrying a\n * `lineNumber` (ParsedPersona, ParsedGlossaryEntry, …).\n */\nexport function groupByLine<T extends { lineNumber: number }>(\n entries: readonly T[],\n pick: (entry: T) => string,\n): Map<string, number[]> {\n const grouped = new Map<string, number[]>();\n for (const entry of entries) {\n const key = pick(entry);\n if (key.length === 0) continue;\n const lines = grouped.get(key) ?? [];\n lines.push(entry.lineNumber);\n grouped.set(key, lines);\n }\n return grouped;\n}\n\n/**\n * Produce duplicate-detection issues from a grouping (key → header line\n * numbers): every key with more than one line yields one issue per line,\n * naming the others. `kind` labels the value class (e.g. \"persona name\",\n * \"persona code\", \"term\", \"alias\").\n */\nexport function findDuplicates(grouped: Map<string, number[]>, kind: string): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n for (const [value, lines] of grouped) {\n if (lines.length <= 1) continue;\n for (const line of lines) {\n const others = lines.filter(other => other !== line).join(', ');\n issues.push({ line, message: `duplicate ${kind} \"${value}\" (also at line ${others})` });\n }\n }\n return issues;\n}\n","/**\n * Persona file model — derivation, parsing, validation, and lookup.\n *\n * Project-level personas live at the resolved namespace root as\n * second-level markdown blocks. Each block has a name, an optional\n * parenthesized short code (auto-derived if absent), a `**Role:**` line,\n * and an optional `**Context:**` block.\n *\n * Persisted short codes follow the compatibility pattern\n * `^[A-Z][A-Z0-9]{1,5}$` (2-6 chars). Newly derived codes use the narrower\n * canonical 3-4 character convention; explicitly authored new codes should use\n * 2-4 characters, while persisted 5-6 character codes remain compatible.\n *\n * See ticket 7YN5QB for the full spec.\n */\n\nimport { readFileSync } from 'node:fs';\n\nimport { resolveConfiguredPath } from './configured-paths.js';\nimport { computeSkipMask, stripInlineComments } from './markdown-sections.js';\nimport { findDuplicates, groupByLine } from './validation.js';\n\n// The three constants below are exported for workspace-internal use (tests\n// asserting the canonical bounds, docs referencing them without hardcoding,\n// future code in the same package). They are deliberately NOT re-exported\n// from `src/presets/typescript/index.ts` — customers interact with persona\n// validation through `safeword doctor`, not by reading these constants\n// directly. Promoting them to safeword's public preset surface would make\n// the values part of safeword's semver contract (changing 6 → 8 would\n// become a breaking change), and there's no current consumer that needs\n// that commitment.\n\n/** Maximum length of a newly derived canonical short code. */\nconst MAX_DERIVED_CODE_LENGTH = 4;\n/** Minimum persona name length — single-char names are rejected at validation. */\nconst MIN_NAME_LENGTH = 2;\n/** Pattern for a valid persona short code. */\nexport const PERSONA_CODE_PATTERN = /^[A-Z][A-Z0-9]{1,5}$/;\n/** Pattern for a newly derived canonical persona short code. */\nexport const CANONICAL_PERSONA_CODE_PATTERN = /^[A-Z][A-Z0-9]{2,3}$/;\n\n/**\n * Derive a short code from a persona name.\n *\n * Single-word names use their first 3 characters (\"Auditor\" → \"AUD\").\n * Two-word names use two characters from the first word plus the second word's\n * initial (\"Platform Operator\" → \"PLO\"). Names with 3+ words use their first\n * 4 initials. Apostrophes are removed within a word; other punctuation separates\n * words; digits are preserved.\n *\n * Note: the returned code may not pass {@link PERSONA_CODE_PATTERN} for\n * pathological inputs (e.g., digit-first names like \"3 Amigos\" → \"3A\").\n * Pattern enforcement happens at validation time, not derivation time.\n */\nexport function derivePersonaCode(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0) return '';\n\n const withoutApostrophes = trimmed.replaceAll(/['’]/g, '');\n const cleaned = withoutApostrophes.replaceAll(/[^A-Z0-9\\s]/gi, ' ');\n const words = cleaned.split(/\\s+/).filter(word => word.length > 0);\n\n const [firstWord] = words;\n if (!firstWord) return '';\n\n // String.charAt returns '' for empty strings — no narrowing needed and\n // no non-null assertion (each word is non-empty per the filter above,\n // but TypeScript can't prove that on indexed access).\n let derived: string;\n if (words.length === 1) {\n derived = firstWord.slice(0, 3);\n } else if (words.length === 2) {\n derived = `${firstWord.slice(0, 2)}${words[1]?.charAt(0) ?? ''}`;\n } else {\n derived = words.map(word => word.charAt(0)).join('');\n }\n\n return derived.toUpperCase().slice(0, MAX_DERIVED_CODE_LENGTH);\n}\n\n/** Derive the pre-canonical code used by safeword before 3–4 letter defaults. */\nfunction deriveLegacyPersonaCode(name: string): string {\n const cleaned = name.trim().replaceAll(/[^A-Z0-9\\s]/gi, '');\n const words = cleaned.split(/\\s+/).filter(word => word.length > 0);\n const [firstWord] = words;\n if (!firstWord) return '';\n\n const derived =\n words.length === 1 ? firstWord.slice(0, 2) : words.map(word => word.charAt(0)).join('');\n return derived.toUpperCase().slice(0, 6);\n}\n\n/** Whether a persona name passes the minimum-length requirement. */\nexport function isValidPersonaName(name: string): boolean {\n return name.trim().length >= MIN_NAME_LENGTH;\n}\n\n/** Whether a code matches the persona-code pattern. */\nexport function isValidPersonaCode(code: string): boolean {\n return PERSONA_CODE_PATTERN.test(code);\n}\n\n/**\n * A parsed persona block — name, code (possibly empty before resolution),\n * line number of the header (1-indexed), and whether the user explicitly\n * authored the code via `## Name (CODE)` syntax.\n */\nexport interface ParsedPersona {\n name: string;\n /** Empty string when no code was authored (will be filled by {@link resolvePersonaCodes}). */\n rawCode: string;\n /** True when the code came from `## Name (CODE)` syntax; false when absent in source. */\n explicit: boolean;\n /** 1-indexed line number of the `## ` header. */\n lineNumber: number;\n /** Whether a `**Role:**` line was found in the block body. */\n hasRole: boolean;\n}\n\n/** A resolved persona — code is always populated (derived if not explicit). */\nexport interface ResolvedPersona extends ParsedPersona {\n code: string;\n codeError?: 'non-canonical-derived-code' | 'collision-space-exhausted';\n}\n\n/** A validation error with a 1-indexed line reference into the source content. */\nexport interface PersonaValidationError {\n line: number;\n message: string;\n}\n\n/**\n * Extract name and (optional) code from a `## ...` header line.\n *\n * Parsed manually rather than with regex to avoid super-linear-backtracking\n * vulnerabilities flagged by `regexp/no-super-linear-backtracking`. The\n * `(CODE)` suffix is detected by checking for a trailing `)` and locating\n * its matching `(` via `lastIndexOf` — no quantifier overlap. Inline HTML\n * comments are stripped from the body before name/code extraction so a\n * trailing `<!-- ... -->` doesn't corrupt the parsed name.\n */\nfunction parseHeaderLine(line: string): { name: string; rawCode: string | undefined } | undefined {\n if (!line.startsWith('## ')) return undefined;\n const body = stripInlineComments(line.slice(3)).trimEnd();\n if (body.endsWith(')')) {\n const openParen = body.lastIndexOf('(');\n if (openParen !== -1) {\n const namePart = body.slice(0, openParen).trim();\n const codePart = body.slice(openParen + 1, -1).trim();\n return { name: namePart, rawCode: codePart };\n }\n }\n return { name: body.trim(), rawCode: undefined };\n}\n\n/**\n * Parse persona blocks from markdown content.\n *\n * A block starts at a level-2 header (`## ...`) and runs until the next\n * level-2 header or end of file. The header may include a parenthesized\n * code (`## Name (PO)`) or omit it (`## Name`). The body is scanned for\n * a `**Role:**` line; presence is recorded but the role text isn't\n * extracted here (validation only needs the existence check).\n *\n * Pure — no I/O.\n */\nexport function parsePersonas(content: string): ParsedPersona[] {\n const lines = content.split('\\n');\n const skip = computeSkipMask(lines);\n const personas: ParsedPersona[] = [];\n let current: ParsedPersona | undefined;\n\n for (const [index, line] of lines.entries()) {\n if (skip[index] === true) continue;\n const header = parseHeaderLine(line);\n if (header) {\n if (current) personas.push(current);\n current = {\n name: header.name,\n rawCode: header.rawCode ?? '',\n explicit: header.rawCode !== undefined,\n lineNumber: index + 1,\n hasRole: false,\n };\n continue;\n }\n if (current && line.startsWith('**Role:**')) {\n current.hasRole = true;\n }\n }\n\n if (current) personas.push(current);\n return personas;\n}\n\n/** Allocate a deterministic collision suffix without exceeding four characters. */\nfunction allocateDerivedCode(\n base: string,\n claimed: ReadonlySet<string>,\n): { code: string; exhausted: boolean } {\n if (!claimed.has(base)) return { code: base, exhausted: false };\n\n for (let suffix = 2; ; suffix += 1) {\n const suffixText = String(suffix);\n const prefixLength = MAX_DERIVED_CODE_LENGTH - suffixText.length;\n if (prefixLength < 1) return { code: base, exhausted: true };\n const candidate = `${base.slice(0, prefixLength)}${suffixText}`;\n if (!claimed.has(candidate)) return { code: candidate, exhausted: false };\n }\n}\n\n/**\n * Resolve auto-derived codes with collision avoidance.\n *\n * For each persona without an explicit code, derive one from the name.\n * If the derived code is already taken (by a user-authored explicit code\n * or a previously-resolved derivation in the same pass), append a numeric\n * suffix starting at 2 (`PO` → `PO2` → `PO3` → ...).\n *\n * Explicit codes are claimed up-front so derived codes always lose\n * collision disputes against user-authored ones.\n */\nexport function resolvePersonaCodes(parsed: readonly ParsedPersona[]): ResolvedPersona[] {\n const claimed = new Set<string>();\n for (const persona of parsed) {\n if (persona.explicit && persona.rawCode.length > 0) {\n claimed.add(persona.rawCode);\n }\n }\n\n const resolved: ResolvedPersona[] = [];\n for (const persona of parsed) {\n if (persona.explicit) {\n resolved.push({ ...persona, code: persona.rawCode });\n continue;\n }\n const base = derivePersonaCode(persona.name);\n const allocation = allocateDerivedCode(base, claimed);\n if (!allocation.exhausted) claimed.add(allocation.code);\n let codeError: ResolvedPersona['codeError'];\n if (allocation.exhausted) {\n codeError = 'collision-space-exhausted';\n } else if (!CANONICAL_PERSONA_CODE_PATTERN.test(allocation.code)) {\n codeError = 'non-canonical-derived-code';\n }\n resolved.push({ ...persona, code: allocation.code, codeError });\n }\n\n return resolved;\n}\n\n/**\n * Validate parsed personas. Returns a list of {@link PersonaValidationError}\n * with 1-indexed line numbers; empty list means the file is well-formed.\n *\n * Checks (each independent):\n * - Persona name is ≥ {@link MIN_NAME_LENGTH} characters\n * - Header has a name (not just `## (CODE)`)\n * - Block has a `**Role:**` line\n * - Persona names are unique within the file\n * - Resolved codes are unique within the file\n * - Resolved codes match {@link PERSONA_CODE_PATTERN}\n * (digit-first names like \"3 Amigos\" derive non-conformant codes and\n * surface here with the explicit-override prompt)\n */\nfunction validateNameAndRole(persona: ParsedPersona): PersonaValidationError[] {\n const errors: PersonaValidationError[] = [];\n if (persona.name.length === 0) {\n errors.push({ line: persona.lineNumber, message: 'missing persona name' });\n } else if (!isValidPersonaName(persona.name)) {\n errors.push({\n line: persona.lineNumber,\n message: 'persona name must be at least 2 characters',\n });\n }\n if (!persona.hasRole) {\n errors.push({ line: persona.lineNumber, message: 'missing Role line' });\n }\n return errors;\n}\n\n/** Produce pattern-violation errors for resolved personas. */\nfunction findPatternErrors(resolved: readonly ResolvedPersona[]): PersonaValidationError[] {\n const errors: PersonaValidationError[] = [];\n for (const persona of resolved) {\n if (persona.code.length === 0) continue;\n if (persona.codeError === 'non-canonical-derived-code') {\n errors.push({\n line: persona.lineNumber,\n message: `name produces non-canonical code \"${persona.code}\" — author an explicit 2–4 letter code via \\`## Name (CODE)\\``,\n });\n continue;\n }\n if (persona.codeError === 'collision-space-exhausted') {\n errors.push({\n line: persona.lineNumber,\n message: `canonical collision space exhausted for \"${persona.code}\" — author an explicit 2–4 letter code via \\`## Name (CODE)\\``,\n });\n continue;\n }\n if (isValidPersonaCode(persona.code)) continue;\n const message = persona.explicit\n ? `code \"${persona.code}\" violates pattern ${PERSONA_CODE_PATTERN.source}`\n : `name produces non-conformant code \"${persona.code}\" — author explicit code via \\`## Name (CODE)\\``;\n errors.push({ line: persona.lineNumber, message });\n }\n return errors;\n}\n\nexport function validatePersonas(parsed: readonly ParsedPersona[]): PersonaValidationError[] {\n const resolved = resolvePersonaCodes(parsed);\n return [\n ...parsed.flatMap(persona => validateNameAndRole(persona)),\n ...findDuplicates(\n groupByLine(parsed, persona => persona.name),\n 'persona name',\n ),\n ...findPatternErrors(resolved),\n ...findDuplicates(\n groupByLine(resolved, persona => persona.code),\n 'persona code',\n ),\n ];\n}\n\n/**\n * Result of resolving a persona reference against the file.\n *\n * Discriminated union — `match` is guaranteed when `status === 'valid'`;\n * `suggestion` is only meaningful (and only ever populated) when\n * `status === 'unknown'`. Callers can narrow without optional chaining\n * after checking `status`.\n */\nexport type PersonaReferenceResult =\n { status: 'valid'; match: ResolvedPersona } | { status: 'unknown'; suggestion?: string };\n\ninterface LegacyPersonaAlias {\n code: string;\n persona: ResolvedPersona;\n}\n\nfunction resolveLegacyPersonaAliases(personas: readonly ResolvedPersona[]): LegacyPersonaAlias[] {\n const claimed = new Set(\n personas.filter(persona => persona.codeError === undefined).map(persona => persona.code),\n );\n const aliases: LegacyPersonaAlias[] = [];\n\n for (const persona of personas) {\n if (persona.codeError !== undefined) continue;\n const base = deriveLegacyPersonaCode(persona.name);\n if (base === '' || base === persona.code) continue;\n\n let candidate = base;\n let suffix = 2;\n while (claimed.has(candidate)) {\n candidate = `${base}${suffix}`;\n suffix += 1;\n }\n if (!isValidPersonaCode(candidate)) continue;\n claimed.add(candidate);\n aliases.push({ code: candidate, persona });\n }\n\n return aliases;\n}\n\nfunction findCasingSuggestion(\n personas: readonly ResolvedPersona[],\n legacyAliases: readonly LegacyPersonaAlias[],\n input: string,\n): string | undefined {\n const lowered = input.toLowerCase();\n for (const persona of personas) {\n if (persona.codeError !== undefined) continue;\n if (persona.code.toLowerCase() === lowered) return persona.code;\n if (persona.name.toLowerCase() === lowered) return persona.name;\n }\n const legacyAlias = legacyAliases.find(alias => alias.code.toLowerCase() === lowered);\n if (legacyAlias) return legacyAlias.code;\n return undefined;\n}\n\n/**\n * Look up a persona reference against a parsed-and-resolved list.\n *\n * Strict on casing: `\"po\"` against existing `PO` returns\n * `{ status: 'unknown', suggestion: 'PO' }`. Lenient matching would\n * silently alias persona codes that legitimately differ by case\n * (`PO` vs `Po` vs `PO2`).\n *\n * Match priority: exact code → exact name → casing-mismatch suggestion.\n *\n * Pure — no I/O. Wrap with {@link validatePersonaReference} for the file-reading\n * path.\n */\nexport function lookupPersonaReference(\n personas: readonly ResolvedPersona[],\n input: string,\n): PersonaReferenceResult {\n if (input.length === 0) return { status: 'unknown' };\n\n for (const persona of personas) {\n if (persona.codeError !== undefined) continue;\n if (persona.code === input || persona.name === input) {\n return { status: 'valid', match: persona };\n }\n }\n\n const legacyAliases = resolveLegacyPersonaAliases(personas);\n const legacyMatch = legacyAliases.find(alias => alias.code === input);\n if (legacyMatch) return { status: 'valid', match: legacyMatch.persona };\n\n return { status: 'unknown', suggestion: findCasingSuggestion(personas, legacyAliases, input) };\n}\n\n/**\n * Resolve a persona reference against the on-disk personas file.\n *\n * Reads from `paths.personas` in `.safeword/config.json` when configured;\n * falls back to the namespace-root default otherwise. Degrades\n * gracefully on a missing or unreadable file — returns\n * `{ status: 'unknown' }` rather than throwing, regardless of whether the\n * resolved path is the default or a configured override. Strict\n * validation lives in `safeword doctor`; this lookup API is meant to be\n * cheap, consistent, and side-effect-free. Do NOT change the unknown\n * return to a throw for configured-but-missing — `safeword doctor` owns\n * the loud signal (ticket K7N2QM).\n */\nexport function validatePersonaReference(cwd: string, input: string): PersonaReferenceResult {\n let content: string;\n try {\n const filePath = resolveConfiguredPath(cwd, 'personas');\n content = readFileSync(filePath, 'utf8');\n } catch {\n return { status: 'unknown' };\n }\n const personas = resolvePersonaCodes(parsePersonas(content));\n return lookupPersonaReference(personas, input);\n}\n","const SYNCTICKETS_QUIET_COMMAND = '`safeword project sync-tickets --quiet`';\n\nexport function buildIndexConflictListMessage(paths: string[]): string {\n return (\n `Ticket index file(s) contained merge-conflict markers: ${paths.join(', ')}. ` +\n `Run ${SYNCTICKETS_QUIET_COMMAND} after resolving the merge conflict.`\n );\n}\n","import type { SafewordSchema } from '../schema.js';\nimport { codexFinalizationIsComplete } from './finalization.js';\n\nfunction withoutFinalizedCodexEntries<T>(\n values: Readonly<Record<string, T>>,\n retiredPaths: ReadonlySet<string>,\n): Record<string, T> {\n return Object.fromEntries(Object.entries(values).filter(([path]) => !retiredPaths.has(path)));\n}\n\n/** Keep explicit Codex finalization stable across later project reconciliation. */\nexport function schemaForCodexDelivery(cwd: string, schema: SafewordSchema): SafewordSchema {\n if (!codexFinalizationIsComplete(cwd)) return schema;\n const retiredPaths = new Set(schema.codexMigration.cleanupFiles);\n return {\n ...schema,\n deprecatedFiles: schema.deprecatedFiles.filter(path => !retiredPaths.has(path)),\n ownedFiles: withoutFinalizedCodexEntries(schema.ownedFiles, retiredPaths),\n managedFiles: withoutFinalizedCodexEntries(schema.managedFiles, retiredPaths),\n jsonMerges: withoutFinalizedCodexEntries(schema.jsonMerges, retiredPaths),\n textPatches: withoutFinalizedCodexEntries(schema.textPatches, retiredPaths),\n legacyTextPatches: withoutFinalizedCodexEntries(schema.legacyTextPatches, retiredPaths),\n contracts: withoutFinalizedCodexEntries(schema.contracts, retiredPaths),\n };\n}\n","import { schemaForClaudeDelivery } from '../claude-plugin/delivery-schema.js';\nimport { schemaForCodexDelivery } from '../codex-plugin/delivery-schema.js';\nimport { type SafewordSchema, schemaForProjectSurfaces } from '../schema.js';\n\nexport function projectLifecycleSchema(cwd: string, agents: readonly string[]): SafewordSchema {\n const deliverySchema = schemaForCodexDelivery(cwd, schemaForClaudeDelivery(cwd));\n return schemaForProjectSurfaces(deliverySchema, [\n 'core',\n ...(agents.includes('cursor') ? (['cursor'] as const) : []),\n ]);\n}\n","import { existsSync } from 'node:fs';\nimport nodePath from 'node:path';\n\nimport { type CliResult, createResult } from '../cli-protocol/result.js';\nimport { isCursorProjectPath, type SafewordSchema } from '../schema.js';\nimport { projectLifecycleSchema } from './schema.js';\n\n/**\n * Safeword-owned Cursor files declared by the schema. Cursor has no host\n * process to interrogate, so its project-local assets are the only surface\n * evidence available.\n */\nfunction cursorOwnedFiles(schema: SafewordSchema): readonly string[] {\n return [...Object.keys(schema.ownedFiles), ...Object.keys(schema.managedFiles)].filter(path =>\n isCursorProjectPath(path),\n );\n}\n\n/** True when this project already carries Safeword-owned Cursor assets. */\nexport function hasCursorProjectAssets(cwd: string, schema: SafewordSchema): boolean {\n return cursorOwnedFiles(schema).some(path => existsSync(nodePath.join(cwd, path)));\n}\n\n/**\n * Observe the Cursor surface from its own assets rather than mirroring the\n * project result, so a Cursor-only gap cannot be reported as healthy.\n */\nexport function observeCursorProject(cwd: string, schema: SafewordSchema): CliResult {\n const owned = cursorOwnedFiles(schema);\n const missing = owned.filter(path => !existsSync(nodePath.join(cwd, path)));\n if (missing.length === 0) {\n return createResult({\n state: 'healthy',\n data: {\n command: 'cursor status',\n coverage: 'project-owned Cursor assets',\n owned_files: owned.length,\n },\n });\n }\n return createResult({\n state: 'action_required',\n findings: [\n {\n code: 'CURSOR_ASSETS_MISSING',\n message: `${missing.length} Safeword-owned Cursor file(s) are missing; run \\`safeword install --agents=cursor\\`.`,\n severity: 'warning',\n },\n ],\n nextActions: [\n { command: 'safeword install --agents=cursor', mutates: true, requiresHuman: false },\n ],\n data: {\n command: 'cursor status',\n coverage: 'project-owned Cursor assets',\n owned_files: owned.length,\n missing_files: missing.length,\n },\n });\n}\n\n/**\n * Advise when a project carries Cursor assets that the current selection\n * excludes, so an upgrade cannot silently leave them at an older release.\n * Resolves the Cursor-inclusive schema itself — the selection's own schema has\n * every Cursor path filtered out and could never detect them.\n */\nexport function unselectedCursorFinding(\n cwd: string,\n agents: readonly string[],\n): CliResult['findings'] {\n if (agents.includes('cursor')) return [];\n if (!hasCursorProjectAssets(cwd, projectLifecycleSchema(cwd, ['cursor']))) return [];\n return [\n {\n code: 'CURSOR_NOT_SELECTED',\n message:\n 'This project has Safeword-owned Cursor assets that the current selection excludes; include `--agents=cursor` to keep them current.',\n severity: 'info',\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,eAAAA,oBAAmB;AAC5B,OAAOC,eAAc;;;ACRrB,SAAS,oBAAuB,QAA8C;AAC5E,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,MAAM,CAAC,KAAK,WAAW,UAAU,CAAC;AAAA,EACxE;AACF;AAGO,SAAS,wBAAwB,KAA6B;AACnE,QAAM,mBAAmB,0BAA0B,GAAG;AACtD,QAAM,mBAAmB,qBAAqB,GAAG,MAAM;AACv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