@yasaswy.nagavolu/agents 0.16.3 → 0.16.5

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 (59) hide show
  1. package/content/agents/idea-agent/council_fanout.py +6 -6
  2. package/content/agents/plan-agent/plan_council_fanout.py +5 -5
  3. package/content/agents/review-agent/review_council_fanout.py +6 -6
  4. package/content/agents/review-agent/visual_diagnosis.py +4 -17
  5. package/content/agents/scribe-agent/scribe_runner.py +4 -1
  6. package/content/agents/visual-review-council/triage_gate.py +4 -9
  7. package/content/agents/visual-review-council/visual_diagnosis.py +4 -17
  8. package/content/global/CLAUDE.md +2 -0
  9. package/content/global/rules/terraform.md +20 -0
  10. package/content/hooks/conclusion-scribe/README.md +4 -1
  11. package/content/hooks/conclusion-scribe/conclusion_scribe_hook.py +63 -235
  12. package/content/hooks/conclusion-scribe/test_conclusion_scribe_hook.py +13 -7
  13. package/content/hooks/tracker_proof_gate.py +201 -0
  14. package/content/manifest.json +103 -17
  15. package/content/proxy/README.md +38 -0
  16. package/content/proxy/agents_env.py +60 -8
  17. package/content/proxy/bg_process_reaper_hook.py +77 -0
  18. package/content/proxy/bg_process_register_hook.py +68 -0
  19. package/content/proxy/bg_process_registry.py +299 -0
  20. package/content/proxy/gitlab_mutation_guard.py +121 -0
  21. package/content/proxy/html_mocker_monitor_guard.py +10 -2
  22. package/content/proxy/html_mocker_subagent_guard.py +14 -10
  23. package/content/proxy/litellm/docker-compose.yml +48 -0
  24. package/content/proxy/litellm/litellm_status.ps1 +81 -56
  25. package/content/proxy/litellm/start-docker.ps1 +76 -0
  26. package/content/proxy/portal/aggregator.py +283 -1
  27. package/content/proxy/portal/portal.html +331 -2
  28. package/content/proxy/prd_closing_gate.py +231 -0
  29. package/content/proxy/project_resolver.py +280 -0
  30. package/content/scripts/gitlab_api.py +57 -22
  31. package/content/scripts/item.py +4 -1
  32. package/content/scripts/prd_registry.py +146 -0
  33. package/content/skills/README.md +4 -0
  34. package/content/skills/html-mocker/SKILL.md +1 -1
  35. package/content/skills/html-mocker/mocker.py +53 -1
  36. package/content/skills/html-mocker/tests/test_mocker_server.py +75 -0
  37. package/content/skills/mattpocock-codebase-design/DESIGN-IT-TWICE.md +1 -1
  38. package/content/skills/mattpocock-grilling/SKILL.md +14 -4
  39. package/content/skills/mattpocock-grilling/agents/openai.yaml +1 -1
  40. package/content/skills/mattpocock-improve-codebase-architecture/SKILL.md +1 -1
  41. package/content/skills/mattpocock-tdd/SKILL.md +2 -0
  42. package/content/skills/mattpocock-to-spec/SKILL.md +2 -2
  43. package/content/skills/mattpocock-to-tickets/SKILL.md +8 -6
  44. package/content/skills/mattpocock-to-tickets/gitlab_phase.py +163 -0
  45. package/content/skills/mattpocock-to-tickets/tests/test_gitlab_phase.py +178 -0
  46. package/content/skills/mattpocock-wait-what/SKILL.md +7 -0
  47. package/content/skills/mattpocock-wait-what/agents/openai.yaml +5 -0
  48. package/content/skills/mattpocock-wayfinder/SKILL.md +10 -10
  49. package/content/skills/publish-article/SKILL.md +16 -5
  50. package/content/skills/publish-article/lint_article.py +128 -33
  51. package/content/skills/publish-article/publish_article.py +49 -14
  52. package/content/skills/publish-article/tests/test_lint_article.py +98 -0
  53. package/content/skills/publish-article/tests/{test_lint_markets.py → test_lint_investing.py} +43 -43
  54. package/content/skills/publish-article/tests/test_publish_article.py +76 -16
  55. package/content/skills/ship-the-code/SKILL.md +1 -1
  56. package/content/skills/ship-the-code/ship.py +11 -34
  57. package/content/skills/ship-the-code/tests/test_ship.py +6 -6
  58. package/lib/agentsEnv.js +59 -5
  59. package/package.json +1 -1
