@multileaf/ai-workflow 0.6.1 → 0.8.0

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.
package/docs/telemetry.md CHANGED
@@ -9,7 +9,9 @@ During an interactive `aiw install`, after the optional model questions, the ins
9
9
  ## Controls
10
10
 
11
11
  ```bash
12
- aiw telemetry status
12
+ aiw telemetry show # buffered events summarized by command and outcome
13
+ aiw telemetry show --verbose # ...plus each event verbatim
14
+ aiw telemetry status # configuration only
13
15
  aiw telemetry enable --commands=include --outcomes=include
14
16
  aiw telemetry enable --commands=exclude --outcomes=include
15
17
  aiw telemetry disable
@@ -0,0 +1,135 @@
1
+ # Token Efficiency Research
2
+
3
+ Research notes and external references for the open problem: **guaranteeing low token consumption without sacrificing output quality**. This document consolidates published methodologies, open-source implementations, and a recommended path for AI Workflow.
4
+
5
+ > Methodology note: sources were collected via GitHub Search API and web search. Descriptions and savings figures come from the projects' own READMEs and blog posts and have not been independently validated. Last reviewed: October 2026.
6
+
7
+ ## The core problem
8
+
9
+ Token optimization without a quality constraint is indistinguishable from degradation. Every credible source converges on the same inversion of the problem:
10
+
11
+ 1. **Fix quality first** as a measurable constraint (benchmark of real work).
12
+ 2. **Then minimize cost subject to that constraint.**
13
+
14
+ "Guaranteeing" low consumption is only possible once quality is pinned to a benchmark that an optimization cannot silently regress.
15
+
16
+ ## Reference publications
17
+
18
+ | Publication | Key contribution | Relevance to AI Workflow |
19
+ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
20
+ | Uber Engineering — [Running a Software Factory Efficiently at Uber Scale](https://www.uber.com/blog/efficient-software-factory/) | Cost equation decomposed into six multiplicative, independently measurable terms; sequential driver decomposition with no unexplained residual; outcome-denominated cost (cost per merged PR, per triaged alert) | The measurement model to adopt: decompose, attribute, and denominate cost by unit of value |
21
+ | Anthropic — [Prompt Caching](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching) and [Token-Saving Updates](https://www.anthropic.com/news/token-saving-updates) | Cache reads at ~0.1x input price; TTL economics (5 min at 1.25x write, 1 h at 2x); thinking blocks cached in tool-use loops | Cache-friendly ordering of system prompt, rules, and project profile |
22
+ | Microsoft Azure — [The Economics of Agent Optimization](https://azure.microsoft.com/en-us/blog/the-economics-of-agent-optimization-context-engineering-for-enterprise-ai-agents/) | Context engineering framed as the primary economic lever for enterprise agents | Aligns with product principle 6 (just-in-time context) |
23
+ | LMSYS — [RouteLLM](https://www.lmsys.org/blog/2024-07-01-routellm/) | Formal cost/quality trade-off for model routing; 2x+ cost reduction with quality held | Routing strategy for the provider-neutral `AiProvider` interface |
24
+ | GetBeam — [AI Agent Token Cost Optimization](https://getbeam.dev/blog/ai-agent-token-cost-optimization.html) | Practical case study with spend decomposition | Cross-check on decomposition methodology |
25
+
26
+ ### Common pattern across publications
27
+
28
+ Savings never come from a single technique. The pattern is:
29
+
30
+ 1. Measure per task, not per aggregate.
31
+ 2. Pin quality with a benchmark built from real work.
32
+ 3. Optimize each cost term separately (price/token, tokens/request, requests/turn).
33
+ 4. Hold the model constant when attributing savings (behavior shifts with every upgrade).
34
+
35
+ ## Repositories by category
36
+
37
+ ### Context engineering and token reduction
38
+
39
+ | Repository | Stars | Notes |
40
+ | ------------------------------------------------------------------------------------------------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
41
+ | [microsoft/LLMLingua](https://github.com/microsoft/LLMLingua) | ~6.8k | Prompt compression (EMNLP'23, ACL'24); 5–20x compression. `gladehq/claude-shorthand` applies it to Claude Code (~55% claimed). Last-resort layer due to quality risk. |
42
+ | [ratel-ai/ratel](https://github.com/ratel-ai/ratel) | ~484 | Context engineering for agents: ~80% fewer tokens via fixing tool overload; in-process BM25 skills and memory. Architecturally the closest peer. |
43
+ | [jia-gao/leanctx](https://github.com/jia-gao/leanctx) | ~323 | Drop-in prompt compression, 40–60% claimed without app changes. |
44
+ | [rossoclt/context-guru](https://github.com/rossoclt/context-guru) | ~70 | Context optimization for coding agents: lower cost and latency "without sacrificing accuracy". |
45
+ | [pleasedodisturb/awesome-llm-token-optimization](https://github.com/pleasedodisturb/awesome-llm-token-optimization) | ~99 | **The reference map.** Quick-wins table (cache 90% input, routing 60–95%, batch 50%, compression 5–20x), papers, and tools by category. Read first. |
46
+ | [wai-21/llm-token-optimization](https://github.com/wai-21/llm-token-optimization) | ~2 | Decision Distillation, skill routing; 60–99% claimed. Unvalidated. |
47
+ | [8b-is/smart-tree](https://github.com/8b-is/smart-tree) | ~271 | Context-aware filesystem tooling replacing 20+ tools; token reduction via tool design. |
48
+
49
+ ### Telemetry across harnesses
50
+
51
+ | Repository | Stars | Notes |
52
+ | --------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
53
+ | [pulsemcp/switchboard](https://github.com/pulsemcp/switchboard) | new | Self-hosted capture of agent transcripts (Claude Code, Codex, others). Cross-harness data source without vendor lock-in — the piece Uber gets from its gateway but a portable system must build. |
54
+ | [DeepAgentLabs/agenticlens](https://github.com/DeepAgentLabs/agenticlens) | ~58 | Open-source profiler: token usage, cost, latency, and optimization opportunities per session. |
55
+ | [traceloop/openllmetry](https://github.com/traceloop/openllmetry) | ~7.5k | GenAI observability on OpenTelemetry. The interoperable schema to adopt if telemetry grows beyond local use. |
56
+ | [gocenalper/agent-optimization](https://github.com/gocenalper/agent-optimization) | ~12 | Live token monitor for Claude Code / Codex: cost tracking, analysis, LLM-powered suggestions. |
57
+ | [BerriAI/litellm](https://github.com/BerriAI/litellm) | high | Proxy with routing and cost tracking for 100+ providers; candidate neutral measurement layer. |
58
+ | [timharris707/modeldeck](https://github.com/timharris707/modeldeck) | ~116 | Usage/quota tracking across Claude Code and Codex accounts. |
59
+
60
+ ### Harnesses, workflows, and SDD
61
+
62
+ | Repository | Stars | Notes |
63
+ | ----------------------------------------------------------------------------------- | ----- | --------------------------------------------------------------------------------------------------------------- |
64
+ | [github/spec-kit](https://github.com/github/spec-kit) | ~142k | De-facto standard for spec-driven development; direct philosophical competitor. |
65
+ | [cisco-open/ai-harness-toolkit](https://github.com/cisco-open/ai-harness-toolkit) | ~15 | Skills for assessing AI-native engineering workflows in repositories. |
66
+ | [Zoria-Lind/dsh-token-optimizer](https://github.com/Zoria-Lind/dsh-token-optimizer) | ~20 | Layered pipeline: output ladder, MCP lazy loading, compaction driver. Small but architecturally interesting. |
67
+ | [ComposioHQ/composio](https://github.com/ComposioHQ/composio) | ~30k | 1000+ toolkits with tool search and context management — the "tool search" pattern Uber describes, productized. |
68
+
69
+ ### Benchmarks with quality data (fix quality before optimizing)
70
+
71
+ | Repository | Stars | Notes |
72
+ | ------------------------------------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
73
+ | [HumphreySun98/repoagentbench](https://github.com/HumphreySun98/repoagentbench) | ~27 | Mines merged PRs into a local, contamination-free coding-agent benchmark. This is Uber's uReview methodology, open-sourced. |
74
+ | [mupt-ai/self-bench](https://github.com/mupt-ai/self-bench) | ~33 | Benchmarks agents on your own repository, Harbor-formatted evals. |
75
+ | [jettison-ai/jettison-parity](https://github.com/jettison-ai/jettison-parity) | new | Benchmark harness for context-optimization middleware: task parity, session cost, harness-agnostic. Defines exactly the experiment needed: same task, different context configuration, measure cost and quality. |
76
+
77
+ ## Savings reference table
78
+
79
+ From the awesome-list and Uber's post, ordered by effort-to-savings ratio:
80
+
81
+ | Lever | Claimed savings | Quality risk | Applies at |
82
+ | -------------------------------------------- | ---------------------- | -------------------------- | ----------------------- |
83
+ | Prompt prefix caching | ~90% of cached input | None (transparent) | Provider layer |
84
+ | Tool schema lazy loading / tool search | 50–70K tokens/session | Low | Harness / MCP layer |
85
+ | Model routing (cheap model for simple tasks) | 60–95% on routed calls | Medium — needs benchmark | Provider / orchestrator |
86
+ | Batch APIs for non-urgent work | ~50% | None (same output) | Provider layer |
87
+ | Code-mode / batched tool calls | 55–100% per workflow | Low | Harness layer |
88
+ | Compaction budget | Context-dependent | Medium | Harness layer |
89
+ | Prompt compression (LLMLingua) | 5–20x | High — degrades edge cases | Last resort, middleware |
90
+
91
+ Combined pipelines claim 95–99% versus a naive baseline, but every high-risk row requires the quality gate below.
92
+
93
+ ## Recommended path for AI Workflow
94
+
95
+ A four-step guarantee pipeline, reusing existing pieces:
96
+
97
+ ### Step 1 — Fix quality with a self-benchmark
98
+
99
+ Mine real SDD tasks (specs, plans, verification results from `.aiw/checkpoints/` and `.aiw/generated/`) into an evaluable set, following the `repoagentbench` / `self-bench` pattern. Define the acceptance rule: **an optimization ships only if outcome does not fall below threshold X% on the benchmark.** AI Workflow already has the ingredients: `evidence.ts`, `traceability.ts`, quality gates, and `src/fixtures`.
100
+
101
+ ### Step 2 — Decompose cost per term
102
+
103
+ Extend `token-usage.ts` toward Uber-style decomposition, per SDD stage and per skill:
104
+
105
+ - input vs output vs cached tokens per request;
106
+ - requests per turn and turns per task;
107
+ - cost per **verified requirement** (outcome-denominated), not per session.
108
+
109
+ Data sources: agent JSONL logs (Claude Code, Codex — the `switchboard` approach) plus AIW checkpoints. Deliver through the existing `dashboard.ts`, evolving it toward anti-pattern detection (Uber reports 16 distinct session anti-patterns; the traces to detect them are already captured).
110
+
111
+ ### Step 3 — Apply levers in ROI order
112
+
113
+ 1. Stable cacheable prefix: system prompt + confirmed profile + rules first; dynamic context last.
114
+ 2. Routing: subagents and mechanical skills to cheaper models, manual override preserved (AIW's provider neutrality makes this a configuration, not a rewrite).
115
+ 3. Tool overload: lazy loading / on-demand tool schemas for MCP surfaces.
116
+ 4. Stage-budgeted compaction (already designed in `token-efficiency.md`).
117
+ 5. Prompt compression only behind the quality gate.
118
+
119
+ ### Step 4 — Continuous guardrail
120
+
121
+ A CI gate that reruns the self-benchmark on changes to models, skills, or configuration and reports Δcost and Δquality. This is the "model held constant" discipline from Uber: savings claims are only attributed when the model is fixed. Fail the gate when quality regresses or cost exceeds threshold.
122
+
123
+ ### Suggested study order
124
+
125
+ 1. `pleasedodisturb/awesome-llm-token-optimization` — full map.
126
+ 2. `jettison-ai/jettison-parity` — how to design the cost/quality experiment.
127
+ 3. `HumphreySun98/repoagentbench` — how to build the benchmark.
128
+ 4. `pulsemcp/switchboard` and `DeepAgentLabs/agenticlens` — cross-harness telemetry layer.
129
+
130
+ ## Gaps and open questions
131
+
132
+ - **Absolute cost data:** none of the sources publish per-task absolute costs in a form transferable to another codebase; only relative deltas. The self-benchmark must establish its own baseline.
133
+ - **Quality drift across model upgrades:** Uber acknowledges behavior shifts with every upgrade; savings measured against one model do not transfer. The CI guardrail (step 4) is the only mitigation found.
134
+ - **Compression safety:** no source provides a formal guarantee that prompt compression preserves behavior on edge cases; treat it as untrusted until benchmarked.
135
+ - **Telemetry privacy:** most third-party trackers are local-first, but AI Workflow's telemetry consent model (opt-in, minimal payload) should gate any integration with observability backends.
@@ -0,0 +1,128 @@
1
+ # Token Efficiency Study Notes
2
+
3
+ Deep-dive notes from studying the five reference repositories recommended in [token-efficiency-research.md](token-efficiency-research.md). Local clones live outside the repository at `../token-research/` (sibling of this repo, not committed).
4
+
5
+ | Repository | Role in the plan | Maturity |
6
+ | -------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------- |
7
+ | `awesome-llm-token-optimization` | Complete map of levers, tools, and papers | Curated list; strong curation discipline |
8
+ | `jettison-ai/jettison-parity` | Cost/quality experiment design | Small but rigorous: offline, deterministic, 29 tests, honest-labeling rules |
9
+ | `HumphreySun98/repoagentbench` | How to build a benchmark from real work | Published on PyPI, real leaderboards (~$11 API spend for 12 runs) |
10
+ | `pulsemcp/switchboard` | Cross-harness telemetry architecture | Early (docs-first repo); architecture doc is the value |
11
+ | `DeepAgentLabs/agenticlens` | Evaluation, diagnosis, and model-fit scoring | Large active codebase (400+ files), versioned releases, research program |
12
+
13
+ ## 1. awesome-llm-token-optimization — the map
14
+
15
+ Beyond the levers already captured in the research doc, the full read surfaced:
16
+
17
+ - **GitHub's own engineering result** ([github.blog](https://github.blog/ai-and-ml/github-copilot/improving-token-efficiency-in-github-agentic-workflows/)): pruning unused MCP tool schemas and swapping MCP calls for the `gh` CLI cut agentic-CI token spend **43–62%** across real workflows. This independently replicates Uber's CLI-resolved MCP lever.
18
+ - **Cockroach Labs**: re-sent context can be **62% of agent inference bills** — quantifies why per-turn context, not generation, is the dominant cost.
19
+ - **ProjectDiscovery**: raising cache hit rate from 7% to 84% across 9.8B cached tokens — the single largest documented saving, achieved purely by prompt-structure discipline (stable prefix).
20
+ - **Anthropic tool search**: 85% token reduction for large tool libraries; token-efficient tool use: 70% output reduction. Both are official provider features, not middleware.
21
+ - **Browser tool efficiency**: accessibility-tree approaches are 10–50x smaller than raw HTML; AI-summarized fetch ~20x better than Playwright MCP (1.5 KB vs 10–33 KB per page). Relevant to any web-driven skill.
22
+ - **Lossless rule-based compression achieves 3–4:1** with no model: strip prose/hedging, preserve numbers/entities/constraints/risks, dense bullets, self-contained 3–5K token sections. This is essentially AI Workflow's existing context strategy, externally validated.
23
+ - **Tokenizer warning**: newer Anthropic tokenizers produce ~30% more tokens for identical text at unchanged per-token prices — model upgrades can silently raise cost without any price change. Any cost attribution must be tokenizer-aware (Uber's "hold the model constant" rule exists for the same reason).
24
+ - **Router research caveat**: a 2026 game-theoretic analysis (arxiv:2602.09902) argues optimal routing is usually _static_ — dynamism mostly adds failure modes. Prefer a small fixed routing table per task category over clever per-request routing.
25
+
26
+ ## 2. jettison-parity — the experiment design
27
+
28
+ The most directly transferable artifact. It answers cost and quality **together**, deterministically and offline.
29
+
30
+ ### Four benchmark families
31
+
32
+ | Family | Measures | Transferable idea |
33
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
34
+ | Standing context | Tokens per turn of persistent context (tool schemas, skill bodies, instruction files), per category, byte-reproducible | Measure AIW's rendered context (AGENTS.md/CLAUDE.md, skills, rules) the same way — before/after any resource change |
35
+ | Task parity | Same task run baseline vs optimized; scores completion, correct tool + params, **critical-fact retention**, rounds, tokens. **Exits nonzero on any regression** | The quality gate: `critical_facts` containment checks that facts which must survive compression actually survive |
36
+ | Session cost | Dollars of an N-turn session pricing cache-read / fresh-input / cache-write **separately**, in cache-hit and cache-miss regimes | Naive `tokens_saved × price` overstates savings ~10x on cache-heavy agents — AIW cost math must be tier-aware |
37
+ | Holdout RCT | Randomized trial over recorded request logs: sha256 arm assignment, mean tokens/request, 95% CI. Synthetic output is always labeled "synthetic demonstration — not evidence" | The standard for claiming a real-world saving once logs exist |
38
+
39
+ ### Honest-measurement rules (adopt verbatim)
40
+
41
+ 1. Every number carries a label: `measured` (exact tokenizer / provider price) vs `estimated`; labels propagate pessimistically.
42
+ 2. Synthetic is never evidence.
43
+ 3. Disclose the config alongside any number (content hash).
44
+ 4. Cache-aware dollars (per billing tier).
45
+ 5. No network, no clocks — byte-identical reruns.
46
+
47
+ ### Adapter surface
48
+
49
+ A single method makes any optimizer scoreable: `optimize_request(body, provider) -> body`. AIW's equivalent boundary is the context assembly that produces a session's initial payload.
50
+
51
+ ### Task file schema (quality pin)
52
+
53
+ ```json
54
+ "expected": {
55
+ "tool": "pg_describe_table",
56
+ "arguments": {"table": "orders"},
57
+ "critical_facts": ["Never run a migration", "db-staging.internal.example.com"],
58
+ "final_answer_contains": "DONE"
59
+ }
60
+ ```
61
+
62
+ Six shipped scenarios cover: tool selection among 20 tools, search→load→call chains, numeric constraints, security rules, output-format requirements, mixed turns.
63
+
64
+ ## 3. repoagentbench — building the benchmark
65
+
66
+ ### Mining pipeline (PR → task)
67
+
68
+ 1. PR title/body/base SHA/diff via `gh`.
69
+ 2. Clone at base commit.
70
+ 3. Split diff into `solution_tests.patch` + `solution_source.patch`; apply **tests only**, so the starting state is "post-PR tests vs pre-PR source".
71
+ 4. Auto-generate `verify.sh` for the detected framework.
72
+
73
+ ### Run protocol (the part to copy)
74
+
75
+ - Fresh workdir + per-task venv per run.
76
+ - `pre_verify` must **FAIL** (proves the task is broken), agent runs, `post_verify` must **PASS** (proves the fix).
77
+ - Artifacts: `diff.patch`, `agent.log`, `events.jsonl` — replayable and diffable.
78
+ - `mock-fix` oracle agent (applies the known PR diff) validates the harness itself: 3/3 pass.
79
+
80
+ ### Findings that matter
81
+
82
+ - **The harness is part of the system under test**: same Anthropic model via aider (no-op fix, FAIL) vs native Claude Code (canonical fix, PASS) on the identical PR. Portability claims must be measured per-harness, not assumed.
83
+ - Contamination control: mine PRs post-dating the model's training cutoff (cites arxiv:2512.10218 — frontier models score 3x better on potentially-contaminated benchmarks).
84
+ - Cheap: ~$11 for 12 real-agent runs. A self-benchmark is not expensive.
85
+
86
+ **AIW translation**: our unit is not a PR but an SDD task — spec → plan → implementation → verification. The analog of "PR tests" is the AIW quality gate / verification evidence; the analog of `pre_verify` is "the requirement has no passing evidence yet".
87
+
88
+ ## 4. switchboard — cross-harness telemetry architecture
89
+
90
+ Early-stage, docs-first. The architectural pattern is the takeaway:
91
+
92
+ - **Canonical format ("OpenTranscripts")**: every agent's transcript is converted by a deterministic, versioned, per-source converter into one schema. New agent → new converter; spec change → version bump.
93
+ - **One hard determinism boundary**: raw → canonical is deterministic ETL; only segmentation and outcome scoring are LLM-driven, downstream and optional (MVP makes zero LLM calls).
94
+ - **Hooks, not interception**: a small separately-distributed package per agent pipes sessions to user-owned storage (S3/GCS/local/HTTP behind one interface). The platform never owns the ingestion edge.
95
+ - Sidecar metadata per session: who ran it, trigger, model, token usage, harness + version. Deterministic rollups over the canonical table feed org-level dashboards.
96
+
97
+ **AIW translation**: AIW checkpoints are already a deterministic, versioned artifact per harness-agnostic run. The missing piece is per-session token/cost sidecar metadata recorded at checkpoint time (model, harness, tokens in/out/cached), which turns existing checkpoints into the `open_transcripts` equivalent without any new ingestion machinery.
98
+
99
+ ## 5. agenticlens — evaluation and model-fit
100
+
101
+ Large active project (v0.10.0). Most relevant constructs:
102
+
103
+ - **Evaluator versioning**: every score carries its evaluator's version; evidence audits tie recommendations to the step they concern.
104
+ - **Experiments**: pass@k, pass^k, confidence intervals, significance tests, factor comparison — statistics done properly for agent evals.
105
+ - **Failure taxonomy + attribution**: deterministic diagnosis rules attribute failures to faulty step/agent, validated on controlled failures.
106
+ - **ModelFit**: task taxonomy, **hard constraints on quality/cost/latency/safety**, weighted scoring, per-category **Pareto frontiers with cost-per-success rankings**, recommendation confidence + explanations.
107
+ - **Advisory routing**: turns saved ModelFit evidence into explainable runtime decisions — advisory by default, execution requires explicit opt-in, with a local audit journal. Aligns with the static-routing finding from §1.
108
+
109
+ **AIW translation**: ModelFit's constraint-then-Pareto structure is exactly step 1–3 of our recommended path; "cost per success" is the outcome-denominated metric from the Uber post, productized.
110
+
111
+ ## Synthesis: implementation blueprint for steps 1–2
112
+
113
+ Combining the five sources, the sequence with concrete designs:
114
+
115
+ 1. **Standing-context benchmark** (jettison-parity, family 1): a command that renders AIW context for a fixture project and reports tokens per category (root context file, skills, rules, tool schemas) with a content hash. Deterministic, offline, zero API cost. First deliverable.
116
+ 2. **Task parity suite** (jettison-parity, family 2 + repoagentbench protocol): SDD tasks from `src/fixtures` with `expected` blocks (required artifacts, `critical_facts` that must survive context filtering, completion markers). Baseline vs optimized context; **exit nonzero on regression**. `pre_verify must fail / post_verify must pass` discipline via existing quality gates.
117
+ 3. **Checkpoint sidecar metadata** (switchboard pattern): record model, harness+version, token tiers (cache read / fresh input / cache write / output) into every `.aiw/checkpoints/` entry. Tier-aware, `measured` vs `estimated` labeled.
118
+ 4. **Cost-per-verified-requirement** (Uber + agenticlens ModelFit): join step-3 metadata with `evidence.ts`/`traceability.ts` to report cost per unit of value, per SDD stage and per skill.
119
+ 5. **Static routing table** (research consensus): a small per-task-category model matrix with hard quality constraints from step 2's benchmark; advisory with manual override, audit-logged.
120
+ 6. **Holdout RCT** (jettison-parity, family 4): once real session logs accumulate, upgrade claims from "benchmark delta" to CI-backed RCT evidence.
121
+
122
+ ### Guardrails to adopt wholesale
123
+
124
+ - Honest labeling (`measured`/`estimated`, pessimistic propagation).
125
+ - Synthetic results are never evidence.
126
+ - Config hash disclosed with every published number.
127
+ - Model (and tokenizer) held constant when attributing savings.
128
+ - Oracle baseline (mock-fix equivalent) to validate the harness itself.
@@ -14,3 +14,107 @@ Token efficiency is a runtime concern, not only a prompt-writing concern.
14
14
  - Measure tokens per agent, package, task, and verification cycle.
15
15
 
16
16
  The runtime should prefer references such as `AUTH-REQ-04` and retrieve their content only when needed.
17
+
18
+ ## Standing-context benchmark
19
+
20
+ `aiw context-bench` measures the persistent context AI Workflow renders into every agent session — deterministically, offline, and with zero API cost. It reports, per category (root context file, skills, rules, agents, hooks, templates, context layers): file count, measured characters, and estimated tokens (characters/4, always labeled `estimated`). A content hash pins the exact fixture behind every number, and the output contains no timestamps, so unchanged projects produce byte-identical reports.
21
+
22
+ ```bash
23
+ aiw context-bench --save # record a checkpoint under .aiw/checkpoints/
24
+ aiw context-bench --baseline=<checkpoint.yml> # exit 1 on any token regression
25
+ ```
26
+
27
+ Any token increase against the baseline is a regression and fails the command (the parity-harness rule). This is the quality gate for context changes: optimize freely, but standing context may not silently grow.
28
+
29
+ ## Task parity suite
30
+
31
+ `aiw parity` pins quality constraints on context assembly. Each parity task is one YAML file under `.aiw/parity/` (or `--tasks=directory`, relative to the project root) describing a scenario and its expectations:
32
+
33
+ ```yaml
34
+ schema: 1
35
+ id: deploy-guardrails
36
+ description: Deployment constraints must survive just-in-time retrieval
37
+ layers:
38
+ global: "Team conventions: trunk-based development."
39
+ project: "Never deploy on Fridays. Staging endpoint is db-staging.internal."
40
+ task: "Ship the migration with a rollback plan."
41
+ critical_facts:
42
+ - Never deploy on Fridays
43
+ - db-staging.internal
44
+ completion_markers:
45
+ - rollback plan
46
+ ```
47
+
48
+ Every task runs twice against the same layers: the full composed context (baseline) and the just-in-time task-retrieval assembler. A task passes only when every critical fact and completion marker survives retrieval — exact containment checks, not similarity. If a fact lives only in a layer that retrieval drops (for example, `session`), the task fails and names the fact: that is a detected context loss, not a benchmark artifact. The command exits nonzero on any failure, so it can gate CI.
49
+
50
+ ### Inter-stage parity tasks
51
+
52
+ Two optional fields turn a parity task into a check on the real handoff between SDD stages:
53
+
54
+ ```yaml
55
+ schema: 1
56
+ id: spec-to-plan
57
+ description: Every requirement id from the approved specification must reach the planning context
58
+ layers:
59
+ task: "Break the specification into ordered implementation tasks."
60
+ sources:
61
+ project: .aiw/generated/specs/specification.md
62
+ required_patterns:
63
+ - 'REQ-\d+'
64
+ ```
65
+
66
+ `sources` loads a project-relative artifact into a layer (project, task, global, or session) before assembly, and `required_patterns` extracts every literal match from the loaded sources — each extracted identifier must survive assembly, or the task fails naming the exact loss (`missing_pattern: REQ-\d+ -> REQ-003`). This guards the identifiers traceability depends on: if a stage's context assembly drops a `REQ-###` or `TASK-###`, `aiw trace` cannot link it later. A missing source artifact is an explicit error, not a silent pass.
67
+
68
+ Cost is reported (estimated tokens, baseline vs assembled) but never gates here — this suite is the quality gate; `aiw context-bench` is the cost gate. The two compose: optimize context freely, but neither standing cost nor critical facts may regress silently.
69
+
70
+ ## Usage sidecar
71
+
72
+ `aiw usage-sidecar` records per-run token usage with billing tiers, measurement labels, and harness attribution, stored as a versioned ledger at `.aiw/checkpoints/usage-sidecar.yml` (sequence-ordered, no timestamps, capped at 500 entries). Four tiers are kept separate because naive `tokens x price` accounting overstates savings on cache-heavy agents:
73
+
74
+ ```bash
75
+ # record a run (measured by default; pass --estimated when values are derived)
76
+ aiw usage-sidecar record --command=session.plan --model=sonnet --harness=claude-code \
77
+ --cache-read=48000 --fresh-input=6000 --cache-write=2000 --output=3100
78
+
79
+ aiw usage-sidecar report # tier totals, cache hit rate, attribution by model and harness
80
+ ```
81
+
82
+ Every entry carries `measured` or `estimated`, and aggregates propagate the label pessimistically: one estimated entry makes the reported total estimated. The report's `cache_hit_rate` (cache-read over billable input) is the single most economically meaningful ratio, since cached reads bill at a fraction of fresh input. Dollar conversion is deliberately not built in — provider prices rot, and unlabeled dollars would be dishonest by default.
83
+
84
+ `aiw scan` auto-records sidecar entries for interpreter and embedding usage with their real measurement label, so the ledger fills without manual effort.
85
+
86
+ ## Cost per verified requirement
87
+
88
+ `aiw cost-report` joins the usage sidecar with the traceability graph to produce the outcome-denominated cost metric — tokens per verified requirement, where verified means the graph links the requirement to evidence:
89
+
90
+ ```bash
91
+ aiw usage-sidecar record --command=session.verification --requirement=REQ-004 --fresh-input=9000 --output=2100
92
+ aiw trace # builds .aiw/generated/artifacts/traceability.yml
93
+ aiw cost-report
94
+ ```
95
+
96
+ Attributed and unattributed tokens are reported side by side so the ratio cannot be gamed by leaving expensive work unattributed, and the denominator counts only requirements with linked evidence — the same discipline as cost-per-merged-PR metrics, on AI Workflow's unit of value.
97
+
98
+ ## Model routing table
99
+
100
+ `aiw routing` maintains a static, evidence-linked routing table at `.aiw/routing.yml`. Research consensus is that optimal routing is usually static — per-request dynamism mostly adds failure modes — so the table maps task categories (dot-separated kebab-case, e.g. `scan.interpreter`) to models deterministically:
101
+
102
+ ```bash
103
+ aiw routing init # scaffold the table
104
+ aiw routing resolve --category=scan.interpreter
105
+ aiw routing show
106
+ ```
107
+
108
+ Every rule carries an `evidence` field naming the benchmark, parity run, or ADR behind it, and the resolver states its advisory level honestly: `evidenced`, `unevidenced-rule` (benchmark it before trusting), `default-fallback`, or `default-unset` (a human must choose). Routing never invokes a model and humans can always override — the same advisory discipline as ModelFit.
109
+
110
+ ## Task-lifecycle token usage
111
+
112
+ `aiw task-usage` measures the full life of one task — from `aiw task start` to the merged PR — in tokens, not dollars. Tokens are the model-invariant metric: routing part of a task to a frontier model and part to an entry-level model changes the price per token but not the input/output consumption, so lifecycle token totals stay comparable across model routing changes and harness migrations.
113
+
114
+ ```bash
115
+ aiw usage-sidecar record --workflow=TEAM-123 --command=session.plan --model=sonnet \
116
+ --requirement=REQ-001 --cache-read=6000 --fresh-input=3000 --output=800
117
+ aiw task-usage --workflow=TEAM-123 # or omit --workflow to use the active SDD task
118
+ ```
119
+
120
+ All input tiers count as input tokens processed (cached reads still consume tokens; they just bill less), with the tier split and `cache_hit_rate` kept visible for cache-behavior analysis. The report shows totals, per-stage breakdown with the models each stage used, requirements touched, and harness attribution.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@multileaf/ai-workflow",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "Portable spec-driven development workflow for AI coding agents",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,6 +31,7 @@ resources:
31
31
  - { id: nestjs-development, version: 0.1.0, path: skills/nestjs-development.md }
