AgentSkillsCN

code-sentinel

面向闪存-半马尔可夫的专家系统。为Triton/PyTorch后端管理持久化的执行轨迹(“哨兵”)。 强制要求:在调试NaN/Inf、形状不匹配、修改autograd逻辑,或进行提交之前,务必调用此技能。 操作步骤:1. 运行`./sentinel.py status`以检查整体健康状况;2. 在提供调试建议前,运行`./sentinel.py verify --trace <name>`;3. 在提交更改前,运行`./sentinel.py pipeline`;4. 通过`dispatch-overview.md`定位活跃的后端;5. 将特定的轨迹加载到上下文中,并与当前git HEAD进行验证。 触发条件:“调试半马尔可夫”“追踪执行”“解释后端调度”“Triton内核调试”“NaN”“形状不匹配”“梯度流动”“哨兵”“验证代码”“检查一致性”“预提交”“回溯”

SKILL.md
--- frontmatter
name: code-sentinel
description: >
  Expert system for flash-semicrf. Manages persistent execution traces ("Sentinels")
  for Triton/PyTorch backends.

  MANDATORY: Invoke this skill BEFORE debugging NaN/Inf, shape mismatches,
  modifying autograd logic, or making commits.

  Actions:
  1. Run `./sentinel.py status` to check overall health
  2. Run `./sentinel.py verify --trace <name>` before providing debugging advice
  3. Run `./sentinel.py pipeline` before committing changes
  4. Locate active backend via `dispatch-overview.md`
  5. Load specific trace into context and verify against current git HEAD

  Triggers: "debug semi-markov", "trace execution", "explain backend dispatch",
  "Triton kernel debug", "NaN", "shape mismatch", "gradient flow", "sentinel",
  "verify code", "check consistency", "pre-commit", "retrace"
allowed-tools: Read, Grep, Glob, Bash

Code Sentinel

Persistent execution traces ("Sentinels") for flash-semicrf backends. Prevents hallucinations about code execution paths by maintaining verified baseline documentation.

Quick Start

bash
# Check overall health
./sentinel.py status

# Scaffold a new trace from source
./sentinel.py init src/flash_semicrf/streaming/new_module.py

# Verify before debugging
./sentinel.py verify --trace triton-forward-k3plus

# Auto-detect and fix anchor drift
./sentinel.py retrace triton-forward-k3plus --auto --apply

# Run full pre-commit pipeline
./sentinel.py pipeline

# Install git hooks
./sentinel.py install-hooks

Verification Protocol (ALWAYS EXECUTE FIRST)

Step 1: Run Verification

bash
./sentinel.py verify --trace <trace-name>

This performs:

  • Commit staleness check (verified hash vs current HEAD)
  • Uncommitted changes detection
  • Anchor verification (pattern -> line number)
  • Assumption verification (mechanical checks)

Step 2: Interpret Output

On success (all verified):

code
Grounded: triton-forward-k3plus @ 40fe66b [PASS]

On failure (drift detected):

code
Grounded: triton-forward-k3plus @ 40fe66b
  Commit: STALE (COMMITTED_CHANGES)
    Verified: 40fe66b | Current: abc1234
  Anchors: 5/7 verified, 2 failed
    [FAIL] RING_BUFFER_WRITE: ANCHOR_DRIFT: Expected ~320, found 345 (drift 25 > 20)
  Assumptions: A1 [PASS], A2 [FAIL], A3 [PASS]

[WARN]  Cannot provide advice until sentinel is updated.

Step 3: Remediate if Needed

If stale, run diff to synchronize understanding:

bash
./sentinel.py retrace triton-forward-k3plus --diff-only

If anchors drifted, auto-update line numbers:

bash
./sentinel.py retrace triton-forward-k3plus --anchors-only

Pre-Commit Pipeline

Run before every commit:

bash
./sentinel.py pipeline

# Or with automatic test execution
SENTINEL_RUN_TESTS=1 ./sentinel.py pipeline

Pipeline steps:

  1. Consistency check - meta ↔ anchors ↔ traces alignment
  2. Trace verification - all sentinels verified
  3. Test advisory - suggest tests for changed files

Backend Selection Tree

code
semi_crf_streaming_forward() [autograd.py:474]
|
+-- K == 1 (no boundary projections)
|   +-- needs_grad: LinearCRFStreaming.apply() [line 590]
|   +-- inference: linear_crf_forward_pytorch() [line 605]
|   --> Trace: k1-linear-crf.md
|
+-- K == 2 (no boundary projections)
|   +-- needs_grad: SemiCRFK2Streaming.apply() [line 616]
|   +-- inference: semi_crf_k2_forward_pytorch() [line 631]
|   --> Trace: k2-fast-path.md
|
+-- K >= 3
    +-- GPU + HAS_TRITON + use_triton
    |   +-- needs_grad: SemiCRFStreamingTriton.apply() [line 642]
    |   +-- inference: launch_streaming_triton_kernel() [line 669]
    |   --> Trace: triton-forward-k3plus.md
    |
    +-- CPU or no Triton
        +-- needs_grad: SemiCRFStreaming.apply() [line 655]
        +-- inference: semi_crf_streaming_forward_pytorch() [line 683]
        --> Trace: pytorch-forward-k3plus.md

