@ngockhoale/ukit 2.6.6 → 2.6.8

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/CHANGELOG.md +37 -0
  2. package/README.md +40 -177
  3. package/manifests/documentation.yaml +143 -15
  4. package/manifests/hostCapabilities.yaml +49 -0
  5. package/manifests/instructionRules.yaml +383 -0
  6. package/manifests/platform.full.yaml +15 -0
  7. package/package.json +3 -1
  8. package/scripts/bench/goldTasks.json +38 -0
  9. package/scripts/bench/runGold.mjs +220 -0
  10. package/scripts/docs/render-instructions.mjs +42 -0
  11. package/scripts/release/verify-release.mjs +6 -0
  12. package/src/cli/commands/code.js +182 -0
  13. package/src/cli/commands/doctor.js +35 -3
  14. package/src/cli/commands/indexTools.js +102 -1
  15. package/src/cli/commands/memory.js +137 -0
  16. package/src/cli/index.js +7 -0
  17. package/src/core/codeintel/compiler.js +316 -0
  18. package/src/core/codeintel/diagnostics.js +114 -0
  19. package/src/core/codeintel/freshness.js +295 -0
  20. package/src/core/codeintel/impact.js +251 -0
  21. package/src/core/codeintel/invalidation.js +150 -0
  22. package/src/core/codeintel/manifest.js +176 -0
  23. package/src/core/codeintel/packet.js +146 -0
  24. package/src/core/codeintel/providers.js +201 -0
  25. package/src/core/codeintel/retriever.js +372 -0
  26. package/src/core/codeintel/router.js +149 -0
  27. package/src/core/codeintel/semanticProvider.js +235 -0
  28. package/src/core/docContracts.js +723 -0
  29. package/src/core/memory/migrate.js +324 -0
  30. package/src/core/memory/records.js +172 -0
  31. package/src/core/memory/retrieval.js +161 -11
  32. package/src/core/memory/store.js +398 -0
  33. package/src/core/memory/storeV2.js +171 -0
  34. package/src/core/memory/storeV2Loader.js +22 -0
  35. package/src/core/projectImportant.js +1 -1
  36. package/src/core/runtimeConfig.js +125 -0
  37. package/src/core/runtimePaths.js +3 -0
  38. package/src/core/uninstall.js +1 -1
  39. package/src/index/taskRouting.js +39 -0
  40. package/src/render/instructionRenderer.js +226 -0
  41. package/templates/.claude/ukit/index/route-task.mjs +40 -0
  42. package/templates/.gitignore +2 -2
  43. package/templates/.omp/RULES.md +1 -0
  44. package/templates/AGENTS.md +89 -218
  45. package/templates/CLAUDE.md +85 -212
  46. package/templates/docs/AI_HANDOFF/tasks/_TEMPLATE.md +5 -0
  47. package/templates/docs/BUGFIX.md +2 -19
  48. package/templates/docs/BUG_INDEX.md +43 -0
  49. package/templates/docs/BUG_METRICS.md +1 -5
  50. package/templates/docs/BUG_TEMPLATE.md +1 -11
  51. package/templates/docs/UKIT_INTERNALS.md +223 -0
  52. package/templates/instructions/core.md +157 -0
  53. package/templates/instructions/layout.yaml +149 -0
  54. package/templates/instructions/overlays/agents.md +15 -0
  55. package/templates/instructions/overlays/claude.md +3 -0
  56. package/templates/instructions/overlays/omp-rules.md +74 -0
  57. package/templates/instructions/overlays/repo.md +9 -0
  58. package/templates/instructions/repo-vars.yaml +23 -0
  59. package/templates/ukit/storage/config.json +30 -0
@@ -22,6 +22,34 @@ const {
22
22
  } = indexCore;
23
23
 
24
24
  const MAX_ACTIVE_ROUTE_SKILLS = 2;