32
32
  - { id: prisma-data-access, version: 0.1.0, path: skills/prisma-data-access.md }
33
33
  - { id: vite-frontend, version: 0.1.0, path: skills/vite-frontend.md }
34
+ - { id: ticket, version: 0.1.0, path: skills/ticket.md }
34
35
  rules:
35
36
  - { id: language-policy, version: 0.1.0, path: rules/language-policy.md }
36
37
  - { id: tdd-policy, version: 0.1.0, path: rules/tdd-policy.md }
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: ticket
3
+ description: Start a feature directly from a ticket or specific requirement without a brainstorming phase.
4
+ ---
5
+
6
+ # Ticket-Driven Task
7
+
8
+ For every approval or optional skip, use the host's native blocking question widget, not a prose-only prompt when the widget is available. Leave choices unselected and offer "Accept skip" / "Do not skip" (or "Approve and continue" / "Request changes" / "Reject/stop" at gates). Wait for an actual submission before running any `aiw` approval or skip command. The CLI records the decision but cannot verify that a widget was used.
9
+
10
+ Use this skill when the user provides a ticket ID (for example `PROJ-142`) or an already-clear requirement and wants to start work immediately.
11
+
12
+ 1. Extract the ticket ID and a short title from the user's request. Start the task with `npx --yes --package=@multileaf/ai-workflow -- aiw task start --ticket=<TICKET> --title="<short title>"` (add `--id=<uuid>` only if the user provides one). If a session is already active, report it with `aiw task status` and stop.
13
+ 2. Brainstorming decision: the ticket already provides the requirement, but skipping is still a human decision. Ask with the blocking widget whether to skip brainstorming ("Accept skip" / "Do not skip"). Only after an explicit acceptance, record it with `npx --yes --package=@multileaf/ai-workflow -- aiw skip brainstorming --reason="Requirement provided by ticket <TICKET>"`. If the user prefers to brainstorm after all, run the brainstorming skill instead.
14
+ 3. Create the specification linked to the ticket with `npx --yes --package=@multileaf/ai-workflow -- aiw spec --ticket=<TICKET> --title="<title>"`, fill in requirements with stable IDs and Given/When/Then acceptance criteria derived from the ticket, then pass `aiw gate specification`, present the artifact, wait, and record the human reply with `aiw approve specification` (or `aiw reject specification --reason=<feedback>` and revise).
15
+ 4. Continue the standard SDD sequence: technical design when the change has architecture impact (`aiw adr`, gate, approval), implementation plan (`aiw plan`, gate, approval), TDD implementation, verification (`aiw verify`, gate, approval), code review, and traceability (`aiw trace`, gate, approval). Check progress at any point with `npx --yes --package=@multileaf/ai-workflow -- aiw task status`, which reports the ticket and the next pending stage.
16
+ 5. Complete with `npx --yes --package=@multileaf/ai-workflow -- aiw workflow complete` only after all stages resolve; the ticket reference stays in the archived session and the specification.
17
+
18
+ Never invent a ticket ID: if the user did not provide one, ask for it (or offer the plain `aiw workflow start` flow). Never skip brainstorming without an explicit human acceptance recorded through `aiw skip brainstorming`. Use `npx --yes --package=@multileaf/ai-workflow -- aiw <command>` when no global CLI is available.