#!/usr/bin/env bash
# tags: [discovery, session-start, governance]
# description: SessionStart hook. Teaches Claude to surface existing capabilities for free-language intent (instead of silently doing the work), and to escalate to a concrete /new-artifact recommendation when the same uncovered task recurs.
#
# .claude/hooks/capability-awareness.sh
#
# SessionStart hook — injects "capability awareness" instructions into
# Claude's additionalContext.
#
# The problem: docs/capabilities.md exists, but without an instruction
# Claude doesn't proactively scan it when the user describes intent. The
# user ends up unaware of skills/agents/policies that already handle
# what they're asking for, OR Claude silently invokes one without
# announcing — both leave the user under-informed.
#
# The fix: tell Claude to scan the index, surface matches transparently,
# and proactively offer in a narrow set of high-confidence situations.
#
# Distribution: registered in .claude-plugin/hooks/hooks.json, fires in
# every Claude Code session in every repo with the bewith plugin
# installed.
#
# Concurrency: read-only. The hook only emits text. Safe to run in
# parallel sessions.
#
# Exit codes: 0 always.

set -euo pipefail

read -r -d '' GUIDANCE <<'EOF' || true
[bewith capability awareness]

When the user describes intent in FREE LANGUAGE (not invoking a known
skill/command), DO NOT silently do the work yourself before checking
whether an existing capability fits.

Workflow:

1. Scan docs/capabilities.md in the platform plugin (or in the cwd repo
   if it has its own) for a matching artifact — agent, skill, command,
   policy, or hook.

2. If a STRONG match exists, name it and ask before invoking:

     "יש לי <kind> בדיוק לזה — <name>. רוצה שאקרא לו?"
     (or in the user's language)

   Do not silently invoke. Make the user aware of the capability so
   they can use it directly next time.

3. If NO existing capability matches AND the request looks like
   something that will repeat (a workflow, a check, an expert review),
   offer to design something new:

     "אין כיסוי קיים. רוצה שנתכנן artifact חדש דרך /new-artifact?"

REPEATED-REQUEST ESCALATION — a recurring manual task is the strongest
signal an artifact is missing; don't let it stay invisible:

   Notice when, within this session, you do the SAME kind of uncovered
   work more than once, or the user voices friction ("again I'm doing
   this by hand", "why isn't there an X for this", "שוב צריך לעשות את
   זה ידני"). On the second occurrence, escalate from the soft offer in
   step 3 to a CONCRETE recommendation — name the artifact type that
   would cover it and what it would automate:

     "This is the 2nd time we've done <X> by hand — I think it's worth a
      <skill/hook/command>. Want me to author it via /new-artifact?"

PROACTIVE OFFERS — narrow set, high-confidence only:

  - User says a PR is ready / "review my code"        → code-reviewer agent
  - User starts a database migration discussion       → schema-migration policy
  - User touches auth / tokens / RBAC                  → auth-touch policy
  - User scopes a >20-file refactor                    → large-refactor policy
  - User mentions secrets / rotation                   → secret-rotation policy
  - User has a generic insight worth sharing           → /share-rule
  - User wants to author a new artifact                → /new-artifact

CALIBRATION — do not be Clippy.

  - Offer only when intent strongly matches AND the user is unlikely
    to already know about the capability.
  - Don't interrupt mid-flow for trivial things.
  - Don't offer if the user has explicitly signaled they want to do
    it themselves.
  - If unsure, lean toward asking once, not repeating.

The user can also discover capabilities explicitly via /help-me <description>.

[bewith continue-intent]

When the user expresses CONTINUE-INTENT in free language — "continue",
"continue working", "keep going", "what's next", "let's pick this up",
"open the PR", "address the review", "let's plan this", "run the checks",
"ship it", "תמשיך", "המשך לעבוד", "מה הלאה" — map it to the /continue loop
and drive it for them. The user should NEVER need to know or type a step
NUMBER; translating their words into the right step is YOUR job, not theirs.

- General "continue / keep going / what's next" → resume the loop. Offer
  the pacing in plain terms: "`/continue` (I pause between steps) or
  `/continue-yolo` (I run straight through)?" Then run it, resuming at the
  right step for the task's current state — and say which step that is in
  WORDS ("picking up at the PR step"), not as a number to memorize.

- Intent that names ONE action → just do THAT step, described in plain
  language. Recognize the action and offer to do it; do not surface a
  number for the user to type:

     "open / raise the PR"            → the PR step
     "address the review / comments"  → the review step
     "let's plan this"                → the plan step
     "run the checks / verify"        → the verification step
     "what should I work on"          → the task-pick step (or /next-task)
     "ship it / merge and close"      → from the PR step onward

  e.g. "On it — I'll open the PR now (the PR step of the loop). Go?"
  NOT "run /continue 10".

The numbered forms (`/continue <n>`, `/continue from <n>`) are an internal
addressing mechanism + a power-user shortcut — lead with the action in
words; never hand the user a number to remember.

Same calibration as above: offer once, don't nag, and never override an
explicit "I'll do X myself."

[bewith role-aware capability filtering]

The user has a "role" that filters which capabilities you surface. Every
agent/skill/command/policy declares `audience: dev | product | both` in its
frontmatter. Match the audience against the role before offering:

  - role=dev    → surface artifacts with audience: dev OR both
  - role=product → surface artifacts with audience: product OR both
  - artifacts with no audience field → treat as `both` (transition window);
    surface a one-line warning once per session: "<name> has no audience
    tag — defaulting to both."

To determine the current role, in this order:

1. Session override — read `~/.claude/session-state.json`. A fresh role
   override wins. It may be the new nested shape
   `{"role": {"value": "...", "expires_at_iso": "..."}}` or the legacy flat
   `{"role": "...", "expires_at_iso": "..."}`; in either case an
   `expires_at_iso` in the future means that role wins.

2. Persistent (canonical) — read `~/.bewith/config.json` and use its `.role`
   (`dev` | `product`) if set. This is the source of truth; `/role` and
   `/settings` write it.

3. Fallback (transition) — read the user_role.md memory file at
   `$HOME/.claude/projects<encoded-cwd>/memory/user_role.md` (cwd with
   `/` → `-`), matching `^role: (dev|product)$`. `/role` keeps this in sync as
   a write-through copy; config.json above is authoritative.

4. If none exist, default to `dev`.

The user changes role with `/role dev`, `/role product`, or
`/role <role> --session` for the current 4-hour session only.

When the user is in role=product and asks something that strongly matches
a dev-only capability (e.g. they describe a coding task), you may surface
the dev artifact with explicit framing: "this is normally a dev tool, but
matches your request — proceed?". The reverse applies for dev → product.
Cross-role surfacing is an exception, not the default.
EOF

jq -n --arg ctx "$GUIDANCE" '{
  hookSpecificOutput: {
    hookEventName: "SessionStart",
    additionalContext: $ctx
  }
}'

exit 0
