Skip to content
Back to skills

Learn

ASecurity

Turn reusable findings into scoped policies or insight files.

  • 98 stars
  • 0 votes
  • 0 copies
  • 6 views
  • Added September 19, 2026
ai-agentsrustgobashreactnodeexpresstestinggitapifrontend

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned November 26, 2026

npx -y skills add indigoai-us/hq-core --skill learn --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Learn?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Learn
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/indigoai-us-learn/badge)](https://www.skillsdirectory.com/skills/indigoai-us-learn)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: learn
description: Turn reusable findings into scoped policies or insight files.
allowed-tools: Read, Write, Edit, Grep, Glob, Bash(qmd:*), Bash(grep:*), Bash(mkdir:*), Bash(date:*), Bash(ls:*), Bash(bash:*), Bash(git:*), Bash(rm:*), Bash(stat:*), Bash, Bash(hq core policy frontmatter:*)
---

# Learn - Automated Learning Pipeline

Capture a learning, classify it, and inject the rule directly into the file it governs (or the insight into the insight tree).

Called programmatically by `/execute-task` and `/run-project` after task completion or failure. Also callable manually with `--hard` flag for hard-enforcement rules (formerly `/learn --hard`). `/handoff` and `/checkpoint` call this for session insights.

**Input:** the user's argument — structured JSON event data, free text description, or empty/"auto" for hook-triggered mode.

## Core Principle

**Two output types, one pipeline.** Content is classified (Step 1.5) and routed to the appropriate format:

### Rules → Policy files (operational directives)

| Scope | Target directory | Format |
|-------|-----------------|--------|
| Company | `companies/{co}/policies/{slug}.md` | Policy file (YAML frontmatter + Rule + Rationale) |
| Repo | `repos/{pub\|priv}/{repo}/.claude/policies/{slug}.md` | Policy file |
| Command (operator) | `personal/policies/{slug}.md` (scope: command) | Policy file |
| Global / personal (**default**) | `personal/policies/{slug}.md` (scope: global) | Policy file |
| Worker (legacy) | `core/workers/*/{id}/worker.yaml` | Instructions block `## Learnings` |

> **`/learn` never writes to `core/policies/`.** `core/` is release-shipped scaffold, replaced wholesale by `/update-hq` — anything written there is lost on the next upgrade (hard policy `hq-customizations-live-in-personal-or-company`). Operator-universal learnings go to `personal/policies/`, which the policy trigger hook (`inject-policy-on-trigger.sh`) reads directly — no `core/policies/` mirror — so they still load as global at SessionStart while living in an upgrade-safe location. A genuine product-level core policy (one that should ship to *every* HQ install) is **not** captured via `/learn`: author it locally, then publish through the hq-core staging repo + `/promote-hq-core` (see `staging-promotion-required`). If a learning is judged truly core, `/learn` stops and points you at that pipeline rather than writing into `core/`.

### Insights → Insight files (educational understanding)

| Scope | Target directory | Format |
|-------|-----------------|--------|
| Global / repo | `workspace/insights/global/{slug}.md` | Insight file (YAML frontmatter + Insight + Context) |
| Company | `companies/{co}/knowledge/insights/{slug}.md` | Insight file in the company's plain synced knowledge directory |
| Tool | `workspace/insights/tools/{slug}.md` | Insight file |
| Conceptual | `workspace/insights/concepts/{slug}.md` | Insight file |

See `core/knowledge/public/hq-core/insights-spec.md` for the insight file format.

**Before creating:** always scan existing policies/insights for updates (Step 4.5). Update > duplicate.

## Step 0: Load Policies (frontmatter-only gate)

Before processing, load applicable policies with minimal context burn:

1. Collect eligible paths in the global policy set except `example-policy.md`, keep their order, and split the stable file order into consecutive chunks of at most 40 files. For each chunk, run `hq core policy frontmatter {file1} {file2} ...` once with each path as a separate argument. Keep each call under 30 KB of output. The first output block belongs to the chunk’s first file argument; each later block belongs to the path named by its preceding `# --- policy-file: <path> ---` separator.
2. Note `enforcement: hard` titles. Only Read the `## Rule` section of hard-enforcement policies if one looks relevant to the current learning

Skip full policy body loads — the frontmatter contains enough metadata for the learn pipeline.

## Step 1: Parse Input

Three input modes:

### Mode 1: Hook-Triggered (auto/empty input)

If the argument is empty or "auto":

1. Check for `workspace/learnings/.observe-patterns-latest.json`
2. If file exists, read it and extract the `observations` array
3. For each observation in the array:
   - Extract `pattern_type`, `confidence`, `description`, `severity`, `evidence`
   - Generate a structured learning event with `source: "hook-observation"`, `scope: "global"` (or inferred from pattern type)
   - Process through Steps 2–9 (extract rules, classify scope, dedup, inject, etc.)
4. Delete the file after processing all observations
5. Report each learning processed

Example `.observe-patterns-latest.json`:
```json
{
  "metadata": {
    "created_at": "2026-03-07T21:35:00Z",
    "session_end_timestamp": "20260307-213500",
    "git_branch": "main",
    "git_commit": "abc1234",
    "project_context": "hq"
  },
  "observations": [
    {
      "pattern_type": "back-pressure-retry",
      "confidence": 0.8,
      "description": "Git log shows fixup/amend commits",
      "severity": "high",
      "evidence": "fixup commits in recent history",
      "recommendation": "Extract pattern about what caused retry"
    }
  ]
}
```

Note: in Codex runtime, the observe-patterns hook is not wired up, so this mode typically returns empty — fall through to manual modes.

### Mode 2: Structured JSON (from /execute-task, /run-project, /handoff, /checkpoint)

If input is a JSON object:
```json
{
  "task_id": "TASK-001",
  "project": "my-project",
  "source": "back-pressure-failure|user-correction|success-pattern|task-completion|build-activity|hook-observation|session-insight",
  "severity": "critical|high|medium|low",
  "scope": "global|worker:{id}|command:{name}|knowledge:{path}|project:{slug}",
  "workers_used": ["backend-dev"],
  "back_pressure_failures": [{"worker": "frontend-dev", "check": "lint", "error": "..."}],
  "retries": 0,
  "key_decisions": ["..."],
  "issues_encountered": ["..."],
  "patterns_discovered": ["..."]
}
```

Parse it and proceed to Step 1.5.

### Mode 3: Free Text (manual invocation or /learn --hard delegation)

Parse for keywords to determine scope. Generate rule statement from the description. Proceed to Step 1.5.

### Mode 4: Batch Input (from /handoff or any caller passing an array)

If the input starts with `[` (JSON array), enter batch mode:

**Batch input format:**
```json
[
  {"type": "rule|insight", "content": "...", "scope": "global|company:{co}|...", "source": "..."},
  ...
]
```

**Batch processing rules:**

1. **Detect batch input:** if the input is a JSON array (starts with `[`), enter batch mode
2. **Run qmd search dedup ONCE for all items:** concatenate all item `content` fields as a single query string for a single `qmd search` call (BM25; never `qmd vsearch` in-turn — first use downloads a ~300MB–2GB GGUF model and has stalled Windows prompts for hours), then match results against each item individually
3. **Process each item through Steps 2–6 normally:** extract rules, classify scope, create/update policy files — one item at a time using the shared dedup results
4. **Write a single event log entry** covering all items processed in the batch
5. **Backward compatibility:** all existing modes (1, 2, 3) work exactly as before — batch is a new detection branch only

## Step 1.5: Classify Content Type

Determine if input is an operational rule or an educational insight:

| Signal | Type | Route to |
|--------|------|----------|
| NEVER/ALWAYS/condition→action | rule | Policy file (Steps 2–6) |
| "why X works", "pattern behind", conceptual explanation | insight | `workspace/insights/` or `companies/{co}/knowledge/insights/` (Step 5b) |
| User correction (`/learn --hard`) | rule | Policy file (always) |
| `back_pressure_failures` | rule | Policy file (always) |
| `patterns_discovered` (educational) | insight | Insight file (Step 5b) |
| `source: "session-insight"` | insight | Insight file (always — from `/handoff` or `/checkpoint` step 0c) |

**Default:** if ambiguous, route as policy (existing behavior). Insights are opt-in.

If content type is **insight**, skip Steps 2 and 5 (rule extraction and policy creation). Proceed to Step 3 for scope classification, Step 4 for dedup, then Step 5b for insight file creation.

## Step 2: Extract Rules

From structured input, generate rules:

- `back_pressure_failures` → `NEVER: {anti-pattern that caused failure}` (scope: worker:{id})
- `retries > 0` → Rule about what caused retry and how to avoid it
- `key_decisions` → `ALWAYS: {pattern}` if broadly applicable
- `issues_encountered` → Scoped rule to prevent recurrence
- `patterns_discovered` → `ALWAYS: {pattern}` for success patterns

From free text:
- Extract the core rule in NEVER/ALWAYS/condition→action format

If no meaningful rules can be extracted (task completed cleanly, no failures, no notable patterns), skip injection — log to event log only.

## Step 3: Classify Scope & Resolve Target

For each extracted rule, determine scope (most specific wins):

| Signal | Scope | Policy directory |
|--------|-------|------------------|
| Related to specific company | `company` | `companies/{co}/policies/` |
| Related to specific repo | `repo` | `repos/{pub\|priv}/{repo}/.claude/policies/` |
| Error in specific command | `command` | `personal/policies/` (with `scope: command`) |
| Failure in specific worker | `worker` | `core/workers/*/{id}/worker.yaml` instructions block (legacy, still supported) |
| Active session company (when no explicit repo, command, or global scope) | `company` | `companies/{co}/policies/` |
| Universal pattern (**default** when no company/repo/session context) | `global` | `personal/policies/` |
| User correction via /learn --hard | From context; default to active session company, then global | Detected scope directory |

**`/learn` does not target `core/policies/`.** The global/command rows route to `personal/policies/` — operator-owned and upgrade-safe — and the policy trigger hook reads `personal/policies/` directly (no `core/policies/` mirror), so each entry still loads as a global/command policy. Reserve `core/policies/` for release-shipped policies authored through the staging → `/promote-hq-core` pipeline. If a rule is genuinely product-core (must ship to every HQ install), stop and direct the user to that pipeline; never Write it into `core/`.

**Primary output = policy files.** The canonical format for persistent rules is structured policy files (per `core/knowledge/public/hq-core/policies-spec.md`). Worker.yaml injection is still supported for worker-specific learnings.

**Resolve company/repo context** (strongest signal wins):
- An explicit scope in the input or user request wins. Honor explicit `repo`, `command`, or `global` scope rather than the session default; explicit global scope targets `personal/policies/`. Verify an explicit company slug against the manifest.
- From the current working directory — the **leaf** `companies/<slug>/` segment (the last one in the path, not the first)
- From `prd.json` metadata if in project context
- From `companies/manifest.yaml` repo lookup if in repo context
- From worker path if worker-scoped (`companies/{co}/workers/` → `{co}`)
- From the active session: `bash core/scripts/hq-session.sh get company_slug`. For free-text and `/learn --hard` input with no explicit repo, command, or global scope, default to this active company and target `companies/{co}/policies/`.

**Verify every resolved slug, including the active session `company_slug`, exists in `companies/manifest.yaml`** before targeting `companies/{co}/policies/`. If the session value is absent or invalid, do not treat it as company context.

**Never silently fall back to a global target for a company-specific learning.** A global target (→ `personal/policies/`) is correct ONLY when the rule is genuinely universal to this operator's HQ. If a rule is clearly company-specific but the company can't be resolved unambiguously, **stop and ask which company** — do not default the write into `personal/policies/` (and never into `core/policies/`). A misrouted company policy syncs into the wrong tenant vault on the next `hq-sync` (HQ-Pro), a category-1 cross-company bug. See `core/policies/hq-company-scoped-writes-verify-company.md`.

## Step 4: Dedup Check

**Primary (if qmd available):**
```bash
qmd search "{rule text}" --json -n 5
```

In-turn dedup is BM25 (`qmd search`) only. **Never run `qmd vsearch`, `qmd query`, `qmd embed`, or `qmd pull` during `/learn`.** Those subcommands auto-download local GGUF models (~300MB–2GB) on first use and have stalled a single Windows HQ prompt for more than two hours. If embeddings are already cached under `~/.cache/qmd/models/` you may still prefer `qmd search` here — keyword overlap is enough to catch duplicate rules. Kick off `hq index background` out of band if semantic search is wanted later.

Check results for similarity to the new rule:
- Similarity > 0.85 → **Skip** (already captured somewhere)
- Similarity 0.6–0.85 → **Merge** (update existing rule to be more precise)
- Similarity < 0.6 → **Add new**

**Fallback (if qmd unavailable):**
Use Grep to search for key terms from the rule across the policy directories:
- Pattern: key terms from the rule (2-3 significant words)
- Files: `*.md` in `companies/*/policies/`, `personal/policies/`, `core/policies/` (the release-shipped set), and any repo policy dirs
- If matching content found → review and decide whether to merge or skip

Record the dedup action for the Step 9 report. Do not print it to the user in the default HQ style.

## Step 4.5: Scan Existing Policies

Before creating a new rule, check if an existing policy file already covers this topic:

1. **Resolve policy directories** based on scope:
   - Company scope → scan `companies/{co}/policies/` (skip `example-policy.md`)
   - Repo scope → scan `{repoPath}/.claude/policies/`
   - Global/command scope → scan `personal/policies/` (the write target) and `core/policies/` (the release-shipped set)

2. **Search for matching policies:**
   ```bash
   # Grep policy titles and rules for keyword overlap
   grep -rl "{key terms from rule}" {policy_dir}/*.md 2>/dev/null
   ```
   Also check `qmd search` results from Step 4 for hits in policy files.

3. **If matching policy found:**
   - Read the policy file
   - **Update** the existing policy: append to `## Rule` section, bump `version`, update `updated` date
   - If new learning contradicts existing policy, flag for user review instead of auto-merging
   - Set `dedup_action: "merged-into-policy"` in event log

4. **If no matching policy found:**
   - Proceed to Step 5 (create new rule)
   - For company/repo/global scoped rules, prefer creating a **policy file** (per `core/knowledge/public/hq-core/policies-spec.md`) over injecting into worker.yaml. Policy files are the canonical format for persistent rules. **Never** write a learned rule into `.claude/CLAUDE.md` / `AGENTS.md` — the charter is release-shipped scaffold, not a learning store (policy `learned-rules-never-in-claude-md`)

## Step 5: Create or Update Policy File (rule content type)

### Primary: Policy File (company/repo/global/command scopes)

If Step 4.5 found a matching policy → update was already handled. Otherwise, create a new policy file.

**Target directory:**
- Company scope → `companies/{co}/policies/{slug}.md`
- Repo scope → `repos/{pub|priv}/{repo}/.claude/policies/{slug}.md`
- Command scope (operator-authored) → `personal/policies/{slug}.md` (scope: command)
- Global scope → `personal/policies/{slug}.md` (scope: global) — **default for non-company/non-repo rules**

> Never Write a `.md` into `core/policies/` from `/learn` — it is lost on `/update-hq` and is now mechanically blocked by `protect-core.sh` (the block message points back here). `personal/policies/` entries are read directly by the policy trigger hook (no `core/policies/` mirror), so they load identically as global/command policies. Genuine product-core policies ship via the staging → `/promote-hq-core` pipeline only.

**Create the directory if needed:**
```bash
mkdir -p {target_directory}
```

**Policy file format** (per `core/knowledge/public/hq-core/policies-spec.md`):

```markdown
---
id: {scope-prefix}-{slug}
title: {Rule title}
when: {boolean trigger expr over context words, or `always`}
on: {[PreToolUse, PostToolUse, UserPromptSubmit, AssistantIntent] | [SessionStart]}
enforcement: {hard|soft}
# company: <slug>   # optional; see Company field below. Uncomment only with one real manifest slug
public: {true|false — see Lifecycle stamping below}
status: active
version: 1
created: {YYYY-MM-DD}
updated: {YYYY-MM-DD}
source: {back-pressure-failure|user-correction|success-pattern|task-completion|hook-observation}
notes: {only when a global or command policy gets public: false — the portability reason}
retire_when: {workaround rules only — the fix condition in plain words}
last_confirmed: {workaround rules only — today's date, YYYY-MM-DD}
---

## Rule

{Rule in imperative form}

## Rationale

{Mechanism and trade-offs only: why the rule works and what it costs}

## Provenance

{Company slugs, customer or person names, ticket or PR numbers, and specific dates from the source learning. Omit the section when there are none.}
```

**Lifecycle stamping (set at authoring time, no confirmation prompt):** `/learn`
fills these fields itself and never asks the user about them
(`hq-learn-auto-no-confirmation`).

- `status: active` on every policy `/learn` writes.
- `public:`
  - Company- and repo-scoped policies: always `public: false`.
  - Global and command-scoped policies: `public: true` only when the `## Rule`
    body passes the portability check in `hq-public-policy-rule-body-generic`:
    no HQ-internal paths (HQ top-level directories such as the company, personal,
    workspace, repos, or core trees, the `.claude` directory, home-relative or
    absolute paths), no company, worker, or repo slugs, and no internal infra
    names (account IDs, bucket, stack, or host names). Otherwise
    `public: false` with the failing check in `notes:`, for example
    `notes: public false because the Rule names an HQ-internal path`.
- Workaround rules: classify the learning as a workaround when it works around
  a named tool, a specific version, or a known defect. Signals are a tool or
  package name with a version number, or the words bug, defect, regression,
  workaround, upstream issue, or until a named tool fixes something. For these,
  write `retire_when:` with the fix condition in plain words (for example
  `retire_when: the CLI ships the native fix for the stale session cache`; no
  quotes or regex symbols, per `policies-spec.md`) and `last_confirmed:` with
  today's date. Rules that are not workarounds omit both fields.
- Provenance routing: when the source learning mentions a company slug, a
  customer or person name, a ticket or PR number, or a specific date, write that
  text under `## Provenance`. `## Rationale` keeps only the mechanism and the
  trade-offs. `## Provenance` is archival: it is not injected and does not count
  toward the hard-body size limit.

**Enforcement mapping:**
- `source: user-correction` → `enforcement: hard`
- `severity: critical` → `enforcement: hard`
- Everything else → `enforcement: soft`

**`when:` / `on:` trigger (just-in-time injection):**
- `when:` is a boolean expression over an OPEN token set — any word that appears in the relevant command/prompt/AI-message text is a live token (`git && push`, `refactor`, `supabase`, `.tsx`, `/deep-plan`, `secret || credential`). Pick the word(s) that naturally show up when the rule is relevant. Operators: `&& || ! ( )`. Full grammar + fact derivation: `core/knowledge/public/hq-core/policies-spec.md`.
- **Every token needs an operator between it and the next one.** `when: merge || pull request` is not "merge, or a pull request" — nothing joins `pull` and `request`, so the expression is rejected outright. Write `merge || (pull && request)`, or pick the single word you meant. Quoted phrases, flags, and globs are outside the charset and are rejected the same way. `validate-policy-frontmatter.sh` blocks this at write time; `bash core/scripts/lint-policy-triggers.sh` finds any that predate the check.
- `on:` is where it is evaluated. Default for a real trigger: `[PreToolUse, PostToolUse, UserPromptSubmit, AssistantIntent]` (the `when:` does the filtering). `[SessionStart]` with `when: always` is a last resort for a hard rule with no nameable signal, not the home for "baseline" or "ambient" rules: those have a moment when they apply (writing a message, reading a file, choosing between options), and the keyword for that moment is the trigger. HP-4 of hq-hook-perf moved every core `when: always` policy to keywords for this reason.
- **`enforcement: hard` + an unconditional `when:` on a reactive event is blocked.** `when: always` (or an OR-chain containing `always`) is TRUE for every command and every prompt, so on `PreToolUse`/`UserPromptSubmit`/`PostToolUse`/`AssistantIntent` it takes a session cap slot from a policy that actually matched. Either move it to `on: [SessionStart]`, or name the real signal — usually the OR-chain is already there and `always` is redundant noise in front of it.
- If you genuinely can't name a signal and the rule is `enforcement: hard`, `when: always` + `on: [SessionStart]` is allowed; a soft rule without a signal is not worth a policy file.
- Set these fields when authoring a policy. For older policies where `tags:` or `trigger:` supplies a derivable signal, the hash-gated SessionStart hook (`migrate-policy-triggers-if-changed.sh`) backfills them on the next session after a policy file changes, and `/update-hq` also runs the backfill after an update. If no signal is derivable, only an `enforcement: hard` policy receives the `when: always` + `on: [SessionStart]` fallback; soft or unset policies remain untriggered. The migrator never overwrites an existing `when:`.

**Keep an `enforcement: hard` body short.** A hard policy is quoted verbatim into
every session it fires in, so its length is a recurring context cost, and the
write hook blocks a binding body over `HQ_POLICY_HARD_RULE_MAX_BYTES` (default
6144). Only the text above the first archival heading counts and is injected:
put the rule and its exceptions under `## Rule`, and move worked examples,
incident write-ups, and API detail under `## Rationale`, `## Examples`,
`## Reference`, or `## Related`, and who/when/which-ticket detail under
`## Provenance`. Nothing is lost — the agent gets
the file path and can read the rest when it needs the reasoning.

### Company field (client-scoped rules outside a company policies directory)

Step 3 still decides where a rule goes: a company-specific rule goes to `companies/{co}/policies/` by default, and that directory already loads only for the session's own companies, so a file there gets no field. The field is only for a rule that Step 3 sends elsewhere because the user gave an explicit `repo`, `command`, or `global` scope, while the rule itself is about one client. Such a file in `personal/policies/` or a repo's `.claude/policies/` would otherwise load in every session. Write `company: {slug}` in its frontmatter (`companies: [a, b]` only when the user named several). The policy reminder (`inject-policy-on-trigger.sh`) then skips it, if soft or unset, in sessions locked to other companies (see the `company:` field in `core/knowledge/public/hq-core/policies-spec.md`).

- The slug must be one the user named, or the active or locked session company (`bash core/scripts/hq-session.sh get company_slug`), and the rule must be about that company. A rule merely learned while a company session is active, but true everywhere, gets no field. Never use this field to move a company rule out of `companies/{co}/policies/`.
- Never infer a company from the policy name, slug, or wording. A word in the rule or in `when:` that matches a company folder name is not a company signal; company folder names are often ordinary words.
- Verify each slug exists in `companies/manifest.yaml` before writing it. If the company is unclear, ask; do not guess.
- Write a real slug only. The template shows the line commented out (`# company: <slug>`); never copy a placeholder or explanation into the value. `validate-policy-frontmatter.sh` blocks a value that is not a slug in `companies/manifest.yaml`, and the reminder ignores names with no company folder.
- Never write a `company:` line unless Step 3 resolved a company scope (a manifest-verified slug) for this rule. If no scope resolved, leave the line out entirely; never write a placeholder, an empty value, or a guess.
- Omit the field for a general rule. A missing field means the rule loads for every company, as before.
- Do not add it to a file in a company policies directory (`companies/{co}/policies/`).
- The field never hides a binding rule: the reminder never skips a `hard` or `gate` rule on this path, so a hard rule tagged with a company still loads in every session. Keep it that way; do not lower a rule's enforcement to make the company skip apply.

**Policy frontmatter validation:** `when:` and `on:` are required and automatically checked by the `validate-policy-frontmatter.sh` write/edit hook. For stack-specific rules, express the service token in `when:` (for example, `when: vercel`); do not add retired applicability metadata. See `core/knowledge/public/hq-core/policies-spec.md` for the complete schema.

**Slug generation:** lowercase, hyphens, from rule keywords. Prefix: `{co}-` for company, `{repo}-` for repo, `hq-cmd-{name}-` for command, `hq-` for global.

### Fallback: Worker.yaml (worker-scoped learnings)

For worker-specific learnings, still inject into `core/workers/*/{id}/worker.yaml` instructions block:

```yaml
instructions: |
  ...existing instructions...

  ## Learnings
  - NEVER: {new rule}
```


## Step 5b: Create Insight File (insight content type only)

If Step 1.5 classified content as **insight**, skip Step 5 (policy creation) and create an insight file instead.

**Target directory by scope:**
- Global / repo-scoped → `workspace/insights/global/{slug}.md`
- Company-scoped → `companies/{co}/knowledge/insights/{slug}.md` (create `insights/` subdir if needed)
- Tool-specific → `workspace/insights/tools/{slug}.md`
- Conceptual/theoretical → `workspace/insights/concepts/{slug}.md`

**Insight file format** (per `core/knowledge/public/hq-core/insights-spec.md`):

```markdown
---
type: insight
domain: [engineering]
tags: [topic-tags]
scope: global | company:{co} | repo:{repo} | tool:{tool}
source_session: T-{timestamp}-{slug}
created: {YYYY-MM-DD}
confidence: high | medium
relates_to: []
---

# {Title}

## Insight

{Core conceptual understanding, 2-4 paragraphs. Educational, not directive.}

## Context

{When/why this matters. What situation makes this knowledge valuable.}

## Example

{Optional. Concrete example showing the insight in practice.}
```

**Slug generation:** kebab-case from title keywords, max 60 chars. No scope prefix (subdirectory provides scope).

**Confidence mapping:**
- Validated through execution/testing → `confidence: high`
- Observed but not extensively tested → `confidence: medium`

**After writing:** proceed to Step 7 (event logging).

## Step 6: Evaluate Global Promotion

Global promotion means **raising a rule's enforcement to hard, in a policy file** — never injecting it into the charter. Learned rules never go in `.claude/CLAUDE.md` / `AGENTS.md` (policy `learned-rules-never-in-claude-md`); they already surface for every session through the policy trigger hook (`inject-policy-on-trigger.sh`), so a hard-enforcement policy file *is* the global path.

If a rule meets ANY of:
- `severity == critical`
- `source == user-correction` (explicit `/learn --hard` invocation)
- Rule triggered 3+ times (check event log)

then ensure it lives as a **hard-enforcement policy file** at global scope:
- Personal/owner learnings → `personal/policies/{slug}.md` (read directly by the policy trigger hook — no `core/policies/` mirror — so it rides global scope and survives `/update-hq`).
- Release-shipped, all-users learnings → `core/policies/{slug}.md` with the public marker (promoted via `hq-pack-admin`).

Set `enforcement: hard` in the policy frontmatter and ensure the file carries `when:`/`on:` frontmatter so the SessionStart trigger hook surfaces it (Step 8). Do **not** touch `CLAUDE.md`.

## Step 6.5: Capture entity candidates (opt-in companies only)

If the bound company has `ontology_capture` on
(`core/scripts/knowledge-prefs.sh get {co} ontology_capture`), follow
`.claude/skills/_shared/session-close-capture.md`: for each person, project,
company, or concept a new or merged rule names, write one entity candidate
(max 5 per run) with `core/scripts/ontology-candidate.sh --kind entity`, source
ref `learn:{event_id}`. Audience is `company` when the rule's scope is
`company:{co}` and the session user otherwise. Off: skip silently. Fail-soft.

## Step 7: Log Event

```bash
mkdir -p workspace/learnings
```

Write `workspace/learnings/learn-{YYYYMMDD-HHMMSS}.json`:
```json
{
  "event_id": "learn-{timestamp}",
  "content_type": "rule|insight",
  "rules": [
    {
      "rule": "NEVER: ...",
      "scope": "worker:frontend-dev",
      "target_file": "core/workers/public/dev-team/frontend-dev/worker.yaml",
      "severity": "high"
    }
  ],
  "source": "back-pressure-failure|session-insight",
  "task_id": "TASK-001",
  "project": "my-project",
  "dedup_action": "new|merged|skipped",
  "promoted_to_global": true,
  "created_at": "{ISO8601}"
}
```

The event log write is mandatory for every invocation (even skipped/trivial ones) — downstream tooling relies on it.

## Step 8: Reindex

```bash
qmd update 2>/dev/null || true
```

`qmd update` is FTS-only and does not download GGUF models. Do **not** follow it with `qmd embed` or `qmd vsearch` in this turn. If the index should grow embeddings, run `hq index background` (or `qmd embed` with `run_in_background: true`) after the report.

No manual digest rebuild is needed: policies surface automatically via the SessionStart trigger hook (`inject-policy-on-trigger.sh`) and the `migrate-policy-triggers.sh` backfill. Ensure any new policy file carries `when:`/`on:` frontmatter so it gets injected. (Personal entries under `personal/policies/` are read directly by the trigger hook — there is no mirror step, so a new file loads on the next qualifying event without any reindex.)

Insight-only runs (content_type: insight) write no policy file, so there is nothing for the trigger hook to surface.

**Batch mode note:** In batch mode (Mode 4), there is no per-item or end-of-batch digest step — each policy file written during the batch surfaces on its own via its `when:`/`on:` frontmatter.

## Step 9: Report

Chat report follows the active output style (`core/policies/hq-audience-mode.md`). Files this skill writes stay full prose. The templates below are chat-only.

For any `scope: company` rule, **surface the resolved company slug and the full target path and confirm them before writing** — this is the visible checkpoint that catches a misroute before it reaches a tenant vault (`hq-company-scoped-writes-verify-company`). After the write, the chat report still follows the audience below.

**Default (`HQ`, and any style that is not `hq-operator`):** one short plain sentence. Do not print Scope, Dedup, Action, file paths, thread IDs, or PIDs. Do not paste the operator template.

When trusted command-report details context is present, lead with a short plain-language summary. Put useful, non-sensitive diagnostics in a collapsed `Technical details` section. Without that context, keep the summary-only format.

When trusted context is absent (for example, a routed natural-language or programmatic invocation), check the flag at report time with `HQ_CLI_BIN="$(command -v hq 2>/dev/null || true)" node .claude/hooks/command-report-details-flag.cjs`. Use expanded details only when it prints `true`; otherwise keep the summary-only format. This gate never overrides `hq-operator` style.

- New or updated rule/insight: `Saved. I'll remember that next time.`
- Multiple items: `Saved {n} lessons so I'll remember them next time.`
- Skipped as duplicate: stay silent, or `Already had that. No change.`
- Stopped because company could not be resolved: keep the one clarifying question (that is a decision, not a report).

**Operator (`/output-style hq-operator`):**

**For rules (content_type: rule):**
```
Learning captured:
  Scope: {company:<slug> | repo:<name> | command | global}
  Rule: {rule}
  Target: {policy file path | worker.yaml path}
  Action: {created-policy | updated-policy | merged-into-policy | worker-yaml-injection}
  Global: {promoted|not promoted}
  Dedup: {new|merged|skipped}
  Event: workspace/learnings/learn-{timestamp}.json
```

**For insights (content_type: insight):**
```
Insight captured:
  Title: {insight title}
  Target: {insight file path}
  Action: {created-insight | updated-insight | merged-into-insight}
  Dedup: {new|merged|skipped}
  Event: workspace/learnings/learn-{timestamp}.json
```

If multiple rules/insights were extracted, report each.

## Rules

- **Policy files first** — always create structured policy files for company/repo/global/command scoped rules. Worker.yaml injection only for worker-specific learnings
- **Scan before create** — always check existing policies for updates before creating new files (Step 4.5)
- **Never inject empty/trivial rules** — "task completed successfully" is not a learning
- **Dedup is mandatory** — always check before injecting (qmd first, Grep fallback)
- **Learned rules never touch the charter** — never write a learned rule into `.claude/CLAUDE.md` / `AGENTS.md`; global promotion = a hard-enforcement policy file (policy `learned-rules-never-in-claude-md`)
- **Reindex after every injection** — keeps qmd search current
- **New policies need `when:`/`on:` frontmatter** — that is what the SessionStart trigger hook (`inject-policy-on-trigger.sh`) uses to surface a policy; no manual digest rebuild exists anymore
- **Event log is always written** — `workspace/learnings/learn-{timestamp}.json` is non-optional
- **Preserve existing rules** — append only, never overwrite existing rules
- **User corrections always promote** — /learn --hard delegations go to a hard-enforcement policy file (never CLAUDE.md)
- **Match existing style** — use the same rule format as existing rules in the target file

Files in this skill

  • SKILL.md27.2 KB
  • agents/openai.yaml145 B

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.