@@ -84,7 +84,7 @@ def build_prompt(goal, context):
84
84
  return PANEL_PROMPT_NO_CONTEXT.format(goal=goal)
85
85
 
86
86
 
87
- def call_litellm(prompt, key, model, max_tokens=2000):
87
+ def call_litellm(prompt, key, model, max_tokens=4000):
88
88
  url = "http://127.0.0.1:4000/chat/completions"
89
89
  body = json.dumps({
90
90
  "model": model,
@@ -120,7 +120,7 @@ def call_litellm(prompt, key, model, max_tokens=2000):
120
120
  return PanelResult.failure(model, e, time.monotonic() - start)
121
121
 
122
122
 
123
- def call_litellm_stream(prompt, key, model, max_tokens=2000):
123
+ def call_litellm_stream(prompt, key, model, max_tokens=4000):
124
124
  """Streaming variant required by models whose upstream rejects non-streaming
125
125
  (e.g. litellm_qwen via Together AI). Accumulates delta.content chunks."""
126
126
  url = "http://127.0.0.1:4000/chat/completions"
@@ -194,10 +194,10 @@ def main():
194
194
  ])
195
195
 
196
196
  with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
197
- f_gemini = ex.submit(call_litellm, prompt, or_key, GEMINI_MODEL, 4000)
198
- f_deepseek = ex.submit(call_litellm, prompt, or_key, DEEPSEEK_MODEL, 6000)
199
- f_qwen = ex.submit(call_litellm_stream, prompt, or_key, QWEN_MODEL, 4000)
200
- f_glm = ex.submit(call_litellm, prompt, or_key, GLM_MODEL, 4000)
197
+ f_gemini = ex.submit(call_litellm, prompt, or_key, GEMINI_MODEL, 8000)
198
+ f_deepseek = ex.submit(call_litellm, prompt, or_key, DEEPSEEK_MODEL, 12000)
199
+ f_qwen = ex.submit(call_litellm_stream, prompt, or_key, QWEN_MODEL, 8000)
200
+ f_glm = ex.submit(call_litellm, prompt, or_key, GLM_MODEL, 8000)
201
201
 
202
202
  render_and_exit([f_gemini.result(), f_deepseek.result(), f_qwen.result(), f_glm.result()])
203
203
 
@@ -88,7 +88,7 @@ def build_prompt(goal, context):
88
88
  return PANEL_PROMPT_NO_CONTEXT.format(goal=goal)
89
89
 
90
90
 
91
- def call_litellm(prompt, key, model, max_tokens=3000):
91
+ def call_litellm(prompt, key, model, max_tokens=6000):
92
92
  url = "http://127.0.0.1:4000/chat/completions"
93
93
  body = json.dumps({
94
94
  "model": model,
@@ -161,10 +161,10 @@ def main():
161
161
  ])
162
162
 
163
163
  with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
164
- f_gemini = ex.submit(call_litellm, prompt, or_key, GEMINI_MODEL, 3000)
165
- f_deepseek = ex.submit(call_litellm, prompt, or_key, DEEPSEEK_MODEL, 4000)
166
- f_qwen = ex.submit(call_litellm, prompt, or_key, QWEN_MODEL, 3000)
167
- f_glm = ex.submit(call_litellm, prompt, or_key, GLM_MODEL, 3000)
164
+ f_gemini = ex.submit(call_litellm, prompt, or_key, GEMINI_MODEL, 6000)
165
+ f_deepseek = ex.submit(call_litellm, prompt, or_key, DEEPSEEK_MODEL, 8000)
166
+ f_qwen = ex.submit(call_litellm, prompt, or_key, QWEN_MODEL, 6000)
167
+ f_glm = ex.submit(call_litellm, prompt, or_key, GLM_MODEL, 6000)
168
168
 
169
169
  render_and_exit([f_gemini.result(), f_deepseek.result(), f_qwen.result(), f_glm.result()])
170
170
 
@@ -88,7 +88,7 @@ def build_prompt(goal, diff):
88
88
  return PANEL_PROMPT.format(goal=goal, diff=diff)
89
89
 
90
90
 
91
- def call_litellm(prompt, key, model, max_tokens=3000):
91
+ def call_litellm(prompt, key, model, max_tokens=6000):
92
92
  url = "http://127.0.0.1:4000/chat/completions"