Failure Mode Routing

SymptomPrimary TraceCheck First
NaN in losstriton-forward-k3plus.mdNEG_INF guards
NaN in backwardtriton-backward-k3plus.mdPartition validation
Wrong gradientstriton-backward-k3plus.mdCross-reference outputs
OOM on GPUtriton-backward-k3plus.mdRecomputation Logic section
K=1/K=2 mismatchk1-linear-crf.mdDispatch conditions
Triton vs PyTorch difftriton-forward-k3plus.mdRing buffer indexing

Available Traces

TracePurposeSource File
dispatch-overview.mdBackend selectionautograd.py
triton-forward-k3plus.mdTriton forward (K>=3)triton_forward.py
triton-backward-k3plus.mdTriton backwardtriton_backward.py
pytorch-forward-k3plus.mdPyTorch forwardpytorch_reference.py
pytorch-backward-k3plus.mdPyTorch backwardpytorch_reference.py
k1-linear-crf.mdK=1 fast pathpytorch_reference.py
k2-fast-path.mdK=2 fast pathpytorch_reference.py
non-streaming-backends.mdNon-streaming APIsemimarkov.py
autograd-kernel-interface.mdAutograd contractautograd.py
crf-heads.mdUser-facing CRF APInn.py

CLI Reference

CommandDescription
./sentinel.py statusShow overall sentinel health
./sentinel.py init SOURCEScaffold a new trace from source file
./sentinel.py init SOURCE --name NAMEScaffold with custom trace name

Note on init scaffolding: The init command intentionally provides only ~17% of a completed trace (structure + line refs). The ~83% gap represents irreducible domain knowledge—explaining why code works, what invariants matter, and which patterns are numerically critical. This is by design: sentinels derive value from encoding understanding that source code alone does not express. Do NOT attempt to auto-generate this content. | ./sentinel.py verify --trace NAME | Verify specific trace | | ./sentinel.py verify --all | Verify all traces | | ./sentinel.py verify --all --check-consistency | Verify all with consistency check | | ./sentinel.py pipeline | Run full pre-commit pipeline | | ./sentinel.py retrace NAME --auto | Auto-analyze anchor impacts | | ./sentinel.py retrace NAME --auto --apply | Analyze and apply safe updates | | ./sentinel.py retrace NAME --diff-only | Show diff without updating | | ./sentinel.py retrace NAME --anchors-only | Force update anchor line numbers | | ./sentinel.py install-hooks | Install git pre-commit hooks | | ./sentinel.py report --format json | Generate JSON report | | ./sentinel.py report --format markdown | Generate Markdown report |

Exit Codes

CodeMeaning
0All verification passed
1One or more anchors missing
2One or more anchors drifted beyond tolerance
3One or more anchor patterns are ambiguous
4Consistency check failed
5Assumption verification failed

Updating Sentinels

When code changes require sentinel updates:

  1. Update trace markdown first

    • Update "Verified against" commit hash
    • Update Algorithm Steps line references
    • Preserve Critical Invariants, Known Issues, Linked Tests
  2. Update anchors.yaml (if patterns changed)

    bash
    ./sentinel.py retrace <name> --anchors-only
    
  3. Update .sentinel-meta.yaml

    • Bump verified_commit
    • Update last_global_verification
  4. Commit together

    bash
    git add traces/ anchors/ .sentinel-meta.yaml sentinel.py
    git commit -m "sentinel: update <trace-name> for <change>"
    

Symbolic Shape Legend

SymbolMeaning
BBatch size
TSequence length
KMaximum segment length
CNumber of classes
C_PADPadded class count (power of 2)

Domain-Specific Invariants

InvariantCheck
Log-partition boundspartition >= viterbi_score
Padding sentinelalpha[t] == NEG_INF for t > T
Prefix-sum initcum_scores[:, 0, :] == 0
Ring buffer aliasingalpha[t] overwrites alpha[t-K]

Example Invocations

bash
# Check health before debugging
./sentinel.py status

# Scaffold a new trace
./sentinel.py init src/flash_semicrf/nn.py --name crf-heads

# Trace the Triton forward kernel
./sentinel.py verify --trace triton-forward-k3plus

# Debug NaN in backward pass
./sentinel.py verify --trace triton-backward-k3plus

# Auto-analyze and fix drifted anchors
./sentinel.py retrace triton-forward-k3plus --auto --apply

# Pre-commit check
./sentinel.py pipeline

# Generate CI report
./sentinel.py report --format json > sentinel-report.json

Files Reference

FilePurpose
sentinel.pyMain CLI orchestrator
.sentinel-meta.yamlMachine-readable sentinel state
anchors/anchors.yamlPattern -> line number mappings
anchors/verify-all.pyBatch anchor verification
anchors/verify-anchor.shSingle anchor verification
verify-assumptions.pyAssumption verification
hooks/pre-commit-*.shGit hook scripts