cleargate 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/MANIFEST.json +72 -16
  3. package/dist/admin-api/index.cjs +0 -1
  4. package/dist/admin-api/index.js +1 -2
  5. package/dist/auth/factory.cjs +0 -1
  6. package/dist/auth/factory.js +2 -3
  7. package/dist/auth/require-token.cjs +0 -1
  8. package/dist/auth/require-token.js +1 -2
  9. package/dist/auth/token-store.cjs +0 -1
  10. package/dist/auth/token-store.js +1 -2
  11. package/dist/{bootstrap-root-QKSA5V75.js → bootstrap-root-2H5HVTCC.js} +1 -2
  12. package/dist/{chunk-PDE37WFQ.js → chunk-A7MSQUU7.js} +2 -3
  13. package/dist/{chunk-BTSZOEWC.js → chunk-P6KEDAK2.js} +0 -1
  14. package/dist/{chunk-E3X7IE5E.js → chunk-PY6FHGV5.js} +1 -2
  15. package/dist/{chunk-5DI2Z3C2.js → chunk-Y53ZZYYU.js} +1 -2
  16. package/dist/cli.cjs +1564 -1414
  17. package/dist/cli.js +1514 -1364
  18. package/dist/lib/ledger.cjs +0 -1
  19. package/dist/lib/ledger.js +1 -2
  20. package/dist/lib/lifecycle-reconcile.cjs +0 -1
  21. package/dist/lib/lifecycle-reconcile.js +2 -3
  22. package/dist/{whoami-EANGN46Z.js → whoami-JKQQPABQ.js} +3 -4
  23. package/package.json +4 -3
  24. package/templates/cleargate-planning/.claude/agents/architect-synth.md +2 -0
  25. package/templates/cleargate-planning/.claude/agents/architect.md +4 -2
  26. package/templates/cleargate-planning/.claude/agents/developer.md +4 -11
  27. package/templates/cleargate-planning/.claude/agents/qa.md +14 -6
  28. package/templates/cleargate-planning/.claude/hooks/pending-task-sentinel.sh +2 -2
  29. package/templates/cleargate-planning/.claude/skills/sprint-execution/SKILL.md +19 -1
  30. package/templates/cleargate-planning/.cleargate/config.example.yml +16 -0
  31. package/templates/cleargate-planning/.cleargate/scripts/close_sprint.deferred-verify.red.node.test.ts +245 -0
  32. package/templates/cleargate-planning/.cleargate/scripts/close_sprint.mjs +227 -0
  33. package/templates/cleargate-planning/.cleargate/scripts/gate-checks.json +5 -4
  34. package/templates/cleargate-planning/.cleargate/scripts/init_sprint.mjs +75 -2
  35. package/templates/cleargate-planning/.cleargate/scripts/pre_gate_common.sh +48 -0
  36. package/templates/cleargate-planning/.cleargate/scripts/pre_gate_runner.sh +57 -1
  37. package/templates/cleargate-planning/.cleargate/scripts/provision_worktree_config.sh +155 -0
  38. package/templates/cleargate-planning/.cleargate/scripts/qa_red_lint.mjs +380 -0
  39. package/templates/cleargate-planning/.cleargate/scripts/run_script.sh +34 -1
  40. package/templates/cleargate-planning/.cleargate/scripts/test/cr077_eviction.red.sh +113 -0
  41. package/templates/cleargate-planning/.cleargate/scripts/test/cr078_init.test.sh +309 -0
  42. package/templates/cleargate-planning/.cleargate/scripts/test/cr079_provision.red.sh +262 -0
  43. package/templates/cleargate-planning/.cleargate/scripts/test/cr080_wrapper.test.sh +177 -0
  44. package/templates/cleargate-planning/.cleargate/scripts/test/cr081_qa_red_lint.red.sh +348 -0
  45. package/templates/cleargate-planning/.cleargate/sprint-runs/_off-sprint/.session-totals.json +1 -0
  46. package/templates/cleargate-planning/.cleargate/sprint-runs/_off-sprint/token-ledger.jsonl +222 -0
  47. package/templates/cleargate-planning/.cleargate/templates/sprint_context.md +17 -0
  48. package/templates/cleargate-planning/.cleargate/templates/story.md +1 -0
  49. package/templates/cleargate-planning/MANIFEST.json +72 -16
  50. package/dist/admin-api/index.cjs.map +0 -1
  51. package/dist/admin-api/index.js.map +0 -1
  52. package/dist/auth/factory.cjs.map +0 -1
  53. package/dist/auth/factory.js.map +0 -1
  54. package/dist/auth/require-token.cjs.map +0 -1
  55. package/dist/auth/require-token.js.map +0 -1
  56. package/dist/auth/token-store.cjs.map +0 -1
  57. package/dist/auth/token-store.js.map +0 -1
  58. package/dist/bootstrap-root-QKSA5V75.js.map +0 -1
  59. package/dist/chunk-5DI2Z3C2.js.map +0 -1
  60. package/dist/chunk-BTSZOEWC.js.map +0 -1
  61. package/dist/chunk-E3X7IE5E.js.map +0 -1
  62. package/dist/chunk-PDE37WFQ.js.map +0 -1
  63. package/dist/cli.cjs.map +0 -1
  64. package/dist/cli.js.map +0 -1
  65. package/dist/lib/ledger.cjs.map +0 -1
  66. package/dist/lib/ledger.js.map +0 -1
  67. package/dist/lib/lifecycle-reconcile.cjs.map +0 -1
  68. package/dist/lib/lifecycle-reconcile.js.map +0 -1
  69. package/dist/templates/cleargate-planning/.claude/agents/architect-reader.md +0 -61
  70. package/dist/templates/cleargate-planning/.claude/agents/architect-synth.md +0 -124
  71. package/dist/templates/cleargate-planning/.claude/agents/architect.md +0 -230
  72. package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-contradict.md +0 -108
  73. package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-ingest.md +0 -194
  74. package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-lint.md +0 -261
  75. package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-query.md +0 -143
  76. package/dist/templates/cleargate-planning/.claude/agents/developer.md +0 -185
  77. package/dist/templates/cleargate-planning/.claude/agents/devops.md +0 -257
  78. package/dist/templates/cleargate-planning/.claude/agents/qa.md +0 -171
  79. package/dist/templates/cleargate-planning/.claude/agents/reporter.md +0 -274
  80. package/dist/templates/cleargate-planning/.claude/hooks/pending-task-sentinel.sh +0 -209
  81. package/dist/templates/cleargate-planning/.claude/hooks/pre-commit-surface-gate.sh +0 -33
  82. package/dist/templates/cleargate-planning/.claude/hooks/pre-commit-test-ratchet.sh +0 -58
  83. package/dist/templates/cleargate-planning/.claude/hooks/pre-commit.sh +0 -19
  84. package/dist/templates/cleargate-planning/.claude/hooks/pre-edit-gate.sh +0 -162
  85. package/dist/templates/cleargate-planning/.claude/hooks/pre-tool-use-autonomy.sh +0 -58
  86. package/dist/templates/cleargate-planning/.claude/hooks/pre-tool-use-task.sh +0 -148
  87. package/dist/templates/cleargate-planning/.claude/hooks/session-start.sh +0 -75
  88. package/dist/templates/cleargate-planning/.claude/hooks/stamp-and-gate.sh +0 -43
  89. package/dist/templates/cleargate-planning/.claude/hooks/token-ledger.sh +0 -590
  90. package/dist/templates/cleargate-planning/.claude/settings.json +0 -68
  91. package/dist/templates/cleargate-planning/.claude/skills/flashcard/SKILL.md +0 -102
  92. package/dist/templates/cleargate-planning/.claude/skills/sprint-execution/SKILL.md +0 -742
  93. package/dist/templates/cleargate-planning/.cleargate/FLASHCARD.md +0 -7
  94. package/dist/templates/cleargate-planning/.cleargate/config.example.yml +0 -67
  95. package/dist/templates/cleargate-planning/.cleargate/config.yml +0 -18
  96. package/dist/templates/cleargate-planning/.cleargate/delivery/archive/.gitkeep +0 -0
  97. package/dist/templates/cleargate-planning/.cleargate/delivery/pending-sync/.gitkeep +0 -0
  98. package/dist/templates/cleargate-planning/.cleargate/knowledge/cleargate-enforcement.md +0 -551
  99. package/dist/templates/cleargate-planning/.cleargate/knowledge/cleargate-protocol.md +0 -878
  100. package/dist/templates/cleargate-planning/.cleargate/knowledge/mid-sprint-triage-rubric.md +0 -160
  101. package/dist/templates/cleargate-planning/.cleargate/knowledge/readiness-gates.md +0 -213
  102. package/dist/templates/cleargate-planning/.cleargate/knowledge/sprint-closeout-checklist.md +0 -71
  103. package/dist/templates/cleargate-planning/.cleargate/scripts/_migrate-schema-v3.mjs +0 -120
  104. package/dist/templates/cleargate-planning/.cleargate/scripts/assert_story_files.mjs +0 -265
  105. package/dist/templates/cleargate-planning/.cleargate/scripts/close_sprint.mjs +0 -1012
  106. package/dist/templates/cleargate-planning/.cleargate/scripts/collision_surface.sh +0 -114
  107. package/dist/templates/cleargate-planning/.cleargate/scripts/constants.mjs +0 -62
  108. package/dist/templates/cleargate-planning/.cleargate/scripts/dedupe_frontmatter.mjs +0 -219
  109. package/dist/templates/cleargate-planning/.cleargate/scripts/file_surface_diff.sh +0 -320
  110. package/dist/templates/cleargate-planning/.cleargate/scripts/gate-checks.json +0 -15
  111. package/dist/templates/cleargate-planning/.cleargate/scripts/init_gate_config.sh +0 -38
  112. package/dist/templates/cleargate-planning/.cleargate/scripts/init_sprint.mjs +0 -240
  113. package/dist/templates/cleargate-planning/.cleargate/scripts/launch_wave.mjs +0 -341
  114. package/dist/templates/cleargate-planning/.cleargate/scripts/lib/report-filename.mjs +0 -54
  115. package/dist/templates/cleargate-planning/.cleargate/scripts/pre_gate_common.sh +0 -206
  116. package/dist/templates/cleargate-planning/.cleargate/scripts/pre_gate_runner.sh +0 -371
  117. package/dist/templates/cleargate-planning/.cleargate/scripts/prefill_report.mjs +0 -280
  118. package/dist/templates/cleargate-planning/.cleargate/scripts/prep_doc_refresh.mjs +0 -378
  119. package/dist/templates/cleargate-planning/.cleargate/scripts/prep_qa_context.mjs +0 -888
  120. package/dist/templates/cleargate-planning/.cleargate/scripts/run_script.sh +0 -209
  121. package/dist/templates/cleargate-planning/.cleargate/scripts/sprint_trends.mjs +0 -71
  122. package/dist/templates/cleargate-planning/.cleargate/scripts/state.schema.json +0 -127
  123. package/dist/templates/cleargate-planning/.cleargate/scripts/suggest_improvements.mjs +0 -717
  124. package/dist/templates/cleargate-planning/.cleargate/scripts/surface-whitelist.txt +0 -27
  125. package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_assert_story_files.sh +0 -261
  126. package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_file_surface.sh +0 -210
  127. package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_flashcard_gate.sh +0 -190
  128. package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_prep_qa_context.sh +0 -482
  129. package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_test_ratchet.sh +0 -327
  130. package/dist/templates/cleargate-planning/.cleargate/scripts/test_ratchet.mjs +0 -261
  131. package/dist/templates/cleargate-planning/.cleargate/scripts/update_state.mjs +0 -246
  132. package/dist/templates/cleargate-planning/.cleargate/scripts/validate_bounce_readiness.mjs +0 -111
  133. package/dist/templates/cleargate-planning/.cleargate/scripts/validate_state.mjs +0 -184
  134. package/dist/templates/cleargate-planning/.cleargate/scripts/write_dispatch.sh +0 -172
  135. package/dist/templates/cleargate-planning/.cleargate/templates/Bug.md +0 -126
  136. package/dist/templates/cleargate-planning/.cleargate/templates/CR.md +0 -130
  137. package/dist/templates/cleargate-planning/.cleargate/templates/Sprint Plan Template.md +0 -137
  138. package/dist/templates/cleargate-planning/.cleargate/templates/epic.md +0 -166
  139. package/dist/templates/cleargate-planning/.cleargate/templates/hotfix.md +0 -111
  140. package/dist/templates/cleargate-planning/.cleargate/templates/initiative.md +0 -122
  141. package/dist/templates/cleargate-planning/.cleargate/templates/sprint_context.md +0 -50
  142. package/dist/templates/cleargate-planning/.cleargate/templates/sprint_report.md +0 -224
  143. package/dist/templates/cleargate-planning/.cleargate/templates/story.md +0 -213
  144. package/dist/templates/cleargate-planning/CLAUDE.md +0 -66
  145. package/dist/templates/cleargate-planning/MANIFEST.json +0 -503
  146. package/dist/templates/synthesis/active-sprint.md +0 -30
  147. package/dist/templates/synthesis/open-gates.md +0 -38
  148. package/dist/templates/synthesis/product-state.md +0 -31
  149. package/dist/templates/synthesis/roadmap.md +0 -63
  150. package/dist/whoami-EANGN46Z.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/lifecycle-reconcile.ts","../src/wiki/parse-frontmatter.ts","../src/lib/parent-rollup.ts"],"sourcesContent":["/**\n * lifecycle-reconcile.ts — CR-017 Lifecycle Status Reconciliation + Decomposition Gate\n *\n * Public API:\n * reconcileLifecycle(opts) → { drift: DriftItem[], clean: number }\n * reconcileDecomposition(opts) → { missing: MissingDecomp[], clean: number }\n * reconcileCurrentSprintStories(opts) → ReconcileCurrentSprintResult (BUG-032)\n * parseCommitMessage(msg) → Array<{ verb, id, type }>\n * VERB_STATUS_MAP — verb-to-expected-status table\n *\n * TERMINAL_STATES referenced from .cleargate/scripts/constants.mjs:45.\n * Do NOT redefine; duplicate literal with source citation.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { parseFrontmatter } from '../wiki/parse-frontmatter.js';\n\n// ─── Constants ─────────────────────────────────────────────────────────────────\n\n/**\n * Terminal statuses for artifact lifecycle (post-CR-067).\n * Source: .cleargate/scripts/constants.mjs:45 TERMINAL_STATES.\n * NOTE: These are the *artifact* terminal statuses, not state.json story states.\n *\n * CR-067 keep/remove decisions:\n * Completed — KEEP (sole canonical terminal post-CR-067 vocab unification)\n * Abandoned — KEEP (explicit non-completion terminal; needed for cleargate_id audit)\n * Closed — KEEP (issue-specific terminal; not subject to CR-067 vocab scope)\n * Resolved — KEEP (bug-specific terminal; not subject to CR-067 vocab scope)\n * Done — REMOVE (CR-067 unified vocab; all Done artifacts migrated to Completed)\n * Verified — REMOVE (CR-067 unified vocab; all Verified artifacts migrated to Completed)\n * Escalated — REMOVE (state.json story-state vocab, not artifact status; lives in TERMINAL_STATE_JSON)\n * Parking Lot — REMOVE (state.json story-state vocab, not artifact status; lives in TERMINAL_STATE_JSON)\n */\nexport const ARTIFACT_TERMINAL_STATUSES = new Set([\n 'Completed',\n 'Abandoned',\n 'Closed',\n 'Resolved',\n]);\n\n/**\n * Canonical single expected status for all artifact gate-checks (post-CR-067).\n * All per-verb expected[] arrays reference this constant.\n */\nconst ARTIFACT_GATE_EXPECTED = ['Completed'] as const;\n\n/**\n * Verb-to-expected-status map (v1).\n * Key: verb pattern (lower-case), Value: { types, expected }.\n * types: which artifact types this verb applies to.\n * expected: accepted terminal statuses for this verb.\n */\nexport const VERB_STATUS_MAP: Readonly<Record<string, { types: string[]; expected: string[] }>> = {\n feat: {\n types: ['STORY', 'EPIC', 'CR'],\n expected: [...ARTIFACT_GATE_EXPECTED],\n },\n fix: {\n types: ['BUG', 'HOTFIX'],\n expected: [...ARTIFACT_GATE_EXPECTED],\n },\n};\n\n// ─── Types ─────────────────────────────────────────────────────────────────────\n\nexport interface DriftItem {\n id: string;\n type: 'STORY' | 'CR' | 'BUG' | 'EPIC' | 'PROPOSAL' | 'HOTFIX';\n expected_status: string;\n actual_status: string | null;\n file_path: string | null;\n in_archive: boolean;\n commit_shas: string[];\n carry_over: boolean;\n}\n\nexport interface ReconcileLifecycleResult {\n drift: DriftItem[];\n clean: number;\n}\n\nexport interface ReconcileLifecycleOpts {\n since: Date;\n until?: Date;\n deliveryRoot: string;\n repoRoot: string;\n /** Test seam: replace spawnSync git calls */\n gitRunner?: (cmd: string, args: string[]) => string;\n}\n\nexport interface MissingDecomp {\n id: string;\n type: 'epic' | 'proposal';\n reason: 'no-child-stories' | 'no-decomposed-epic' | 'file-missing';\n expected_files: string[];\n}\n\nexport interface ReconcileDecompositionResult {\n missing: MissingDecomp[];\n clean: number;\n}\n\nexport interface ReconcileDecompositionOpts {\n sprintPlanPath: string;\n deliveryRoot: string;\n}\n\n// ─── ID shape regex (longest-alternative-first per BUG-010 + assert_story_files.mjs) ──\n\nconst ID_PATTERN = /\\b(STORY-\\d{3}-\\d{2}|(CR|BUG|EPIC|HOTFIX)-\\d{3}|(PROPOSAL|PROP)-\\d{3})\\b/g;\n\n/** Artifact type names recognized by the reconciler */\ntype ArtifactType = 'STORY' | 'CR' | 'BUG' | 'EPIC' | 'PROPOSAL' | 'HOTFIX';\n\nfunction normalizeId(raw: string): string {\n // PROP-NNN → PROPOSAL-NNN (BUG-009 lesson)\n return raw.replace(/^PROP-(\\d+)$/, 'PROPOSAL-$1');\n}\n\nfunction idType(id: string): ArtifactType | null {\n if (/^STORY-\\d{3}-\\d{2}$/.test(id)) return 'STORY';\n if (/^CR-\\d{3}$/.test(id)) return 'CR';\n if (/^BUG-\\d{3}$/.test(id)) return 'BUG';\n if (/^EPIC-\\d{3}$/.test(id)) return 'EPIC';\n if (/^PROPOSAL-\\d{3}$/.test(id)) return 'PROPOSAL';\n if (/^HOTFIX-\\d{3}$/.test(id)) return 'HOTFIX';\n return null;\n}\n\n// ─── parseCommitMessage ────────────────────────────────────────────────────────\n\n/**\n * Parse a commit message (subject + optional first body line) for work-item IDs.\n * Returns one entry per ID found with the verb inferred from conventional prefix.\n *\n * commit format: `<verb>(<scope>): <description>\\n\\n<body>`\n * multi-ID: `fix(cli)!: BUG-001 fix + CR-001 align`\n * merge: `merge: STORY-001-01 → main`\n */\nexport function parseCommitMessage(\n msg: string,\n): Array<{ verb: string; id: string; type: string }> {\n const lines = msg.split('\\n');\n const subject = lines[0] ?? '';\n\n // First non-empty body line (if any) after the blank separator\n let firstBodyLine = '';\n for (let i = 1; i < lines.length; i++) {\n if (lines[i]?.trim()) {\n firstBodyLine = lines[i]!;\n break;\n }\n }\n\n // Extract verb from subject: `feat(...)`, `fix(...)`, `merge:`, `chore(...)`, etc.\n const verbMatch = /^(\\w+)[(!]/.exec(subject) ?? /^(\\w+):/.exec(subject);\n const verb = verbMatch ? verbMatch[1]!.toLowerCase() : '';\n\n // Scan subject + first body line for IDs\n const searchText = subject + (firstBodyLine ? '\\n' + firstBodyLine : '');\n const results: Array<{ verb: string; id: string; type: string }> = [];\n const seen = new Set<string>();\n\n let m: RegExpExecArray | null;\n ID_PATTERN.lastIndex = 0;\n while ((m = ID_PATTERN.exec(searchText)) !== null) {\n const rawId = m[0]!;\n const id = normalizeId(rawId);\n if (seen.has(id)) continue;\n seen.add(id);\n const type = idType(id);\n if (!type) continue;\n results.push({ verb, id, type });\n }\n\n return results;\n}\n\n// ─── File finders ─────────────────────────────────────────────────────────────\n\ninterface FoundFile {\n absPath: string;\n inArchive: boolean;\n relPath: string; // relative to deliveryRoot\n}\n\nfunction findArtifactFile(deliveryRoot: string, id: string): FoundFile | null {\n const prefix = `${id}_`;\n const dirs: Array<{ rel: string; inArchive: boolean }> = [\n { rel: 'pending-sync', inArchive: false },\n { rel: 'archive', inArchive: true },\n ];\n for (const { rel, inArchive } of dirs) {\n const dir = path.join(deliveryRoot, rel);\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n continue;\n }\n // match `ID_*.md` OR `ID.md`\n const match = entries.find(\n (e) => (e.startsWith(prefix) || e === `${id}.md`) && e.endsWith('.md'),\n );\n if (match) {\n const absPath = path.join(dir, match);\n return { absPath, inArchive, relPath: `${rel}/${match}` };\n }\n }\n return null;\n}\n\nfunction readArtifactStatus(absPath: string): { status: string | null; carryOver: boolean } {\n let raw: string;\n try {\n raw = fs.readFileSync(absPath, 'utf8');\n } catch {\n return { status: null, carryOver: false };\n }\n try {\n const { fm } = parseFrontmatter(raw);\n const status = typeof fm['status'] === 'string' ? fm['status'] : null;\n const carryOver = fm['carry_over'] === true;\n return { status, carryOver };\n } catch {\n return { status: null, carryOver: false };\n }\n}\n\n// ─── reconcileLifecycle ────────────────────────────────────────────────────────\n\n/**\n * Scan git log in [since, until] range and reconcile artifact statuses.\n *\n * For each commit touching feat/fix verbs with IDs:\n * - Find the artifact file in pending-sync or archive\n * - Check if status is at expected terminal status\n * - Report drift items for non-terminal artifacts\n * - Skip artifacts with carry_over: true\n */\nexport function reconcileLifecycle(opts: ReconcileLifecycleOpts): ReconcileLifecycleResult {\n const { since, until = new Date(), deliveryRoot, repoRoot } = opts;\n\n const gitRunner =\n opts.gitRunner ??\n ((cmd: string, args: string[]) => {\n const result = spawnSync(cmd, args, { encoding: 'utf8', cwd: repoRoot });\n return (result.stdout ?? '') as string;\n });\n\n // git log --format=\"%H %s%n%b%n---COMMIT---\" --after=<since> --before=<until>\n const sinceIso = since.toISOString();\n const untilIso = until.toISOString();\n const logOutput = gitRunner('git', [\n 'log',\n `--after=${sinceIso}`,\n `--before=${untilIso}`,\n '--format=%H%x00%s%x00%b%x00---COMMIT---',\n '--',\n ]);\n\n // Map: id → DriftItem (accumulates SHAs for bundled-commit grouping)\n // We track each id independently; bundled-commit = multiple SHAs per id\n const idToItem = new Map<string, DriftItem>();\n // Track ids that were found CLEAN (fully reconciled)\n const cleanIds = new Set<string>();\n\n if (logOutput.trim()) {\n // Split by commit separator\n const rawCommits = logOutput.split('---COMMIT---\\n').filter((c) => c.trim());\n\n for (const raw of rawCommits) {\n // Each commit entry: sha\\0subject\\0body\\0\n const [sha = '', subject = '', body = ''] = raw.split('\\x00');\n const trimSha = sha.trim();\n const trimSubject = subject.trim();\n const trimBody = body.trim();\n\n if (!trimSha || !trimSubject) continue;\n\n const commitMsg = trimSubject + (trimBody ? '\\n\\n' + trimBody : '');\n const parsed = parseCommitMessage(commitMsg);\n\n for (const { verb, id, type } of parsed) {\n // Skip merge, chore, docs, refactor, test, file, plan verbs (no expectation)\n if (verb === 'merge' || verb === 'chore' || verb === 'docs' || verb === 'refactor'\n || verb === 'test' || verb === 'file' || verb === 'plan') {\n continue;\n }\n\n // Skip PROPOSAL types — proposals aren't shipped via feat/fix commits\n if (type === 'PROPOSAL') continue;\n\n const verbConfig = VERB_STATUS_MAP[verb];\n if (!verbConfig) continue;\n\n // Verb mismatch: feat(BUG-NNN) → soft warning only, handled at call site\n // We still need to find the file and check status for the call site to report\n\n // Find the artifact file\n const found = findArtifactFile(deliveryRoot, id);\n if (!found) {\n // Unknown ID — log once at info level (no drift)\n // We skip unknown IDs (no file found); call site logs info\n continue;\n }\n\n // Read status + carry_over from CURRENT frontmatter\n const { status, carryOver } = readArtifactStatus(found.absPath);\n\n // carry_over: true → skip silently\n if (carryOver) continue;\n\n // Determine expected statuses for this (verb, type) pair\n let expectedStatuses: string[];\n if (verb === 'feat' && type === 'BUG') {\n // verb mismatch — soft warning, does not block; still check status\n // Use Completed as expected for BUG even with feat verb (post-CR-067)\n expectedStatuses = [...ARTIFACT_GATE_EXPECTED];\n } else if (!verbConfig.types.includes(type)) {\n // Type not covered by this verb's map — skip\n continue;\n } else {\n expectedStatuses = verbConfig.expected;\n }\n\n const isTerminal = status !== null && expectedStatuses.includes(status);\n const isArchived = found.inArchive;\n\n if (isTerminal && isArchived) {\n // Clean\n cleanIds.add(id);\n // If we previously recorded drift for this id (from another commit), remove it\n // (Most recent status check wins — carry_over already handled above)\n idToItem.delete(id);\n } else if (!idToItem.has(id)) {\n // New drift item\n const expectedStr = expectedStatuses[0] ?? 'Completed';\n idToItem.set(id, {\n id,\n type: type as DriftItem['type'],\n expected_status: expectedStr,\n actual_status: status,\n file_path: found.relPath,\n in_archive: isArchived,\n commit_shas: [trimSha],\n carry_over: carryOver,\n });\n } else {\n // Existing drift item — add SHA if not already present\n const existing = idToItem.get(id)!;\n if (!existing.commit_shas.includes(trimSha)) {\n existing.commit_shas.push(trimSha);\n }\n }\n }\n }\n }\n\n // Remove from drift any IDs that ended up in cleanIds\n for (const id of cleanIds) {\n idToItem.delete(id);\n }\n\n const drift = Array.from(idToItem.values());\n return { drift, clean: cleanIds.size };\n}\n\n// ─── reconcileCrossSprintOrphans ──────────────────────────────────────────────\n\n/**\n * Orphan drift item: a file in pending-sync/ with a non-terminal status\n * that has been marked Done (or another terminal state) in a closed sprint's\n * state.json — indicating it was completed but never archived.\n */\nexport interface OrphanDriftItem {\n id: string;\n type: 'CR' | 'STORY' | 'BUG' | 'EPIC' | 'HOTFIX';\n pending_sync_status: string;\n state_json_state: string;\n state_json_sprint: string;\n file_path: string;\n}\n\nexport interface ReconcileOrphansOpts {\n /** Path to .cleargate/delivery */\n deliveryRoot: string;\n /** Path to .cleargate/sprint-runs */\n sprintRunsRoot: string;\n}\n\nexport interface ReconcileOrphansResult {\n drift: OrphanDriftItem[];\n clean: number;\n}\n\n/**\n * Detect cross-sprint orphan drift: items in pending-sync/ with status: Ready\n * (or any non-terminal status) that are recorded as Done in a closed sprint's\n * state.json. These were completed but never archived at sprint close.\n *\n * Active-sprint exclusion: reads .active sentinel to identify the current\n * sprint and skips that sprint's state.json (in-flight items are not orphans).\n *\n * Scope: only scans pending-sync/*.md files matching the work-item-ID pattern.\n * Does NOT scan .script-incidents/ or any subdirectory.\n */\nexport function reconcileCrossSprintOrphans(opts: ReconcileOrphansOpts): ReconcileOrphansResult {\n const { deliveryRoot, sprintRunsRoot } = opts;\n\n // Terminal states from state.json (story-level states, not artifact statuses)\n const TERMINAL_STATE_JSON = new Set(['Done', 'Escalated', 'Parking Lot']);\n\n // Read the active sprint sentinel (to exclude it from orphan detection)\n let activeSprintId: string | null = null;\n try {\n activeSprintId = fs.readFileSync(path.join(sprintRunsRoot, '.active'), 'utf8').trim();\n } catch {\n // No .active file — no active sprint; scan all sprints\n }\n\n // Collect all pending-sync *.md files (no subdirectory traversal)\n const pendingDir = path.join(deliveryRoot, 'pending-sync');\n let pendingFiles: string[];\n try {\n pendingFiles = fs.readdirSync(pendingDir).filter(\n (f) => f.endsWith('.md') && !f.startsWith('.'),\n );\n } catch {\n pendingFiles = [];\n }\n\n // Build a map: id → { status, filePath } for each pending-sync item\n interface PendingItem {\n status: string;\n filePath: string;\n type: OrphanDriftItem['type'];\n }\n const pendingMap = new Map<string, PendingItem>();\n\n for (const fileName of pendingFiles) {\n const absPath = path.join(pendingDir, fileName);\n const { status } = readArtifactStatus(absPath);\n if (status === null) continue;\n // Skip already-terminal items in pending-sync (shouldn't be there but be safe)\n if (ARTIFACT_TERMINAL_STATUSES.has(status)) continue;\n\n // Extract ID from filename: filenames use <ID>_<slug>.md or <ID>.md format.\n // ID_PATTERN uses \\b word-boundaries which don't fire between a digit and '_'\n // (since '_' is a word char), so we extract the prefix before the first '_' or '.'.\n const fileNameNoExt = fileName.endsWith('.md') ? fileName.slice(0, -3) : fileName;\n const prefixPart = fileNameNoExt.split('_')[0] ?? fileNameNoExt;\n const rawId = prefixPart;\n const id = normalizeId(rawId);\n const type = idType(id);\n if (!type || type === 'PROPOSAL') continue;\n\n pendingMap.set(id, {\n status,\n filePath: path.join('pending-sync', fileName),\n type: type as OrphanDriftItem['type'],\n });\n }\n\n if (pendingMap.size === 0) {\n return { drift: [], clean: 0 };\n }\n\n // Walk sprint-runs directories for state.json files\n let sprintDirs: string[];\n try {\n sprintDirs = fs.readdirSync(sprintRunsRoot).filter((entry) => {\n // Skip the .active sentinel file and any hidden files\n if (entry.startsWith('.')) return false;\n // Skip non-directories (e.g. files in root)\n try {\n return fs.statSync(path.join(sprintRunsRoot, entry)).isDirectory();\n } catch {\n return false;\n }\n });\n } catch {\n sprintDirs = [];\n }\n\n const drift: OrphanDriftItem[] = [];\n // Track which IDs we've flagged to avoid duplicates (first sprint that shows Done wins)\n const flagged = new Set<string>();\n let clean = 0;\n\n for (const sprintDir of sprintDirs) {\n // Skip the active sprint\n if (activeSprintId && sprintDir === activeSprintId) continue;\n\n const stateFile = path.join(sprintRunsRoot, sprintDir, 'state.json');\n let stateJson: Record<string, unknown>;\n try {\n const raw = fs.readFileSync(stateFile, 'utf8');\n stateJson = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n const stories = stateJson['stories'] as Record<string, { state: string }> | undefined;\n if (!stories || typeof stories !== 'object') continue;\n\n for (const [id, storyEntry] of Object.entries(stories)) {\n // Skip if already flagged from an earlier sprint\n if (flagged.has(id)) continue;\n\n const pending = pendingMap.get(id);\n if (!pending) continue; // not in pending-sync\n\n const stateInJson = storyEntry?.state ?? '';\n if (TERMINAL_STATE_JSON.has(stateInJson)) {\n // This item is Done in a closed sprint but still in pending-sync — orphan drift\n flagged.add(id);\n drift.push({\n id,\n type: pending.type,\n pending_sync_status: pending.status,\n state_json_state: stateInJson,\n state_json_sprint: sprintDir,\n file_path: pending.filePath,\n });\n } else {\n // Item is in pending-sync AND in state.json but NOT terminal — correctly in-flight\n clean++;\n }\n }\n }\n\n return { drift, clean };\n}\n\n// ─── reconcileDecomposition ───────────────────────────────────────────────────\n\n/**\n * Read the sprint plan's epics: and proposals: frontmatter arrays and verify\n * that each referenced epic has ≥1 child story file, and each proposal has\n * a decomposed epic.\n */\nexport function reconcileDecomposition(opts: ReconcileDecompositionOpts): ReconcileDecompositionResult {\n const { sprintPlanPath, deliveryRoot } = opts;\n\n // Parse sprint plan frontmatter\n let raw: string;\n try {\n raw = fs.readFileSync(sprintPlanPath, 'utf8');\n } catch {\n return { missing: [], clean: 0 };\n }\n\n let fm: Record<string, unknown>;\n try {\n ({ fm } = parseFrontmatter(raw));\n } catch {\n return { missing: [], clean: 0 };\n }\n\n const epics: string[] = Array.isArray(fm['epics']) ? fm['epics'].map(String) : [];\n const proposals: string[] = Array.isArray(fm['proposals']) ? fm['proposals'].map(String) : [];\n\n const pendingDir = path.join(deliveryRoot, 'pending-sync');\n const archiveDir = path.join(deliveryRoot, 'archive');\n\n // Read both dirs for all .md files\n function listMdFiles(dir: string): string[] {\n try {\n return fs.readdirSync(dir).filter((f) => f.endsWith('.md'));\n } catch {\n return [];\n }\n }\n const pendingFiles = listMdFiles(pendingDir);\n const archiveFiles = listMdFiles(archiveDir);\n const allFiles = [...pendingFiles, ...archiveFiles];\n\n const missing: MissingDecomp[] = [];\n let clean = 0;\n\n // Check epics\n for (const epicId of epics) {\n // Find the epic file\n const epicFile = allFiles.find(\n (f) => f.startsWith(`${epicId}_`) || f === `${epicId}.md`,\n );\n if (!epicFile) {\n missing.push({\n id: epicId,\n type: 'epic',\n reason: 'file-missing',\n expected_files: [`pending-sync/${epicId}_<name>.md`],\n });\n continue;\n }\n\n // Find child stories: any STORY-*.md with parent_epic_ref: epicId\n const childStories = findChildStories(\n epicId,\n pendingDir,\n pendingFiles,\n archiveDir,\n archiveFiles,\n );\n\n if (childStories.length === 0) {\n missing.push({\n id: epicId,\n type: 'epic',\n reason: 'no-child-stories',\n expected_files: [\n `pending-sync/${epicId.replace('EPIC-', 'STORY-')}-01_<name>.md`,\n ],\n });\n } else {\n clean++;\n }\n }\n\n // Check proposals\n for (const proposalId of proposals) {\n // Find a decomposed epic that cites this proposal in context_source\n const decomposedEpic = findDecomposedEpic(\n proposalId,\n pendingDir,\n pendingFiles,\n );\n if (!decomposedEpic) {\n missing.push({\n id: proposalId,\n type: 'proposal',\n reason: 'no-decomposed-epic',\n expected_files: [`pending-sync/EPIC-<NNN>_<name>.md with context_source citing ${proposalId}`],\n });\n } else {\n clean++;\n }\n }\n\n return { missing, clean };\n}\n\n/**\n * Find story files in pending-sync or archive that have parent_epic_ref: epicId.\n */\nfunction findChildStories(\n epicId: string,\n pendingDir: string,\n pendingFiles: string[],\n archiveDir: string,\n archiveFiles: string[],\n): string[] {\n const results: string[] = [];\n const epicNumMatch = /^EPIC-(\\d+)$/.exec(epicId);\n if (!epicNumMatch) return results;\n const epicNum = epicNumMatch[1]!;\n\n const storyPrefix = `STORY-${epicNum}-`;\n\n for (const [files, dir] of [[pendingFiles, pendingDir], [archiveFiles, archiveDir]] as const) {\n for (const f of files) {\n if (!f.startsWith(storyPrefix) && !f.startsWith('STORY-')) continue;\n // Quick filename match first\n if (!f.includes(storyPrefix)) continue;\n const absPath = path.join(dir, f);\n try {\n const raw = fs.readFileSync(absPath, 'utf8');\n const { fm } = parseFrontmatter(raw);\n const parentRef = fm['parent_epic_ref'];\n if (parentRef === epicId) {\n results.push(f);\n }\n } catch {\n // skip malformed files\n }\n }\n }\n return results;\n}\n\n/**\n * Find an epic file in pending-sync whose context_source cites proposalId.\n */\nfunction findDecomposedEpic(\n proposalId: string,\n pendingDir: string,\n pendingFiles: string[],\n): string | null {\n for (const f of pendingFiles) {\n if (!f.startsWith('EPIC-')) continue;\n const absPath = path.join(pendingDir, f);\n try {\n const raw = fs.readFileSync(absPath, 'utf8');\n const { fm } = parseFrontmatter(raw);\n const contextSource = fm['context_source'];\n if (\n typeof contextSource === 'string' &&\n contextSource.includes(proposalId)\n ) {\n return f;\n }\n } catch {\n // skip\n }\n }\n return null;\n}\n\n// ─── Verb mismatch checker (exported for test use) ────────────────────────────\n\n/**\n * Check if a (verb, type) combination is a mismatch (soft warning only in v1).\n * Returns a warning message or null if no mismatch.\n */\nexport function checkVerbMismatch(verb: string, type: string): string | null {\n if (verb === 'feat' && type === 'BUG') {\n return `verb 'feat' unusual for BUG; expected 'fix'`;\n }\n if (verb === 'fix' && (type === 'STORY' || type === 'EPIC' || type === 'CR')) {\n return `verb 'fix' unusual for ${type}; expected 'feat'`;\n }\n return null;\n}\n\n// ─── reconcileCurrentSprintStories (BUG-032) ─────────────────────────────────\n\n/**\n * Result item for a story processed by reconcileCurrentSprintStories.\n */\nexport interface CurrentSprintStoryFlip {\n id: string;\n type: OrphanDriftItem['type'];\n old_status: string;\n new_status: 'Completed';\n file_path: string;\n archived: boolean;\n}\n\nexport interface ReconcileCurrentSprintResult {\n flipped: CurrentSprintStoryFlip[];\n skipped_already_terminal: number;\n skipped_not_done: number;\n}\n\nexport interface ReconcileCurrentSprintOpts {\n /** Path to .cleargate/delivery */\n deliveryRoot: string;\n /** Path to .cleargate/sprint-runs */\n sprintRunsRoot: string;\n /** The sprint ID being closed (e.g. \"SPRINT-30\") */\n sprintId: string;\n /**\n * When true: scan ALL closed sprints (sprint_status: Completed) and flip\n * any Done stories whose frontmatter is still non-terminal.\n * Used by `cleargate sprint reconcile-lifecycle --retroactive`.\n */\n retroactive?: boolean;\n}\n\n/**\n * Atomic in-place frontmatter field rewrite (raw-bytes regex-replace).\n * Follows FLASHCARD 2026-04-24 #frontmatter #write-back pattern.\n * Rewrites a single YAML field in the --- block, preserving all other content.\n *\n * @param filePath - absolute path to the markdown file\n * @param field - YAML key name (e.g. 'status', 'approved')\n * @param rawValue - raw YAML value string (e.g. '\"Completed\"', 'true')\n */\nfunction setFrontmatterFieldAtomic(filePath: string, field: string, rawValue: string): void {\n const raw = fs.readFileSync(filePath, 'utf8');\n const fm = raw.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!fm) throw new Error(`No frontmatter in ${filePath}`);\n let newFm = fm[1];\n const fieldRx = new RegExp(`^${field}:.*$`, 'm');\n if (fieldRx.test(newFm)) {\n newFm = newFm.replace(fieldRx, `${field}: ${rawValue}`);\n } else {\n // Field not present — append it to the frontmatter block\n newFm = newFm.trimEnd() + `\\n${field}: ${rawValue}`;\n }\n const newRaw = raw.replace(fm[1], newFm);\n const tmp = filePath + '.tmp.' + process.pid;\n fs.writeFileSync(tmp, newRaw, 'utf8');\n fs.renameSync(tmp, filePath);\n}\n\n/**\n * Flip all Done-state stories in the closing sprint from their current frontmatter\n * status to `status: Completed, approved: true`, then move the file from\n * pending-sync/ to archive/.\n *\n * Root cause addressed (BUG-032): `reconcileCrossSprintOrphans` explicitly skips\n * the active sprint via the `.active` sentinel. No existing step flips same-sprint\n * story frontmatter at close time. This function fills that gap.\n *\n * Idempotence: stories already at a terminal status (Completed, Abandoned, etc.)\n * are skipped silently. Running this function twice produces the same result.\n *\n * When `retroactive: true`: scans ALL sprint-runs directories (not just the\n * provided sprintId) and flips any stories in Done-state sprints whose frontmatter\n * is still non-terminal. Used by `cleargate sprint reconcile-lifecycle --retroactive`.\n *\n * Implementation note: iterates over state.json story IDs and uses `findArtifactFile`\n * to locate the pending-sync file. This handles both standard `STORY-\\d{3}-\\d{2}`\n * and non-standard (test fixture) IDs like `STORY-TEST-01` correctly.\n */\nexport function reconcileCurrentSprintStories(\n opts: ReconcileCurrentSprintOpts,\n): ReconcileCurrentSprintResult {\n const { deliveryRoot, sprintRunsRoot, sprintId, retroactive = false } = opts;\n\n const TERMINAL_STATE_JSON = new Set(['Done', 'Escalated', 'Parking Lot']);\n const archiveDir = path.join(deliveryRoot, 'archive');\n\n // Determine which sprint dirs to scan\n let sprintDirsToScan: string[];\n if (retroactive) {\n // Retroactive: scan ALL sprint-runs dirs that are Completed\n try {\n sprintDirsToScan = fs.readdirSync(sprintRunsRoot).filter((entry) => {\n if (entry.startsWith('.')) return false;\n try {\n return fs.statSync(path.join(sprintRunsRoot, entry)).isDirectory();\n } catch {\n return false;\n }\n });\n } catch {\n sprintDirsToScan = [];\n }\n // Filter to Completed sprints only\n sprintDirsToScan = sprintDirsToScan.filter((dir) => {\n const stateFile = path.join(sprintRunsRoot, dir, 'state.json');\n try {\n const raw = fs.readFileSync(stateFile, 'utf8');\n const s = JSON.parse(raw) as Record<string, unknown>;\n return s['sprint_status'] === 'Completed';\n } catch {\n return false;\n }\n });\n } else {\n // Normal close: scan only the current sprint\n sprintDirsToScan = [sprintId];\n }\n\n const flipped: CurrentSprintStoryFlip[] = [];\n let skipped_already_terminal = 0;\n let skipped_not_done = 0;\n const flippedIds = new Set<string>();\n\n for (const dir of sprintDirsToScan) {\n const stateFile = path.join(sprintRunsRoot, dir, 'state.json');\n let stateJson: Record<string, unknown>;\n try {\n const raw = fs.readFileSync(stateFile, 'utf8');\n stateJson = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n const stories = stateJson['stories'] as Record<string, { state: string }> | undefined;\n if (!stories || typeof stories !== 'object') continue;\n\n for (const [storyId, storyEntry] of Object.entries(stories)) {\n if (flippedIds.has(storyId)) continue; // already handled by an earlier sprint dir\n\n const stateInJson = storyEntry?.state ?? '';\n if (!TERMINAL_STATE_JSON.has(stateInJson)) {\n skipped_not_done++;\n continue;\n }\n\n // State is Done (or other terminal) in state.json — find the pending-sync file\n // Use findArtifactFile which handles ID_*.md and ID.md patterns for any ID format\n const found = findArtifactFile(deliveryRoot, storyId);\n if (!found) continue; // file not in pending-sync or archive — nothing to flip\n\n // Skip if file is already in archive (idempotence guard — already flipped)\n if (found.inArchive) {\n // Read status to check if it's already terminal\n const { status } = readArtifactStatus(found.absPath);\n if (status !== null && ARTIFACT_TERMINAL_STATUSES.has(status)) {\n skipped_already_terminal++;\n }\n // Either way, skip — already archived\n continue;\n }\n\n // File is in pending-sync — read current status\n const { status: currentStatus } = readArtifactStatus(found.absPath);\n if (currentStatus !== null && ARTIFACT_TERMINAL_STATUSES.has(currentStatus)) {\n // Already terminal in pending-sync (unusual but safe to skip)\n skipped_already_terminal++;\n continue;\n }\n\n // Compute destination path in archive/\n const fileName = path.basename(found.absPath);\n const destPath = path.join(archiveDir, fileName);\n const srcPath = found.absPath;\n\n // 1. Set status: \"Completed\" in frontmatter (Done state is authoritative)\n setFrontmatterFieldAtomic(srcPath, 'status', '\"Completed\"');\n // 2. Set approved: true in frontmatter\n setFrontmatterFieldAtomic(srcPath, 'approved', 'true');\n // 3. Move file from pending-sync/ to archive/\n fs.mkdirSync(archiveDir, { recursive: true });\n\n // Idempotence: if file already in archive, do not double-move\n if (!fs.existsSync(destPath)) {\n fs.renameSync(srcPath, destPath);\n } else {\n // Archive already has this file — remove the pending-sync copy\n fs.rmSync(srcPath, { force: true });\n }\n\n flippedIds.add(storyId);\n flipped.push({\n id: storyId,\n type: (idType(storyId) ?? 'STORY') as OrphanDriftItem['type'],\n old_status: currentStatus ?? 'unknown',\n new_status: 'Completed',\n file_path: path.join('archive', fileName),\n archived: true,\n });\n }\n }\n\n return { flipped, skipped_already_terminal, skipped_not_done };\n}\n\n// ─── Parent rollup re-exports (STORY-066-01) ──────────────────────────────────\n\nexport { rollUpParentStatus, walkActiveParents, type RollupResult } from './parent-rollup.js';\n","/**\n * YAML frontmatter parser backed by js-yaml with CORE_SCHEMA (YAML 1.2 core).\n *\n * Parses `---\\n<yaml>\\n---\\n<body>` into a typed frontmatter map + body string.\n * Preserves native types (null, boolean, number, string), nested maps, and\n * arrays. Uses CORE_SCHEMA so ISO-8601 timestamp strings are NOT coerced to\n * Date objects (YAML 1.1's quirk).\n *\n * Historical note: an earlier hand-rolled parser flattened indented nested\n * maps into top-level keys and stringified null/boolean scalars. See\n * BUG-001 and FLASHCARD entry `#yaml #frontmatter`.\n */\n\nimport yaml from 'js-yaml';\n\nexport function parseFrontmatter(raw: string): { fm: Record<string, unknown>; body: string } {\n const lines = raw.split('\\n');\n if (lines[0] !== '---') {\n throw new Error('parseFrontmatter: input does not start with ---');\n }\n let closeIdx = -1;\n for (let i = 1; i < lines.length; i++) {\n if (lines[i] === '---') { closeIdx = i; break; }\n }\n if (closeIdx === -1) {\n throw new Error('parseFrontmatter: missing closing ---');\n }\n\n const yamlText = lines.slice(1, closeIdx).join('\\n');\n const bodyLines = lines.slice(closeIdx + 1);\n // strip one leading blank line if present\n if (bodyLines[0] === '') bodyLines.shift();\n const body = bodyLines.join('\\n');\n\n if (yamlText.trim() === '') {\n return { fm: {}, body };\n }\n\n let parsed: unknown;\n try {\n parsed = yaml.load(yamlText, { schema: yaml.CORE_SCHEMA });\n } catch (err) {\n throw new Error(`parseFrontmatter: invalid YAML: ${(err as Error).message}`);\n }\n\n if (parsed === null || parsed === undefined) {\n return { fm: {}, body };\n }\n if (typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('parseFrontmatter: frontmatter is not a YAML mapping');\n }\n\n return { fm: parsed as Record<string, unknown>, body };\n}\n","/**\n * parent-rollup.ts — CR-066 parent status rollup library\n *\n * Pure library: no I/O side-effects beyond reading frontmatter from disk.\n * Writing flips is the responsibility of the caller (STORY-066-02).\n *\n * Public API:\n * rollUpParentStatus(parentFilePath, opts) → Promise<RollupResult>\n * walkActiveParents(opts) → Promise<RollupResult[]>\n * RollupResult (interface)\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { parseFrontmatter } from '../wiki/parse-frontmatter.js';\nimport { ARTIFACT_TERMINAL_STATUSES } from './lifecycle-reconcile.js';\n\n// ─── Types ─────────────────────────────────────────────────────────────────────\n\nexport interface RollupResult {\n parent_id: string;\n parent_path: string;\n current_status: string;\n proposed_status: 'Completed' | null;\n coverage: 'full' | 'partial' | 'zero' | 'sub-epic-partial';\n terminal_children: string[];\n pending_children: string[];\n verdict: 'auto-flip' | 'halt-partial' | 'halt-zero-children' | 'skip-deferred' | 'no-op';\n halt_reason?: string;\n}\n\nexport interface WalkActiveParentsOpts {\n deliveryRoot: string;\n archiveRoot: string;\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Safely parse frontmatter from a file path.\n * Returns null on any read or parse error.\n */\nfunction readFm(filePath: string): Record<string, unknown> | null {\n try {\n const raw = fs.readFileSync(filePath, 'utf8');\n const { fm } = parseFrontmatter(raw);\n return fm;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract the canonical ID from frontmatter, checking all known ID-key conventions\n * in priority order before falling back to the filename stem.\n *\n * Key priority order mirrors template conventions:\n * story_id (story.md) → epic_id (epic.md) → sprint_id (Sprint Plan Template.md)\n * → bug_id (Bug.md) → cr_id (CR.md) → initiative_id (initiative.md)\n * → hotfix_id (hotfix.md)\n *\n * Filename stem fallback: takes the first underscore-delimited segment so that\n * files named \"EPIC-010_Multi_Participant_MCP_Sync.md\" resolve to \"EPIC-010\".\n */\nfunction extractId(fm: Record<string, unknown>, filePath: string): string {\n for (const key of [\n 'story_id',\n 'epic_id',\n 'sprint_id',\n 'bug_id',\n 'cr_id',\n 'initiative_id',\n 'hotfix_id',\n ]) {\n const val = fm[key];\n if (typeof val === 'string' && val.trim() !== '') return val.trim();\n }\n // Fallback: parse from filename stem (first underscore-delimited segment)\n const stem = path.basename(filePath, '.md');\n return stem.split('_')[0] ?? stem;\n}\n\n/**\n * Enumerate all children of a parent across both archive and pending-sync.\n * Children are identified by `parent_cleargate_id` OR `parent_epic_ref` frontmatter\n * matching the parentId.\n *\n * Caching is done via the fmCache map (keyed by absolute path) to avoid\n * re-reading files during recursive sub-epic walks.\n */\nfunction enumerateChildren(\n parentId: string,\n deliveryRoot: string,\n archiveRoot: string,\n fmCache: Map<string, Record<string, unknown>>\n): { id: string; status: string }[] {\n const pendingSyncDir = path.join(deliveryRoot, 'pending-sync');\n const results: { id: string; status: string }[] = [];\n\n const pools: string[] = [];\n if (fs.existsSync(archiveRoot)) pools.push(archiveRoot);\n if (fs.existsSync(pendingSyncDir)) pools.push(pendingSyncDir);\n\n for (const dir of pools) {\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n entries = [];\n }\n\n for (const entry of entries) {\n if (!entry.endsWith('.md')) continue;\n const absPath = path.join(dir, entry);\n\n let fm = fmCache.get(absPath);\n if (fm === undefined) {\n const parsed = readFm(absPath);\n if (parsed === null) continue;\n fm = parsed;\n fmCache.set(absPath, fm);\n }\n\n // Match by parent_cleargate_id or parent_epic_ref\n const parentCleargateId = fm['parent_cleargate_id'];\n const parentEpicRef = fm['parent_epic_ref'];\n\n const isChild =\n (typeof parentCleargateId === 'string' && parentCleargateId.trim() === parentId) ||\n (typeof parentEpicRef === 'string' && parentEpicRef.trim() === parentId);\n\n if (!isChild) continue;\n\n const childId = extractId(fm, absPath);\n const status = typeof fm['status'] === 'string' ? fm['status'].trim() : '';\n results.push({ id: childId, status });\n }\n }\n\n return results;\n}\n\n// ─── Core rollup logic ────────────────────────────────────────────────────────\n\n/**\n * Internal implementation with cycle-detection via visited set.\n */\nasync function rollUpParentStatusInternal(\n parentFilePath: string,\n opts: WalkActiveParentsOpts,\n visited: Set<string>,\n fmCache: Map<string, Record<string, unknown>>\n): Promise<RollupResult> {\n const { deliveryRoot, archiveRoot } = opts;\n\n // Read parent frontmatter\n let fm = fmCache.get(parentFilePath);\n if (fm === undefined) {\n const raw = readFm(parentFilePath);\n if (raw === null) {\n throw new Error(`parent-rollup: cannot read frontmatter from ${parentFilePath}`);\n }\n fm = raw;\n fmCache.set(parentFilePath, fm);\n }\n\n const parentId = extractId(fm, parentFilePath);\n const currentStatus = typeof fm['status'] === 'string' ? fm['status'].trim() : '';\n\n // Short-circuit: already terminal\n if (ARTIFACT_TERMINAL_STATUSES.has(currentStatus)) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'full',\n terminal_children: [],\n pending_children: [],\n verdict: 'no-op',\n };\n }\n\n // Cycle detection (before recursing into sub_epics)\n if (visited.has(parentId)) {\n throw new Error(`parent-rollup: sub_epics cycle detected at ${parentId}`);\n }\n visited.add(parentId);\n\n // Sub-epic recursion path\n const subEpicsField = fm['sub_epics'];\n const subEpics: string[] =\n Array.isArray(subEpicsField) && subEpicsField.length > 0\n ? (subEpicsField as unknown[]).filter((s): s is string => typeof s === 'string')\n : [];\n\n if (subEpics.length > 0) {\n // Recurse into sub-epics\n const pendingSyncDir = path.join(deliveryRoot, 'pending-sync');\n\n const terminalSubEpics: string[] = [];\n const pendingSubEpics: string[] = [];\n\n for (const subEpicId of subEpics) {\n // Locate the sub-epic file — search pending-sync and archive\n let subEpicPath: string | null = null;\n const candidateDirs = [pendingSyncDir, archiveRoot];\n for (const dir of candidateDirs) {\n if (!fs.existsSync(dir)) continue;\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n entries = [];\n }\n for (const entry of entries) {\n if (!entry.endsWith('.md')) continue;\n const absPath = path.join(dir, entry);\n let subFm = fmCache.get(absPath);\n if (subFm === undefined) {\n const parsed = readFm(absPath);\n if (parsed === null) continue;\n subFm = parsed;\n fmCache.set(absPath, subFm);\n }\n const entryId = extractId(subFm, absPath);\n if (entryId === subEpicId) {\n subEpicPath = absPath;\n break;\n }\n }\n if (subEpicPath !== null) break;\n }\n\n if (subEpicPath === null) {\n // Sub-epic file not found; treat as pending\n pendingSubEpics.push(subEpicId);\n continue;\n }\n\n // Read sub-epic frontmatter to check for DEFERRED\n let subFm = fmCache.get(subEpicPath);\n if (subFm === undefined) {\n const parsed = readFm(subEpicPath);\n if (parsed === null) {\n pendingSubEpics.push(subEpicId);\n continue;\n }\n subFm = parsed;\n fmCache.set(subEpicPath, subFm);\n }\n\n const subStatus = typeof subFm['status'] === 'string' ? subFm['status'].trim() : '';\n\n // Exclude DEFERRED sub-epics from denominator entirely\n if (subStatus === 'DEFERRED') {\n continue;\n }\n\n // Already terminal (e.g. Completed) counts as done — no further recursion needed\n if (ARTIFACT_TERMINAL_STATUSES.has(subStatus)) {\n terminalSubEpics.push(subEpicId);\n continue;\n }\n\n // Recurse: make a snapshot of visited before entering sub-epic, restore after\n // (so sibling sub-epics don't block each other)\n const visitedSnapshot = new Set(visited);\n const subResult = await rollUpParentStatusInternal(\n subEpicPath,\n opts,\n visitedSnapshot,\n fmCache\n );\n\n if (subResult.verdict === 'auto-flip' || subResult.verdict === 'no-op') {\n terminalSubEpics.push(subEpicId);\n } else {\n pendingSubEpics.push(subEpicId);\n }\n }\n\n // Remove parentId from visited since we're returning up the stack\n visited.delete(parentId);\n\n const total = terminalSubEpics.length + pendingSubEpics.length;\n\n if (total === 0) {\n // All sub-epics were DEFERRED (excluded) or none exist — treat as zero-children\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'zero',\n terminal_children: [],\n pending_children: [],\n verdict: 'halt-zero-children',\n halt_reason: `${parentId}: 0 children drafted; not reconcilable — decompose or abandon`,\n };\n }\n\n if (pendingSubEpics.length === 0) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: 'Completed',\n coverage: 'full',\n terminal_children: terminalSubEpics,\n pending_children: [],\n verdict: 'auto-flip',\n };\n }\n\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'sub-epic-partial',\n terminal_children: terminalSubEpics,\n pending_children: pendingSubEpics,\n verdict: 'halt-partial',\n halt_reason: `${parentId}: ${terminalSubEpics.length}/${total} sub-epics terminal — pending: ${pendingSubEpics.join(', ')}`,\n };\n }\n\n // Leaf-epic / sprint: enumerate children from archive + pending-sync\n const children = enumerateChildren(parentId, deliveryRoot, archiveRoot, fmCache);\n\n visited.delete(parentId);\n\n if (children.length === 0) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'zero',\n terminal_children: [],\n pending_children: [],\n verdict: 'halt-zero-children',\n halt_reason: `${parentId}: 0 children drafted; not reconcilable — decompose or abandon`,\n };\n }\n\n const terminalChildren: string[] = [];\n const pendingChildren: string[] = [];\n\n for (const child of children) {\n if (ARTIFACT_TERMINAL_STATUSES.has(child.status)) {\n terminalChildren.push(child.id);\n } else {\n pendingChildren.push(child.id);\n }\n }\n\n const total = terminalChildren.length + pendingChildren.length;\n\n if (pendingChildren.length === 0) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: 'Completed',\n coverage: 'full',\n terminal_children: terminalChildren,\n pending_children: [],\n verdict: 'auto-flip',\n };\n }\n\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'partial',\n terminal_children: terminalChildren,\n pending_children: pendingChildren,\n verdict: 'halt-partial',\n halt_reason: `${parentId}: ${terminalChildren.length}/${total} children terminal — pending: ${pendingChildren.join(', ')}`,\n };\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Roll up the status of a single parent (Epic or Sprint).\n *\n * @param parentFilePath — absolute path to the parent .md file\n * @param opts — deliveryRoot: root of the delivery tree; archiveRoot: absolute path to archive/\n * @returns RollupResult with verdict, coverage, and child lists\n */\nexport async function rollUpParentStatus(\n parentFilePath: string,\n opts: WalkActiveParentsOpts\n): Promise<RollupResult> {\n const visited = new Set<string>();\n const fmCache = new Map<string, Record<string, unknown>>();\n return rollUpParentStatusInternal(parentFilePath, opts, visited, fmCache);\n}\n\n/**\n * Walk all active parents (EPIC-*.md + SPRINT-*.md) in deliveryRoot/pending-sync/\n * and return one RollupResult per parent.\n *\n * Already-terminal parents (status: Completed/Done/etc.) emit verdict: 'no-op'.\n */\nexport async function walkActiveParents(\n opts: WalkActiveParentsOpts\n): Promise<RollupResult[]> {\n const { deliveryRoot } = opts;\n const pendingSyncDir = path.join(deliveryRoot, 'pending-sync');\n\n let entries: string[];\n try {\n entries = fs.readdirSync(pendingSyncDir);\n } catch {\n return [];\n }\n\n const parentFiles = entries.filter(\n (e) =>\n e.endsWith('.md') &&\n (e.startsWith('EPIC-') || e.startsWith('SPRINT-'))\n );\n\n const results: RollupResult[] = [];\n const fmCache = new Map<string, Record<string, unknown>>();\n\n for (const entry of parentFiles) {\n const absPath = path.join(pendingSyncDir, entry);\n try {\n const visited = new Set<string>();\n const result = await rollUpParentStatusInternal(absPath, opts, visited, fmCache);\n results.push(result);\n } catch (err) {\n // Propagate cycle errors; skip unreadable files\n if (err instanceof Error && err.message.includes('sub_epics cycle detected')) {\n throw err;\n }\n // Other errors (e.g. unreadable) — skip silently\n }\n }\n\n return results;\n}\n"],"mappings":";;;;;;;;AAAA;AAcA,YAAYA,SAAQ;AACpB,YAAYC,WAAU;AACt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MACF;AAGA,YAAM,WAAgB,eAAS,MAAM,OAAO;AAC5C,YAAM,WAAgB,WAAK,YAAY,QAAQ;AAC/C,YAAM,UAAU,MAAM;AAGtB,gCAA0B,SAAS,UAAU,aAAa;AAE1D,gCAA0B,SAAS,YAAY,MAAM;AAErD,MAAG,cAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAG5C,UAAI,CAAI,eAAW,QAAQ,GAAG;AAC5B,QAAG,eAAW,SAAS,QAAQ;AAAA,MACjC,OAAO;AAEL,QAAG,WAAO,SAAS,EAAE,OAAO,KAAK,CAAC;AAAA,MACpC;AAEA,iBAAW,IAAI,OAAO;AACtB,cAAQ,KAAK;AAAA,QACX,IAAI;AAAA,QACJ,MAAO,OAAO,OAAO,KAAK;AAAA,QAC1B,YAAY,iBAAiB;AAAA,QAC7B,YAAY;AAAA,QACZ,WAAgB,WAAK,WAAW,QAAQ;AAAA,QACxC,UAAU;AAAA,MACZ,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,0BAA0B,iBAAiB;AAC/D;","names":["fs","path","subFm","total"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B,IAIM,aACA,YAEO,WACA;AARb;AAAA;AAAA;AAIA,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AACvD,IAAM,aAAa,MAAM,KAAK,QAAQ,YAAY,CAAC;AAE5C,IAAM,YAA4B,2BAAW;AAC7C,IAAM,aAA6B,4BAAY;AAAA;AAAA;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/auth/factory.ts","../src/auth/keychain-store.ts","../src/auth/file-store.ts"],"sourcesContent":["import * as os from 'node:os';\nimport * as path from 'node:path';\nimport { KeychainTokenStore } from './keychain-store.js';\nimport { FileTokenStore } from './file-store.js';\nimport type { TokenStore, TokenStoreFactoryOptions } from './token-store.js';\n\nconst DEFAULT_KEYCHAIN_SERVICE = 'cleargate';\n\nfunction resolveFilePath(opts: TokenStoreFactoryOptions): string {\n if (opts.filePath) return opts.filePath;\n const home = os.homedir();\n if (!home) {\n throw new Error(\n 'Cannot determine home directory. Set opts.filePath explicitly or ensure os.homedir() returns a non-empty string.',\n );\n }\n return path.join(home, '.cleargate', 'auth.json');\n}\n\nfunction defaultWarn(msg: string): void {\n process.stderr.write(msg + '\\n');\n}\n\n/**\n * Creates a TokenStore, selecting the keychain backend when available and\n * falling back to file storage with a stderr warning when the OS keychain\n * cannot be accessed.\n */\nexport async function createTokenStore(\n opts: TokenStoreFactoryOptions = {},\n): Promise<TokenStore> {\n const filePath = resolveFilePath(opts);\n const service = opts.keychainService ?? DEFAULT_KEYCHAIN_SERVICE;\n const warn = opts.warn ?? defaultWarn;\n\n // Short-circuit if backend is forced (test seam, skips probe)\n if (opts.forceBackend === 'file') {\n return new FileTokenStore(filePath);\n }\n if (opts.forceBackend === 'keychain') {\n return new KeychainTokenStore(service);\n }\n\n // Probe the keychain to determine availability\n try {\n const { Entry } = await import('@napi-rs/keyring');\n new Entry(service, '__cleargate_probe__').getPassword();\n // Probe succeeded (returned string | null cleanly) — use keychain\n return new KeychainTokenStore(service);\n } catch {\n // Constructor threw (native module load failed, libsecret missing on Linux)\n // OR getPassword() threw (dbus not running, prompt cancelled)\n // Either way, keychain is unavailable for this CLI invocation\n warn(\n `cleargate: OS keychain unavailable, falling back to file storage at ${filePath}. Run with --log-level=debug for details.`,\n );\n return new FileTokenStore(filePath);\n }\n}\n","import { Entry } from '@napi-rs/keyring';\nimport type { TokenStore } from './token-store.js';\n\nexport class KeychainTokenStore implements TokenStore {\n readonly backend = 'keychain' as const;\n\n constructor(private readonly service: string) {}\n\n async save(profile: string, token: string): Promise<void> {\n new Entry(this.service, profile).setPassword(token);\n }\n\n async load(profile: string): Promise<string | null> {\n try {\n const result = new Entry(this.service, profile).getPassword();\n // getPassword() returns string | null per @napi-rs/keyring@1.2.0 index.d.ts:124\n // Despite the docstring claiming it throws NoEntry, the return type wins.\n // Handle both: null return AND potential thrown NoEntry (platform-specific).\n return result ?? null;\n } catch {\n // NoEntry or other keychain error — treat as absent\n return null;\n }\n }\n\n async remove(profile: string): Promise<void> {\n try {\n new Entry(this.service, profile).deletePassword();\n } catch {\n // Entry didn't exist or other keychain error — idempotent, swallow\n }\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport type { TokenStore } from './token-store.js';\n\nconst ProfileEntrySchema = z.object({ refreshToken: z.string().min(1) }).strict();\n\nexport const AuthFileSchema = z\n .object({\n version: z.literal(1),\n profiles: z.record(z.string().min(1), ProfileEntrySchema),\n })\n .strict();\n\ntype AuthFile = z.infer<typeof AuthFileSchema>;\n\nconst EMPTY_AUTH_FILE: AuthFile = { version: 1, profiles: {} };\n\nexport class FileTokenStore implements TokenStore {\n readonly backend = 'file' as const;\n\n constructor(private readonly filePath: string) {}\n\n async save(profile: string, token: string): Promise<void> {\n const current = await this.readFile();\n const updated: AuthFile = {\n ...current,\n profiles: {\n ...current.profiles,\n [profile]: { refreshToken: token },\n },\n };\n await this.writeFile(updated);\n }\n\n async load(profile: string): Promise<string | null> {\n const data = await this.readFile();\n return data.profiles[profile]?.refreshToken ?? null;\n }\n\n async remove(profile: string): Promise<void> {\n let current: AuthFile;\n try {\n current = await this.readFile();\n } catch {\n // File doesn't exist or unreadable — no-op since there's nothing to remove\n return;\n }\n if (!(profile in current.profiles)) {\n return; // Profile doesn't exist — idempotent\n }\n const { [profile]: _removed, ...rest } = current.profiles;\n const updated: AuthFile = { ...current, profiles: rest };\n await this.writeFile(updated);\n }\n\n private async readFile(): Promise<AuthFile> {\n let raw: string;\n try {\n raw = await fs.readFile(this.filePath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return EMPTY_AUTH_FILE;\n }\n throw err;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new Error(\n `Failed to parse auth file at ${this.filePath}: invalid JSON`,\n );\n }\n\n const result = AuthFileSchema.safeParse(parsed);\n if (!result.success) {\n // Check for version mismatch specifically\n const versionCheck = (parsed as Record<string, unknown>)?.['version'];\n if (versionCheck !== 1) {\n throw new Error(\n `Invalid auth file at ${this.filePath}: unsupported version ${String(versionCheck)}. Please upgrade \\`cleargate\\` to read this file.`,\n );\n }\n throw new Error(\n `Invalid auth file at ${this.filePath}: ${result.error.message}`,\n );\n }\n\n return result.data;\n }\n\n private async writeFile(data: AuthFile): Promise<void> {\n const dir = path.dirname(this.filePath);\n await fs.mkdir(dir, { recursive: true, mode: 0o700 });\n // Explicit chmod after mkdir — mkdir only sets mode on newly created dirs\n await fs.chmod(dir, 0o700).catch(() => {\n // If chmod fails on existing dir, that's acceptable — we don't want to\n // surprise users who have set custom modes on ~/.cleargate/\n });\n\n const json = JSON.stringify(data, null, 2);\n const tmpPath = path.join(dir, '.auth.json.tmp');\n\n // Atomic write: write to tmp then rename to avoid partial-write corruption\n await fs.writeFile(tmpPath, json, { mode: 0o600 });\n // Explicit chmod after writeFile — writeFile only sets mode on file creation\n await fs.chmod(tmpPath, 0o600);\n await fs.rename(tmpPath, this.filePath);\n // After rename, chmod the final path to ensure it stays 0600\n await fs.chmod(this.filePath, 0o600);\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,YAAY,QAAQ;AACpB,YAAYA,WAAU;;;ACDtB;AAAA,SAAS,aAAa;AAGf,IAAM,qBAAN,MAA+C;AAAA,EAGpD,YAA6B,SAAiB;AAAjB;AAAA,EAAkB;AAAA,E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