93
93
  body = json.dumps({
94
94
  "model": model,
@@ -118,7 +118,7 @@ def call_litellm(prompt, key, model, max_tokens=3000):
118
118
  return PanelResult.failure(model, e, time.monotonic() - start)
119
119
 
120
120
 
121
- def call_litellm_stream(prompt, key, model, max_tokens=2000):
121
+ def call_litellm_stream(prompt, key, model, max_tokens=6000):
122
122
  """Streaming variant required by litellm_qwen (Together AI backend rejects
123
123
  non-streaming requests for this model). Only collects delta.content —
124
124
  reasoning_content (chain-of-thought) is intentionally discarded."""
@@ -204,10 +204,10 @@ def main():
204
204
  ])
205
205
 
206
206
  with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
207
- f_gemini = ex.submit(call_litellm, prompt, litellm_key, GEMINI_MODEL, 3000)
208
- f_deepseek = ex.submit(call_litellm, prompt, litellm_key, DEEPSEEK_MODEL, 4000)
209
- f_qwen = ex.submit(call_litellm_stream, prompt, litellm_key, QWEN_MODEL, 3000)
210
- f_glm = ex.submit(call_litellm, prompt, litellm_key, GLM_MODEL, 3000)
207
+ f_gemini = ex.submit(call_litellm, prompt, litellm_key, GEMINI_MODEL, 6000)
208
+ f_deepseek = ex.submit(call_litellm, prompt, litellm_key, DEEPSEEK_MODEL, 8000)
209
+ f_qwen = ex.submit(call_litellm_stream, prompt, litellm_key, QWEN_MODEL, 6000)
210
+ f_glm = ex.submit(call_litellm, prompt, litellm_key, GLM_MODEL, 6000)
211
211
 
212
212
  render_and_exit([f_gemini.result(), f_deepseek.result(), f_qwen.result(), f_glm.result()])
213
213
 
@@ -48,6 +48,9 @@ except Exception:
48
48
  sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
49
49
  from council_common import preflight_proxy # noqa: E402
50
50
 
51
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "proxy"))
52
+ from agents_env import get_secret # noqa: E402
53
+
51
54
 
52
55
  def _feed_call(caller, model, status, duration, usage=None, error=None):
53
56
  try:
@@ -61,21 +64,6 @@ def _feed_call(caller, model, status, duration, usage=None, error=None):
61
64
  # Helpers
62
65
  # ---------------------------------------------------------------------------
63
66
 
64
- def load_env_file(env_path: str) -> dict[str, str]:
65
- """Parse KEY=VALUE lines from an env file."""
66
- env: dict[str, str] = {}
67
- try:
68
- for line in Path(env_path).read_text(encoding="utf-8").splitlines():
69
- line = line.strip()
70
- if not line or line.startswith("#") or "=" not in line:
71
- continue
72
- k, _, v = line.partition("=")
73
- env[k.strip()] = v.strip().strip('"').strip("'")
74
- except Exception:
75
- pass
76
- return env
77
-
78
-
79
67
  def load_settings_key(settings_path: str, key: str) -> str | None:
80
68
  """Read a key from ~/.claude/settings.json env block."""
81
69
  try:
@@ -377,8 +365,7 @@ def main() -> None:
377
365
  print(f"DIAGNOSIS_BLOCKED: {down_reason}")
378
366
  sys.exit(1)
379
367
 
380
- env = load_env_file(args.env_file)
381
- gitlab_token = env.get("GITLAB_TOKEN")
368
+ gitlab_token = get_secret("GITLAB_TOKEN", project_root=Path(args.env_file).resolve().parent)
382
369
 
383
370
  # 2. Load item — get gitlab_issue_iid
384
371
  item = find_item(args.items, item_id)
@@ -37,6 +37,9 @@ try:
37
37
  except Exception:
38
38
  _log_call = None
39
39
 
40
+ sys.path.insert(0, str(_AGENT_DIR.parent.parent / "proxy"))
41
+ from agents_env import get_secret # noqa: E402
42
+
40
43
 
41
44
  def _feed_call(model, status, duration, usage=None, error=None):
42
45
  try:
@@ -553,7 +556,7 @@ def call_qwen(prompt: str, key: str, max_tokens: int = 1000) -> str:
553
556
  # ── Main ──────────────────────────────────────────────────────────────────────
554
557
 
555
558
  def main():
556
- token = os.environ.get("GITLAB_TOKEN", "")
559
+ token = get_secret("GITLAB_TOKEN", default="", project_root=Path.cwd())
557
560
  key = os.environ.get("LITELLM_MASTER_KEY", "")
