mednotes-opencode 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (430) hide show
  1. package/.opencode/agents/med-chat-triager.md +204 -0
  2. package/.opencode/agents/med-flashcard-maker.md +63 -0
  3. package/.opencode/agents/med-knowledge-architect.md +230 -0
  4. package/.opencode/agents/med-link-graph-curator.md +177 -0
  5. package/.opencode/agents/med-publish-guard.md +62 -0
  6. package/.opencode/commands/flashcards.md +25 -0
  7. package/.opencode/commands/mednotes/create.md +25 -0
  8. package/.opencode/commands/mednotes/enrich.md +27 -0
  9. package/.opencode/commands/mednotes/fix-wiki.md +27 -0
  10. package/.opencode/commands/mednotes/history.md +22 -0
  11. package/.opencode/commands/mednotes/link-body.md +25 -0
  12. package/.opencode/commands/mednotes/link-related.md +27 -0
  13. package/.opencode/commands/mednotes/link.md +27 -0
  14. package/.opencode/commands/mednotes/pdf-library.md +27 -0
  15. package/.opencode/commands/mednotes/process-chats.md +23 -0
  16. package/.opencode/commands/mednotes/setup.md +21 -0
  17. package/.opencode/commands/mednotes/status.md +27 -0
  18. package/.opencode/commands/mednotes/telemetry.md +27 -0
  19. package/.opencode/commands/report.md +26 -0
  20. package/.opencode/mednotes/AGENTS.md +57 -0
  21. package/.opencode/mednotes/agents/med-chat-triager.md +197 -0
  22. package/.opencode/mednotes/agents/med-flashcard-maker.md +56 -0
  23. package/.opencode/mednotes/agents/med-knowledge-architect.md +224 -0
  24. package/.opencode/mednotes/agents/med-link-graph-curator.md +171 -0
  25. package/.opencode/mednotes/agents/med-publish-guard.md +55 -0
  26. package/.opencode/mednotes/contracts/.gitkeep +1 -0
  27. package/.opencode/mednotes/contracts/agents.json +116 -0
  28. package/.opencode/mednotes/contracts/opencode-plugin.json +70 -0
  29. package/.opencode/mednotes/docs/agent-prompt-hardening.md +567 -0
  30. package/.opencode/mednotes/docs/agent-role-contracts.md +94 -0
  31. package/.opencode/mednotes/docs/anki-mcp-twenty-rules.md +214 -0
  32. package/.opencode/mednotes/docs/anki-templates/README.md +39 -0
  33. package/.opencode/mednotes/docs/anki-templates/cloze.back.html +23 -0
  34. package/.opencode/mednotes/docs/anki-templates/cloze.front.html +14 -0
  35. package/.opencode/mednotes/docs/anki-templates/qa.back.html +24 -0
  36. package/.opencode/mednotes/docs/anki-templates/qa.front.html +14 -0
  37. package/.opencode/mednotes/docs/anki-templates/style.css +182 -0
  38. package/.opencode/mednotes/docs/atomicity-splitting-policy.md +113 -0
  39. package/.opencode/mednotes/docs/extension-docs.md +40 -0
  40. package/.opencode/mednotes/docs/flashcard-ingestion.md +278 -0
  41. package/.opencode/mednotes/docs/knowledge-architect.md +208 -0
  42. package/.opencode/mednotes/docs/merge-policy.md +110 -0
  43. package/.opencode/mednotes/docs/public-vocabulary.md +104 -0
  44. package/.opencode/mednotes/docs/semantic-linker.md +141 -0
  45. package/.opencode/mednotes/docs/taxonomy-policy.md +90 -0
  46. package/.opencode/mednotes/docs/triage-policy.md +187 -0
  47. package/.opencode/mednotes/docs/vault-version-control.md +758 -0
  48. package/.opencode/mednotes/docs/vocabulary-db-recovery.md +58 -0
  49. package/.opencode/mednotes/docs/workflow-output-contract.md +779 -0
  50. package/.opencode/mednotes/hooks/hooks.json +79 -0
  51. package/.opencode/mednotes/package-lock.json +6361 -0
  52. package/.opencode/mednotes/package.json +15 -0
  53. package/.opencode/mednotes/pyproject.toml +48 -0
  54. package/.opencode/mednotes/scripts/bootstrap_windows_python_uv.cmd +13 -0
  55. package/.opencode/mednotes/scripts/bootstrap_windows_python_uv.ps1 +172 -0
  56. package/.opencode/mednotes/scripts/enrich_notes.py +23 -0
  57. package/.opencode/mednotes/scripts/full_reset_windows_python_uv.cmd +13 -0
  58. package/.opencode/mednotes/scripts/hooks/antigravity_hook_status.mjs +212 -0
  59. package/.opencode/mednotes/scripts/hooks/mednotes_hook/adapters/antigravity.mjs +169 -0
  60. package/.opencode/mednotes/scripts/hooks/mednotes_hook/adapters/harness_payload.mjs +103 -0
  61. package/.opencode/mednotes/scripts/hooks/mednotes_hook/adapters/opencode_plugin.mjs +341 -0
  62. package/.opencode/mednotes/scripts/hooks/mednotes_hook/adapters/opencode_user_config_sync.mjs +177 -0
  63. package/.opencode/mednotes/scripts/hooks/mednotes_hook/anki_preflight.mjs +214 -0
  64. package/.opencode/mednotes/scripts/hooks/mednotes_hook/cli.mjs +143 -0
  65. package/.opencode/mednotes/scripts/hooks/mednotes_hook/diagnostics.mjs +11 -0
  66. package/.opencode/mednotes/scripts/hooks/mednotes_hook/domain/agent_directive_core.mjs +160 -0
  67. package/.opencode/mednotes/scripts/hooks/mednotes_hook/fsm_directive.mjs +1470 -0
  68. package/.opencode/mednotes/scripts/hooks/mednotes_hook/hook_errors.mjs +120 -0
  69. package/.opencode/mednotes/scripts/hooks/mednotes_hook/retention.mjs +114 -0
  70. package/.opencode/mednotes/scripts/hooks/mednotes_hook/runtime.mjs +174 -0
  71. package/.opencode/mednotes/scripts/hooks/mednotes_hook/telemetry_capture.mjs +511 -0
  72. package/.opencode/mednotes/scripts/hooks/mednotes_hook/vault_guard.mjs +624 -0
  73. package/.opencode/mednotes/scripts/hooks/mednotes_hook.mjs +5 -0
  74. package/.opencode/mednotes/scripts/mednotes/_runtime_paths.py +24 -0
  75. package/.opencode/mednotes/scripts/mednotes/anki_model_validator.py +18 -0
  76. package/.opencode/mednotes/scripts/mednotes/capture_extension_diff.py +1562 -0
  77. package/.opencode/mednotes/scripts/mednotes/feedback_report.py +16 -0
  78. package/.opencode/mednotes/scripts/mednotes/flashcard_index.py +18 -0
  79. package/.opencode/mednotes/scripts/mednotes/flashcard_pipeline.py +18 -0
  80. package/.opencode/mednotes/scripts/mednotes/flashcard_report.py +18 -0
  81. package/.opencode/mednotes/scripts/mednotes/flashcard_sources.py +18 -0
  82. package/.opencode/mednotes/scripts/mednotes/obsidian/README.md +6 -0
  83. package/.opencode/mednotes/scripts/mednotes/obsidian_note_utils.py +20 -0
  84. package/.opencode/mednotes/scripts/mednotes/pdf_library/cli.py +16 -0
  85. package/.opencode/mednotes/scripts/mednotes/project_fsm.py +229 -0
  86. package/.opencode/mednotes/scripts/mednotes/setup_telemetry_email.py +404 -0
  87. package/.opencode/mednotes/scripts/mednotes/sync_anki_twenty_rules.py +18 -0
  88. package/.opencode/mednotes/scripts/mednotes/sync_opencode_user_config.py +36 -0
  89. package/.opencode/mednotes/scripts/mednotes/wiki/cli.py +20 -0
  90. package/.opencode/mednotes/scripts/mednotes/wiki_graph.py +18 -0
  91. package/.opencode/mednotes/scripts/mednotes/wiki_tree.py +134 -0
  92. package/.opencode/mednotes/scripts/reset_windows_python_uv.ps1 +625 -0
  93. package/.opencode/mednotes/scripts/run_python.mjs +109 -0
  94. package/.opencode/mednotes/scripts/vault/vault_commit.ps1 +19 -0
  95. package/.opencode/mednotes/scripts/vault/vault_commit.sh +18 -0
  96. package/.opencode/mednotes/scripts/vault/vault_git.ps1 +19 -0
  97. package/.opencode/mednotes/scripts/vault/vault_git.py +3107 -0
  98. package/.opencode/mednotes/scripts/vault/vault_git.sh +18 -0
  99. package/.opencode/mednotes/scripts/vault/vault_precommit.ps1 +19 -0
  100. package/.opencode/mednotes/scripts/vault/vault_precommit.sh +18 -0
  101. package/.opencode/mednotes/skills/THIRD_PARTY_NOTICES.md +45 -0
  102. package/.opencode/mednotes/skills/create-medical-flashcards/SKILL.md +113 -0
  103. package/.opencode/mednotes/skills/create-medical-note/SKILL.md +90 -0
  104. package/.opencode/mednotes/skills/enrich-medical-note/SKILL.md +120 -0
  105. package/.opencode/mednotes/skills/fix-medical-wiki/SKILL.md +559 -0
  106. package/.opencode/mednotes/skills/link-medical-wiki/SKILL.md +224 -0
  107. package/.opencode/mednotes/skills/obsidian-cli/SKILL.md +118 -0
  108. package/.opencode/mednotes/skills/obsidian-markdown/SKILL.md +207 -0
  109. package/.opencode/mednotes/skills/obsidian-markdown/references/CALLOUTS.md +58 -0
  110. package/.opencode/mednotes/skills/obsidian-markdown/references/EMBEDS.md +63 -0
  111. package/.opencode/mednotes/skills/obsidian-markdown/references/PROPERTIES.md +61 -0
  112. package/.opencode/mednotes/skills/obsidian-ops/SKILL.md +136 -0
  113. package/.opencode/mednotes/skills/pdf-library/SKILL.md +45 -0
  114. package/.opencode/mednotes/skills/process-medical-chats/SKILL.md +246 -0
  115. package/.opencode/mednotes/skills/workflow-report/SKILL.md +100 -0
  116. package/.opencode/mednotes/src/mednotes/__init__.py +5 -0
  117. package/.opencode/mednotes/src/mednotes/domains/__init__.py +5 -0
  118. package/.opencode/mednotes/src/mednotes/domains/flashcards/README.md +26 -0
  119. package/.opencode/mednotes/src/mednotes/domains/flashcards/__init__.py +2 -0
  120. package/.opencode/mednotes/src/mednotes/domains/flashcards/build_demo_apkg.py +177 -0
  121. package/.opencode/mednotes/src/mednotes/domains/flashcards/contracts.py +385 -0
  122. package/.opencode/mednotes/src/mednotes/domains/flashcards/flashcards_machine.py +522 -0
  123. package/.opencode/mednotes/src/mednotes/domains/flashcards/fsm.py +817 -0
  124. package/.opencode/mednotes/src/mednotes/domains/flashcards/index.py +630 -0
  125. package/.opencode/mednotes/src/mednotes/domains/flashcards/install_models.py +445 -0
  126. package/.opencode/mednotes/src/mednotes/domains/flashcards/model.py +359 -0
  127. package/.opencode/mednotes/src/mednotes/domains/flashcards/obsidian_links.py +135 -0
  128. package/.opencode/mednotes/src/mednotes/domains/flashcards/obsidian_note_utils.py +546 -0
  129. package/.opencode/mednotes/src/mednotes/domains/flashcards/pipeline.py +580 -0
  130. package/.opencode/mednotes/src/mednotes/domains/flashcards/report.py +510 -0
  131. package/.opencode/mednotes/src/mednotes/domains/flashcards/sources.py +682 -0
  132. package/.opencode/mednotes/src/mednotes/domains/flashcards/sync_rules.py +184 -0
  133. package/.opencode/mednotes/src/mednotes/domains/history/__init__.py +1 -0
  134. package/.opencode/mednotes/src/mednotes/domains/history/history_fsm.py +852 -0
  135. package/.opencode/mednotes/src/mednotes/domains/history/history_machine.py +453 -0
  136. package/.opencode/mednotes/src/mednotes/domains/setup/__init__.py +7 -0
  137. package/.opencode/mednotes/src/mednotes/domains/setup/setup_fsm.py +808 -0
  138. package/.opencode/mednotes/src/mednotes/domains/setup/setup_machine.py +973 -0
  139. package/.opencode/mednotes/src/mednotes/domains/wiki/README.md +64 -0
  140. package/.opencode/mednotes/src/mednotes/domains/wiki/__init__.py +1 -0
  141. package/.opencode/mednotes/src/mednotes/domains/wiki/api.py +668 -0
  142. package/.opencode/mednotes/src/mednotes/domains/wiki/batch_state.py +102 -0
  143. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/__init__.py +1 -0
  144. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/atomicity/__init__.py +1 -0
  145. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/atomicity/atomicity.py +877 -0
  146. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/body_link/__init__.py +1 -0
  147. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/body_link/body_linker.py +1562 -0
  148. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/effects/__init__.py +1 -0
  149. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/effects/effect_adapters.py +949 -0
  150. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/effects/fix_wiki_runtime_adapters.py +433 -0
  151. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/graph/__init__.py +1 -0
  152. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/graph/coverage.py +413 -0
  153. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/graph/graph.py +396 -0
  154. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/graph/graph_fixes.py +161 -0
  155. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/hygiene/__init__.py +1 -0
  156. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/hygiene/hygiene.py +483 -0
  157. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/__init__.py +2 -0
  158. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/anchors.py +185 -0
  159. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/core/__init__.py +0 -0
  160. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/core/cache.py +223 -0
  161. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/core/config.py +131 -0
  162. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/core/download.py +224 -0
  163. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/core/frontmatter.py +59 -0
  164. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/core/insert.py +227 -0
  165. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/core/local_import.py +54 -0
  166. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/sources/__init__.py +42 -0
  167. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/sources/web_profiles.py +99 -0
  168. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/sources/web_search.py +203 -0
  169. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/illustrate/sources/wikimedia.py +102 -0
  170. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/markdown/__init__.py +1 -0
  171. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/markdown/markdown_db_adapter.mjs +434 -0
  172. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/markdown/markdown_node_runtime.py +274 -0
  173. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/markdown/markdown_query.py +227 -0
  174. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/__init__.py +1 -0
  175. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/artifacts.py +605 -0
  176. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/canonical_merge.py +277 -0
  177. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/markdown_zones.py +85 -0
  178. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/meaning_planner.py +307 -0
  179. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_iter.py +67 -0
  180. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_merge.py +278 -0
  181. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_plan.py +409 -0
  182. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_policy.py +22 -0
  183. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_style/__init__.py +79 -0
  184. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_style/fixes.py +264 -0
  185. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_style/frontmatter.py +435 -0
  186. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_style/models.py +208 -0
  187. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_style/prompts.py +37 -0
  188. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_style/tables.py +236 -0
  189. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/note_style/validate.py +404 -0
  190. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/provenance.py +478 -0
  191. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/raw_chats.py +273 -0
  192. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/notes/sources_backfill.py +235 -0
  193. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/__init__.py +10 -0
  194. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/anchors.py +16 -0
  195. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/captions.py +47 -0
  196. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/cli.py +179 -0
  197. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/cloud.py +52 -0
  198. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/config.py +196 -0
  199. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/context_packets.py +76 -0
  200. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/db.py +81 -0
  201. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/doctor.py +102 -0
  202. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/figure_ids.py +42 -0
  203. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/ingest.py +326 -0
  204. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/insert.py +316 -0
  205. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/mentions.py +57 -0
  206. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/ocr.py +71 -0
  207. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/paths.py +35 -0
  208. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/pdf_engine.py +77 -0
  209. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/schema.py +155 -0
  210. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/search.py +188 -0
  211. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/tui/__init__.py +1 -0
  212. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/tui/app.py +89 -0
  213. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/tui/image_backend.py +29 -0
  214. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/pdf/tui/state.py +65 -0
  215. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/publish/__init__.py +1 -0
  216. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/publish/publish.py +1139 -0
  217. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/publish/publish_receipts.py +365 -0
  218. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/publish/publish_recovery.py +240 -0
  219. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/__init__.py +1 -0
  220. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/agent_behavior_corpus.py +2069 -0
  221. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/agent_report_validation.py +4448 -0
  222. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/agent_run_audit.py +852 -0
  223. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/architect_prompt_eval.py +341 -0
  224. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/body_linker_eval.py +240 -0
  225. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/curator_output_validation.py +175 -0
  226. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/curator_prompt_eval.py +865 -0
  227. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/quality/triager_prompt_eval.py +1295 -0
  228. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/related_notes/__init__.py +1 -0
  229. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/related_notes/related_notes.py +1920 -0
  230. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/related_notes/related_notes_headless.py +1186 -0
  231. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/specialist/__init__.py +1 -0
  232. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/specialist/plan_attestation.py +148 -0
  233. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/specialist/specialist_receipts.py +360 -0
  234. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/specialist/specialist_runtime.py +52 -0
  235. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/specialist/specialist_task_runner.py +2470 -0
  236. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/style/__init__.py +1 -0
  237. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/style/style.py +1952 -0
  238. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/subagents/__init__.py +1 -0
  239. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/subagents/agents.py +1767 -0
  240. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/__init__.py +1 -0
  241. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/alias_projection.py +331 -0
  242. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/link_terms.py +151 -0
  243. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/llm_disambiguation.py +182 -0
  244. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/__init__.py +116 -0
  245. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/audit.py +201 -0
  246. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/migration.py +314 -0
  247. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/normalize.py +72 -0
  248. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/policy.py +135 -0
  249. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/resolve.py +413 -0
  250. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/schema.py +157 -0
  251. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/taxonomy/status.py +137 -0
  252. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/vocabulary_bootstrap.py +509 -0
  253. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/vocabulary_curator_batch.py +1115 -0
  254. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/vocabulary_ingestion.py +632 -0
  255. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/vocabulary_map.py +930 -0
  256. package/.opencode/mednotes/src/mednotes/domains/wiki/capabilities/vocabulary/vocabulary_recovery.py +1388 -0
  257. package/.opencode/mednotes/src/mednotes/domains/wiki/cli.py +6665 -0
  258. package/.opencode/mednotes/src/mednotes/domains/wiki/common.py +69 -0
  259. package/.opencode/mednotes/src/mednotes/domains/wiki/config.py +210 -0
  260. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/__init__.py +74 -0
  261. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/agent_report.py +242 -0
  262. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/agent_run_audit.py +196 -0
  263. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/agents.py +601 -0
  264. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/curator.py +256 -0
  265. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/effect_payloads.py +519 -0
  266. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/happy_path.py +190 -0
  267. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/link_git.py +110 -0
  268. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/link_runtime_artifact.py +52 -0
  269. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/note_plan.py +75 -0
  270. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/paths.py +114 -0
  271. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/public_report.py +53 -0
  272. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/publish.py +111 -0
  273. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/raw_coverage.py +217 -0
  274. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/related_notes.py +136 -0
  275. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/related_notes_headless.py +153 -0
  276. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/related_notes_runtime.py +395 -0
  277. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/schema_registry.py +637 -0
  278. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/specialist.py +432 -0
  279. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/status.py +62 -0
  280. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/style_rewrite.py +568 -0
  281. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/vocabulary_ingestion.py +223 -0
  282. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/workflow_blockers.py +510 -0
  283. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/workflow_guardrails.py +637 -0
  284. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/workflow_outcomes.py +121 -0
  285. package/.opencode/mednotes/src/mednotes/domains/wiki/contracts/workflow_receipts.py +100 -0
  286. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/__init__.py +1 -0
  287. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/__init__.py +1 -0
  288. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/__main__.py +4 -0
  289. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/cli.py +275 -0
  290. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/__init__.py +2 -0
  291. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/candidates.py +193 -0
  292. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/cli.py +189 -0
  293. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/gemini.py +220 -0
  294. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/inputs.py +120 -0
  295. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/models.py +34 -0
  296. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/parsing.py +48 -0
  297. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/prompts.py +216 -0
  298. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/quality.py +54 -0
  299. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/reporting.py +24 -0
  300. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/runner.py +433 -0
  301. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/utils.py +39 -0
  302. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/enrich/workflow/vault_guard_bridge.py +17 -0
  303. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/__init__.py +1 -0
  304. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_context_packets.py +454 -0
  305. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_decision_projection.py +133 -0
  306. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_effects.py +1260 -0
  307. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_fsm.py +2768 -0
  308. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_machine.py +1588 -0
  309. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_plan.py +306 -0
  310. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_primary_objective.py +316 -0
  311. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_problem.py +153 -0
  312. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_receipt_evidence.py +306 -0
  313. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_states.py +290 -0
  314. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/fix_wiki_user_report.py +342 -0
  315. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/fix_wiki/health.py +6332 -0
  316. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/__init__.py +1 -0
  317. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/link_fsm.py +1119 -0
  318. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/link_git.py +638 -0
  319. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/link_machine.py +1106 -0
  320. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/link_retry_governance.py +374 -0
  321. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/link_runtime_result.py +485 -0
  322. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/link_triggers.py +183 -0
  323. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/linking.py +2758 -0
  324. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/reference_repair.py +718 -0
  325. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link/related_notes_fsm.py +1855 -0
  326. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link_related/__init__.py +1 -0
  327. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/link_related/link_related_machine.py +834 -0
  328. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/process_chats/__init__.py +1 -0
  329. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/process_chats/process_chats_fsm.py +1592 -0
  330. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/process_chats/process_chats_machine.py +3097 -0
  331. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/process_chats/process_chats_primary_objective.py +28 -0
  332. package/.opencode/mednotes/src/mednotes/domains/wiki/flows/process_chats/process_chats_runtime_result.py +185 -0
  333. package/.opencode/mednotes/src/mednotes/domains/wiki/performance.py +97 -0
  334. package/.opencode/mednotes/src/mednotes/kernel/__init__.py +6 -0
  335. package/.opencode/mednotes/src/mednotes/kernel/agent_directive.py +336 -0
  336. package/.opencode/mednotes/src/mednotes/kernel/base.py +51 -0
  337. package/.opencode/mednotes/src/mednotes/kernel/blockers.py +39 -0
  338. package/.opencode/mednotes/src/mednotes/kernel/effect_executor.py +55 -0
  339. package/.opencode/mednotes/src/mednotes/kernel/effect_intent.py +69 -0
  340. package/.opencode/mednotes/src/mednotes/kernel/effects.py +160 -0
  341. package/.opencode/mednotes/src/mednotes/kernel/errors.py +38 -0
  342. package/.opencode/mednotes/src/mednotes/kernel/fsm_event.py +35 -0
  343. package/.opencode/mednotes/src/mednotes/kernel/fsm_model.py +55 -0
  344. package/.opencode/mednotes/src/mednotes/kernel/fsm_transition_result.py +75 -0
  345. package/.opencode/mednotes/src/mednotes/kernel/guardrails.py +188 -0
  346. package/.opencode/mednotes/src/mednotes/kernel/progress.py +319 -0
  347. package/.opencode/mednotes/src/mednotes/kernel/public_report.py +346 -0
  348. package/.opencode/mednotes/src/mednotes/kernel/state_machine.py +164 -0
  349. package/.opencode/mednotes/src/mednotes/kernel/workflow.py +619 -0
  350. package/.opencode/mednotes/src/mednotes/platform/__init__.py +5 -0
  351. package/.opencode/mednotes/src/mednotes/platform/backup_policy.py +382 -0
  352. package/.opencode/mednotes/src/mednotes/platform/feedback/__init__.py +62 -0
  353. package/.opencode/mednotes/src/mednotes/platform/feedback/cli.py +275 -0
  354. package/.opencode/mednotes/src/mednotes/platform/feedback/contracts.py +83 -0
  355. package/.opencode/mednotes/src/mednotes/platform/feedback/core.py +4168 -0
  356. package/.opencode/mednotes/src/mednotes/platform/feedback/integrity.py +989 -0
  357. package/.opencode/mednotes/src/mednotes/platform/feedback/operational_contract.py +2293 -0
  358. package/.opencode/mednotes/src/mednotes/platform/feedback/telemetry.py +875 -0
  359. package/.opencode/mednotes/src/mednotes/platform/feedback/telemetry_config.py +65 -0
  360. package/.opencode/mednotes/src/mednotes/platform/opencode_runtime_config.py +182 -0
  361. package/.opencode/mednotes/src/mednotes/platform/paths/__init__.py +1560 -0
  362. package/.opencode/mednotes/src/mednotes/platform/secrets.py +89 -0
  363. package/.opencode/mednotes/src/mednotes/platform/user_config.py +103 -0
  364. package/.opencode/mednotes/src/mednotes/platform/vault_guard.py +214 -0
  365. package/.opencode/mednotes/uv.lock +932 -0
  366. package/.opencode/mednotes.generated.json +395 -0
  367. package/.opencode/opencode.json +31 -0
  368. package/.opencode/plugins/mednotes-fsm.mjs +7 -0
  369. package/.opencode/plugins/mednotes_hook/adapters/antigravity.mjs +169 -0
  370. package/.opencode/plugins/mednotes_hook/adapters/harness_payload.mjs +103 -0
  371. package/.opencode/plugins/mednotes_hook/adapters/opencode_plugin.mjs +341 -0
  372. package/.opencode/plugins/mednotes_hook/adapters/opencode_user_config_sync.mjs +177 -0
  373. package/.opencode/plugins/mednotes_hook/anki_preflight.mjs +214 -0
  374. package/.opencode/plugins/mednotes_hook/cli.mjs +143 -0
  375. package/.opencode/plugins/mednotes_hook/diagnostics.mjs +11 -0
  376. package/.opencode/plugins/mednotes_hook/domain/agent_directive_core.mjs +160 -0
  377. package/.opencode/plugins/mednotes_hook/fsm_directive.mjs +1470 -0
  378. package/.opencode/plugins/mednotes_hook/hook_errors.mjs +120 -0
  379. package/.opencode/plugins/mednotes_hook/retention.mjs +114 -0
  380. package/.opencode/plugins/mednotes_hook/runtime.mjs +174 -0
  381. package/.opencode/plugins/mednotes_hook/telemetry_capture.mjs +511 -0
  382. package/.opencode/plugins/mednotes_hook/vault_guard.mjs +624 -0
  383. package/AGENTS.md +57 -0
  384. package/README.md +194 -0
  385. package/adapters/antigravity/agents.json +80 -0
  386. package/adapters/antigravity/templates/med-chat-triager.md +214 -0
  387. package/adapters/antigravity/templates/med-flashcard-maker.md +72 -0
  388. package/adapters/antigravity/templates/med-knowledge-architect.md +241 -0
  389. package/adapters/antigravity/templates/med-link-graph-curator.md +187 -0
  390. package/adapters/antigravity/templates/med-publish-guard.md +71 -0
  391. package/adapters/gemini-cli/gemini-extension.json +14 -0
  392. package/adapters/gemini-cli/package.json +15 -0
  393. package/adapters/gemini-cli/pyproject.toml +48 -0
  394. package/bin/mednotes-opencode.mjs +155 -0
  395. package/contracts/agents.json +116 -0
  396. package/core/agents/med-chat-triager.md +197 -0
  397. package/core/agents/med-flashcard-maker.md +56 -0
  398. package/core/agents/med-knowledge-architect.md +224 -0
  399. package/core/agents/med-link-graph-curator.md +171 -0
  400. package/core/agents/med-publish-guard.md +55 -0
  401. package/core/commands/flashcards.toml +22 -0
  402. package/core/commands/mednotes/create.toml +22 -0
  403. package/core/commands/mednotes/enrich.toml +24 -0
  404. package/core/commands/mednotes/fix-wiki.toml +24 -0
  405. package/core/commands/mednotes/history.toml +19 -0
  406. package/core/commands/mednotes/link-body.toml +22 -0
  407. package/core/commands/mednotes/link-related.toml +24 -0
  408. package/core/commands/mednotes/link.toml +24 -0
  409. package/core/commands/mednotes/pdf-library.toml +24 -0
  410. package/core/commands/mednotes/process-chats.toml +20 -0
  411. package/core/commands/mednotes/setup.toml +18 -0
  412. package/core/commands/mednotes/status.toml +24 -0
  413. package/core/commands/mednotes/telemetry.toml +24 -0
  414. package/core/commands/report.toml +23 -0
  415. package/core/skills/THIRD_PARTY_NOTICES.md +45 -0
  416. package/core/skills/create-medical-flashcards/SKILL.md +113 -0
  417. package/core/skills/create-medical-note/SKILL.md +90 -0
  418. package/core/skills/enrich-medical-note/SKILL.md +120 -0
  419. package/core/skills/fix-medical-wiki/SKILL.md +559 -0
  420. package/core/skills/link-medical-wiki/SKILL.md +224 -0
  421. package/core/skills/obsidian-cli/SKILL.md +118 -0
  422. package/core/skills/obsidian-markdown/SKILL.md +207 -0
  423. package/core/skills/obsidian-markdown/references/CALLOUTS.md +58 -0
  424. package/core/skills/obsidian-markdown/references/EMBEDS.md +63 -0
  425. package/core/skills/obsidian-markdown/references/PROPERTIES.md +61 -0
  426. package/core/skills/obsidian-ops/SKILL.md +136 -0
  427. package/core/skills/pdf-library/SKILL.md +45 -0
  428. package/core/skills/process-medical-chats/SKILL.md +246 -0
  429. package/core/skills/workflow-report/SKILL.md +100 -0
  430. package/package.json +45 -0