1
- {"version":3,"sources":["../src/config.ts","../src/lib/membership.ts","../src/auth/acquire.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { z } from 'zod';\n\nexport const ConfigSchema = z\n .object({\n mcpUrl: z.string().url().optional(),\n profile: z.string().min(1).default('default'),\n logLevel: z.enum(['debug', 'info', 'warn', 'error']).default('info'),\n })\n .strict();\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/** Partial raw config used for each layer before merge */\ntype RawConfig = Partial<{\n mcpUrl: string | undefined;\n profile: string | undefined;\n logLevel: string | undefined;\n}>;\n\nexport interface LoadConfigOptions {\n flags?: RawConfig;\n env?: NodeJS.ProcessEnv;\n configPath?: string;\n}\n\n/**\n * Synchronously loads and merges config from all layers:\n * flags > env > config file > zod defaults\n */\nexport function loadConfig(opts: LoadConfigOptions = {}): Config {\n const {\n flags = {},\n env = process.env,\n configPath,\n } = opts;\n\n // Resolve config file path\n const resolvedConfigPath =\n configPath ??\n (() => {\n const home = os.homedir();\n if (!home) return null;\n return path.join(home, '.cleargate', 'config.json');\n })();\n\n // Layer: file\n let fileLayer: RawConfig = {};\n if (resolvedConfigPath) {\n try {\n const raw = fs.readFileSync(resolvedConfigPath, 'utf8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new Error(\n `Failed to parse config file at ${resolvedConfigPath}: invalid JSON`,\n );\n }\n // Validate file contents strictly (unknown keys will throw here)\n const fileResult = ConfigSchema.safeParse(parsed);\n if (!fileResult.success) {\n throw new Error(\n `Invalid config file at ${resolvedConfigPath}: ${fileResult.error.message}`,\n );\n }\n fileLayer = fileResult.data;\n } catch (err) {\n // Re-throw parse/validation errors; silently skip only ENOENT\n if (\n err instanceof Error &&\n 'code' in err &&\n (err as NodeJS.ErrnoException).code === 'ENOENT'\n ) {\n // file doesn't exist — skip silently\n } else {\n throw err;\n }\n }\n }\n\n // Layer: env\n const envLayer: RawConfig = {};\n if (env['CLEARGATE_MCP_URL']) {\n envLayer.mcpUrl = env['CLEARGATE_MCP_URL'];\n }\n if (env['CLEARGATE_PROFILE']) {\n envLayer.profile = env['CLEARGATE_PROFILE'];\n }\n if (env['CLEARGATE_LOG_LEVEL']) {\n envLayer.logLevel = env['CLEARGATE_LOG_LEVEL'];\n }\n\n // Merge: flags > env > file (start from {} so zod defaults fill in missing fields)\n const merged: Record<string, unknown> = {\n ...fileLayer,\n ...envLayer,\n ...(flags.mcpUrl !== undefined ? { mcpUrl: flags.mcpUrl } : {}),\n ...(flags.profile !== undefined ? { profile: flags.profile } : {}),\n ...(flags.logLevel !== undefined ? { logLevel: flags.logLevel } : {}),\n };\n\n // Remove undefined values so zod defaults apply properly\n for (const key of Object.keys(merged)) {\n if (merged[key] === undefined) {\n delete merged[key];\n }\n }\n\n const result = ConfigSchema.safeParse(merged);\n if (!result.success) {\n throw new Error(`Config validation failed: ${result.error.message}`);\n }\n\n return result.data;\n}\n\n/**\n * Asserts mcpUrl is present, throws a user-friendly error if not.\n */\nexport function requireMcpUrl(cfg: Config): string {\n if (cfg.mcpUrl === undefined) {\n throw new Error(\n 'mcpUrl not configured. Run `cleargate join <invite-url>` first.',\n );\n }\n return cfg.mcpUrl;\n}\n\nexport interface SaveConfigOptions {\n configPath?: string;\n}\n\n/**\n * Persist a partial update into ~/.cleargate/config.json.\n *\n * Reads the existing raw JSON (if present), shallow-merges `updates` on top, and\n * writes atomically with mode 0600. Unknown keys already in the file (e.g.\n * project_id, written by other surfaces) are preserved — strict Zod validation\n * is intentionally skipped here because admin-url.ts and other readers store\n * fields outside the strict schema.\n */\nexport function saveConfig(\n updates: Partial<{ mcpUrl: string; profile: string; logLevel: string }>,\n opts: SaveConfigOptions = {},\n): void {\n const home = os.homedir();\n if (!home) {\n throw new Error('Cannot determine home directory.');\n }\n const configPath =\n opts.configPath ?? path.join(home, '.cleargate', 'config.json');\n const dir = path.dirname(configPath);\n\n let existing: Record<string, unknown> = {};\n try {\n const raw = fs.readFileSync(configPath, 'utf8');\n const parsed = JSON.parse(raw);\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n existing = parsed as Record<string, unknown>;\n }\n } catch (err) {\n if (\n !(\n err instanceof Error &&\n 'code' in err &&\n (err as NodeJS.ErrnoException).code === 'ENOENT'\n )\n ) {\n // Treat parse errors as recoverable — overwrite rather than fail join.\n }\n }\n\n const merged: Record<string, unknown> = { ...existing };\n for (const [k, v] of Object.entries(updates)) {\n if (v !== undefined) merged[k] = v;\n }\n\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n try {\n fs.chmodSync(dir, 0o700);\n } catch {\n // existing dir with custom mode — leave alone\n }\n\n const tmpPath = path.join(dir, '.config.json.tmp');\n const json = JSON.stringify(merged, null, 2) + '\\n';\n fs.writeFileSync(tmpPath, json, { mode: 0o600 });\n fs.chmodSync(tmpPath, 0o600);\n fs.renameSync(tmpPath, configPath);\n fs.chmodSync(configPath, 0o600);\n}\n","/**\n * membership.ts — CR-011\n *\n * Single source of truth for ClearGate membership state detection.\n * Cheap-path: reads ~/.cleargate/auth.json, decodes the stored refresh JWT\n * (introspection only — no signature verification), checks expiry.\n *\n * Returns 'pre-member' on: file missing | malformed JSON | malformed JWT | exp <= now.\n * Returns 'member' with decoded claims otherwise.\n *\n * No network call. Used by whoami --json, preAction gating hook, doctor --session-start banner.\n */\n\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { Buffer } from 'node:buffer';\n\n// ─── Public types ─────────────────────────────────────────────────────────────\n\nexport type MembershipState =\n | { state: 'member'; email: string; project_id: string; expires_at: string }\n | { state: 'pre-member' };\n\nexport interface GetMembershipStateOpts {\n /** Profile name (default: 'default'). */\n profile?: string;\n /** Test seam: override the ~/.cleargate home directory. */\n cleargateHome?: string;\n /** Test seam: clock for expiry comparison (ms epoch). */\n now?: () => number;\n /**\n * BUG-031: working directory for per-repo join evidence check.\n * If set, getMembershipState checks for .cleargate/.join.json in this\n * directory before returning 'member'. If absent, returns 'pre-member'\n * regardless of global auth.json validity.\n * Default: process.cwd().\n */\n projectRoot?: string;\n}\n\n// ─── JWT decode helper (extracted from whoami.ts) ─────────────────────────────\n\n/**\n * Decode a JWT payload without verifying the signature (introspection only).\n * Returns null if the token is malformed.\n */\nexport function decodeJwtPayload(jwt: string): Record<string, unknown> | null {\n const parts = jwt.split('.');\n if (parts.length !== 3) return null;\n try {\n const json = Buffer.from(parts[1]!, 'base64url').toString('utf8');\n return JSON.parse(json) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n// ─── Auth file schema (mirrors src/auth/file-store.ts without Zod) ────────────\n\ninterface AuthFile {\n version: number;\n profiles: Record<string, { refreshToken: string }>;\n}\n\nfunction readAuthFile(authFilePath: string): AuthFile | null {\n let raw: string;\n try {\n raw = fs.readFileSync(authFilePath, 'utf8');\n } catch {\n // ENOENT or permission error → pre-member\n return null;\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n (parsed as Record<string, unknown>)['version'] !== 1 ||\n typeof (parsed as Record<string, unknown>)['profiles'] !== 'object'\n ) {\n return null;\n }\n return parsed as AuthFile;\n } catch {\n return null;\n }\n}\n\n// ─── Main export ─────────────────────────────────────────────────────────────\n\n// ─── Per-repo join file schema ────────────────────────────────────────────────\n\ninterface JoinFile {\n project_id: string;\n joined_at?: string;\n}\n\n/**\n * Read .cleargate/.join.json from the given project root.\n * Returns null on ENOENT or malformed JSON.\n */\nfunction readJoinFile(projectRoot: string): JoinFile | null {\n const joinFilePath = path.join(projectRoot, '.cleargate', '.join.json');\n try {\n const raw = fs.readFileSync(joinFilePath, 'utf8');\n const parsed = JSON.parse(raw) as unknown;\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Record<string, unknown>)['project_id'] !== 'string'\n ) {\n return null;\n }\n return parsed as JoinFile;\n } catch {\n return null;\n }\n}\n\n/**\n * Detect membership state locally.\n *\n * Algorithm (BUG-031 fix: per-repo isolation):\n * 1. Resolve auth file path: <cleargateHome>/auth.json (default: ~/.cleargate/auth.json)\n * 2. Read & parse the file as an AuthFile { version, profiles }.\n * 3. Look up the profile's refreshToken.\n * 4. Decode the refreshToken as a JWT (base64url, no sig verify).\n * 5. Extract exp, sub (= email proxy), project_id from global auth.\n * 6. If exp <= now (ms) → pre-member.\n * 7. BUG-031: Check per-repo .cleargate/.join.json in projectRoot (default: process.cwd()).\n * If absent → pre-member regardless of global auth.json validity.\n * If present → use its project_id (per-repo binding beats global auth project_id).\n * 8. Otherwise → member with per-repo project_id.\n *\n * Cross-Cutting Rule #3: Identity (email) is global; project_id is per-repo.\n */\nexport function getMembershipState(opts?: GetMembershipStateOpts): MembershipState {\n const profile = opts?.profile ?? 'default';\n const nowMs = (opts?.now ?? Date.now)();\n const projectRoot = opts?.projectRoot ?? process.cwd();\n\n // Resolve the auth file path\n const home = opts?.cleargateHome ?? path.join(os.homedir(), '.cleargate');\n const authFilePath = path.join(home, 'auth.json');\n\n // Read the auth file\n const authFile = readAuthFile(authFilePath);\n if (authFile === null) {\n return { state: 'pre-member' };\n }\n\n // Look up the profile\n const profileEntry = authFile.profiles[profile];\n if (!profileEntry || typeof profileEntry.refreshToken !== 'string') {\n return { state: 'pre-member' };\n }\n\n // Decode the stored refresh token as a JWT\n const claims = decodeJwtPayload(profileEntry.refreshToken);\n if (claims === null) {\n return { state: 'pre-member' };\n }\n\n // Check expiry (exp is in seconds per JWT spec)\n const exp = claims['exp'];\n if (typeof exp !== 'number' || !Number.isFinite(exp)) {\n return { state: 'pre-member' };\n }\n const expMs = exp * 1000;\n if (expMs <= nowMs) {\n return { state: 'pre-member' };\n }\n\n // Extract email from global auth (identity is global — Cross-Cutting Rule #3)\n // sub is the member UUID; we use it as the email proxy since the JWT\n // doesn't carry a separate email field (flashcard: sub = member UUID, not email).\n const sub = claims['sub'];\n const email = typeof sub === 'string' ? sub : '';\n const expiresAt = new Date(expMs).toISOString();\n\n // BUG-031: per-repo isolation — check for per-repo .join.json in projectRoot.\n // A valid global auth token alone is NOT sufficient to report 'member'.\n // The working directory MUST have a per-repo join marker (written by `cleargate join`).\n const joinFile = readJoinFile(projectRoot);\n if (joinFile === null) {\n // No per-repo join evidence → pre-member regardless of global auth.json validity.\n return { state: 'pre-member' };\n }\n\n // Per-repo project_id beats global auth project_id (per-repo binding is authoritative).\n const projectId = joinFile.project_id;\n\n return { state: 'member', email, project_id: projectId, expires_at: expiresAt };\n}\n","/**\n * acquireAccessToken — resolve a short-lived MCP access-token JWT.\n *\n * Resolution order (first success wins):\n * 1. CLEARGATE_MCP_TOKEN env var — CI / dev short-circuit (assumed JWT, not verified locally).\n * 2. In-memory single-flight cache (keyed by `${profile}::${mcpUrl}`) — returns cached token\n * if still valid (expires 60s before access token's `exp` claim).\n * 3. Stored refresh token (keychain/file) + POST /auth/refresh → rotates refresh token, returns access token.\n *\n * Errors surface to caller with a clear message so command handlers can exit cleanly.\n *\n * Lives here (not in mcp-client.ts) because the refresh flow needs TokenStore + mcpUrl and\n * mcp-client.ts is kept thin (just: host, bearer, JSON-RPC).\n */\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { createTokenStore } from './factory.js';\nimport type { TokenStore } from './token-store.js';\n\n// ── In-memory + on-disk single-flight cache ──────────────────────────────────\n// In-memory: process-local; naturally cleared when the Node CLI exits.\n// On-disk: ~/.cleargate/access-token.json (mode 0600), survives across CLI\n// invocations. Critical because each `cleargate` call is a fresh\n// process — without a disk cache every call hits keychain to load\n// the refresh token, then rotates it via /auth/refresh, which\n// re-saves to keychain and resets the macOS ACL → re-prompt loop.\n// Key: `${profile}::${mcpUrl}` — two profiles in same process never collide.\n// Env-token path (CLEARGATE_MCP_TOKEN) bypasses both caches entirely.\n\nconst CACHE = new Map<string, { accessToken: string; expiresAtMs: number }>();\n\ninterface DiskCacheEntry {\n accessToken: string;\n expiresAtMs: number;\n}\ninterface DiskCacheFile {\n version: 1;\n entries: Record<string, DiskCacheEntry>;\n}\n\nfunction defaultDiskCachePath(env: NodeJS.ProcessEnv = process.env): string | null {\n // Test override: setting CLEARGATE_DISK_CACHE_PATH=off disables the disk\n // cache entirely; setting it to a path uses that file instead of the home dir.\n const override = env['CLEARGATE_DISK_CACHE_PATH'];\n if (override === 'off') return null;\n if (typeof override === 'string' && override.length > 0) return override;\n const home = os.homedir();\n if (!home) return null;\n return path.join(home, '.cleargate', 'access-token.json');\n}\n\nfunction readDiskCache(filePath: string): DiskCacheFile {\n try {\n const raw = fs.readFileSync(filePath, 'utf8');\n const parsed = JSON.parse(raw) as unknown;\n if (\n parsed !== null &&\n typeof parsed === 'object' &&\n (parsed as { version?: unknown }).version === 1 &&\n typeof (parsed as { entries?: unknown }).entries === 'object' &&\n (parsed as { entries?: unknown }).entries !== null\n ) {\n return parsed as DiskCacheFile;\n }\n } catch {\n // ENOENT, parse error, schema mismatch — treat as empty\n }\n return { version: 1, entries: {} };\n}\n\nfunction writeDiskCache(filePath: string, data: DiskCacheFile): void {\n const dir = path.dirname(filePath);\n try {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n try {\n fs.chmodSync(dir, 0o700);\n } catch {\n // existing dir with custom mode — leave alone\n }\n const tmpPath = path.join(dir, '.access-token.json.tmp');\n fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2) + '\\n', { mode: 0o600 });\n fs.chmodSync(tmpPath, 0o600);\n fs.renameSync(tmpPath, filePath);\n fs.chmodSync(filePath, 0o600);\n } catch {\n // Disk-cache failures are non-fatal — the next call just refreshes again.\n }\n}\n\n/** Test seam: clear the in-memory acquire cache between tests. */\nexport function __resetAcquireCache(): void {\n CACHE.clear();\n}\n\n/** Decode a JWT payload without verifying the signature (CLI-side only). */\nfunction decodeJwtPayload(token: string): Record<string, unknown> | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n const padded = parts[1].replace(/-/g, '+').replace(/_/g, '/');\n const json = Buffer.from(padded, 'base64').toString('utf8');\n return JSON.parse(json) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nexport interface AcquireOptions {\n mcpUrl: string;\n profile: string;\n /** Force a fresh /auth/refresh even if the cache has a valid entry. */\n forceRefresh?: boolean;\n /** Test seam: overrides globalThis.fetch */\n fetch?: typeof globalThis.fetch;\n /** Test seam: overrides createTokenStore */\n createStore?: () => Promise<TokenStore>;\n /** Test seam: overrides process.env lookup */\n env?: NodeJS.ProcessEnv;\n /** Test seam: overrides Date.now() for expiry calculations. */\n now?: () => number;\n /** Test seam: overrides ~/.cleargate/access-token.json path. */\n diskCachePath?: string | null;\n}\n\nexport class AcquireError extends Error {\n constructor(\n message: string,\n public readonly code:\n | 'env_token'\n | 'no_stored_token'\n | 'invalid_token'\n | 'token_revoked'\n | 'transport'\n | 'unexpected_status'\n | 'bad_response',\n ) {\n super(message);\n this.name = 'AcquireError';\n }\n}\n\n/**\n * Returns a bearer string suitable for Authorization headers against /mcp and\n * /admin-api. Rotates the stored refresh token on success.\n */\nexport async function acquireAccessToken(opts: AcquireOptions): Promise<string> {\n const env = opts.env ?? process.env;\n const nowFn = opts.now ?? Date.now;\n\n // 1. Env short-circuit — CI / dev / manual paste. Assumed to be a valid JWT.\n // Env tokens are NOT cached — they have no known exp without decoding + the\n // env is set per-invocation in CI anyway.\n const envToken = env['CLEARGATE_MCP_TOKEN'];\n if (envToken && envToken.length > 0) {\n return envToken;\n }\n\n // 2a. In-memory cache check (skip when forceRefresh is set).\n const cacheKey = `${opts.profile}::${opts.mcpUrl}`;\n if (!opts.forceRefresh) {\n const cached = CACHE.get(cacheKey);\n if (cached && nowFn() < cached.expiresAtMs) {\n return cached.accessToken;\n }\n }\n\n // 2b. On-disk cache check — survives across CLI invocations and avoids\n // the keychain re-prompt loop that comes from per-call refresh-token\n // rotation. Disabled by passing diskCachePath: null (tests) or\n // CLEARGATE_DISK_CACHE_PATH=off in the real process env.\n // Note: consults process.env (not opts.env) because tests deliberately\n // pass empty `env: {}` to suppress CLEARGATE_MCP_TOKEN, but still want\n // the disk-cache override picked up from the test runner's env.\n const diskCachePath =\n opts.diskCachePath === undefined ? defaultDiskCachePath() : opts.diskCachePath;\n if (!opts.forceRefresh && diskCachePath) {\n const file = readDiskCache(diskCachePath);\n const entry = file.entries[cacheKey];\n if (entry && nowFn() < entry.expiresAtMs) {\n // Promote into in-memory cache for the rest of this process's lifetime.\n CACHE.set(cacheKey, entry);\n return entry.accessToken;\n }\n }\n\n // 3. Stored refresh token → POST /auth/refresh.\n const store = await (opts.createStore ?? createTokenStore)();\n const stored = await store.load(opts.profile);\n if (!stored) {\n throw new AcquireError(\n `No stored credentials for profile '${opts.profile}'. Run \\`cleargate join <invite-url>\\` first, or export CLEARGATE_MCP_TOKEN.`,\n 'no_stored_token',\n );\n }\n\n const fetchFn = opts.fetch ?? globalThis.fetch;\n\n let response: Response;\n try {\n response = await fetchFn(`${opts.mcpUrl}/auth/refresh`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ refresh_token: stored }),\n });\n } catch (err) {\n throw new AcquireError(\n `cannot reach ${opts.mcpUrl} (${err instanceof Error ? err.message : String(err)})`,\n 'transport',\n );\n }\n\n if (response.status === 401) {\n const body = (await response.json().catch(() => ({}))) as { error?: string };\n if (body.error === 'token_revoked') {\n throw new AcquireError(\n 'refresh token was revoked. Run `cleargate join <invite-url>` to re-authenticate.',\n 'token_revoked',\n );\n }\n throw new AcquireError(\n 'refresh token is invalid or expired. Run `cleargate join <invite-url>` to re-authenticate.',\n 'invalid_token',\n );\n }\n\n if (!response.ok) {\n throw new AcquireError(`unexpected status ${response.status} from /auth/refresh`, 'unexpected_status');\n }\n\n const body = (await response.json().catch(() => null)) as\n | { access_token?: unknown; refresh_token?: unknown }\n | null;\n if (\n !body ||\n typeof body.access_token !== 'string' ||\n typeof body.refresh_token !== 'string' ||\n body.access_token.length === 0 ||\n body.refresh_token.length === 0\n ) {\n throw new AcquireError('server returned unexpected /auth/refresh response shape', 'bad_response');\n }\n\n // Rotate — store the new refresh token so the next call uses a fresh jti.\n await store.save(opts.profile, body.refresh_token);\n\n const accessToken = body.access_token;\n\n // 4. Cache the new access token (expire 60s before the JWT exp claim) in\n // BOTH the in-memory map and on disk. The disk cache is what stops the\n // keychain re-prompt loop on subsequent CLI invocations.\n const payload = decodeJwtPayload(accessToken);\n const exp = payload?.exp;\n if (typeof exp === 'number' && Number.isFinite(exp)) {\n const expiresAtMs = (exp - 60) * 1000;\n const entry: DiskCacheEntry = { accessToken, expiresAtMs };\n CACHE.set(cacheKey, entry);\n if (diskCachePath) {\n const file = readDiskCache(diskCachePath);\n file.entries[cacheKey] = entry;\n writeDiskCache(diskCachePath, file);\n }\n }\n // If exp is missing or non-numeric, do NOT cache — next call will re-refresh.\n\n return accessToken;\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,SAAS;AAEX,IAAM,eAAe,EACzB,OAAO;AAAA,EACN,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EAClC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,SAAS;AAAA,EAC5C,UAAU,EAAE,KAAK,CAAC,SAAS,QAAQ,QAAQ,OAAO,CAAC,EAAE,QAAQ,MAAM;AACrE,CAAC,EACA,OAAO;AAqBH,SAAS,WAAW,OAA0B,CAAC,GAAW;AAC/D,QAAM;AAAA,IACJ,QAAQ,CAAC;AAAA,IACT,MAAM,QAAQ;AAAA,IACd;AAAA,EACF,IAAI;AAGJ,QAAM,qBACJ,eACC,MAAM;AACL,UAAM,OAAU,WAAQ;AACxB,QAAI,CAAC,KAAM,QAAO;AAClB,WAAY,UAAK,MAAM,cAAc,aAAa;AAAA,EACpD,GAAG;AAGL,MAAI,YAAuB,CAAC;AAC5B,MAAI,oBAAoB;AACtB,QAAI;AACF,YAAM,MAAS,gBAAa,oBAAoB,MAAM;AACtD,UAAI;AACJ,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