25
+
26
+ // Declared complexity→docs mapping (DOC-201 FR-001). Canonical declaration lives in
27
+ // manifests/documentation.yaml `context_layers`; this constant is the routing-side copy
28
+ // (the router must not read the registry at runtime — zero new deps). Keep in sync.
29
+ // `queued-task` is omitted v1: docs/TASKS.md does not exist in every repo (SPEC §14).
30
+ // `shared-simple` mirrors the non-trivial layer to match deriveContextMode's FULL lane.
31
+ const CONTEXT_LAYER_DOCS = {
32
+ taskTypes: {
33
+ trivial: [],
34
+ simple: ['docs/MEMORY.md'],
35
+ 'non-trivial': ['docs/MEMORY.md', 'docs/PROJECT.md', 'docs/CODE_MAP.md'],
36
+ 'shared-simple': ['docs/MEMORY.md', 'docs/PROJECT.md', 'docs/CODE_MAP.md'],
37
+ },
38
+ intents: {
39
+ 'open-ended': ['docs/STATUS.md'],
40
+ 'open-ended-status': ['docs/STATUS.md'],
41
+ handoff: ['docs/AI_HANDOFF/INDEX.md'],
42
+ },
43
+ };
44
+ const CONTEXT_DOCS_MAX = 4;
45
+
46
+ function deriveContextDocs({ taskType = null, intentMode = null } = {}) {
47
+ const docs = [
48
+ ...(CONTEXT_LAYER_DOCS.taskTypes[taskType] ?? []),
49
+ ...(CONTEXT_LAYER_DOCS.intents[intentMode] ?? []),
50
+ ];
51
+ return unique(docs).slice(0, CONTEXT_DOCS_MAX);
52
+ }
25
53
  const STOPWORDS = new Set([
26
54
  'the', 'a', 'an', 'and', 'or', 'to', 'for', 'of', 'with', 'in', 'on', 'is', 'are',
27
55
  'this', 'that', 'it', 'as', 'by', 'be', 'use', 'using', 'implement', 'fix', 'task',
@@ -1293,6 +1321,7 @@ function formatDisplayRouteSummary(routeSummary = null, routingContext = {}) {
1293
1321
  taskSegment,
1294
1322
  extractRouteLineSegment(line, 'handoff'),
1295
1323
  extractRouteLineSegment(line, 'targets'),
1324
+ extractRouteLineSegment(line, 'docs'),
1296
1325
  extractRouteLineSegment(line, 'tests'),
1297
1326
  extractRouteLineSegment(line, 'styles'),
1298
1327
  policySegment,
@@ -2108,6 +2137,7 @@ function buildRouteSummary({
2108
2137
  contextRecommendation = null,
2109
2138
  verificationRecommendation = null,
2110
2139
  nextAction = null,
2140
+ contextDocs = null,
2111
2141
  } = {}) {
2112
2142
  const autonomyLevel = routingContext.autonomyLevel ?? 'balanced';
2113
2143
  const delegationRecommendation = deriveDelegationRecommendation({
@@ -2174,10 +2204,19 @@ function buildRouteSummary({
2174
2204
  const nextActionCommand = compactHelperLane ? null : nextAction?.command ?? null;
2175
2205
  const handoffFile = routingContext.intentMode === 'handoff' ? 'docs/AI_HANDOFF/ACTIVE.md' : null;
2176
2206
  const visionLane = Boolean(routingContext.visionLane);
2207
+ // DOC-201 FR-002: resolved context-layer docs (declared in manifests/documentation.yaml).
2208
+ // Explicit override wins; otherwise derive from taskType + intentMode.
2209
+ const resolvedContextDocs = ((Array.isArray(contextDocs) ? contextDocs : null)
2210
+ ?? deriveContextDocs({ taskType, intentMode: routingContext.intentMode ?? null }))
2211
+ .slice(0, CONTEXT_DOCS_MAX);
2212
+ const docsSegment = resolvedContextDocs.length > 0
2213
+ ? `docs=[${resolvedContextDocs.slice(0, CONTEXT_DOCS_MAX).map((p) => path.posix.basename(String(p).replaceAll('\\', '/'))).join(',')}]`
2214
+ : null;
2177
2215
  const line = [
2178
2216
  routingContext.taskType ? `task=${routingContext.taskType}` : null,
2179
2217
  handoffFile ? `handoff=${handoffFile}` : null,
2180
2218
  formatCompactSegment('targets', primaryTargets),
2219
+ docsSegment,
2181
2220
  formatCompactSegment('tests', relatedTests),
2182
2221
  formatCompactSegment('styles', styleFiles),
2183
2222
  editGuardHint ? `editGuard=${editGuardHint}` : null,
@@ -2209,6 +2248,7 @@ function buildRouteSummary({
2209
2248
  nextActionCommand,
2210
2249
  helperHint,
2211
2250
  contextMode,
2251
+ contextDocs: resolvedContextDocs,
2212
2252
  ...(visionLane ? {
2213
2253
  visionLane: true,
2214
2254
  visionReason: routingContext.visionReason ?? null,
@@ -54,8 +54,8 @@ Thumbs.db
54
54
  # templates/.claude/ukit/index/task-budget-validator.mjs). The root .gitignore
55
55
  # already carries the anchored /.claude/ /.codex/ /.omp/ /.ukit/ exclusions.
56
56
  opencode.json
57
- AGENTS.md
58
- CLAUDE.md
57
+ /AGENTS.md
58
+ /CLAUDE.md
59
59
  docs/STATUS.md
60
60
  docs/TASKS.md
61
61
  .codex/settings.local.json
@@ -1,4 +1,5 @@
1
1
  # .omp/RULES.md — sticky always-apply rules
2
+ <!-- generated: templates/instructions/ — edit sources, then yarn docs:render -->
2
3
 
3
4
  omp re-attaches this file near every turn from its native location (`.omp/RULES.md` only, never a
4
5
  copy elsewhere). It carries the always-apply subset of root `AGENTS.md` that must survive even when
@@ -1,242 +1,139 @@
1
1
  # AGENTS.md — {{project.name}}
2
+ <!-- generated: templates/instructions/ — edit sources, then yarn docs:render -->
2
3
 
3
4
  ## Core Rule
4
-
5
- - Human-facing UKit workflow should collapse to one remembered command: `ukit install`.
5
+ <!-- RULES: CORE-01 CORE-02 -->
6
+ - Human-facing UKit workflow collapses to one remembered command: `ukit install`.
6
7
  - After install, default to natural-language work inside **Claude Code / Codex / OpenCode / omp**.
7
8
  - **Quality first, then speed, then token discipline.**
8
- - **Never stop after read-only steps.** For implement/apply/fix requests, continue to actual Edit/Write and verification in the same turn.
9
+ - **Never stop after read-only steps** — implement/apply/fix requests continue to Edit/Write + verification in the same turn.
9
10
 
10
11
  ## Fast Classification
11
-
12
- - **Trivial** — typo, label, small rename, spacing, toggle flag, obvious config change.
13
- - Act directly. No doc reads. No planning. No index. No agents.
14
- - **Simple** — 1-2 files, clear scope, existing pattern.
15
- - Handle directly. Pull only the smallest useful context via resolver or targeted read.
16
- - **Non-trivial / Risky** — auth, security, migration, uninstall, shared runtime, race/flaky, data-loss.
17
- - Read deeper, verify harder, and avoid shortcuts.
18
- - Use index-first loop, then skill activation, then targeted verification.
12
+ <!-- RULE: CLS-01 -->
13
+ - **Trivial** — typo, label, small rename, spacing, toggle flag, obvious config change. Act directly. No doc reads, planning, index, or agents.
14
+ <!-- RULE: CLS-02 -->
15
+ - **Simple** — 1-2 files, clear scope, existing pattern. Handle directly; pull only the smallest useful context via resolver or targeted read.
16
+ <!-- RULE: CLS-03 -->
17
+ - **Non-trivial / Risky** — auth, security, migration, uninstall, shared runtime, race/flaky, data-loss. Read deeper, verify harder; index-first loop → skill activation → targeted verification.
19
18
 
20
19
  ## Execution Contract (mandatory)
21
-
22
- - For explicit implement/apply/fix requests, **continue until the actual edit is made** or a real blocker is found.
23
- - Do NOT stop after a read-only inspection step (Read/Grep/Glob/search).
24
- - If routed state says `pull-indexed-context`, treat it as internal continuation — after the bounded read, **continue to edit/verify in the same turn** when safe.
25
- - If routed state shows `continuation required` or a stuck-lane rescue mode, finish the named milestone before widening reads or repeating analysis.
26
- - **Do NOT say "done", "applied", or "fixed" after Read/Grep/analysis alone.** Completion wording requires concrete Edit/Write evidence in the current turn, and verification when the scope is risky.
27
- - **Every stop says why — no silent idle.** When a turn ends because only the user can act (login, approval, protected-file edit), open the reply with one line naming the exact action: `WAITING ON YOU: <command/action>`, and schedule a one-shot wakeup (~20-30 min) when the harness provides one so the session re-checks and auto-continues once the user has acted. An ended turn cannot observe external/auth changes by itself, so without that line (and the wakeup) the idle session looks identical to a stall. Any error — failed command, hook, test, publish — is reported verbatim in the same turn, never silently retried past the user.
20
+ <!-- RULE: EXEC-01 -->
21
+ - For explicit implement/apply/fix requests, **continue until the actual edit is made** or a real blocker is found — never stop after a read-only inspection step.
22
+ <!-- RULE: EXEC-03 -->
23
+ - Routed states like `pull-indexed-context` or `continuation required` — treat it as an internal continuation step, not a stopping point; finish the named milestone before widening reads.
24
+ <!-- RULE: EXEC-02 -->
25
+ - **Do NOT say "done"/"applied"/"fixed" after Read/Grep/analysis alone** — completion wording requires concrete Edit/Write evidence this turn, plus verification when scope is risky.
26
+ <!-- RULE: EXEC-04 -->
27
+ - **Every stop says why — no silent idle.** Turns ending on a user-only action open with `WAITING ON YOU: <command/action>` plus a one-shot wakeup (~20-30 min) when available — an ended turn cannot observe external changes, so without it idle looks identical to a stall. Report any error verbatim the same turn.
28
28
 
29
29
  ## Long-Run Continuity
30
-
31
- Mirrors what UKit hooks inject at runtime on Claude Code and omp; on harnesses without hooks (Codex, OpenCode) this section is the only carrier — keep it in sync with `.claude/hooks/context-window-guard.sh`.
32
-
33
- - Near token-cap: **LAND one thing** — finish the smallest in-flight item end-to-end (edit + verify, ≤3 tool calls) and report it done. **DEFER the rest** — one line per remaining step into `docs/STATUS.md`, or split into bounded `docs/AI_HANDOFF/` tasks. **DELEGATE** broad work (searches, big reads, multi-file edits) to subagents whose tool output lives in their own windows. Only then compact.
34
- - After any compact or handoff: do not reread pre-compact context — continue from the persisted disk state, delegate broad work, keep replies short. If the first turn after a compact still sits at ≥60% of the cap, stop rereading immediately and recover by delegating or starting a fresh session from the disk state; do not burn the window again.
35
- - A run ends only on completion evidence, a genuine blocker, or a user-only action — and per the Execution Contract above, every such stop names its reason in the final reply.
30
+ <!-- RULES: LONG-01 LONG-02 -->
31
+ - Near token-cap: **LAND one thing** end-to-end (edit + verify, ≤3 tool calls), **DEFER** the rest into `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents. Only then compact.
32
+ - After any compact or handoff: continue from persisted disk state — never reread pre-compact context; delegate broad work, keep replies short.
33
+ - A run ends only on completion evidence, a genuine blocker, or a user-only action — every stop names its reason. Detail: `docs/UKIT_INTERNALS.md`.
36
34
 
37
35
  ## Index-First Loop
36
+ For any task needing code context:
38
37
 
39
- For any task that needs code context:
40
-
41
- 1. Check if index is fresh (`.cache/index/` artifacts). If stale or missing, refresh:
42
- - `node .claude/ukit/index/refresh-index.mjs`
43
- - fallback: `node .claude/ukit/index/build-index.mjs`
44
- 2. Query likely files:
45
- - `node .claude/ukit/index/query-index.mjs "<error|symbol|path>"`
46
- 3. For bug signatures:
47
- - `node .claude/ukit/index/triage.mjs "<error signature>"`
48
- 4. Open only the **top 1-3 suspect files first**, then widen if needed.
49
- `query-index` and `resolve-context` print an `outline:` block (`line: signature`) for the
50
- top suspects. Use it to jump straight to the relevant region with
51
- `Read(file, offset=<line>)` instead of reading the whole file.
52
- The outline locates code; it does not describe behaviour. **Any code you are about to
53
- change must still be read.**
54
- 5. For analog/reuse patterns, check if `resolve-context` returns related existing patterns.
55
-
56
- For clearly non-code specialist lanes (docs-only, status, task queue), skip the source-code index.
38
+ <!-- RULE: IDX-01 -->
39
+ 1. Check the index is fresh (`.cache/index/`); if stale/missing, refresh via `node .claude/ukit/index/refresh-index.mjs`.
40
+ 2. Query files: `node .claude/ukit/index/query-index.mjs "<error|symbol|path>"`; bug signatures: `triage.mjs "<error signature>"`.
41
+ <!-- RULE: IDX-02 -->
42
+ 3. Open only the **top 1-3 suspect files first**, then widen if needed — the `outline:` block lets you jump straight to `Read(file, offset=<line>)`.
43
+ <!-- RULE: IDX-03 -->
44
+ The outline locates code; it does not describe behaviour — **any code you are about to change must still be read**.
45
+ 4. For analog/reuse patterns, check `resolve-context`. Non-code lanes (docs-only, status, task queue) skip the source-code index.
57
46
 
58
47
  ## Automatic Skill Activation (mandatory)
59
-
60
- - End users should not need to know skill names.
61
- - On every non-trivial task — and again after the first relevant tool calls — inspect installed project-local skills and **auto-activate the matching skill immediately**.
62
- - Match from both prompt wording and tool/file evidence.
63
- - Use the smallest effective set, usually 1-2 skills.
64
- - If evidence becomes more specific than the original prompt, upgrade the active skill choice immediately.
65
- - If docs work is detected, read `.claude/skills/docs-quality/SKILL.md` when present.
66
- - Prefer routed context and routed verification over ad-hoc broad reading.
67
- - Reuse `.claude/ukit/skill-router-state.json` when it already carries compact route memory.
68
- - If shared route state already includes `previous-context` or `recent-output`, reuse those first.
48
+ <!-- RULE: SKILL-01 -->
49
+ - On every non-trivial task — and again after the first relevant tool calls — inspect installed project-local skills and **auto-activate the matching skill immediately**; end users should not need skill names. Match from prompt wording and tool/file evidence.
50
+ <!-- RULES: SKILL-02 SKILL-03 -->
51
+ - Use the smallest effective set (usually 1-2 skills); if evidence sharpens, upgrade the active skill choice immediately.
52
+ - Prefer routed context/verification over ad-hoc broad reading; reuse `.claude/ukit/skill-router-state.json` compact route memory.
69
53
 
70
54
  ### Common skill triggers
71
55
 
72
- - review / audit / diff / PR feedback → `.claude/skills/code-review/SKILL.md`
73
- - bug / error / crash / triage / failing path → `.claude/skills/debugging-toolkit/SKILL.md`
74
- - test / spec / coverage / fixture → `.claude/skills/testing-quality/SKILL.md`
75
- - docs / README / changelog / handoff / editing `docs/` / cleaning `docs/TASKS.md` → `.claude/skills/docs-quality/SKILL.md`
76
- - open-ended next step / project status / continue with no concrete target / choose queued task → `.claude/skills/next-step/SKILL.md`
77
- - explicit handoff / wrap up / update `docs/STATUS.md` → `.claude/skills/update-status/SKILL.md`
78
- - auth / security / token / permission / validation / risky shell-path-delete-db work → `.claude/skills/discover-security/SKILL.md`
79
- - stale workspace / reinstall / cleanup / maintenance → `.claude/skills/repo-maintenance/SKILL.md`
56
+ - review / audit / diff / PR feedback → `code-review` · bug / error / crash / triage → `debugging-toolkit` · test / spec / coverage / fixture → `testing-quality`
57
+ - docs / README / changelog / handoff / `docs/` edits → `docs-quality` (`.claude/skills/docs-quality/SKILL.md`) · open-ended / status / continue / queued task → `next-step` · wrap up / `docs/STATUS.md` update → `update-status`
58
+ - auth / security / token / permission / risky work → `discover-security` · stale workspace / reinstall / cleanup → `repo-maintenance` (all under `.claude/skills/<name>/SKILL.md`)
80
59
 
81
60
  ## Internal Helper Policy
82
-
83
- - Prefer `node .claude/ukit/index/route-task.mjs "<prompt>" [--tool-command <cmd>] [--target <file>]` when routing is complex or ambiguous.
84
- - Prefer `node .claude/ukit/index/resolve-context.mjs ...` for indexed related-file context.
85
- - Prefer `node .claude/ukit/index/verify-context.mjs ...` for concrete verification lanes.
86
- - **Do not ask normal contributors to run internal helper commands**; run them yourself or tell them to rerun `ukit install`.
87
- - Do not ask normal contributors to memorize `ukit doctor`, `ukit diff`, `ukit uninstall`, or `ukit index ...` unless they explicitly need maintainer/debug help.
88
- - If the workspace needs a refresh, prefer telling them to rerun `ukit install`.
61
+ <!-- RULES: HELP-01 HELP-02 -->
62
+ - Prefer the internal index helpers (`node .claude/ukit/index/route-task.mjs`, `resolve-context.mjs`, `verify-context.mjs`) for routing, related-file context, and verification.
63
+ - **Do not ask normal contributors to run internal helper commands** or memorize maintainer commands (`ukit doctor`, `ukit diff`, `ukit uninstall`) — run them yourself.
64
+ <!-- RULE: FALLBACK-01 -->
65
+ - Missing/corrupt runtime files or stale workspace → tell maintainers to rerun `ukit install`. Detail: `docs/UKIT_INTERNALS.md`.
89
66
 
90
67
  ## Skill Quality (maintainer-only)
91
-
92
- - When editing a template skill/agent under `templates/.claude/`, read `.claude/skills/skill-quality/SKILL.md` before shipping the change.
68
+ - When editing a template skill/agent under `templates/.claude/`, read `.claude/skills/skill-quality/SKILL.md` before shipping.
93
69
 
94
70
  ## UKit v{{ukit.version}} Shared Runtime
95
-
96
- - Shared runtime state lives in `.ukit/storage/`.
97
- - Treat `.ukit/storage/config.json` as the source of runtime toggles for compact, token pipeline, router, memory, validation, and Safe Patch behavior.
98
- - Reuse `.ukit/storage/memory/` before asking users to restate decisions.
99
- - For non-trivial work, prefer `ukit memory recall "<current task>"` before widening doc reads.
100
- - Reusable cache/compact/output state lives in `.ukit/storage/cache/prompt-cache.json`, `.ukit/storage/cache/compact-history.json`, `.ukit/storage/cache/compact-pressure.json`, `.ukit/storage/cache/output-history.json`, and preserved raw tool outputs under `.ukit/storage/cache/tee/`.
101
- - Shared route memory lives in `.claude/ukit/skill-router-state.json`.
102
- - If shared route state already includes compact `previous-context` or `recent-output`, reuse those first.
103
- - If an older repo still has a visible `ukit/` runtime root, rerun `ukit install`; UKit should migrate the shared runtime into hidden `.ukit/` when safe.
104
- - Maintainers can inspect runtime state with `ukit status` and `ukit memory export`, but normal teammates should still only need `ukit install`.
105
- - If runtime files are missing or corrupt, tell maintainers to rerun `ukit install`.
106
- - Threshold-based compact pressure is internal orchestration; do not expose it to users.
107
- - For Codex Desktop long sessions, UKit can use soft auto-compact handoffs. Default `compact.codexContext.compactTarget=150` means about 150 compact handoff lines (120-150 preferred, hard max 170), not 150 tokens.
71
+ - Runtime state lives in `.ukit/storage/`; `.ukit/storage/config.json` holds runtime toggles (compact, token pipeline, router, memory, validation, Safe Patch).
72
+ - Reuse `.ukit/storage/memory/` + `ukit memory recall "<current task>"` before asking users to restate decisions; inspect via `ukit status` / `ukit memory export`.
73
+ - Route memory: `.claude/ukit/skill-router-state.json` — reuse compact `previous-context`/`recent-output` first. Cache state: `.ukit/storage/cache/output-history.json`, tee/. Missing/corrupt runtime or old `ukit/` root → rerun `ukit install`. Detail: `docs/UKIT_INTERNALS.md`.
108
74
 
109
75
  ## Prompt Caching
110
-
111
- - Deterministic, stable context lets a provider reuse a prompt prefix — and it is worth doing even when no caching is guaranteed.
112
- - Full ruleset: `docs/PROMPT_CACHING.md` (read on demand; it is not loaded into every session).
76
+ <!-- RULES: CTX-01 CTX-02 CTX-03 CTX-04 CTX-05 CTX-06 CTX-07 CTX-08 CTX-09 CTX-10 -->
77
+ - Full ruleset: `docs/PROMPT_CACHING.md` (read on demand; not loaded every session).
113
78
  - CTX-01 deterministic segment bytes · CTX-02 keep roles and order · CTX-03 keep tool IDs and continuation state · CTX-04 no clock/random IDs in static blocks · CTX-05 compaction starts a new epoch · CTX-06 never change data to match a cache · CTX-07 no unconfirmed cache fields · CTX-08 tool-result reuse needs valid freshness · CTX-09 missing usage is unknown, not zero · CTX-10 never cut a required check to reduce calls.
114
- - Never sort messages, trim meaningful whitespace, rewrite reasoning fields, or move a user request into system context.
115
- - Upstream vendor docs are reference only — never a guarantee about the route you actually use.
116
79
 
117
80
  ## Safe Patch Protocol
118
-
119
- - Safe Patch is internal orchestration: normal users still only need `ukit install` and natural language.
120
- - For risky/shared/large edits, prefer unique current-file anchors over line numbers or stale pasted blocks.
121
- - Do not silently merge stale specs: if `old_string` is missing or ambiguous, re-read current source and ask whether to apply as-is, adapt, or skip.
122
- - Preserve UTF-8 BOM/no-BOM and LF/CRLF for existing multilingual/user-authored files.
123
- - Use `node .claude/ukit/index/safe-patch.mjs` internally when normal Edit/Write may normalize bytes or when anchor-based matching is needed.
81
+ <!-- RULES: SAFE-02 SAFE-03 SAFE-01 -->
82
+ - Risky/shared/large edits: prefer unique current-file anchors over line numbers or stale pasted blocks; if `old_string` is missing/ambiguous, re-read current source and ask whether to apply as-is, adapt, or skip.
83
+ - Preserve UTF-8 BOM/no-BOM and LF/CRLF for existing multilingual/user-authored files. Helper: `node .claude/ukit/index/safe-patch.mjs`; detail: `docs/UKIT_INTERNALS.md`.
124
84
 
125
85
  ## Handoff Quality Gate — OPT-IN
126
-
86
+ <!-- RULE: HAND-01 -->
127
87
  CHỈ kích hoạt khi task đi qua `docs/AI_HANDOFF/` (user nói "execute task TASK-xxx" hoặc target là `docs/AI_HANDOFF/tasks/*.md`). Daily prompt → KHÔNG đụng, flow cũ giữ nguyên.
128
88
 
129
- Khi Handoff mode: đọc `docs/AI_HANDOFF/RULES.md` để biết 4 phase (Idea+Plan → Create Tasks → Implement+Test → Review+Test) + state machine + comment thread + self-report model. Config: `.ukit/storage/config.json` → `handoff.*`.
89
+ Khi Handoff mode: đọc `docs/AI_HANDOFF/RULES.md` để biết 4 phase (Idea+Plan → Create Tasks → Implement+Test → Review+Test) + state machine + self-report model. Config: `.ukit/storage/config.json` → `handoff.*`.
130
90
 
131
91
  ## Context + Verification Budget
132
-
133
- - **Trivial**: no docs, and no index query unless the file target is unclear.
134
- - **Simple**: `docs/MEMORY.md` only, plus resolver-selected files/tests.
135
- - **Non-trivial**: `docs/MEMORY.md` + `docs/PROJECT.md` + `docs/CODE_MAP.md`.
136
- - `docs/STATUS.md`: use for open-ended status/continue prompts or meaningful continuation context; stale status is orientation only.
137
- - `docs/TASKS.md`: use only for queued-task prompts or when status points at queued work; safely clean exact duplicates/completed overflow by default without deleting unfinished human-authored tasks.
138
- - `docs/WORKLOG.md`: only recent relevant entries. Follow the Budget Rules at the top of the file; archive oldest entries to `docs/WORKLOG_ARCHIVE.md` when over limits.
139
- - Follow routed verification policy: targeted first, widen only when risk/shared scope justifies it, ask before blanket broad runs.
92
+ <!-- RULE: BUDGET-01 -->
93
+ - **Trivial**: no docs, no index query unless the file target is unclear. **Simple**: `docs/MEMORY.md` only + resolver-selected files/tests. **Non-trivial**: `docs/MEMORY.md` + `docs/PROJECT.md` + `docs/CODE_MAP.md`.
94
+ <!-- RULES: BUDGET-02 BUDGET-03 -->
95
+ - `docs/STATUS.md` for open-ended/continue prompts; `docs/TASKS.md` only for queued-task prompts; `docs/WORKLOG.md` recent entries only (archive overflow). Verification: targeted first, widen only on risk/shared scope, ask before blanket broad runs.
140
96
 
141
97
  ## Living Status Workflow
142
-
143
- - `docs/STATUS.md` captures compact current state, active work, debug threads, blockers, verification, and next candidates.
144
- - It is not source truth and must not replace source/index-first investigation.
145
- - For "what next?" / "continue" prompts without a concrete target, use `next-step` and show a freshness cue before relying on the status file.
146
- - For concrete debug/implementation/review prompts, keep the concrete workflow primary even if the user asks for an approach or next step.
147
- - After meaningful work, use `update-status`; skip trivial/no-state-change tasks and avoid transcript-style noise.
148
- - `docs/TASKS.md` is a local AI task queue: prefer `Ready for AI` when asked to pick queued work, and clean duplicates/prune `Done Recently` safely when reading/updating it.
98
+ <!-- RULE: STATUS-01 -->
99
+ - `docs/STATUS.md` captures compact current state — not source truth, never replaces source/index-first investigation.
100
+ - "What next?"/"continue" → `next-step` with a freshness cue; after meaningful work → `update-status`. `docs/TASKS.md` is the local AI task queue — prefer `Ready for AI`. Detail: `docs/UKIT_INTERNALS.md`.
149
101
 
150
102
  ## Small-Task Maintainer (internal)
151
-
152
- - UKit may route low-risk internal decisions to the `ukit-small-task-maintainer` subagent using `subagents.smallTaskModel` (default `unic-lite`).
153
- - Use it for safe/reversible UKit chores: dọn `docs/TASKS.md`, queued-task classification, fast-vs-slow/safe-vs-risky lane decisions, skill-routing/step-budget hints, agent context-budget decisions, compact/summary decisions, docs/status summarization, auto-triage, queue maintenance, and small workspace cleanup.
154
- - Run it as a sidecar/parallel lane only; do not block, replace, or slow the user task.
155
- - If the small-task lane sees security, risky/shared code, release/publish, data-loss, architecture, deep-reasoning risk, weak context, or quality risk, it hands back to the main model.
156
- - This is optional internal orchestration config from `.ukit/storage/config.json`; never turn it into an end-user workflow.
157
- - Always preserve the CoDev priority: quality > safety > speed > token discipline.
103
+ <!-- RULE: SUBAG-02 -->
104
+ - The `ukit-small-task-maintainer` subagent (`subagents.smallTaskModel`, default `unic-lite`) handles safe/reversible UKit chores as a sidecar lane — never block or slow the user task; risky work hands back to the main model. Detail: `docs/UKIT_INTERNALS.md`.
158
105
 
159
106
  ## Post-Edit Sidecar Review (internal)
160
-
161
- - If routed state's `routeSummary.line` includes a `review=code-reviewer(diff)` segment, a `local-build` or `shared-edit` task qualifies for a non-blocking second opinion — this exists because the daily-flow executor model can miss edge cases.
162
- - Only launch it once write evidence AND verification evidence already exist for the task (never before; never as a substitute for either).
163
- - Launch the `code-reviewer` agent (see the harness table under 3-Tier Model Routing) with `REVIEW_TARGET_TYPE=diff`, in the background, on the `smart` tier per `subagents.diffReviewModel`. Do not wait for it — continue and report the task as done using the normal completion rules.
164
- - Its findings are advisory only: never re-open, block, or delay the already-reported completion on their account. Surface them to the user as a follow-up note if/when they arrive.
165
- - This is internal orchestration — end users never invoke it directly; `ukit install` plus natural language remains the whole surface. No new commands.
107
+ - When routed state's `routeSummary.line` carries `review=code-reviewer(diff)`, launch `code-reviewer` in background (`smart` tier) **only after** write + verification evidence; findings advisory — never block the reported completion. Detail: `docs/UKIT_INTERNALS.md`.
166
108
 
167
109
  ## Selective Subagent Policy (internal only)
168
-
169
- - Keep direct execution as the default for trivial/simple work.
170
- - Delegate only when it meaningfully shrinks context or enables useful parallel progress.
171
- - Good delegation triggers:
172
- - noisy side lanes (broad logs/search/test output)
173
- - 3+ independent failures/files/checks
174
- - explicit batch/plan execution
175
- - broad implementation/debug lanes that can return a concise summary
176
- - If route memory includes `delegate=<lane>`, treat it as an internal hint after any required indexed-context step.
177
- - Do not ask end users to name agents or remember agent commands.
110
+ <!-- RULE: SUBAG-01 -->
111
+ - Direct execution is default for trivial/simple work; delegate only on meaningful context shrink or parallel gains (noisy side lanes, 3+ independent failures, batch plans). Never ask end users to name agents or remember agent commands.
178
112
 
179
113
  ## Adaptive Autonomy
180
-
181
- - `autonomy.level` in `.ukit/storage/config.json` controls how much UKit acts without asking first: `conservative` (ask more), `balanced` (default), `free-run` (auto-run more), `vibecode` (run one prompt to a finished result; the completion gate stops only on completion evidence, a genuine blocker, or a dangerous-command decision).
182
- - End users should not need to change this; maintainers may tune it per-project.
114
+ <!-- RULE: AUTO-01 -->
115
+ - `autonomy.level` in `.ukit/storage/config.json` controls how much UKit acts without asking: `conservative` (ask more), `balanced` (default), `free-run` (auto-run more), `vibecode` (one prompt to a finished result; the gate stops only on completion evidence, a genuine blocker, or a dangerous-command decision). End users should not need to change it.
183
116
 
184
117
  ## 3-Tier Model Routing
185
-
118
+ <!-- RULES: TIER-01 TIER-02 -->
186
119
  **Internal orchestration only — end users still just use natural language. No new commands.**
187
120
 
188
- UKit routes tasks to one of three model tiers based on task complexity:
189
-
190
121
  | Tier | Generic alias | Claude model | Typical tasks |
191
122
  |------|--------------|--------------|---------------|
192
123
  | lite | `unic-lite` | claude-haiku | Reads, git queries, bash summaries, small doc edits |
193
124
  | code | `unic-code` | claude-sonnet | Normal coding, local fixes, shared edits, builds, debugging, impact mapping |
194
- | smart | `unic-smart` | claude-opus | Release review/audit, and escalated deep reasoning after repeated failure |
195
-
196
- ### Contract-to-tier mapping
125
+ | smart | `unic-smart` | claude-opus | Release review/audit, escalated deep reasoning after repeated failure |
197
126
 
198
- | Contract | Tier |
199
- |----------|------|
200
- | `tiny-fix` | lite |
201
- | `local-fix`, `local-build`, `shared-edit`, `find-cause`, `map-impact` | code |
202
- | `review-release` | smart |
203
-
204
- ### How a tier is actually bound
205
-
206
- The main session model never changes mid-turn. A tier only takes effect when work is handed to
207
- an agent whose own definition binds that model:
208
-
209
- | Harness | Agent definitions | How to launch one |
210
- |---------|-------------------|-------------------|
211
- | Claude Code | `.claude/agents/*.md` (`model:` frontmatter) | Agent tool, `subagent_type: "<name>"` |
212
- | omp | `.omp/agents/*.md` (`model: "@lite"` / `"@code"` / `"@smart"` / `"@vision"`, resolved through `modelRoles` in `.omp/config.yml`) | task-agent `<name>` |
213
-
214
- When a task's contract maps to a tier other than the current session model, hand it to the
215
- matching agent instead of doing it inline. Doing everything inline is exactly what makes UKit
216
- behave as if it only had one model — the tier table above has no effect on its own.
217
-
218
- ### Escalation rule
219
-
220
- When the same file or symbol fails `debugLoopThreshold` (default: 2) times in one session, UKit routes the next attempt one tier higher (capped at `smart`). Config: `orchestration.escalation` in `.ukit/storage/config.json`.
221
-
222
- This is internal orchestration — end users do not need to know about tiers, thresholds, or escalation. The AI handles routing transparently.
223
-
224
- ### Vision lane (capability, not a cost tier)
225
-
226
- `unic-vision` is a **capability lane**, not a fourth cost tier — it is orthogonal to lite/code/smart above and never appears as a row in the tier table. Whether a mapping can read images is a capability fact, not a provider fact: a mapping that has not **verified** native vision must never guess at image contents — choose native-first when verified, otherwise route to the specialist.
227
-
228
- - **Gateway detection**: UNIC routing for a Claude Code session is decided ONLY by what changes Claude Code's own outbound endpoint — `ANTHROPIC_BASE_URL` (env var, or the `env.ANTHROPIC_BASE_URL` key in project/home `.claude/settings.json`) containing `unicjsc.com`. Other tools' configs — Codex `config.toml`, Kilo `secrets.json`, or an `OPENAI_BASE_URL` env var — describe a different tool's endpoint entirely and never decide this session's routing.
229
- - **Advisory routing (no hard block)**: when an image reaches the prompt, the vision router reminds the session to have `ukit-vision-analyst` analyse it before relying on its contents. Edits are **never blocked** — correctness relies on the model routing images to the analyst instead of guessing.
230
- - This is internal orchestration — end users never invoke a vision command directly; `ukit install` plus natural language remains the whole surface. No new commands.
127
+ - A tier takes effect only when work is handed to an agent whose definition binds that model (`model:` frontmatter in `.claude/agents/*.md`; `model:` `@lite`/`@code`/`@smart`/`@vision` in `.omp/agents/*.md` via `modelRoles`) — the main session model never changes mid-turn.
128
+ - Contract map: `tiny-fix` → lite · `local-fix`, `local-build`, `shared-edit`, `find-cause`, `map-impact` → code · `review-release` → smart. Escalation: same file/symbol failing `debugLoopThreshold` (default 2) times routes the next attempt one tier higher, capped at `smart`.
129
+ - `unic-vision` is a capability lane, not a cost tier — unverified vision must never guess image contents; route images to `ukit-vision-analyst`. Harness table: `docs/UKIT_INTERNALS.md`.
231
130
 
232
131
  ## Session Start — OpenCode
233
132
 
133
+ <!-- RULE: HOST-OC-01 -->
234
134
  At the start of every OpenCode session, before working on the first task:
235
- 1. Check `.claude/ukit/skill-router-state.json` — if `line` has route hints matching the current task, reuse them instead of re-routing from scratch.
236
- 2. Note which skills are installed by scanning `.claude/skills/` (directory listing only); read the full SKILL.md only when a task triggers it.
237
- 3. For every non-trivial task: run `/ukit-route <task summary>` immediately to get skill + context hints **before** writing any code.
238
- 4. If the route result points to a skill, read that SKILL.md before acting — do not skip this step.
239
- 5. If `.ukit/storage/config.json` has `router.enabled: true`, prefer the router output over ad-hoc guessing.
135
+ 1. Reuse matching route hints from `.claude/ukit/skill-router-state.json`; scan `.claude/skills/` (listing only) and read a SKILL.md only when a task triggers it.
136
+ 2. For every non-trivial task, run `/ukit-route <task summary>` for skill + context hints **before** writing code; if it names a skill, read that SKILL.md — do not skip. When `router.enabled: true` in `.ukit/storage/config.json`, prefer router output over guessing; treat it as internal continuation — continue to edit/verify, don't stop.
240
137
 
241
138
  ## Project Owner Instructions — Codex and OpenCode
242
139
 
@@ -245,61 +142,35 @@ When running in Codex or OpenCode, read and follow the root
245
142
  project-owner instruction source. Do not copy its contents into this file.
246
143
  If it is missing or unreadable, state that limitation and continue with the
247
144
  remaining project instructions.
248
-
145
+ <!-- RULES: OWN-01 HOST-OWN-01 -->
249
146
  ## Skills
250
-
251
- - Canonical skills live in `.claude/skills/`.
252
- - Adapter mirrors may also exist, for example `.codex/skills/` → `.claude/skills/` (symlink). **omp** has no mirror: it reads `.claude/skills/` directly through its own `claude` discovery provider.
253
- - **OpenCode**: reads `AGENTS.md` at session start only — it does NOT auto-load `.claude/skills/`. The model must explicitly read the triggered SKILL.md.
254
- - If `opencode.json` ships `ukit-*` commands, treat them as internal helper entrypoints only and **never ask end users to run them**; humans should still only need `ukit install`.
147
+ - Canonical skills live in `.claude/skills/`; adapter mirrors may exist (`.codex/skills/` → symlink). **omp** reads `.claude/skills/` via its `claude` discovery provider.
148
+ - **OpenCode**: reads `AGENTS.md` at session start only — it does NOT auto-load skills; the model must explicitly read the triggered SKILL.md.
149
+ - `ukit-*` commands in `opencode.json` are internal helper entrypoints — never ask end users to run them.
255
150
 
256
151
  ## Project Snapshot
257
-
258
152
  - Project: {{project.name}} | Root: {{project.root}}
259
153
  - Packs: {{project.stack}} | Frontend: {{stack.frontend}} | Backend API: {{stack.backendApi}} | PostgreSQL: {{stack.postgres}}
260
154
  - Package manager: {{runtime.packageManager}} | OS: {{runtime.os}} | Node: {{runtime.nodeVersion}} | Provider: {{providers.unic}}
261
155
 
262
156
  ## Working Rules
263
-
264
157
  - Keep scope tight, prefer the smallest correct change set, and reuse existing code.
265
- - For explicit implement/apply/fix requests, keep working until the actual edit is made or a real blocker is found; do not stop after a read-only inspection step.
266
- - If routed state still says `pull-indexed-context`, treat it as an internal continuation step, not a stopping point.
267
- - If routed state shows `continuation required` or a stuck-lane rescue mode, finish the named milestone before widening reads or rephrasing the same partial status.
268
- - Never claim "done", "applied", or "fixed" after Read/Grep/analysis alone. Completion language requires concrete Edit/Write evidence in the current turn, plus verification when the change is risky.
269
- - Update `docs/WORKLOG.md` after significant work.
270
- - If source contradicts docs, update docs immediately.
158
+ - Update `docs/WORKLOG.md` after significant work; if source contradicts docs, update docs immediately.
271
159
  - Use `{{runtime.packageManager}}`.
272
160
 
273
161
  ## DuraOne Skill — Conditional Activation
274
-
275
- DuraOne skill chỉ active khi pack `duraone` được cài hoặc `.claude/skills/duraone/SKILL.md` tồn tại.
276
-
277
- - Khi active: luôn đọc `.claude/skills/duraone/SKILL.md` trước khi code.
278
- - References:
279
- - `.claude/skills/duraone/references/frontend.md`
280
- - `.claude/skills/duraone/references/backend.md`
281
- - `.claude/skills/duraone/references/sql.md`
282
- - `.claude/skills/duraone/references/workflow.md`
283
- - Khi không active: dùng generic coding standards + project-specific patterns từ index.
162
+ <!-- RULE: DURA-01 -->
163
+ DuraOne skill chỉ active khi pack `duraone` được cài hoặc `.claude/skills/duraone/SKILL.md` tồn tại — khi active, luôn đọc SKILL.md + references trước khi code; khi không, dùng generic standards + index patterns. Chi tiết: `docs/UKIT_INTERNALS.md`.
284
164
 
285
165
  ## Completion Checklist
286
-
287
- - Requirements implemented
288
- - No unrelated changes
289
- - Verification executed and reported
290
- - Docs updated when source truth changed
291
-
166
+ - Requirements implemented · No unrelated changes · Verification executed and reported · Docs updated when source truth changed.
292
167
 
293
168
  ## Handoff Fullstack Rules
294
-
295
- - `docs/AI_HANDOFF/RUN.md` là run cursor có thẩm quyền; `Phase:` ≠ `done`/`blocked` nghĩa là run còn sống — Stop gate sẽ từ chối stop và trả về `Next:` step.
296
- - Recap/checkpoint không bao giờ là completion — chỉ `HANDOFF FULLSTACK COMPLETE` (sau khi `Phase: done`) hoặc `HANDOFF FULLSTACK BLOCKED` (sau khi `Phase: blocked`) mới kết thúc run.
297
- - Resume tự động mọi task chưa xong: current, legacy, pending, interrupted, recovery (`-R<n>` thay `cancelled_superseded`), và task mới được giao.
298
- - Handoff-create phải viết `docs/AI_HANDOFF/SPEC.md` chi tiết trước khi tạo task; task nào cũng mang `Spec references`.
299
- - Kết thúc cycle: docs sync → archive `docs/AI_HANDOFF/archive/cycle-NN/` → `Phase: done` → Final Report có marker.
300
- - `handoff-clear` bắt buộc đóng RUN.md (`Phase: done` hoặc xóa) — cursor sống sẽ giữ Stop gate chặn session sau.
169
+ <!-- RULE: HAND-02 -->
170
+ - `docs/AI_HANDOFF/RUN.md` là run cursor có thẩm quyền; `Phase:` ≠ `done`/`blocked` nghĩa là run còn sống — Stop gate từ chối stop và trả về `Next:` step.
171
+ - Recap/checkpoint không bao giờ là completion — chỉ `HANDOFF FULLSTACK COMPLETE` (sau `Phase: done`) hoặc `HANDOFF FULLSTACK BLOCKED` (sau `Phase: blocked`) mới kết thúc run. Resume tự động mọi task chưa xong (current, legacy, pending, interrupted, recovery `-R<n>`).
172
+ - Kết thúc cycle: docs sync → archive `docs/AI_HANDOFF/archive/cycle-NN/` → `Phase: done`. `handoff-clear` bắt buộc đóng RUN.md. Full rules: `docs/AI_HANDOFF/RULES.md`.
301
173
 
302
174
  ## Compact Instructions
303
-
304
175
  Khi compact giữa một handoff run: giữ lại goal, RUN.md path + phase hiện tại, task inventory, task đang làm, `Next:` step, blockers, verification evidence, commits, worktree/copy-back state, và quy tắc "compact không phải completion". Sau compact: đọc lại RUN.md + INDEX.md rồi chạy tiếp `Next:` ngay.
305
176
  {{codegraphSection}}