558
561
 
559
562
  if not token:
@@ -42,6 +42,8 @@ import urllib.parse
42
42
  import urllib.request
43
43
  from pathlib import Path
44
44
 
45
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "proxy"))
46
+ from agents_env import get_secret # noqa: E402
45
47
 
46
48
  HERE = Path(__file__).resolve().parent
47
49
  DIAGNOSIS_SCRIPT = HERE / "visual_diagnosis.py"
@@ -194,15 +196,8 @@ def _updated_at_epoch(item: dict) -> float:
194
196
  return 0.0
195
197
 
196
198
 
197
- def load_gitlab_token(cwd: Path, env_file: str = ".env") -> str | None:
198
- try:
199
- for line in (cwd / env_file).read_text(encoding="utf-8").splitlines():
200
- line = line.strip()
201
- if line.startswith("GITLAB_TOKEN="):
202
- return line.partition("=")[2].strip().strip('"').strip("'")
203
- except Exception:
204
- pass
205
- return None
199
+ def load_gitlab_token(cwd: Path) -> str | None:
200
+ return get_secret("GITLAB_TOKEN", project_root=cwd)
206
201
 
207
202
 
208
203
  def discover_project_slug(cwd: Path) -> str:
@@ -48,6 +48,9 @@ except Exception:
48
48
  sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
49
49
  from council_common import preflight_proxy # noqa: E402
50
50
 
51
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "proxy"))
52
+ from agents_env import get_secret # noqa: E402
53
+
51
54
 
52
55
  def _feed_call(caller, model, status, duration, usage=None, error=None):
53
56
  try:
@@ -61,21 +64,6 @@ def _feed_call(caller, model, status, duration, usage=None, error=None):
61
64
  # Helpers
62
65
  # ---------------------------------------------------------------------------
63
66
 
64
- def load_env_file(env_path: str) -> dict[str, str]:
65
- """Parse KEY=VALUE lines from an env file."""
66
- env: dict[str, str] = {}
67
- try:
68
- for line in Path(env_path).read_text(encoding="utf-8").splitlines():
69
- line = line.strip()
70
- if not line or line.startswith("#") or "=" not in line:
71
- continue
72
- k, _, v = line.partition("=")
73
- env[k.strip()] = v.strip().strip('"').strip("'")
74
- except Exception:
75
- pass
76
- return env
77
-
78
-
79
67
  def load_settings_key(settings_path: str, key: str) -> str | None:
80
68
  """Read a key from ~/.claude/settings.json env block."""
81
69
  try:
@@ -383,8 +371,7 @@ def main() -> None:
383
371
  print(f"DIAGNOSIS_BLOCKED: {down_reason}")
384
372
  sys.exit(1)
385
373
 
386
- env = load_env_file(args.env_file)
387
- gitlab_token = env.get("GITLAB_TOKEN")
374
+ gitlab_token = get_secret("GITLAB_TOKEN", project_root=Path(args.env_file).resolve().parent)
388
375
 
389
376
  # 2. Load item — get gitlab_issue_iid
390
377
  item = find_item(args.items, item_id)
