@lsctech/polaris 0.1.0 → 0.1.3

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 (211) hide show
  1. package/dist/cli/adopt-assets.js +187 -0
  2. package/dist/cli/adopt-cognition.js +1 -2
  3. package/dist/cli/adopt-genesis.js +84 -0
  4. package/dist/cli/adopt-instructions.js +1 -2
  5. package/dist/cli/adopt-report.js +67 -0
  6. package/dist/cli/adopt-workspace.js +114 -0
  7. package/dist/cli/adoption-plan.js +11 -0
  8. package/dist/cli/init.js +79 -7
  9. package/dist/workspace/.polaris/roles/analyst.md +38 -0
  10. package/dist/workspace/.polaris/roles/closeout-librarian.md +122 -0
  11. package/dist/workspace/.polaris/roles/cognition-librarian.md +37 -0
  12. package/dist/workspace/.polaris/roles/finalizer.md +45 -0
  13. package/dist/workspace/.polaris/roles/foreman.md +165 -0
  14. package/dist/workspace/.polaris/roles/librarian.md +74 -0
  15. package/dist/workspace/.polaris/roles/worker.md +119 -0
  16. package/dist/workspace/.polaris/session-type +1 -0
  17. package/dist/workspace/.polaris/skills/ROUTING.md +109 -0
  18. package/dist/workspace/.polaris/skills/caveman/SKILL.md +74 -0
  19. package/dist/workspace/.polaris/skills/caveman-compress/scripts/compress.py +272 -0
  20. package/dist/workspace/.polaris/skills/closeout-librarian/POLARIS.md +46 -0
  21. package/dist/workspace/.polaris/skills/closeout-librarian/SKILL.md +59 -0
  22. package/dist/workspace/.polaris/skills/closeout-librarian/chain.md +116 -0
  23. package/dist/workspace/.polaris/skills/closeout-librarian/steps/01-load-cluster-context.md +78 -0
  24. package/dist/workspace/.polaris/skills/closeout-librarian/steps/02-drift-reconciliation.md +157 -0
  25. package/dist/workspace/.polaris/skills/closeout-librarian/steps/03-reconcile-polaris-md.md +93 -0
  26. package/dist/workspace/.polaris/skills/closeout-librarian/steps/04-reconcile-summary-md.md +106 -0
  27. package/dist/workspace/.polaris/skills/closeout-librarian/steps/05-doc-ingestion.md +114 -0
  28. package/dist/workspace/.polaris/skills/closeout-librarian/steps/06-link-validation.md +128 -0
  29. package/dist/workspace/.polaris/skills/closeout-librarian/steps/07-yaml-linking.md +95 -0
  30. package/dist/workspace/.polaris/skills/closeout-librarian/steps/08-librarian-commit.md +119 -0
  31. package/dist/workspace/.polaris/skills/closeout-librarian/steps/09-sealed-result.md +118 -0
  32. package/dist/workspace/.polaris/skills/docs-ingest/SKILL.md +68 -0
  33. package/dist/workspace/.polaris/skills/docs-ingest/chain.json +23 -0
  34. package/dist/workspace/.polaris/skills/docs-ingest/chain.md +149 -0
  35. package/dist/workspace/.polaris/skills/docs-ingest/steps/01-orient-ingest.md +85 -0
  36. package/dist/workspace/.polaris/skills/docs-ingest/steps/02-classify-batch.md +87 -0
  37. package/dist/workspace/.polaris/skills/docs-ingest/steps/03-conflict-check.md +66 -0
  38. package/dist/workspace/.polaris/skills/docs-ingest/steps/04-place-and-link.md +77 -0
  39. package/dist/workspace/.polaris/skills/docs-ingest/steps/05-finalize-ingest.md +49 -0
  40. package/dist/workspace/.polaris/skills/docs-promote/SKILL.md +79 -0
  41. package/dist/workspace/.polaris/skills/docs-promote/chain.json +25 -0
  42. package/dist/workspace/.polaris/skills/docs-promote/chain.md +80 -0
  43. package/dist/workspace/.polaris/skills/docs-promote/steps/01-orient-promote.md +53 -0
  44. package/dist/workspace/.polaris/skills/docs-promote/steps/02-review-candidates.md +51 -0
  45. package/dist/workspace/.polaris/skills/docs-promote/steps/03-read-linked-code.md +50 -0
  46. package/dist/workspace/.polaris/skills/docs-promote/steps/04-conflict-surface.md +65 -0
  47. package/dist/workspace/.polaris/skills/docs-promote/steps/05-await-approval.md +61 -0
  48. package/dist/workspace/.polaris/skills/docs-promote/steps/06-execute-promote-deprecate.md +65 -0
  49. package/dist/workspace/.polaris/skills/docs-promote/steps/07-finalize-promote.md +44 -0
  50. package/dist/workspace/.polaris/skills/polaris-analyze/SKILL.md +94 -0
  51. package/dist/workspace/.polaris/skills/polaris-analyze/chain.json +20 -0
  52. package/dist/workspace/.polaris/skills/polaris-analyze/chain.md +105 -0
  53. package/dist/workspace/.polaris/skills/polaris-analyze/issue-reconciliation.md +149 -0
  54. package/dist/workspace/.polaris/skills/polaris-analyze/issue-template.md +133 -0
  55. package/dist/workspace/.polaris/skills/polaris-analyze/linked-skills/repo-analysis.md +55 -0
  56. package/dist/workspace/.polaris/skills/polaris-analyze/steps/01-fetch-and-orient.md +79 -0
  57. package/dist/workspace/.polaris/skills/polaris-analyze/steps/02-map-affected-code.md +58 -0
  58. package/dist/workspace/.polaris/skills/polaris-analyze/steps/03-assess-issue.md +58 -0
  59. package/dist/workspace/.polaris/skills/polaris-analyze/steps/04-blocker-check.md +60 -0
  60. package/dist/workspace/.polaris/skills/polaris-analyze/steps/05-create-cluster-plan.md +197 -0
  61. package/dist/workspace/.polaris/skills/polaris-analyze/steps/06-final-report.md +60 -0
  62. package/dist/workspace/.polaris/skills/polaris-catalog/SKILL.md +91 -0
  63. package/dist/workspace/.polaris/skills/polaris-catalog/chain.json +22 -0
  64. package/dist/workspace/.polaris/skills/polaris-catalog/chain.md +85 -0
  65. package/dist/workspace/.polaris/skills/polaris-catalog/steps/01-orient-catalog.md +92 -0
  66. package/dist/workspace/.polaris/skills/polaris-catalog/steps/02-reconcile-polaris-md.md +33 -0
  67. package/dist/workspace/.polaris/skills/polaris-catalog/steps/03-reconcile-summary-md.md +70 -0
  68. package/dist/workspace/.polaris/skills/polaris-catalog/steps/04-classify-and-place.md +117 -0
  69. package/dist/workspace/.polaris/skills/polaris-catalog/steps/05-catalog-commit.md +94 -0
  70. package/dist/workspace/.polaris/skills/polaris-medic/SKILL.md +52 -0
  71. package/dist/workspace/.polaris/skills/polaris-medic/chain.md +111 -0
  72. package/dist/workspace/.polaris/skills/polaris-medic/steps/01-orient-medic.md +75 -0
  73. package/dist/workspace/.polaris/skills/polaris-medic/steps/02-diagnose.md +79 -0
  74. package/dist/workspace/.polaris/skills/polaris-medic/steps/03-repair.md +64 -0
  75. package/dist/workspace/.polaris/skills/polaris-medic/steps/04-validate.md +66 -0
  76. package/dist/workspace/.polaris/skills/polaris-medic/steps/05-create-chart.md +85 -0
  77. package/dist/workspace/.polaris/skills/polaris-medic/steps/06-closeout.md +86 -0
  78. package/dist/workspace/.polaris/skills/polaris-reconcile/SKILL.md +75 -0
  79. package/dist/workspace/.polaris/skills/polaris-reconcile/chain.json +20 -0
  80. package/dist/workspace/.polaris/skills/polaris-reconcile/chain.md +67 -0
  81. package/dist/workspace/.polaris/skills/polaris-reconcile/steps/01-orient-reconcile.md +82 -0
  82. package/dist/workspace/.polaris/skills/polaris-reconcile/steps/02-reconcile-polaris-md.md +95 -0
  83. package/dist/workspace/.polaris/skills/polaris-reconcile/steps/03-reconcile-summary-md.md +108 -0
  84. package/dist/workspace/.polaris/skills/polaris-reconcile/steps/04-reconcile-commit.md +88 -0
  85. package/dist/workspace/.polaris/skills/polaris-run/SKILL.md +135 -0
  86. package/dist/workspace/.polaris/skills/polaris-run/chain.json +19 -0
  87. package/dist/workspace/.polaris/skills/polaris-run/chain.md +298 -0
  88. package/dist/workspace/.polaris/skills/polaris-run/execution-adapter.md +34 -0
  89. package/dist/workspace/.polaris/skills/polaris-run/linked-skills/repo-analysis.md +58 -0
  90. package/dist/workspace/.polaris/skills/polaris-run/steps/01-orient-cluster.md +96 -0
  91. package/dist/workspace/.polaris/skills/polaris-run/steps/02-prepare-branch.md +53 -0
  92. package/dist/workspace/.polaris/skills/polaris-run/steps/03-select-child.md +63 -0
  93. package/dist/workspace/.polaris/skills/polaris-run/steps/04-execute-child.md +75 -0
  94. package/dist/workspace/.polaris/skills/polaris-run/steps/05-validate-child.md +57 -0
  95. package/dist/workspace/.polaris/skills/polaris-run/steps/06-commit-and-update-linear.md +74 -0
  96. package/dist/workspace/.polaris/skills/polaris-run/steps/07-decide-continuation.md +89 -0
  97. package/dist/workspace/.polaris/skills/polaris-run/steps/08-closeout-librarian.md +146 -0
  98. package/dist/workspace/.polaris/skills/polaris-run/steps/08-final-delivery.md +91 -0
  99. package/dist/workspace/.polaris/skills/polaris-run/steps/09-final-delivery.md +104 -0
  100. package/dist/workspace/.polaris/skills/polaris-tools/README.md +63 -0
  101. package/dist/workspace/.polaris/skills/polaris-tools/SKILL.md +94 -0
  102. package/dist/workspace/.polaris/skills/polaris-tools/tools.js +191 -0
  103. package/dist/workspace/smartdocs/architecture/.gitkeep +0 -0
  104. package/dist/workspace/smartdocs/audits/.gitkeep +0 -0
  105. package/dist/workspace/smartdocs/decisions/.gitkeep +0 -0
  106. package/dist/workspace/smartdocs/doctrine/active/.gitkeep +0 -0
  107. package/dist/workspace/smartdocs/runtime/.gitkeep +0 -0
  108. package/dist/workspace/smartdocs/specs/active/.gitkeep +0 -0
  109. package/dist/workspace/smartdocs/specs/archive/.gitkeep +0 -0
  110. package/dist/workspace/workspace/.polaris/roles/analyst.md +38 -0
  111. package/dist/workspace/workspace/.polaris/roles/closeout-librarian.md +122 -0
  112. package/dist/workspace/workspace/.polaris/roles/cognition-librarian.md +37 -0
  113. package/dist/workspace/workspace/.polaris/roles/finalizer.md +45 -0
  114. package/dist/workspace/workspace/.polaris/roles/foreman.md +165 -0
  115. package/dist/workspace/workspace/.polaris/roles/librarian.md +74 -0
  116. package/dist/workspace/workspace/.polaris/roles/worker.md +119 -0
  117. package/dist/workspace/workspace/.polaris/session-type +1 -0
  118. package/dist/workspace/workspace/.polaris/skills/ROUTING.md +109 -0
  119. package/dist/workspace/workspace/.polaris/skills/caveman/SKILL.md +74 -0
  120. package/dist/workspace/workspace/.polaris/skills/caveman-compress/scripts/compress.py +272 -0
  121. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/POLARIS.md +46 -0
  122. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/SKILL.md +59 -0
  123. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/chain.md +116 -0
  124. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/01-load-cluster-context.md +78 -0
  125. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/02-drift-reconciliation.md +157 -0
  126. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/03-reconcile-polaris-md.md +93 -0
  127. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/04-reconcile-summary-md.md +106 -0
  128. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/05-doc-ingestion.md +114 -0
  129. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/06-link-validation.md +128 -0
  130. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/07-yaml-linking.md +95 -0
  131. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/08-librarian-commit.md +119 -0
  132. package/dist/workspace/workspace/.polaris/skills/closeout-librarian/steps/09-sealed-result.md +118 -0
  133. package/dist/workspace/workspace/.polaris/skills/docs-ingest/SKILL.md +68 -0
  134. package/dist/workspace/workspace/.polaris/skills/docs-ingest/chain.json +23 -0
  135. package/dist/workspace/workspace/.polaris/skills/docs-ingest/chain.md +149 -0
  136. package/dist/workspace/workspace/.polaris/skills/docs-ingest/steps/01-orient-ingest.md +85 -0
  137. package/dist/workspace/workspace/.polaris/skills/docs-ingest/steps/02-classify-batch.md +87 -0
  138. package/dist/workspace/workspace/.polaris/skills/docs-ingest/steps/03-conflict-check.md +66 -0
  139. package/dist/workspace/workspace/.polaris/skills/docs-ingest/steps/04-place-and-link.md +77 -0
  140. package/dist/workspace/workspace/.polaris/skills/docs-ingest/steps/05-finalize-ingest.md +49 -0
  141. package/dist/workspace/workspace/.polaris/skills/docs-promote/SKILL.md +79 -0
  142. package/dist/workspace/workspace/.polaris/skills/docs-promote/chain.json +25 -0
  143. package/dist/workspace/workspace/.polaris/skills/docs-promote/chain.md +80 -0
  144. package/dist/workspace/workspace/.polaris/skills/docs-promote/steps/01-orient-promote.md +53 -0
  145. package/dist/workspace/workspace/.polaris/skills/docs-promote/steps/02-review-candidates.md +51 -0
  146. package/dist/workspace/workspace/.polaris/skills/docs-promote/steps/03-read-linked-code.md +50 -0
  147. package/dist/workspace/workspace/.polaris/skills/docs-promote/steps/04-conflict-surface.md +65 -0
  148. package/dist/workspace/workspace/.polaris/skills/docs-promote/steps/05-await-approval.md +61 -0
  149. package/dist/workspace/workspace/.polaris/skills/docs-promote/steps/06-execute-promote-deprecate.md +65 -0
  150. package/dist/workspace/workspace/.polaris/skills/docs-promote/steps/07-finalize-promote.md +44 -0
  151. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/SKILL.md +94 -0
  152. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/chain.json +20 -0
  153. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/chain.md +105 -0
  154. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/issue-reconciliation.md +149 -0
  155. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/issue-template.md +133 -0
  156. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/linked-skills/repo-analysis.md +55 -0
  157. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/steps/01-fetch-and-orient.md +79 -0
  158. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/steps/02-map-affected-code.md +58 -0
  159. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/steps/03-assess-issue.md +58 -0
  160. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/steps/04-blocker-check.md +60 -0
  161. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/steps/05-create-cluster-plan.md +197 -0
  162. package/dist/workspace/workspace/.polaris/skills/polaris-analyze/steps/06-final-report.md +60 -0
  163. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/SKILL.md +91 -0
  164. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/chain.json +22 -0
  165. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/chain.md +85 -0
  166. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/steps/01-orient-catalog.md +92 -0
  167. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/steps/02-reconcile-polaris-md.md +33 -0
  168. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/steps/03-reconcile-summary-md.md +70 -0
  169. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/steps/04-classify-and-place.md +117 -0
  170. package/dist/workspace/workspace/.polaris/skills/polaris-catalog/steps/05-catalog-commit.md +94 -0
  171. package/dist/workspace/workspace/.polaris/skills/polaris-medic/SKILL.md +52 -0
  172. package/dist/workspace/workspace/.polaris/skills/polaris-medic/chain.md +111 -0
  173. package/dist/workspace/workspace/.polaris/skills/polaris-medic/steps/01-orient-medic.md +75 -0
  174. package/dist/workspace/workspace/.polaris/skills/polaris-medic/steps/02-diagnose.md +79 -0
  175. package/dist/workspace/workspace/.polaris/skills/polaris-medic/steps/03-repair.md +64 -0
  176. package/dist/workspace/workspace/.polaris/skills/polaris-medic/steps/04-validate.md +66 -0
  177. package/dist/workspace/workspace/.polaris/skills/polaris-medic/steps/05-create-chart.md +85 -0
  178. package/dist/workspace/workspace/.polaris/skills/polaris-medic/steps/06-closeout.md +86 -0
  179. package/dist/workspace/workspace/.polaris/skills/polaris-reconcile/SKILL.md +75 -0
  180. package/dist/workspace/workspace/.polaris/skills/polaris-reconcile/chain.json +20 -0
  181. package/dist/workspace/workspace/.polaris/skills/polaris-reconcile/chain.md +67 -0
  182. package/dist/workspace/workspace/.polaris/skills/polaris-reconcile/steps/01-orient-reconcile.md +82 -0
  183. package/dist/workspace/workspace/.polaris/skills/polaris-reconcile/steps/02-reconcile-polaris-md.md +95 -0
  184. package/dist/workspace/workspace/.polaris/skills/polaris-reconcile/steps/03-reconcile-summary-md.md +108 -0
  185. package/dist/workspace/workspace/.polaris/skills/polaris-reconcile/steps/04-reconcile-commit.md +88 -0
  186. package/dist/workspace/workspace/.polaris/skills/polaris-run/SKILL.md +135 -0
  187. package/dist/workspace/workspace/.polaris/skills/polaris-run/chain.json +19 -0
  188. package/dist/workspace/workspace/.polaris/skills/polaris-run/chain.md +298 -0
  189. package/dist/workspace/workspace/.polaris/skills/polaris-run/execution-adapter.md +34 -0
  190. package/dist/workspace/workspace/.polaris/skills/polaris-run/linked-skills/repo-analysis.md +58 -0
  191. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/01-orient-cluster.md +96 -0
  192. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/02-prepare-branch.md +53 -0
  193. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/03-select-child.md +63 -0
  194. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/04-execute-child.md +75 -0
  195. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/05-validate-child.md +57 -0
  196. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/06-commit-and-update-linear.md +74 -0
  197. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/07-decide-continuation.md +89 -0
  198. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/08-closeout-librarian.md +146 -0
  199. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/08-final-delivery.md +91 -0
  200. package/dist/workspace/workspace/.polaris/skills/polaris-run/steps/09-final-delivery.md +104 -0
  201. package/dist/workspace/workspace/.polaris/skills/polaris-tools/README.md +63 -0
  202. package/dist/workspace/workspace/.polaris/skills/polaris-tools/SKILL.md +94 -0
  203. package/dist/workspace/workspace/.polaris/skills/polaris-tools/tools.js +191 -0
  204. package/dist/workspace/workspace/smartdocs/architecture/.gitkeep +0 -0
  205. package/dist/workspace/workspace/smartdocs/audits/.gitkeep +0 -0
  206. package/dist/workspace/workspace/smartdocs/decisions/.gitkeep +0 -0
  207. package/dist/workspace/workspace/smartdocs/doctrine/active/.gitkeep +0 -0
  208. package/dist/workspace/workspace/smartdocs/runtime/.gitkeep +0 -0
  209. package/dist/workspace/workspace/smartdocs/specs/active/.gitkeep +0 -0
  210. package/dist/workspace/workspace/smartdocs/specs/archive/.gitkeep +0 -0
  211. package/package.json +4 -4
@@ -0,0 +1,272 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Caveman Memory Compression Orchestrator
4
+
5
+ Usage:
6
+ python scripts/compress.py <filepath>
7
+ """
8
+
9
+ import os
10
+ import re
11
+ import shutil
12
+ import subprocess
13
+ from pathlib import Path
14
+ from typing import List
15
+
16
+ OUTER_FENCE_REGEX = re.compile(
17
+ r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL
18
+ )
19
+
20
+ # Filenames and paths that almost certainly hold secrets or PII. Compressing
21
+ # them ships raw bytes to the Anthropic API — a third-party data boundary that
22
+ # developers on sensitive codebases cannot cross. detect.py already skips .env
23
+ # by extension, but credentials.md / secrets.txt / ~/.aws/credentials would
24
+ # slip through the natural-language filter. This is a hard refuse before read.
25
+ SENSITIVE_BASENAME_REGEX = re.compile(
26
+ r"(?ix)^("
27
+ r"\.env(\..+)?"
28
+ r"|\.netrc"
29
+ r"|credentials(\..+)?"
30
+ r"|secrets?(\..+)?"
31
+ r"|passwords?(\..+)?"
32
+ r"|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?"
33
+ r"|authorized_keys"
34
+ r"|known_hosts"
35
+ r"|.*\.(pem|key|p12|pfx|crt|cer|jks|keystore|asc|gpg)"
36
+ r")$"
37
+ )
38
+
39
+ SENSITIVE_PATH_COMPONENTS = frozenset({".ssh", ".aws", ".gnupg", ".kube", ".docker"})
40
+
41
+ SENSITIVE_NAME_TOKENS = (
42
+ "secret", "credential", "password", "passwd",
43
+ "apikey", "accesskey", "token", "privatekey",
44
+ )
45
+
46
+
47
+ def is_sensitive_path(filepath: Path) -> bool:
48
+ """Heuristic denylist for files that must never be shipped to a third-party API."""
49
+ name = filepath.name
50
+ if SENSITIVE_BASENAME_REGEX.match(name):
51
+ return True
52
+ lowered_parts = {p.lower() for p in filepath.parts}
53
+ if lowered_parts & SENSITIVE_PATH_COMPONENTS:
54
+ return True
55
+ # Normalize separators so "api-key" and "api_key" both match "apikey".
56
+ lower = re.sub(r"[_\-\s.]", "", name.lower())
57
+ return any(tok in lower for tok in SENSITIVE_NAME_TOKENS)
58
+
59
+
60
+ def strip_llm_wrapper(text: str) -> str:
61
+ """Strip outer ```markdown ... ``` fence when it wraps the entire output."""
62
+ m = OUTER_FENCE_REGEX.match(text)
63
+ if m:
64
+ return m.group(2)
65
+ return text
66
+
67
+ try:
68
+ from .detect import should_compress
69
+ from .validate import validate
70
+ except ImportError:
71
+ import sys
72
+ import os
73
+ sys.path.insert(0, os.path.dirname(__file__))
74
+ from detect import should_compress # type: ignore[no-redef]
75
+ from validate import validate # type: ignore[no-redef]
76
+
77
+ MAX_RETRIES = 2
78
+
79
+
80
+ # ---------- Claude Calls ----------
81
+
82
+
83
+ def call_claude(prompt: str) -> str:
84
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
85
+ if api_key:
86
+ try:
87
+ import anthropic
88
+
89
+ client = anthropic.Anthropic(api_key=api_key)
90
+ msg = client.messages.create(
91
+ model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"),
92
+ max_tokens=8192,
93
+ messages=[{"role": "user", "content": prompt}],
94
+ )
95
+ return strip_llm_wrapper(msg.content[0].text.strip())
96
+ except ImportError:
97
+ pass # anthropic not installed, fall back to CLI
98
+ # Fallback: use claude CLI (handles desktop auth)
99
+ claude_bin = os.environ.get("CLAUDE_BIN") or shutil.which("claude")
100
+ if claude_bin is None:
101
+ raise RuntimeError(
102
+ "Claude CLI not found. Set CLAUDE_BIN to the full path, "
103
+ "or ensure 'claude' is on your PATH."
104
+ )
105
+ print(f"Using Claude CLI: {claude_bin}")
106
+ try:
107
+ result = subprocess.run(
108
+ [claude_bin, "--print"],
109
+ input=prompt,
110
+ text=True,
111
+ capture_output=True,
112
+ check=True,
113
+ timeout=300,
114
+ )
115
+ return strip_llm_wrapper(result.stdout.strip())
116
+ except subprocess.TimeoutExpired as e:
117
+ raise RuntimeError("Claude CLI call timed out after 300 seconds.") from e
118
+ except subprocess.CalledProcessError as e:
119
+ raise RuntimeError(f"Claude call failed:\n{e.stderr}") from e
120
+
121
+
122
+ def build_compress_prompt(original: str) -> str:
123
+ return f"""
124
+ Compress this markdown into caveman format.
125
+
126
+ STRICT RULES:
127
+ - Do NOT modify anything inside ``` code blocks
128
+ - Do NOT modify anything inside inline backticks
129
+ - Preserve ALL URLs exactly
130
+ - Preserve ALL headings exactly
131
+ - Preserve file paths and commands
132
+ - Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file.
133
+
134
+ Only compress natural language.
135
+
136
+ TEXT:
137
+ {original}
138
+ """
139
+
140
+
141
+ def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str:
142
+ errors_str = "\n".join(f"- {e}" for e in errors)
143
+ return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found.
144
+
145
+ CRITICAL RULES:
146
+ - DO NOT recompress or rephrase the file
147
+ - ONLY fix the listed errors — leave everything else exactly as-is
148
+ - The ORIGINAL is provided as reference only (to restore missing content)
149
+ - Preserve caveman style in all untouched sections
150
+
151
+ ERRORS TO FIX:
152
+ {errors_str}
153
+
154
+ HOW TO FIX:
155
+ - Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED
156
+ - Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED
157
+ - Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED
158
+ - Do not touch any section not mentioned in the errors
159
+
160
+ ORIGINAL (reference only):
161
+ {original}
162
+
163
+ COMPRESSED (fix this):
164
+ {compressed}
165
+
166
+ Return ONLY the fixed compressed file. No explanation.
167
+ """
168
+
169
+
170
+ # ---------- Core Logic ----------
171
+
172
+
173
+ def compress_file(filepath: Path) -> bool:
174
+ # Resolve and validate path
175
+ filepath = filepath.resolve()
176
+ MAX_FILE_SIZE = 500_000 # 500KB
177
+ if not filepath.exists():
178
+ raise FileNotFoundError(f"File not found: {filepath}")
179
+ if filepath.stat().st_size > MAX_FILE_SIZE:
180
+ raise ValueError(f"File too large to compress safely (max 500KB): {filepath}")
181
+
182
+ # Refuse files that look like they contain secrets or PII. Compressing ships
183
+ # the raw bytes to the Anthropic API — a third-party boundary — so we fail
184
+ # loudly rather than silently exfiltrate credentials or keys. Override is
185
+ # intentional: the user must rename the file if the heuristic is wrong.
186
+ if is_sensitive_path(filepath):
187
+ raise ValueError(
188
+ f"Refusing to compress {filepath}: filename looks sensitive "
189
+ "(credentials, keys, secrets, or known private paths). "
190
+ "Compression sends file contents to the Anthropic API. "
191
+ "Rename the file if this is a false positive."
192
+ )
193
+
194
+ print(f"Processing: {filepath}")
195
+
196
+ if not should_compress(filepath):
197
+ print("Skipping (not natural language)")
198
+ return False
199
+
200
+ original_text = filepath.read_text(errors="replace")
201
+ backup_path = filepath.with_name(filepath.stem + ".original.md")
202
+
203
+ if not original_text.strip():
204
+ print("❌ Refusing to compress: file is empty or whitespace-only.")
205
+ return False
206
+
207
+ # Check if backup already exists to prevent accidental overwriting
208
+ if backup_path.exists():
209
+ print(f"⚠️ Backup file already exists: {backup_path}")
210
+ print("The original backup may contain important content.")
211
+ print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.")
212
+ return False
213
+
214
+ # Step 1: Compress
215
+ print("Compressing with Claude...")
216
+ compressed = call_claude(build_compress_prompt(original_text))
217
+
218
+ if compressed is None or not compressed.strip():
219
+ print("❌ Compression aborted: Claude returned an empty response.")
220
+ print(" Original file is untouched (no backup created).")
221
+ return False
222
+
223
+ if compressed.strip() == original_text.strip():
224
+ print("❌ Compression aborted: output is identical to input.")
225
+ print(" Likely causes: Claude refused, returned the prompt verbatim, or the file is")
226
+ print(" already in caveman form. Original file is untouched (no backup created).")
227
+ return False
228
+
229
+ # Save original as backup, then verify the backup readback before
230
+ # touching the input file. If the filesystem dropped bytes (encoding,
231
+ # antivirus, disk full), unlink the bad backup and abort instead of
232
+ # leaving the user with a corrupt backup + compressed primary.
233
+ backup_path.write_text(original_text)
234
+ backup_readback = backup_path.read_text(errors="replace")
235
+ if backup_readback != original_text:
236
+ print(f"❌ Backup write verification failed: {backup_path}")
237
+ print(" In-memory original differs from on-disk backup. Aborting before touching the input file.")
238
+ try:
239
+ backup_path.unlink()
240
+ except OSError:
241
+ pass
242
+ return False
243
+ filepath.write_text(compressed)
244
+
245
+ # Step 2: Validate + Retry
246
+ for attempt in range(MAX_RETRIES):
247
+ print(f"\nValidation attempt {attempt + 1}")
248
+
249
+ result = validate(backup_path, filepath)
250
+
251
+ if result.is_valid:
252
+ print("Validation passed")
253
+ break
254
+
255
+ print("❌ Validation failed:")
256
+ for err in result.errors:
257
+ print(f" - {err}")
258
+
259
+ if attempt == MAX_RETRIES - 1:
260
+ # Restore original on failure
261
+ filepath.write_text(original_text)
262
+ backup_path.unlink(missing_ok=True)
263
+ print("❌ Failed after retries — original restored")
264
+ return False
265
+
266
+ print("Fixing with Claude...")
267
+ compressed = call_claude(
268
+ build_fix_prompt(original_text, compressed, result.errors)
269
+ )
270
+ filepath.write_text(compressed)
271
+
272
+ return True
@@ -0,0 +1,46 @@
1
+ # .polaris/skills/closeout-librarian/
2
+
3
+ ## Purpose
4
+
5
+ This directory contains the Closeout Librarian skill package.
6
+
7
+ The Closeout Librarian is a bounded runtime role dispatched by the Foreman exactly once
8
+ per completed cluster, after all children are done and before PR creation.
9
+
10
+ ## Contents
11
+
12
+ | File | Purpose |
13
+ |------|---------|
14
+ | `SKILL.md` | Skill entry point — read first, contains bootloader instructions and packet schema reference |
15
+ | `chain.md` | Step-order execution map — the Librarian executes this in strict step order |
16
+ | `steps/01-load-cluster-context.md` | Build work inventory from packet and cluster evidence |
17
+ | `steps/02-reconcile-polaris-md.md` | Update affected POLARIS.md files |
18
+ | `steps/03-reconcile-summary-md.md` | Refresh SUMMARY.md as continuation artifact |
19
+ | `steps/04-doc-ingestion.md` | Ingest/promote/archive documentation |
20
+ | `steps/05-link-validation.md` | Validate and repair broken links |
21
+ | `steps/06-yaml-linking.md` | Update YAML references for promoted documents |
22
+ | `steps/07-librarian-commit.md` | Commit documentation changes |
23
+ | `steps/08-sealed-result.md` | Write sealed result JSON and terminate |
24
+
25
+ ## Invocation
26
+
27
+ This skill is NOT invoked by user command. It is dispatched by the Foreman during
28
+ step 08 of the `polaris-run` chain after cluster-complete is confirmed.
29
+
30
+ The Foreman generates the packet via:
31
+ ```bash
32
+ npm run polaris -- librarian packet <cluster-id>
33
+ ```
34
+
35
+ Then dispatches the Librarian as a bounded subagent session.
36
+
37
+ ## Authority
38
+
39
+ The Closeout Librarian may update POLARIS.md, SUMMARY.md, ingest documents, and commit
40
+ documentation changes. It may NOT modify source code, runtime state, or create PRs.
41
+
42
+ Full authority boundaries: `.polaris/roles/closeout-librarian.md`
43
+
44
+ ## Spec Reference
45
+
46
+ `smartdocs/specs/active/closeout-librarian-spec.md`
@@ -0,0 +1,59 @@
1
+ ---
2
+ name: closeout-librarian
3
+ description: Reconcile completed cluster work into project cognition and documentation. Runs exactly once per cluster, after all children complete and before PR creation.
4
+ role: closeout-librarian
5
+ role_file: .polaris/roles/closeout-librarian.md
6
+ ---
7
+
8
+ ## Entry Points
9
+
10
+ This skill is invoked by the Foreman as a dispatched session. It is NOT a user-facing command.
11
+
12
+ Invocation: The Foreman dispatches the Closeout Librarian after confirming `cluster-complete` status
13
+ and before running `polaris finalize`. The packet path is passed as the session prompt.
14
+
15
+ ---
16
+
17
+ ## Polaris Skill Bootloader
18
+
19
+ This skill does NOT use the standard Polaris skill bootloader. The Closeout Librarian
20
+ receives its packet directly from the Foreman — the packet is the sole authoritative
21
+ instruction source for this session.
22
+
23
+ The Librarian MUST:
24
+ 1. Read the packet at the path provided in the dispatch prompt.
25
+ 2. Validate the packet schema (role must be `"closeout-librarian"`).
26
+ 3. Execute `chain.md` in strict step order.
27
+ 4. Write the sealed result to `packet.result_path` before the session ends.
28
+
29
+ If the packet cannot be read or fails schema validation, write a failure result immediately
30
+ and terminate. Do not attempt to reconstruct the packet from context.
31
+
32
+ ---
33
+
34
+ ## Authority Reminder
35
+
36
+ The Closeout Librarian may NOT modify implementation code, runtime state, or dispatch
37
+ any workers. Its sole output is documentation/cognition changes + sealed result JSON.
38
+
39
+ Full authority boundaries: `.polaris/roles/closeout-librarian.md`
40
+
41
+ ---
42
+
43
+ ## Packet Schema
44
+
45
+ The packet is a `CloseoutLibrarianPacket`. See:
46
+ - `smartdocs/specs/active/closeout-librarian-spec.md` §3 for full schema
47
+ - `src/cognition/closeout-librarian-types.ts` for TypeScript types
48
+
49
+ Required packet fields: `role`, `run_id`, `dispatch_id`, `cluster_id`,
50
+ `completed_children`, `child_summaries`, `affected_folders`, `polaris_md_paths`,
51
+ `result_path`, `prohibited_write_paths`, `allowed_write_paths`.
52
+
53
+ ---
54
+
55
+ ## Execution
56
+
57
+ Read `chain.md` and execute steps in strict order.
58
+
59
+ Do not skip steps. Do not reorder steps.
@@ -0,0 +1,116 @@
1
+ ---
2
+ name: closeout-librarian-chain
3
+ description: Step-order execution map for the Closeout Librarian. Runs once per completed cluster.
4
+ ---
5
+
6
+ # Closeout Librarian Chain
7
+
8
+ ## Authority
9
+
10
+ **The packet is authoritative. Do not infer cluster scope from conversation context.**
11
+
12
+ Read the packet before any analysis. Execute steps in strict order.
13
+
14
+ ## Scope Contract
15
+
16
+ The Closeout Librarian operates on documentation and cognition only.
17
+
18
+ **Allowed writes:** POLARIS.md, SUMMARY.md (affected folders), smartdocs ingestion targets,
19
+ cognition archive, YAML frontmatter in doc files, sealed result JSON, librarian commit.
20
+
21
+ **Prohibited writes:** Source code, runtime state files, telemetry JSONL, cluster plan,
22
+ Linear issue status, PR creation.
23
+
24
+ ---
25
+
26
+ ## Step Traversal Order
27
+
28
+ ```text
29
+ 01-load-cluster-context ← Read packet, load cluster evidence, build work inventory
30
+ 02-drift-reconciliation ← Run formal drift reconciliation checklist
31
+ 03-reconcile-polaris-md ← Update affected POLARIS.md files to reflect current reality
32
+ 04-reconcile-summary-md ← Refresh SUMMARY.md as continuation artifact
33
+ 05-doc-ingestion ← Ingest/promote/archive documentation from completed work
34
+ 06-link-validation ← Validate and repair broken links across affected docs
35
+ 07-yaml-linking ← Update YAML references for ingested/promoted documents
36
+ 08-librarian-commit ← Commit all documentation changes as sealed librarian commit
37
+ 09-sealed-result ← Write CloseoutLibrarianResult JSON to result_path, terminate
38
+ ```
39
+
40
+ All steps must complete in order. Termination after step 09 is mandatory.
41
+
42
+ ---
43
+
44
+ ## Execution Rules
45
+
46
+ ### Step Gate Behavior
47
+
48
+ - Each step must complete before the next begins.
49
+ - If a step encounters a recoverable error (e.g., one broken link that cannot be repaired),
50
+ record the blocker and continue.
51
+ - If a step encounters a fatal error (e.g., packet unreadable, commit fails), record
52
+ `status: "failure"` in the result and proceed to step 09 (sealed result write).
53
+ - Do not skip to step 09 for recoverable errors — complete the remaining steps.
54
+
55
+ ### Write Discipline
56
+
57
+ Before writing any file, verify it is in `packet.allowed_write_paths`.
58
+ If the target file is in `packet.prohibited_write_paths`, skip and record as blocker.
59
+
60
+ ### Commit Timing
61
+
62
+ All writes occur during steps 03–07. No writes occur during step 08 or after.
63
+ Step 08 creates exactly one git commit containing all documentation changes from this session.
64
+ If no documentation changed (all steps found everything current), step 08 makes no commit.
65
+ The result records `commit_sha: null` in this case — do not create an empty commit.
66
+
67
+ ### Result Timing
68
+
69
+ Step 09 writes the sealed result JSON and terminates. No further writes are permitted after
70
+ the sealed result is written.
71
+
72
+ ---
73
+
74
+ ## Narration Rules
75
+
76
+ The Closeout Librarian does NOT produce user-facing narration during normal execution.
77
+
78
+ **Allowed output:**
79
+ - The sealed result JSON written to `result_path` (step 08)
80
+ - Escalation output if blocked on a decision that requires operator input
81
+
82
+ **Prohibited output:**
83
+ - Step-by-step progress narration
84
+ - Summary of what was found
85
+ - Interim status updates
86
+
87
+ All communication with the Foreman occurs through the sealed result and the commit record.
88
+
89
+ ---
90
+
91
+ ## Telemetry Events
92
+
93
+ Emit the following structured events to the telemetry file (if path provided in packet):
94
+
95
+ | Event | Step | Fields |
96
+ |---|---|---|
97
+ | `librarian-start` | 01 | `run_id`, `cluster_id`, `dispatch_id`, `timestamp` |
98
+ | `librarian-step-complete` | each step | `step`, `run_id`, `timestamp`, `outcome` |
99
+ | `librarian-commit` | 08 | `commit_sha`, `files_changed`, `timestamp` |
100
+ | `librarian-complete` | 09 | `status`, `run_id`, `timestamp` |
101
+
102
+ If no telemetry file is specified in the packet, skip telemetry events silently.
103
+
104
+ ---
105
+
106
+ ## Failure Handling
107
+
108
+ | Condition | Action |
109
+ |---|---|
110
+ | Packet unreadable | Write failure result to `result_path` if possible, otherwise stderr. Terminate. |
111
+ | Packet schema invalid | Write failure result, terminate |
112
+ | POLARIS.md has unresolvable conflict | Record blocker, skip that file, continue |
113
+ | Commit fails | Status: failure, record commit error, proceed to step 09 |
114
+ | Result write fails | Stderr only. Cannot recover. |
115
+ | All blockers, no writes | Status: `"blocked"`, list blockers, commit nothing |
116
+ | Some work done, some blocked | Status: `"partial"`, describe both |
@@ -0,0 +1,78 @@
1
+ ---
2
+ name: closeout-librarian-step-01
3
+ description: Read packet, load cluster evidence, and build the work inventory for this reconciliation session.
4
+ ---
5
+
6
+ # Step 01 — Load Cluster Context
7
+
8
+ ## Purpose
9
+
10
+ Build a complete picture of what the cluster accomplished. This is the foundation for all
11
+ subsequent reconciliation steps. Nothing is written in this step.
12
+
13
+ ## Actions
14
+
15
+ ### 1.1 Read and Validate Packet
16
+
17
+ Read the packet from the path provided in the dispatch prompt.
18
+
19
+ Validate required fields:
20
+ - `role` must be `"closeout-librarian"`
21
+ - `run_id`, `dispatch_id`, `cluster_id` must be present and non-empty
22
+ - `completed_children` must be a non-empty array
23
+ - `result_path` must be present
24
+ - `allowed_write_paths` must be present
25
+
26
+ If validation fails: write a minimal failure result to `result_path` and terminate.
27
+
28
+ ### 1.2 Load Child Summaries
29
+
30
+ For each entry in `packet.child_summaries`:
31
+ 1. Read the compact-return result at `child_summary.compact_return_path` (if present)
32
+ 2. Read the cognition note at `child_summary.cognition_note_path` (if present)
33
+ 3. Note `child_summary.changed_files` — the primary file inventory for this cluster
34
+
35
+ Build a combined `all_changed_files` list (deduplicated) across all children.
36
+
37
+ ### 1.3 Load Folder Cognition Context
38
+
39
+ For each entry in `packet.polaris_md_paths`:
40
+ 1. Read `polaris_md` (current POLARIS.md for this folder)
41
+ 2. Read `summary_md` (current SUMMARY.md, if path provided and file exists)
42
+ 3. Read `cognition_index` (archive index, if path provided and file exists)
43
+
44
+ Note which folders have pending cognition notes (from `packet.cognition_notes`).
45
+
46
+ ### 1.4 Build Work Inventory
47
+
48
+ Produce an internal inventory (not written to disk):
49
+
50
+ ```yaml
51
+ work_inventory:
52
+ cluster_id: <from packet>
53
+ completed_children: [<ids>]
54
+ all_changed_files: [<deduplicated list>]
55
+ affected_folders: [<from packet.affected_folders>]
56
+ pending_cognition_notes: [<paths>]
57
+ docs_candidate_for_ingestion: [<from packet.smartdocs_raw_paths>]
58
+ polaris_md_files: { <folder>: <current content> }
59
+ summary_md_files: { <folder>: <current content or null> }
60
+ ```
61
+
62
+ ### 1.5 Load Run Report
63
+
64
+ Read the run report at `packet.run_report_path` (if present). This provides a structured
65
+ summary of what work was done.
66
+
67
+ ### 1.6 Emit Telemetry
68
+
69
+ Emit `librarian-start` event (if telemetry path provided).
70
+
71
+ ## Completion Criteria
72
+
73
+ - Packet validated
74
+ - All available child summaries loaded
75
+ - All available folder cognition loaded
76
+ - Work inventory built
77
+
78
+ Proceed to step 02.