@@ -0,0 +1,989 @@
1
+ """Lightweight extension integrity manifest and runtime drift checks."""
2
+ from __future__ import annotations
3
+
4
+ import difflib
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import time
11
+ from datetime import UTC, datetime
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ INTEGRITY_MANIFEST_SCHEMA = "medical-notes-workbench.extension-integrity-manifest.v1"
16
+ INTEGRITY_STATUS_SCHEMA = "medical-notes-workbench.extension-integrity-status.v1"
17
+ INTEGRITY_CACHE_SCHEMA = "medical-notes-workbench.extension-integrity-cache.v1"
18
+ MANIFEST_FILENAME = "extension-integrity-manifest.json"
19
+ CACHE_FILENAME = "extension-integrity-cache.json"
20
+
21
+ DEFAULT_THROTTLE_SECONDS = 6 * 60 * 60
22
+ DEFAULT_TIMEOUT_SECONDS = 1.0
23
+ MAX_REPORTED_FILES = 24
24
+ MAX_DIFF_FILES = 3
25
+ MAX_DIFF_LINES = 28
26
+ MAX_SAMPLE_CHARS = 420
27
+ MAX_TEXT_BYTES = 128 * 1024
28
+ MAX_EXTENSION_DIFF_FILES = 12
29
+ MAX_EXTENSION_DIFF_CHARS = 96 * 1024
30
+ MAX_GIT_HISTORY_COMMITS = 600
31
+ PROMPT_ENCODING_CORRUPTION_CODE = "extension.prompt_encoding_corruption"
32
+
33
+ MONITORED_EXACT_FILES = {
34
+ "GEMINI.md",
35
+ "gemini-extension.json",
36
+ "package.json",
37
+ "pyproject.toml",
38
+ }
39
+ MONITORED_DIRS = {
40
+ "commands",
41
+ "docs",
42
+ "skills",
43
+ "agents",
44
+ "hooks",
45
+ "policies",
46
+ "mcp",
47
+ "scripts",
48
+ "src",
49
+ }
50
+ MONITORED_SUFFIXES = {
51
+ ".md",
52
+ ".toml",
53
+ ".json",
54
+ ".py",
55
+ ".mjs",
56
+ ".js",
57
+ ".cjs",
58
+ ".sh",
59
+ ".ps1",
60
+ ".cmd",
61
+ ".txt",
62
+ ".yaml",
63
+ ".yml",
64
+ }
65
+ TEXT_SUFFIXES = MONITORED_SUFFIXES | {""}
66
+ EXCLUDED_PARTS = {
67
+ ".git",
68
+ ".venv",
69
+ "__pycache__",
70
+ "node_modules",
71
+ ".mypy_cache",
72
+ ".pytest_cache",
73
+ "dist",
74
+ "feedback",
75
+ "outbox",
76
+ "cache",
77
+ }
78
+ EXCLUDED_NAMES = {
79
+ MANIFEST_FILENAME,
80
+ CACHE_FILENAME,
81
+ ".DS_Store",
82
+ ".env",
83
+ ".telemetry-defaults.json",
84
+ "telemetry.defaults.json",
85
+ "uv.lock",
86
+ }
87
+
88
+ SCRIPT_SUFFIXES = {".py", ".js", ".mjs", ".cjs", ".sh", ".ps1", ".cmd"}
89
+ FULL_DIFF_EXACT_FILES = {"GEMINI.md", "gemini-extension.json", "package.json", "pyproject.toml"}
90
+ FULL_DIFF_PREFIXES = (
91
+ "commands/",
92
+ "docs/",
93
+ "skills/",
94
+ "agents/",
95
+ "hooks/",
96
+ "scripts/",
97
+ "src/",
98
+ )
99
+
100
+ CORRUPTED_CANONICAL_HEADINGS = (
101
+ "Fontes Consolidadas",
102
+ "Notas Relacionadas",
103
+ "Fechamento",
104
+ )
105
+ CORRUPTED_HEADING_RE = re.compile(
106
+ r"(?m)^##\s+\?+\s+(" + "|".join(re.escape(item) for item in CORRUPTED_CANONICAL_HEADINGS) + r")\s*$"
107
+ )
108
+
109
+
110
+ def now_iso() -> str:
111
+ return datetime.now(UTC).replace(microsecond=0).isoformat()
112
+
113
+
114
+ def generate_integrity_manifest(root: str | Path, *, version: str = "") -> dict[str, Any]:
115
+ """Build a manifest for public extension prompts, launchers and scripts."""
116
+ root_path = Path(root).resolve()
117
+ files = []
118
+ for path in _iter_public_files(root_path):
119
+ state = _file_state(path, root_path)
120
+ files.append(
121
+ {
122
+ "path": state["path"],
123
+ "kind": _file_kind(state["path"]),
124
+ "sha256": state["sha256"],
125
+ "normalized_sha256": state.get("normalized_sha256", ""),
126
+ "size_bytes": state["size_bytes"],
127
+ "line_count": state["line_count"],
128
+ }
129
+ )
130
+ files.sort(key=lambda item: item["path"])
131
+ return {
132
+ "schema": INTEGRITY_MANIFEST_SCHEMA,
133
+ "generated_at": now_iso(),
134
+ "app_version": version or "unknown",
135
+ "root_kind": "gemini-cli-extension",
136
+ "file_count": len(files),
137
+ "files": files,
138
+ }
139
+
140
+
141
+ def write_integrity_manifest(root: str | Path, *, output_path: str | Path | None = None, version: str = "") -> Path:
142
+ root_path = Path(root).resolve()
143
+ manifest = generate_integrity_manifest(root_path, version=version)
144
+ target = Path(output_path).resolve() if output_path else root_path / MANIFEST_FILENAME
145
+ target.parent.mkdir(parents=True, exist_ok=True)
146
+ _atomic_write_json(target, manifest)
147
+ return target
148
+
149
+
150
+ def check_extension_integrity(
151
+ *,
152
+ root: str | Path | None = None,
153
+ manifest_path: str | Path | None = None,
154
+ cache_dir: str | Path | None = None,
155
+ include_diff: bool = False,
156
+ force: bool = False,
157
+ throttle_seconds: int = DEFAULT_THROTTLE_SECONDS,
158
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
159
+ ) -> dict[str, Any]:
160
+ """Compare the installed extension with its build-time manifest.
161
+
162
+ The check is intentionally cheap after the first run: it stats expected
163
+ files, reuses cached hashes while size/mtime match, and only scans for
164
+ unexpected files when forced or the throttle window has expired.
165
+ """
166
+ started = time.monotonic()
167
+ resolved_root, resolved_manifest = _resolve_root_and_manifest(root=root, manifest_path=manifest_path)
168
+ if not resolved_root or not resolved_manifest:
169
+ return _skipped_status("manifest_not_found", started=started)
170
+
171
+ cache_path = _cache_path(cache_dir)
172
+ cache = _read_cache(cache_path)
173
+ manifest = _read_manifest(resolved_manifest)
174
+ if not manifest:
175
+ return _skipped_status("manifest_unreadable", started=started, root=resolved_root, manifest_path=resolved_manifest)
176
+
177
+ manifest_hash = _hash_bytes(resolved_manifest.read_bytes())
178
+ expected_files = _manifest_files(manifest)
179
+ cache_fresh = _cache_fresh(cache, manifest_hash=manifest_hash, throttle_seconds=throttle_seconds)
180
+ cached_states = cache.get("file_states") if isinstance(cache.get("file_states"), dict) else {}
181
+ baseline_samples = cache.get("baseline_samples") if isinstance(cache.get("baseline_samples"), dict) else {}
182
+
183
+ modified: list[dict[str, Any]] = []
184
+ missing: list[dict[str, Any]] = []
185
+ unexpected: list[dict[str, Any]] = []
186
+ line_ending_only: list[dict[str, Any]] = []
187
+ encoding_corruption: list[dict[str, Any]] = []
188
+ diff_samples: list[dict[str, Any]] = []
189
+ next_states: dict[str, dict[str, Any]] = {}
190
+ next_baseline_samples = dict(baseline_samples)
191
+ reused_hashes = 0
192
+ hashed_files = 0
193
+ warnings: list[str] = []
194
+
195
+ try:
196
+ for rel, expected in expected_files.items():
197
+ _raise_if_timeout(started, timeout_seconds)
198
+ path = resolved_root / rel
199
+ if not path.is_file():
200
+ missing.append(_missing_entry(expected))
201
+ continue
202
+ stat = path.stat()
203
+ cached_value = cached_states.get(rel)
204
+ cached = cached_value if isinstance(cached_value, dict) else {}
205
+ if _same_state(cached, stat):
206
+ state = dict(cached)
207
+ state.setdefault("path", rel)
208
+ reused_hashes += 1
209
+ else:
210
+ state = _file_state(path, resolved_root, stat=stat)
211
+ hashed_files += 1
212
+ next_states[rel] = state
213
+ if state.get("sha256") == expected.get("sha256"):
214
+ if _is_text_file(path):
215
+ next_baseline_samples[rel] = _sample_text(path)
216
+ continue
217
+ corruption = _encoding_corruption_entry(rel, path)
218
+ if corruption:
219
+ encoding_corruption.append(corruption)
220
+ if _same_normalized_text(state, expected):
221
+ line_ending_only.append(_line_ending_only_entry(expected, state))
222
+ if _is_text_file(path):
223
+ next_baseline_samples[rel] = _sample_text(path)
224
+ continue
225
+ entry = _modified_entry(expected, state)
226
+ modified.append(entry)
227
+ if include_diff and len(diff_samples) < MAX_DIFF_FILES:
228
+ diff_samples.append(_diff_sample(rel, path, baseline_samples.get(rel), entry["kind"]))
229
+
230
+ scan_unexpected = force or not cache_fresh or not cache.get("last_unexpected_scan_at")
231
+ if scan_unexpected:
232
+ for path in _iter_public_files(resolved_root):
233
+ _raise_if_timeout(started, timeout_seconds)
234
+ rel = _relative_path(path, resolved_root)
235
+ if rel in expected_files:
236
+ continue
237
+ state = _file_state(path, resolved_root)
238
+ unexpected.append(_unexpected_entry(state))
239
+ corruption = _encoding_corruption_entry(rel, path)
240
+ if corruption:
241
+ encoding_corruption.append(corruption)
242
+ if include_diff and len(diff_samples) < MAX_DIFF_FILES:
243
+ diff_samples.append(_diff_sample(rel, path, None, state["kind"]))
244
+ else:
245
+ warnings.append("unexpected_file_scan_throttled")
246
+ cached_status = cache.get("status") if isinstance(cache.get("status"), dict) else {}
247
+ unexpected = list(cached_status.get("unexpected_files") or [])
248
+ except TimeoutError:
249
+ status = _status(
250
+ checked=False,
251
+ skipped_reason="integrity_check_skipped_timeout",
252
+ started=started,
253
+ root=resolved_root,
254
+ manifest_path=resolved_manifest,
255
+ manifest=manifest,
256
+ manifest_hash=manifest_hash,
257
+ cache_hit=cache_fresh,
258
+ warnings=["integrity_check_skipped_timeout"],
259
+ )
260
+ _write_cache(
261
+ cache_path,
262
+ {
263
+ **cache,
264
+ "schema": INTEGRITY_CACHE_SCHEMA,
265
+ "checked_at": status["checked_at"],
266
+ "status": status,
267
+ },
268
+ )
269
+ return status
270
+
271
+ summary = {
272
+ "modified_count": len(modified),
273
+ "missing_count": len(missing),
274
+ "unexpected_count": len(unexpected),
275
+ "changed_count": len(modified) + len(missing) + len(unexpected),
276
+ "line_ending_only_count": len(line_ending_only),
277
+ "encoding_corruption_count": len(encoding_corruption),
278
+ "manifest_file_count": len(expected_files),
279
+ "reused_hash_count": reused_hashes,
280
+ "hashed_file_count": hashed_files,
281
+ }
282
+ drift_detected = bool(summary["changed_count"])
283
+ extension_diffs = _extension_diffs(
284
+ resolved_root,
285
+ modified=modified,
286
+ missing=missing,
287
+ unexpected=unexpected,
288
+ ) if include_diff and drift_detected else []
289
+ status = _status(
290
+ checked=True,
291
+ skipped_reason="",
292
+ started=started,
293
+ root=resolved_root,
294
+ manifest_path=resolved_manifest,
295
+ manifest=manifest,
296
+ manifest_hash=manifest_hash,
297
+ cache_hit=cache_fresh and not force and not hashed_files and not drift_detected,
298
+ warnings=warnings,
299
+ summary=summary,
300
+ drift_detected=drift_detected,
301
+ modified_files=modified[:MAX_REPORTED_FILES],
302
+ missing_files=missing[:MAX_REPORTED_FILES],
303
+ unexpected_files=unexpected[:MAX_REPORTED_FILES],
304
+ line_ending_only_files=line_ending_only[:MAX_REPORTED_FILES],
305
+ encoding_corruption_files=encoding_corruption[:MAX_REPORTED_FILES],
306
+ diff_samples=diff_samples,
307
+ extension_diffs=extension_diffs,
308
+ )
309
+ next_cache = {
310
+ "schema": INTEGRITY_CACHE_SCHEMA,
311
+ "root": str(resolved_root),
312
+ "manifest_hash": manifest_hash,
313
+ "checked_at": status["checked_at"],
314
+ "last_unexpected_scan_at": status["checked_at"] if (force or not cache_fresh or not cache.get("last_unexpected_scan_at")) else cache.get("last_unexpected_scan_at"),
315
+ "status": status,
316
+ "file_states": next_states,
317
+ "baseline_samples": next_baseline_samples,
318
+ }
319
+ _write_cache(cache_path, next_cache)
320
+ return status
321
+
322
+
323
+ def safe_check_extension_integrity(**kwargs: Any) -> dict[str, Any]:
324
+ try:
325
+ return check_extension_integrity(**kwargs)
326
+ except Exception as exc:
327
+ return {
328
+ "schema": INTEGRITY_STATUS_SCHEMA,
329
+ "checked": False,
330
+ "checked_at": now_iso(),
331
+ "drift_detected": False,
332
+ "skipped_reason": "integrity_check_failed",
333
+ "error": redact_snippet(str(exc), max_chars=240),
334
+ "summary": {
335
+ "modified_count": 0,
336
+ "missing_count": 0,
337
+ "unexpected_count": 0,
338
+ "changed_count": 0,
339
+ "line_ending_only_count": 0,
340
+ "encoding_corruption_count": 0,
341
+ },
342
+ }
343
+
344
+
345
+ def _iter_public_files(root: Path) -> list[Path]:
346
+ paths: list[Path] = []
347
+ seen: set[Path] = set()
348
+ for rel in MONITORED_EXACT_FILES:
349
+ path = root / rel
350
+ if _is_monitored_file(path, root) and path not in seen:
351
+ seen.add(path)
352
+ paths.append(path)
353
+ for dirname in sorted(MONITORED_DIRS):
354
+ base = root / dirname
355
+ if not base.exists():
356
+ continue
357
+ for path in base.rglob("*"):
358
+ if _is_monitored_file(path, root) and path not in seen:
359
+ seen.add(path)
360
+ paths.append(path)
361
+ return sorted(paths, key=lambda item: _relative_path(item, root))
362
+
363
+
364
+ def _is_monitored_file(path: Path, root: Path) -> bool:
365
+ if not path.is_file():
366
+ return False
367
+ rel = _relative_path(path, root)
368
+ parts = Path(rel).parts
369
+ if (
370
+ not parts
371
+ or any(part in EXCLUDED_PARTS or part.endswith(".egg-info") for part in parts)
372
+ or path.name in EXCLUDED_NAMES
373
+ ):
374
+ return False
375
+ if rel in MONITORED_EXACT_FILES:
376
+ return True
377
+ if parts[0] not in MONITORED_DIRS:
378
+ return False
379
+ return path.suffix.lower() in MONITORED_SUFFIXES
380
+
381
+
382
+ def _file_state(path: Path, root: Path, *, stat: os.stat_result | None = None) -> dict[str, Any]:
383
+ stat = stat or path.stat()
384
+ text = _read_text_sample(path)
385
+ full_text = _read_text(path) if _is_text_file(path) else ""
386
+ return {
387
+ "path": _relative_path(path, root),
388
+ "kind": _file_kind(_relative_path(path, root)),
389
+ "sha256": _hash_file(path),
390
+ "normalized_sha256": _hash_normalized_text(full_text) if full_text else "",
391
+ "size_bytes": int(stat.st_size),
392
+ "mtime_ns": int(stat.st_mtime_ns),
393
+ "line_count": _line_count(path, sample=full_text or text),
394
+ }
395
+
396
+
397
+ def _hash_file(path: Path) -> str:
398
+ digest = hashlib.sha256()
399
+ with path.open("rb") as fh:
400
+ for chunk in iter(lambda: fh.read(1024 * 1024), b""):
401
+ digest.update(chunk)
402
+ return digest.hexdigest()
403
+
404
+
405
+ def _hash_bytes(value: bytes) -> str:
406
+ return hashlib.sha256(value).hexdigest()
407
+
408
+
409
+ def _read_bytes(path: Path) -> bytes:
410
+ try:
411
+ return path.read_bytes()
412
+ except OSError:
413
+ return b""
414
+
415
+
416
+ def _line_count(path: Path, *, sample: str | None = None) -> int:
417
+ if not _is_text_file(path):
418
+ return 0
419
+ try:
420
+ text = sample if sample is not None else path.read_text(encoding="utf-8", errors="replace")
421
+ except OSError:
422
+ return 0
423
+ return text.count("\n") + (1 if text and not text.endswith("\n") else 0)
424
+
425
+
426
+ def _sample_text(path: Path) -> str:
427
+ return redact_snippet(_read_text_sample(path), max_chars=MAX_SAMPLE_CHARS)
428
+
429
+
430
+ def _read_text_sample(path: Path) -> str:
431
+ if not _is_text_file(path):
432
+ return ""
433
+ try:
434
+ with path.open("r", encoding="utf-8", errors="replace") as fh:
435
+ return fh.read(MAX_TEXT_BYTES)
436
+ except OSError:
437
+ return ""
438
+
439
+
440
+ def _read_text(path: Path) -> str:
441
+ if not _is_text_file(path):
442
+ return ""
443
+ try:
444
+ return path.read_text(encoding="utf-8", errors="replace")
445
+ except OSError:
446
+ return ""
447
+
448
+
449
+ def _is_text_file(path: Path) -> bool:
450
+ return path.suffix.lower() in TEXT_SUFFIXES
451
+
452
+
453
+ def _hash_normalized_text(text: str) -> str:
454
+ return _hash_bytes(text.replace("\r\n", "\n").replace("\r", "\n").encode("utf-8"))
455
+
456
+
457
+ def _normalize_line_endings_bytes(value: bytes) -> bytes:
458
+ return value.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
459
+
460
+
461
+ def _same_state(cached: dict[str, Any], stat: os.stat_result) -> bool:
462
+ return bool(
463
+ cached.get("sha256")
464
+ and int(cached.get("size_bytes", -1)) == int(stat.st_size)
465
+ and int(cached.get("mtime_ns", -1)) == int(stat.st_mtime_ns)
466
+ )
467
+
468
+
469
+ def _same_normalized_text(state: dict[str, Any], expected: dict[str, Any]) -> bool:
470
+ expected_normalized = str(expected.get("normalized_sha256") or "")
471
+ actual_normalized = str(state.get("normalized_sha256") or "")
472
+ return bool(expected_normalized and actual_normalized and expected_normalized == actual_normalized)
473
+
474
+
475
+ def _manifest_files(manifest: dict[str, Any]) -> dict[str, dict[str, Any]]:
476
+ files = manifest.get("files")
477
+ if not isinstance(files, list):
478
+ return {}
479
+ result: dict[str, dict[str, Any]] = {}
480
+ for item in files:
481
+ if not isinstance(item, dict) or not item.get("path"):
482
+ continue
483
+ result[str(item["path"])] = item
484
+ return result
485
+
486
+
487
+ def _missing_entry(expected: dict[str, Any]) -> dict[str, Any]:
488
+ return {
489
+ "path": expected.get("path", ""),
490
+ "kind": expected.get("kind") or _file_kind(str(expected.get("path") or "")),
491
+ "expected_sha256": expected.get("sha256", ""),
492
+ "expected_normalized_sha256": expected.get("normalized_sha256", ""),
493
+ "size_bytes": expected.get("size_bytes", 0),
494
+ "line_count": expected.get("line_count", 0),
495
+ }
496
+
497
+
498
+ def _modified_entry(expected: dict[str, Any], state: dict[str, Any]) -> dict[str, Any]:
499
+ return {
500
+ "path": state.get("path", expected.get("path", "")),
501
+ "kind": expected.get("kind") or state.get("kind") or _file_kind(str(state.get("path") or "")),
502
+ "expected_sha256": expected.get("sha256", ""),
503
+ "expected_normalized_sha256": expected.get("normalized_sha256", ""),
504
+ "actual_sha256": state.get("sha256", ""),
505
+ "size_delta": int(state.get("size_bytes", 0)) - int(expected.get("size_bytes", 0)),
506
+ "line_delta": int(state.get("line_count", 0)) - int(expected.get("line_count", 0)),
507
+ }
508
+
509
+
510
+ def _line_ending_only_entry(expected: dict[str, Any], state: dict[str, Any]) -> dict[str, Any]:
511
+ return {
512
+ "path": state.get("path", expected.get("path", "")),
513
+ "kind": expected.get("kind") or state.get("kind") or _file_kind(str(state.get("path") or "")),
514
+ "expected_sha256": expected.get("sha256", ""),
515
+ "actual_sha256": state.get("sha256", ""),
516
+ "normalized_sha256": state.get("normalized_sha256", expected.get("normalized_sha256", "")),
517
+ "size_delta": int(state.get("size_bytes", 0)) - int(expected.get("size_bytes", 0)),
518
+ "line_delta": int(state.get("line_count", 0)) - int(expected.get("line_count", 0)),
519
+ "change": "line_ending_only",
520
+ }
521
+
522
+
523
+ def _unexpected_entry(state: dict[str, Any]) -> dict[str, Any]:
524
+ return {
525
+ "path": state.get("path", ""),
526
+ "kind": state.get("kind", ""),
527
+ "actual_sha256": state.get("sha256", ""),
528
+ "size_bytes": state.get("size_bytes", 0),
529
+ "line_count": state.get("line_count", 0),
530
+ }
531
+
532
+
533
+ def _encoding_corruption_entry(rel: str, path: Path) -> dict[str, Any] | None:
534
+ if not _is_text_file(path):
535
+ return None
536
+ text = _read_text(path)
537
+ matches = [
538
+ {"heading": match.group(1), "line": text[: match.start()].count("\n") + 1}
539
+ for match in CORRUPTED_HEADING_RE.finditer(text)
540
+ ]
541
+ if not matches:
542
+ return None
543
+ return {
544
+ "path": rel,
545
+ "kind": _file_kind(rel),
546
+ "code": PROMPT_ENCODING_CORRUPTION_CODE,
547
+ "matches": matches[:8],
548
+ }
549
+
550
+
551
+ def _diff_sample(rel: str, path: Path, baseline_sample: Any, kind: str) -> dict[str, Any]:
552
+ current = _sample_text(path)
553
+ if not baseline_sample:
554
+ return {
555
+ "path": rel,
556
+ "kind": kind,
557
+ "diff_unavailable_reason": "baseline_not_cached",
558
+ "current_excerpt": current,
559
+ }
560
+ before = str(baseline_sample).splitlines()
561
+ after = current.splitlines()
562
+ lines = list(
563
+ difflib.unified_diff(
564
+ before,
565
+ after,
566
+ fromfile=f"expected/{rel}",
567
+ tofile=f"current/{rel}",
568
+ n=2,
569
+ lineterm="",
570
+ )
571
+ )
572
+ return {
573
+ "path": rel,
574
+ "kind": kind,
575
+ "sample": redact_snippet("\n".join(lines[:MAX_DIFF_LINES]), max_chars=MAX_SAMPLE_CHARS),
576
+ "truncated": len(lines) > MAX_DIFF_LINES,
577
+ }
578
+
579
+
580
+ def _extension_diffs(
581
+ root: Path,
582
+ *,
583
+ modified: list[dict[str, Any]],
584
+ missing: list[dict[str, Any]],
585
+ unexpected: list[dict[str, Any]],
586
+ ) -> list[dict[str, Any]]:
587
+ items: list[tuple[str, dict[str, Any]]] = []
588
+ for change, values in (("modified", modified), ("missing", missing), ("unexpected", unexpected)):
589
+ for item in values:
590
+ rel = str(item.get("path") or "")
591
+ if _allowed_full_diff_path(rel):
592
+ items.append((change, item))
593
+ diffs: list[dict[str, Any]] = []
594
+ has_git = _has_git_worktree(root)
595
+ for change, item in items[:MAX_EXTENSION_DIFF_FILES]:
596
+ rel = str(item.get("path") or "")
597
+ entry = {
598
+ "path": rel,
599
+ "kind": item.get("kind") or _file_kind(rel),
600
+ "change": change,
601
+ }
602
+ patch = ""
603
+ reason = ""
604
+ if has_git and change in {"modified", "missing"}:
605
+ patch = _git_diff(root, rel)
606
+ if not patch:
607
+ reason = "git_diff_empty"
608
+ baseline, baseline_source = _recover_baseline_from_git(root, rel, item)
609
+ if baseline is not None:
610
+ current = b"" if change == "missing" else _read_bytes(root / rel)
611
+ patch = _unified_diff_bytes(baseline, current, fromfile=f"manifest/{rel}", tofile=f"current/{rel}")
612
+ if patch:
613
+ entry["baseline_source"] = baseline_source
614
+ reason = ""
615
+ else:
616
+ entry["baseline_source"] = "git:diff"
617
+ elif not has_git:
618
+ reason = "git_repository_not_available"
619
+ if not patch and has_git and change == "unexpected":
620
+ patch = _new_file_patch(root, rel)
621
+ if not patch:
622
+ reason = reason or "new_file_patch_unavailable"
623
+ else:
624
+ entry["baseline_source"] = "new-file"
625
+ if patch:
626
+ sanitized = redact_operational_text(patch, max_chars=MAX_EXTENSION_DIFF_CHARS)
627
+ entry["patch"] = sanitized
628
+ entry["truncated"] = len(sanitized) < len(patch)
629
+ else:
630
+ entry["full_diff_unavailable_reason"] = reason or "full_diff_unavailable"
631
+ diffs.append(entry)
632
+ if len(items) > MAX_EXTENSION_DIFF_FILES:
633
+ diffs.append(
634
+ {
635
+ "path": "",
636
+ "kind": "summary",
637
+ "change": "truncated",
638
+ "full_diff_unavailable_reason": f"only_first_{MAX_EXTENSION_DIFF_FILES}_diffs_included",
639
+ "omitted_count": len(items) - MAX_EXTENSION_DIFF_FILES,
640
+ }
641
+ )
642
+ return diffs
643
+
644
+
645
+ def _allowed_full_diff_path(rel: str) -> bool:
646
+ rel = rel.replace("\\", "/")
647
+ if rel in FULL_DIFF_EXACT_FILES:
648
+ return True
649
+ return rel.startswith(FULL_DIFF_PREFIXES)
650
+
651
+
652
+ def _git_diff(root: Path, rel: str) -> str:
653
+ try:
654
+ result = subprocess.run(
655
+ ["git", "-C", str(root), "diff", "--no-ext-diff", "--no-color", "--binary", "--", rel],
656
+ text=True,
657
+ capture_output=True,
658
+ check=False,
659
+ timeout=2,
660
+ )
661
+ except (OSError, subprocess.SubprocessError):
662
+ return ""
663
+ if result.returncode not in {0, 1}:
664
+ return ""
665
+ return result.stdout
666
+
667
+
668
+ def _recover_baseline_from_git(root: Path, rel: str, item: dict[str, Any]) -> tuple[bytes | None, str]:
669
+ expected_sha = str(item.get("expected_sha256") or "")
670
+ expected_normalized_sha = str(item.get("expected_normalized_sha256") or "")
671
+ try:
672
+ revs = subprocess.run(
673
+ ["git", "-C", str(root), "rev-list", "--all", "--", rel],
674
+ text=True,
675
+ capture_output=True,
676
+ check=False,
677
+ timeout=4,
678
+ )
679
+ except (OSError, subprocess.SubprocessError):
680
+ return None, ""
681
+ if revs.returncode != 0:
682
+ return None, ""
683
+ commits = [line.strip() for line in revs.stdout.splitlines() if line.strip()]
684
+ for commit in commits[:MAX_GIT_HISTORY_COMMITS]:
685
+ try:
686
+ show = subprocess.run(
687
+ ["git", "-C", str(root), "show", f"{commit}:{rel}"],
688
+ capture_output=True,
689
+ check=False,
690
+ timeout=4,
691
+ )
692
+ except (OSError, subprocess.SubprocessError):
693
+ continue
694
+ if show.returncode != 0:
695
+ continue
696
+ data = show.stdout if isinstance(show.stdout, bytes) else str(show.stdout).encode("utf-8", errors="replace")
697
+ if expected_sha and _hash_bytes(data) == expected_sha:
698
+ return data, f"git:{commit[:12]}"
699
+ if expected_normalized_sha and _hash_bytes(_normalize_line_endings_bytes(data)) == expected_normalized_sha:
700
+ return data, f"git:{commit[:12]}:normalized"
701
+ return None, ""
702
+
703
+
704
+ def _has_git_worktree(root: Path) -> bool:
705
+ try:
706
+ result = subprocess.run(
707
+ ["git", "-C", str(root), "rev-parse", "--is-inside-work-tree"],
708
+ text=True,
709
+ capture_output=True,
710
+ check=False,
711
+ timeout=2,
712
+ )
713
+ except (OSError, subprocess.SubprocessError):
714
+ return False
715
+ return result.returncode == 0 and result.stdout.strip().lower() == "true"
716
+
717
+
718
+ def _new_file_patch(root: Path, rel: str) -> str:
719
+ path = root / rel
720
+ if not path.is_file() or not _is_text_file(path):
721
+ return ""
722
+ data = _read_bytes(path)
723
+ if not data:
724
+ return ""
725
+ return _unified_diff_bytes(b"", data, fromfile="/dev/null", tofile=f"current/{rel}")
726
+
727
+
728
+ def _unified_diff_bytes(old: bytes, new: bytes, *, fromfile: str, tofile: str) -> str:
729
+ if len(old) > MAX_TEXT_BYTES or len(new) > MAX_TEXT_BYTES:
730
+ return ""
731
+ old_text = old.decode("utf-8", errors="replace")
732
+ new_text = new.decode("utf-8", errors="replace")
733
+ lines = list(
734
+ difflib.unified_diff(
735
+ old_text.splitlines(keepends=True),
736
+ new_text.splitlines(keepends=True),
737
+ fromfile=fromfile,
738
+ tofile=tofile,
739
+ )
740
+ )
741
+ return "".join(lines)
742
+
743
+
744
+ def _file_kind(rel: str) -> str:
745
+ path = Path(rel)
746
+ parts = path.parts
747
+ suffix = path.suffix.lower()
748
+ if rel == "GEMINI.md" or (len(parts) >= 2 and parts[0] == "skills" and path.name == "SKILL.md"):
749
+ return "prompt"
750
+ if parts and parts[0] == "commands":
751
+ return "launcher"
752
+ if parts and parts[0] == "docs":
753
+ return "runbook" if len(parts) > 1 and parts[1] == "workflows" else "documentation"
754
+ if suffix in {".py", ".mjs", ".js", ".cjs", ".sh", ".ps1", ".cmd"}:
755
+ return "script"
756
+ if parts and parts[0] in {"agents", "policies", "mcp"}:
757
+ return parts[0][:-1] if parts[0].endswith("s") else parts[0]
758
+ return "metadata"
759
+
760
+
761
+ def _resolve_root_and_manifest(
762
+ *,
763
+ root: str | Path | None,
764
+ manifest_path: str | Path | None,
765
+ ) -> tuple[Path | None, Path | None]:
766
+ if manifest_path:
767
+ manifest = Path(os.path.expandvars(str(manifest_path))).expanduser().resolve()
768
+ return manifest.parent, manifest if manifest.is_file() else None
769
+ if root:
770
+ root_path = Path(os.path.expandvars(str(root))).expanduser().resolve()
771
+ manifest = root_path / MANIFEST_FILENAME
772
+ return root_path, manifest if manifest.is_file() else None
773
+ env_root = os.getenv("MEDNOTES_EXTENSION_ROOT")
774
+ if env_root:
775
+ root_path = Path(os.path.expandvars(env_root)).expanduser().resolve()
776
+ manifest = root_path / MANIFEST_FILENAME
777
+ return root_path, manifest if manifest.is_file() else None
778
+ for start in [Path.cwd(), Path(__file__).resolve()]:
779
+ for parent in [start, *start.parents]:
780
+ manifest = parent / MANIFEST_FILENAME
781
+ if manifest.is_file():
782
+ return parent, manifest
783
+ return None, None
784
+
785
+
786
+ def _cache_path(cache_dir: str | Path | None) -> Path | None:
787
+ if not cache_dir:
788
+ return None
789
+ return Path(os.path.expandvars(str(cache_dir))).expanduser() / CACHE_FILENAME
790
+
791
+
792
+ def _read_manifest(path: Path) -> dict[str, Any] | None:
793
+ try:
794
+ data = json.loads(path.read_text(encoding="utf-8"))
795
+ except (OSError, json.JSONDecodeError):
796
+ return None
797
+ if not isinstance(data, dict) or data.get("schema") != INTEGRITY_MANIFEST_SCHEMA:
798
+ return None
799
+ return data
800
+
801
+
802
+ def _read_cache(path: Path | None) -> dict[str, Any]:
803
+ if not path or not path.exists():
804
+ return {}
805
+ try:
806
+ data = json.loads(path.read_text(encoding="utf-8"))
807
+ except (OSError, json.JSONDecodeError):
808
+ return {}
809
+ return data if isinstance(data, dict) else {}
810
+
811
+
812
+ def _write_cache(path: Path | None, data: dict[str, Any] | None = None, *, status: dict[str, Any] | None = None) -> None:
813
+ if not path:
814
+ return
815
+ path.parent.mkdir(parents=True, exist_ok=True)
816
+ payload = data or {"schema": INTEGRITY_CACHE_SCHEMA, "checked_at": now_iso(), "status": status or {}}
817
+ _atomic_write_json(path, payload)
818
+
819
+
820
+ def _cache_fresh(cache: dict[str, Any], *, manifest_hash: str, throttle_seconds: int) -> bool:
821
+ if cache.get("manifest_hash") != manifest_hash:
822
+ return False
823
+ checked_at = _parse_time(str(cache.get("checked_at") or ""))
824
+ if checked_at <= 0:
825
+ return False
826
+ return time.time() - checked_at < max(0, throttle_seconds)
827
+
828
+
829
+ def _parse_time(value: str) -> float:
830
+ try:
831
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
832
+ except ValueError:
833
+ return 0
834
+ return parsed.timestamp()
835
+
836
+
837
+ def _status(
838
+ *,
839
+ checked: bool,
840
+ skipped_reason: str,
841
+ started: float,
842
+ root: Path | None = None,
843
+ manifest_path: Path | None = None,
844
+ manifest: dict[str, Any] | None = None,
845
+ manifest_hash: str = "",
846
+ cache_hit: bool = False,
847
+ warnings: list[str] | None = None,
848
+ summary: dict[str, Any] | None = None,
849
+ drift_detected: bool = False,
850
+ modified_files: list[dict[str, Any]] | None = None,
851
+ missing_files: list[dict[str, Any]] | None = None,
852
+ unexpected_files: list[dict[str, Any]] | None = None,
853
+ line_ending_only_files: list[dict[str, Any]] | None = None,
854
+ encoding_corruption_files: list[dict[str, Any]] | None = None,
855
+ diff_samples: list[dict[str, Any]] | None = None,
856
+ extension_diffs: list[dict[str, Any]] | None = None,
857
+ ) -> dict[str, Any]:
858
+ manifest = manifest or {}
859
+ summary = summary or {
860
+ "modified_count": 0,
861
+ "missing_count": 0,
862
+ "unexpected_count": 0,
863
+ "changed_count": 0,
864
+ "line_ending_only_count": 0,
865
+ "encoding_corruption_count": 0,
866
+ "manifest_file_count": manifest.get("file_count", 0),
867
+ "reused_hash_count": 0,
868
+ "hashed_file_count": 0,
869
+ }
870
+ encoding_files = encoding_corruption_files or []
871
+ status_warnings = list(warnings or [])
872
+ if encoding_files and PROMPT_ENCODING_CORRUPTION_CODE not in status_warnings:
873
+ status_warnings.append(PROMPT_ENCODING_CORRUPTION_CODE)
874
+ return {
875
+ "schema": INTEGRITY_STATUS_SCHEMA,
876
+ "checked": checked,
877
+ "checked_at": now_iso(),
878
+ "skipped_reason": skipped_reason,
879
+ "drift_detected": drift_detected,
880
+ "cache_hit": cache_hit,
881
+ "elapsed_ms": int((time.monotonic() - started) * 1000),
882
+ "root_label": _path_label(root) if root else "",
883
+ "manifest_path": _path_label(manifest_path) if manifest_path else "",
884
+ "manifest_hash": manifest_hash,
885
+ "manifest_generated_at": manifest.get("generated_at", ""),
886
+ "app_version": manifest.get("app_version", "unknown"),
887
+ "summary": summary,
888
+ "modified_files": modified_files or [],
889
+ "missing_files": missing_files or [],
890
+ "unexpected_files": unexpected_files or [],
891
+ "line_ending_only_files": line_ending_only_files or [],
892
+ "encoding_corruption_files": encoding_files,
893
+ "diff_samples": diff_samples or [],
894
+ "extension_diffs": extension_diffs or [],
895
+ "warnings": status_warnings,
896
+ }
897
+
898
+
899
+ def _skipped_status(
900
+ reason: str,
901
+ *,
902
+ started: float,
903
+ root: Path | None = None,
904
+ manifest_path: Path | None = None,
905
+ ) -> dict[str, Any]:
906
+ return _status(
907
+ checked=False,
908
+ skipped_reason=reason,
909
+ started=started,
910
+ root=root,
911
+ manifest_path=manifest_path,
912
+ warnings=[reason],
913
+ )
914
+
915
+
916
+ def _raise_if_timeout(started: float, timeout_seconds: float) -> None:
917
+ if timeout_seconds > 0 and time.monotonic() - started > timeout_seconds:
918
+ raise TimeoutError
919
+
920
+
921
+ def _relative_path(path: Path, root: Path) -> str:
922
+ return path.resolve().relative_to(root.resolve()).as_posix()
923
+
924
+
925
+ def _path_label(path: Path | None) -> str:
926
+ if not path:
927
+ return ""
928
+ text = str(path)
929
+ home = str(Path.home())
930
+ if text.startswith(home):
931
+ return "~" + text[len(home):]
932
+ parts = path.parts
933
+ if len(parts) > 4:
934
+ return "/".join(parts[-4:])
935
+ return text
936
+
937
+
938
+ def redact_snippet(value: Any, *, max_chars: int = MAX_SAMPLE_CHARS) -> str:
939
+ text = str(value)
940
+ text = re.sub(r"```.*?```", "[code omitted]", text, flags=re.DOTALL)
941
+ text = _redact_sensitive_operational_text(text)
942
+ text = re.sub(r"\s+", " ", text).strip()
943
+ if len(text) > max_chars:
944
+ return text[: max_chars - 3].rstrip() + "..."
945
+ return text
946
+
947
+
948
+ def redact_operational_text(value: Any, *, max_chars: int = MAX_EXTENSION_DIFF_CHARS) -> str:
949
+ text = _redact_sensitive_operational_text(str(value))
950
+ if len(text) > max_chars:
951
+ return text[: max_chars - 3].rstrip() + "..."
952
+ return text
953
+
954
+
955
+ def _redact_sensitive_operational_text(text: str) -> str:
956
+ text = re.sub(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", "[email]", text)
957
+ text = re.sub(
958
+ r"(?i)\b(api[_-]?key|token|secret|password|authorization|bearer)(\s*[:=]\s*)([\"']?)[^\s\"']+",
959
+ r"\1\2[redacted]",
960
+ text,
961
+ )
962
+ text = re.sub(
963
+ r"(?i)(--(?:api-key|auth-token|token|secret|password)\s+)([^\s\"']+)",
964
+ r"\1[redacted]",
965
+ text,
966
+ )
967
+ text = re.sub(r"https?://[^\s)>\"]+", lambda match: _redact_url(match.group(0)), text)
968
+ text = re.sub(r"\b[A-Za-z0-9_=-]{36,}\b", "[redacted-token]", text)
969
+ return re.sub(r"(?<!\w)/(?:Users|home|private|tmp|var|Volumes)/[^\s\"')]+", lambda m: _short_path(m.group(0)), text)
970
+
971
+
972
+ def _redact_url(url: str) -> str:
973
+ if "?" not in url:
974
+ return url
975
+ head, _query = url.split("?", 1)
976
+ return f"{head}?[redacted]"
977
+
978
+
979
+ def _short_path(value: str) -> str:
980
+ parts = Path(value).parts
981
+ if len(parts) <= 3:
982
+ return value
983
+ return "/.../" + "/".join(parts[-3:])
984
+
985
+
986
+ def _atomic_write_json(path: Path, data: dict[str, Any]) -> None:
987
+ tmp = path.with_suffix(path.suffix + ".tmp")
988
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
989
+ tmp.replace(path)