@@ -33,6 +33,8 @@ At the start of every session, before substantive work, call `mcp__claude_ai_one
33
33
 
34
34
  **Save without asking.** When a session produces an architecture decision, bug fix, new convention, or structural/config change — especially to shared or global harness config, hooks, or any cross-project infrastructure — call `remember()` immediately in the same turn, without asking the user for permission first. Never ask "want me to save this to memory?" as a question; just do it. The only time it's appropriate to ask is genuine scope ambiguity — e.g. uncertainty about whether something is project-specific (`project=` param) or should be global (omit `project=`) — and even then, default to a reasonable guess and only ask if genuinely unclear, don't block on it.
35
35
 
36
+ **Surprise logging.** When investigating already-supposedly-done work and the investigation surfaces a genuine surprise — a fact that contradicts the assumed/documented state, an unflagged gap, a claim that turns out false only after tracing to source — log it to one-brain as BOTH `log_episode` and `remember`, not just one. Applies whether the underlying task succeeds or fails.
37
+
36
38
  ## Codify Over Instruct
37
39
 
38
40
  Prefer code over natural-language rules. Mechanical constraints (paths, formats, naming, validity) belong in hooks/scripts/validators; word instructions are reserved for intent and judgement calls (creative direction, tone, priorities) that code cannot check.
@@ -80,3 +80,23 @@ what the design "should" do. This class of error — stating a wrong-but-plausib
80
80
  mechanism, not just a stale fact — is easy to introduce while fixing one inaccuracy and
81
81
  easy for a fast reviewer to miss, since the sentence itself reads fine; only cross-
82
82
  checking against the literal `Condition` block catches it.
83
+
84
+ ## 7. Never hardcode an account ID as a `variable` default either — a default still ships
85
+
86
+ A `variable "state_bucket_name" { default = "my-agents-tofu-state-<real-account-id>" }`
87
+ block looks like it followed the rules — it IS a variable, not a raw resource literal —
88
+ but the default value still ships verbatim in committed source the moment anyone reads
89
+ the file. "Use a variable" and "don't expose the account ID" are two different
90
+ requirements; satisfying the first doesn't satisfy the second.
91
+
92
+ Prefer deriving the account ID dynamically at apply/init time instead of storing it
93
+ anywhere, literal or default: `aws sts get-caller-identity --query Account --output text`
94
+ in the calling script or CI job, using whatever role/profile is already active in that
95
+ context. Reserve a real (no-default) required variable for cases where the value can't
96
+ be derived from the current identity.
97
+
98
+ The one case dynamic derivation genuinely cannot cover: an ARN needed to *establish* auth
99
+ in the first place — e.g. the role ARN passed to `assume-role-with-web-identity` before
100
+ any AWS credentials exist yet. There is no identity to query at that point, so that value
101
+ has to come from an external source (a CI/CD variable, a local env var) rather than
102
+ `sts get-caller-identity` — don't try to force the dynamic pattern there.
@@ -51,9 +51,12 @@ repos that live outside the scanned root(s).
51
51
  | Key | Meaning |
52
52
  |---|---|
53
53
  | `PROJECT_MAP` | Override/fallback: semicolon-separated `<short-name>=<namespace%2Frepo>` entries for repos NOT under a scanned root (see auto-discovery above). Wins over auto-discovered entries on key conflicts. |
54
- | `GITLAB_TOKEN` / `GITLAB_TOKEN_FILE` | token inline, or a path to a `.env` containing `GITLAB_TOKEN=` |
55
54
  | `ONE_BRAIN_ENV` | path to an env file with `OB_MCP_URL` + `OB_MCP_BEARER_TOKEN` (optional; defaults to `~/.claude/one-brain/recall.env`) |
56
55
 
56
+ `GITLAB_TOKEN` is no longer configured here — it resolves via the shared
57
+ `agents_env.get_secret()` contract (live env var, then `~/.claude/agents.env`,
58
+ then this repo's `.env`). See `proxy/agents_env.py`'s module docstring.
59
+
57
60
  `SCRIBE_HOOK_ROOTS` (env var, not in `conclusion-scribe.env`) overrides the
58
61
  auto-discovery root(s); default `C:\dev`.
59
62
 
@@ -47,10 +47,12 @@ All machine/user-specific values live in ~/.claude/hooks/conclusion-scribe.env
47
47
  (override/fallback only -- repos under SCRIBE_HOOK_ROOTS, default
48
48
  C:\\dev, auto-resolve from their gitlab.com git remote; see
49
49
  _resolve_project_path. PROJECT_MAP wins on key conflicts.)
50
- GITLAB_TOKEN=<token> (or:)
51
- GITLAB_TOKEN_FILE=<path to a .env containing GITLAB_TOKEN=...>
52
50
  ONE_BRAIN_ENV=<path to env with OB_MCP_URL / OB_MCP_BEARER_TOKEN>
53
51
 
52
+ GITLAB_TOKEN is resolved via the shared agents_env.get_secret() contract
53
+ (live env var, then <base>/agents.env, then a project-root .env) rather than
54
+ this file — see agents_env.py's module docstring for the exact order.
55
+
54
56
  Set SCRIBE_HOOK_DRY_RUN=1 to print planned GitLab/one-brain actions to
55
57
  stderr instead of calling out (used by tests) -- the background Haiku
56
58
  subprocess is unaffected by DRY_RUN (no shared-state side effects of its
@@ -83,6 +85,64 @@ import urllib.request
83
85
  from datetime import datetime, timedelta, timezone
84
86
  from pathlib import Path
85
87
 
88
+ # proxy/ is a sibling of hooks/ once deployed (flat-deploys to <target>/hooks/,
89
+ # see manifest.json), but two levels up from this file in the source repo
90
+ # (hooks/conclusion-scribe/). Try both so the import works from either layout;
91
+ # whichever base we find also doubles as the GITLAB_TOKEN project_root tier
92
+ # (my-agents/.env in source, ~/.claude/.env if ever present when deployed).
93
+ # Optional import, same as the call_log import above: the staged public-
94
+ # bundle copy (share/hooks/conclusion-scribe/) has no proxy/ sibling, so a
95
+ # missing proxy tree degrades to a bare os.environ read, never a crash.
96
+ _BASE_ROOT = None
97
+ for _candidate in (Path(__file__).resolve().parent.parent,
98
+ Path(__file__).resolve().parent.parent.parent):
99
+ if (_candidate / "proxy" / "agents_env.py").exists():
100
+ sys.path.insert(0, str(_candidate / "proxy"))
101
+ _BASE_ROOT = _candidate
102
+ break
103
+ try:
104
+ from agents_env import get_secret # noqa: E402
105
+ except ImportError:
106
+ def get_secret(name, default=None, base=None, project_root=None): # noqa: ARG001
107
+ return os.environ.get(name, default)
108
+
109
+ # project_resolver.py (proxy/) is the shared GitLab-slug resolver -- see that
110
+ # module's docstring. Aliased back to this file's original underscored names
111
+ # so every call site below is unchanged; degrades to no-op fallbacks for the
112
+ # staged public-bundle copy, which has no proxy/ sibling (same pattern as the
113
+ # get_secret fallback above).
114
+ try:
115
+ from project_resolver import (
116
+ git_remote_url as _git_remote_url,
117
+ parse_gitlab_slug as _parse_gitlab_slug,
118
+ discover_project_map as _discover_project_map,
119
+ discovered_project_map as _discovered_project_map,
120
+ resolve_project_path as _resolve_project_path,
121
+ merged_project_map as _merged_project_map,
122
+ project_short_name_for_cwd as _project_short_name_for_cwd,
123
+ )
124
+ except ImportError:
125
+ def _git_remote_url(repo_dir): # noqa: ARG001
126
+ return None
127
+
128
+ def _parse_gitlab_slug(url): # noqa: ARG001
129
+ return None
130
+
131
+ def _discover_project_map(root=None): # noqa: ARG001
132
+ return {}
133
+
134
+ def _discovered_project_map(force=False): # noqa: ARG001
135
+ return {}
136
+
137
+ def _resolve_project_path(short_name): # noqa: ARG001
138
+ return None
139
+
140
+ def _merged_project_map():
141
+ return {}
142
+
143
+ def _project_short_name_for_cwd(cwd, merged_map): # noqa: ARG001
144
+ return None
145
+
86
146
  CONFIG_PATH = Path(os.environ.get("SCRIBE_HOOK_CONFIG", "") or
87
147
  (Path.home() / ".claude" / "hooks" / "conclusion-scribe.env"))
88
148
 
@@ -102,210 +162,6 @@ def _load_config() -> dict:
102
162
 
103
163
  _CFG = _load_config()
104
164
 
105
- PROJECT_PATHS = {}
106
- for _pair in _CFG.get("PROJECT_MAP", "").split(";"):
107
- if "=" in _pair:
108
- _repo, _path = _pair.split("=", 1)
109
- PROJECT_PATHS[_repo.strip()] = _path.strip()
110
-
111
- # --- PROJECT_MAP auto-discovery -------------------------------------------
112
- # Scans immediate subdirectories of SCRIBE_HOOK_ROOTS (default C:\dev) for
113
- # gitlab.com remotes so a repo/submodule under those roots resolves without
114
- # any PROJECT_MAP entry. PROJECT_PATHS (parsed above from the static
115
- # PROJECT_MAP env var) remains an override/supplement for repos NOT under a
116
- # scanned root -- it wins on key conflicts. See _resolve_project_path.
117
- GITLAB_SSH_RE = re.compile(r"^git@gitlab\.com:(.+?)(?:\.git)?$")
118
- GITLAB_HTTPS_RE = re.compile(r"^https://gitlab\.com/(.+?)(?:\.git)?$")
119
- GITMODULES_SECTION_RE = re.compile(r'^\[submodule "(.+)"\]$')
120
- GITMODULES_PATH_RE = re.compile(r'^path\s*=\s*(.+)$')
121
- PROJECT_MAP_CACHE_TTL_SECONDS = 24 * 60 * 60
122
-
123
-
124
- def _discovery_roots() -> list[Path]:
125
- raw = os.environ.get("SCRIBE_HOOK_ROOTS", "") or r"C:\dev"
126
- return [Path(p.strip()) for p in raw.split(";") if p.strip()]
127
-
128
-
129
- def _git_remote_url(repo_dir: Path) -> str | None:
130
- try:
131
- proc = subprocess.run(
132
- ["git", "-C", str(repo_dir), "remote", "get-url", "origin"],
133
- capture_output=True, text=True, timeout=5,
134
- )
135
- except Exception:
136
- return None
137
- if proc.returncode != 0:
138
- return None
139
- url = (proc.stdout or "").strip()
140
- return url or None
141
-
142
-
143
- def _parse_gitlab_slug(url: str | None) -> str | None:
144
- if not url:
145
- return None
146
- m = GITLAB_SSH_RE.match(url) or GITLAB_HTTPS_RE.match(url)
147
- if not m:
148
- return None
149
- path = m.group(1).strip("/")
150
- if not path:
151
- return None
152
- return urllib.parse.quote(path, safe="")
153
-
154
-
155
- def _parse_gitmodules(gitmodules_path: Path) -> list[tuple[str, str]]:
156
- """Returns [(submodule_name, path), ...] parsed from a .gitmodules file.
157
- Regex/line-based on purpose -- avoids trusting shell interpolation of
158
- submodule names via `git submodule foreach`."""
159
- try:
160
- text = gitmodules_path.read_text(encoding="utf-8", errors="replace")
161
- except OSError:
162
- return []
163
- entries = []
164
- name = None
165
- sub_path = None
166
- for raw_line in text.splitlines():
167
- line = raw_line.strip()
168
- m = GITMODULES_SECTION_RE.match(line)
169
- if m:
170
- if name and sub_path:
171
- entries.append((name, sub_path))
172
- name, sub_path = m.group(1), None
173
- continue
174
- m = GITMODULES_PATH_RE.match(line)
175
- if m and name:
176
- sub_path = m.group(1).strip()
177
- if name and sub_path:
178
- entries.append((name, sub_path))
179
- return entries
180
-
181
-
182
- def _add_slug(target: dict, key_name: str, slug: str) -> None:
183
- target[key_name] = slug
184
- real_slug = slug.rsplit("%2F", 1)[-1]
185
- target[real_slug] = slug
186
-
187
-
188
- def _discover_project_map(root: str | Path | None = None) -> dict:
189
- """Fail-open: any per-repo error just skips that repo/submodule -- never
190
- raises out of this function."""
191
- result: dict = {}
192
- roots = [Path(root)] if root is not None else _discovery_roots()
193
- for base in roots:
194
- try:
195
- if not base.is_dir():
196
- continue
197
- children = list(base.iterdir())
198
- except Exception:
199
- continue
200
- for child in children:
201
- try:
202
- if not child.is_dir() or not (child / ".git").exists():
203
- continue
204
- except Exception:
205
- continue
206
- try:
207
- slug = _parse_gitlab_slug(_git_remote_url(child))
208
- if slug:
209
- _add_slug(result, child.name, slug)
210
- except Exception:
211
- pass
212
- gitmodules = child / ".gitmodules"
213
- try:
214
- if not gitmodules.is_file():
215
- continue
216
- submodules = _parse_gitmodules(gitmodules)
217
- except Exception:
218
- continue
219
- for sub_name, sub_path in submodules:
220
- try:
221
- sub_slug = _parse_gitlab_slug(_git_remote_url(child / sub_path))
222
- if sub_slug:
223
- _add_slug(result, sub_name, sub_slug)
224
- except Exception:
225
- continue
226
- return result
227
-
228
-
229
- def _project_map_cache_path() -> Path:
230
- override = os.environ.get("SCRIBE_HOOK_PROJECT_MAP_CACHE")
231
- if override:
232
- return Path(override)
233
- return CONFIG_PATH.parent / ".scribe_project_map_cache.json"
234
-
235
-
236
- def _load_project_map_cache() -> dict | None:
237
- try:
238
- data = json.loads(_project_map_cache_path().read_text(encoding="utf-8"))
239
- if isinstance(data, dict) and isinstance(data.get("map"), dict) and "scanned_at" in data:
240
- return data
241
- except Exception:
242
- pass
243
- return None
244
-
245
-
246
- def _save_project_map_cache(discovered: dict) -> None:
247
- try:
248
- path = _project_map_cache_path()
249
- path.parent.mkdir(parents=True, exist_ok=True)
250
- path.write_text(json.dumps({
251
- "scanned_at": datetime.now(timezone.utc).isoformat(),
252
- "map": discovered,
253
- }), encoding="utf-8")
254
- except OSError:
255
- pass
256
-
257
-
258
- def _project_map_cache_is_fresh(cache: dict) -> bool:
259
- try:
260
- scanned_at = datetime.fromisoformat(cache["scanned_at"])
261
- age = datetime.now(timezone.utc) - scanned_at
262
- return age < timedelta(seconds=PROJECT_MAP_CACHE_TTL_SECONDS)
263
- except Exception:
264
- return False
265
-
266
-
267
- def _rescan_project_map() -> dict:
268
- try:
269
- discovered = _discover_project_map()
270
- except Exception:
271
- discovered = None
272
- if discovered is None:
273
- cache = _load_project_map_cache()
274
- return cache["map"] if cache else {}
275
- _save_project_map_cache(discovered)
276
- return discovered
277
-
278
-
279
- def _discovered_project_map(force: bool = False) -> dict:
280
- if not force:
281
- cache = _load_project_map_cache()
282
- if cache and _project_map_cache_is_fresh(cache):
283
- return cache["map"]
284
- return _rescan_project_map()
285
-
286
-
287
- def _resolve_project_path(short_name: str) -> str | None:
288
- """Effective PROJECT_MAP lookup: cache-or-fresh-discovered map, merged
289
- with the static PROJECT_MAP env var (which wins on conflicts, since it
290
- covers repos outside the scanned roots). A miss forces one immediate
291
- rescan so a brand-new clone under a scanned root resolves without
292
- waiting out the cache TTL."""
293
- try:
294
- merged = {**_discovered_project_map(), **PROJECT_PATHS}
295
- if short_name in merged:
296
- return merged[short_name]
297
- merged = {**_discovered_project_map(force=True), **PROJECT_PATHS}
298
- return merged.get(short_name)
299
- except Exception:
300
- return PROJECT_PATHS.get(short_name)
301
-
302
-
303
- def _merged_project_map() -> dict:
304
- try:
305
- return {**_discovered_project_map(), **PROJECT_PATHS}
306
- except Exception:
307
- return dict(PROJECT_PATHS)
308
-
309
165
 
310
166
  # --- detection --------------------------------------------------------------
311
167
  # A real commit SHA is lowercase hex and (with overwhelming probability)
@@ -400,23 +256,6 @@ def _is_conclusive(text: str) -> bool:
400
256
 
401
257
  # --- fact extraction (code only -- no LLM ever authors an identifier) ------
402
258
 
403
- def _project_short_name_for_cwd(cwd: str | None, merged_map: dict) -> str | None:
404
- if not cwd:
405
- return None
406
- try:
407
- slug = _parse_gitlab_slug(_git_remote_url(Path(cwd)))
408
- except Exception:
409
- slug = None
410
- if not slug:
411
- try:
412
- return Path(cwd).name or None
413
- except Exception:
414
- return None
415
- for short, mapped_slug in merged_map.items():
416
- if mapped_slug == slug:
417
- return short
418
- return slug.rsplit("%2F", 1)[-1]
419
-
420
259
 
421
260
  def _head_sha(cwd: str | None) -> str | None:
422
261
  if not cwd:
@@ -677,18 +516,7 @@ def _update_state_entry(key: str, **fields) -> None:
677
516
  # --- GitLab / one-brain filing ----------------------------------------------
678
517
 
679
518
  def _gitlab_token() -> str:
680
- tok = os.environ.get("GITLAB_TOKEN", "") or _CFG.get("GITLAB_TOKEN", "")
681
- if tok:
682
- return tok
683
- token_file = _CFG.get("GITLAB_TOKEN_FILE", "")
684
- if token_file:
685
- try:
686
- for line in Path(token_file).read_text(encoding="utf-8").splitlines():
687
- if line.startswith("GITLAB_TOKEN="):
688
- return line.split("=", 1)[1].strip().strip('"')
689
- except OSError:
690
- pass
691
- return ""
519
+ return get_secret("GITLAB_TOKEN", default="", project_root=_BASE_ROOT) or ""
692
520
 
693
521
 
694
522
  def _post_gitlab_note(issue_ref: str, body: str) -> int | None: