Sync ctx 3643cc5 (part 2)
Browse filesGitHub commit: 3643cc5dbe6b3004713ad9c82c73308c7eb1ff5d
- qa/feature_status.csv +18 -8
- qa/tool-selection-token-history/Plan.md +227 -0
- qa/tool-selection-token-history/SPEC.md +174 -0
- qa/tool-selection-token-history/tracker.csv +10 -0
- src/ctx/__init__.py +2 -0
- src/ctx/adapters/generic/ctx_core_tools.py +466 -25
- src/ctx/adapters/generic/runtime_lifecycle.py +176 -8
- src/ctx/adapters/loopflow.py +59 -0
- src/ctx/api.py +37 -0
- src/ctx/cli/recommend.py +80 -7
- src/ctx/cli/run.py +32 -4
- src/ctx/mcp_server/__init__.py +14 -4
- src/ctx/mcp_server/server.py +11 -2
- src/ctx/monitor/app.py +3 -0
- src/ctx/monitor/compat.py +19 -2
- src/ctx/monitor/pages/activity.py +59 -0
- src/ctx/monitor/pages/ops.py +1 -1
- src/ctx/monitor/pages/recommend.py +178 -0
- src/ctx/monitor/routes.py +3 -1
- src/ctx/monitor/services/runtime.py +208 -2
qa/feature_status.csv
CHANGED
|
@@ -50,9 +50,9 @@ CLI-048,,docs/qa/feature-user-story-status.csv,CLI,Harness update and uninstall
|
|
| 50 |
CLI-049,,docs/qa/feature-user-story-status.csv,CLI,LoopFlow and agent-loop adapter,python -m ctx.adapters.loopflow,src/ctx/adapters/loopflow.py and src/tests/test_loopflow_adapter.py,High,As a DSL runner or custom agent-loop author I can ask ctx for scoped planning capabilities before each loop plan,Adapter emits a JSON contract with permission-gated skills agents MCPs ctx MCP server metadata and gated harness recommendations only when a user-owned/API/local model is declared,Graph/wiki available or recommendation functions mocked,python -m pytest src/tests/test_loopflow_adapter.py -q,Automated Test,Tested Pass,test_loopflow_adapter.py covers loop-file parsing permission filtering MCP tool metadata harness gating shell-quoted harness install commands CLI JSON output and empty permission fail-closed behavior.,,,,,,2026-06-30,CLI Lane,Tracks the module entry point documented in docs/harness/attaching-to-hosts.md.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 51 |
HOOK-001,,docs/qa/feature-user-story-status.csv,Hooks,Backup PostToolUse runtime hook,hooks/backup_on_change.py,hooks/backup_on_change.py and src/tests/test_quality_hook.py,Medium,As a Claude Code user I can snapshot tracked config changes from a PostToolUse hook,The hook reads stdin JSON detects tracked files runs snapshot-if-changed and always exits 0 so edits are not blocked,Temp Claude home and tracked config fixture needed,python -m pytest src/tests/test_quality_hook.py -q,Automated Test,Tested Pass,test_quality_hook.py covers root backup hook stdin parsing tracked-file dispatch snapshot reason shaping and nonblocking exit even when snapshot returns nonzero.,,,,,,2026-06-30,Core/Docs Lane,Validated in Phase 2 runtime hook behavior slice without increasing the test inventory count.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 52 |
HOOK-002,,docs/qa/feature-user-story-status.csv,Hooks,Quality Stop runtime hook,hooks/quality_on_session_end.py,hooks/quality_on_session_end.py and src/tests/test_quality_hook.py,Medium,As a Claude Code user I can refresh touched skill quality on session stop without blocking shutdown,The hook reads event state recomputes bounded touched slugs writes audit state and always exits 0 on advisory failures,Temp Claude home and skill event fixture needed,python -m pytest src/tests/test_quality_hook.py -q,Automated Test,Tested Pass,test_quality_hook.py covers touched slug selection state cutoff max slug cap missing file behavior and main nonblocking exit when recompute fails.,,,,,,2026-06-30,Core/Docs Lane,Validated in Phase 2 runtime hook behavior slice without increasing the test inventory count.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 53 |
-
PYAPI-001,,docs/qa/feature-user-story-status.csv,Python API,Public Python API,ctx.api and ctx top-level re-exports,src/ctx/api.py and src/ctx/__init__.py,High,As a harness author I can import ctx from Python without depending on internal modules,recommend_bundle graph_query wiki_search wiki_get list_all_entities default_wiki_dir and CtxCoreToolbox keep stable signatures safe defaults and top-level re-exports,Runtime wiki or synthetic fixture available,pytest src/tests/test_public_api.py -q,Automated Test,Tested Pass,test_public_api.py covers __all__ exports top-level re-exports signatures happy paths empty paths and telemetry privacy payloads.,,,,,,2026-
|
| 54 |
-
MCP-001,,docs/qa/feature-user-story-status.csv,MCP/Core Tools,Read/query tool catalog,"ctx__recommend_bundle, ctx__graph_query, ctx__wiki_search, ctx__wiki_get",src/ctx/adapters/generic/ctx_core_tools.py and src/ctx/mcp_server/server.py,High,As an MCP or generic harness client I can call ctx read tools consistently,Read tools return recommendations graph neighborhoods wiki search and wiki entity payloads through both generic toolbox and MCP stdio surfaces,Synthetic graph/wiki fixture available,pytest src/tests/test_harness_ctx_core.py src/tests/test_mcp_server.py -q,Automated Test,Tested Pass,test_harness_ctx_core.py and test_mcp_server.py pin the read tool names schemas dispatch success paths and JSON-RPC tools/list exposure.,,,,,,2026-
|
| 55 |
-
MCP-002,,docs/qa/feature-user-story-status.csv,MCP/Core Tools,Lifecycle and session tool catalog,"ctx__observe_dev_event, ctx__load_entity, ctx__mark_entity_used, ctx__record_validation, ctx__record_escalation, ctx__unload_entity, ctx__session_end, ctx__session_state",src/ctx/adapters/generic/ctx_core_tools.py and ctx.runtime_lifecycle.record,High,As an MCP or generic harness client I can record runtime lifecycle evidence,Lifecycle tools append privacy-safe
|
| 56 |
MCP-003,,docs/qa/feature-user-story-status.csv,MCP Router,Trusted third-party MCP attachment,McpClient and McpRouter,src/ctx/adapters/generic/tools/mcp_router.py,High,As a generic harness user I can attach trusted third-party MCP servers safely,Router starts MCP subprocesses with isolated environment namespaces tools handles timeouts and redacts secrets from errors,Fake MCP server fixture available,pytest src/tests/test_mcp_router.py -q,Automated Test,Tested Pass,test_mcp_router.py covers client start stop tool listing calls namespace routing timeout crash handling environment isolation and stderr secret redaction.,,,,,,2026-06-29,API/MCP Lane,Added because third-party MCP attachment is user-facing host functionality not just internal plumbing.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 57 |
MCP-004,,docs/qa/feature-user-story-status.csv,MCP/Core Tools,Response format negotiation,output_format and _response_format,src/ctx/adapters/generic/ctx_core_tools.py,High,As a tool caller I can request JSON or GCF output from read tools,Read tool schemas expose optional output_format and _response_format aliases and fall back to JSON errors when GCF codec is unavailable,Generic toolbox fixture available,pytest src/tests/test_harness_ctx_core.py -q,Automated Test,Tested Pass,test_harness_ctx_core.py covers optional schema fields JSON default GCF opt-in public alias and codec-missing fallback.,,,,,,2026-06-29,API/MCP Lane,Tracks a schema-visible behavior exposed to MCP/tool clients.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 58 |
DASH-001,,docs/qa/feature-user-story-status.csv,Dashboard,Home page,/,src/ctx/monitor/routes.py,High,As a user I can land on a useful dashboard home,Home shows current counts and high-value entry points without stale numbers,Monitor running,GET /,Manual/Documented,Tested Pass,GET / returned 200 in 1506ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
@@ -62,6 +62,7 @@ DASH-004,,docs/qa/feature-user-story-status.csv,Dashboard,SkillSpector page,/ski
|
|
| 62 |
DASH-005,,docs/qa/feature-user-story-status.csv,Dashboard,Wiki index/catalog,"/wiki, /catalog, and /catalog/",src/ctx/monitor/routes.py,Medium,As a user I can search entity catalog,Wiki/catalog supports autocomplete-like search and tiles for skill agent MCP harness,Monitor running,GET /catalog?type=agent&q=review,Manual/Documented,Retested Pass,FAIL: live route timed out after 60018ms before fix,CTX-AZ-001,/catalog with query rebuilt too much server-side catalog state while /api/entities/search was fast,GET /catalog?type=agent&q=review,Fixed by using bounded search results for queried wiki/catalog render,PASS: live route 200 in 1422ms after monitor restart; focused tests 4 passed,2026-06-23,Dashboard/Docs Lane,Regression covered by test_render_wiki_index_query_uses_bounded_search,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 63 |
DASH-006,,docs/qa/feature-user-story-status.csv,Dashboard,Wiki entity page,/wiki/<slug>,src/ctx/monitor/routes.py,High,As a user I can inspect a full entity page,Entity page has Overview Subgraph Quality tabs and rendered markdown/frontmatter,Monitor running,GET /wiki/github?type=mcp-server,Manual/Documented,Tested Pass,GET /wiki/github?type=mcp-server returned 200 in 2705ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 64 |
DASH-007,,docs/qa/feature-user-story-status.csv,Dashboard,Graph page,/graph,src/ctx/monitor/routes.py,Medium,As a user I can explore graph interactively,Graph loads live search results click-to-focus double-click-back filters match histogram and useful inspector,Monitor running,GET /graph then interact,Manual/Documented,Retested Pass,PASS: /graph returned 200 in 31ms after monitor restart,,,,,PASS: Playwright test_ctx_monitor_browser.py::test_graph_page_uses_builtin_svg_renderer covered renderer click focus double-click back filters histogram live search type shapes and inspector.,2026-06-23,Dashboard/Docs Lane,Browser interaction pass completed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 65 |
DASH-020,,docs/qa/feature-user-story-status.csv,Dashboard,Graph live search type preservation,/graph focus search,src/ctx/monitor/pages/graph_client.py,Medium,As a dashboard user searching duplicate graph slugs I can keep the selected entity type,Live search sends the selected focus type to /api/entities/search.json so duplicate slugs resolve to the intended skill agent MCP server or harness,Monitor running with graph search data,pytest src/tests/test_ctx_monitor.py::test_render_graph_focus_controls_preserve_type -q,Automated Test,Retested Pass,FAIL: graph live search fetched /api/entities/search.json without type even when focus-type was selected.,DASH-UX-004,Graph live search ignored the selected focus entity type and could suggest the wrong duplicate slug type,pytest src/tests/test_ctx_monitor.py::test_render_graph_focus_controls_preserve_type -q,Fixed by appending selectedFocusType to the live entity search request,PASS: focused graph render test pins selected type in live search URL generation.,2026-06-29,Dashboard/Docs Lane,Added from dashboard/graph expert lane UX finding.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 66 |
DASH-008,,docs/qa/feature-user-story-status.csv,Dashboard,Manage page,/manage,src/ctx/monitor/routes.py,High,As a user I can manage entities,Manage supports search upload/upsert delete/manual edit with safety prompts,Monitor running,GET /manage,Manual/Documented,Tested Pass,GET /manage returned 200 in 261ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 67 |
DASH-009,,docs/qa/feature-user-story-status.csv,Dashboard,Harness setup,/harness,src/ctx/monitor/routes.py,High,As a local/API model user I can use a harness wizard,Harness Setup interviews model and goals recommends matching harness or no-fit PRD,Monitor running,GET /harness,Manual/Documented,Tested Pass,GET /harness returned 200 in 23ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
@@ -69,7 +70,7 @@ DASH-010,,docs/qa/feature-user-story-status.csv,Dashboard,Docs page,/docs,src/ct
|
|
| 69 |
DASH-011,,docs/qa/feature-user-story-status.csv,Dashboard,Config page,/config,src/ctx/monitor/routes.py,High,As a user I can view/edit important config,Config shows explanations defaults required fields validation and safe save,Monitor running,GET /config and POST /api/config,Manual/Documented,Tested Pass,GET /config returned 200 in 12ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 70 |
DASH-012,,docs/qa/feature-user-story-status.csv,Dashboard,Status page,/status,src/ctx/monitor/routes.py,High,As a user I can see system health,Status reports graph/wiki/cache/session health with actionable errors,Monitor running,GET /status,Manual/Documented,Tested Pass,GET /status returned 200 in 3750ms after restart; functional but slower than core pages.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 71 |
DASH-013,,docs/qa/feature-user-story-status.csv,Dashboard,KPI page,/kpi,src/ctx/monitor/routes.py,High,As a user I can inspect recommendation effectiveness,KPIs show usage score quality and lifecycle trends without slow unbounded render,Monitor running,GET /kpi,Manual/Documented,Tested Pass,GET /kpi returned 200 in 107ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 72 |
-
DASH-014,,docs/qa/feature-user-story-status.csv,Dashboard,Runtime page,/runtime,src/ctx/monitor/
|
| 73 |
DASH-015,,docs/qa/feature-user-story-status.csv,Dashboard,Sessions page,/sessions,src/ctx/monitor/routes.py,High,As a user I can inspect sessions,Sessions page lists transcripts and details without leaking secrets,Monitor running,GET /sessions,Manual/Documented,Tested Pass,GET /sessions returned 200 in 269ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 74 |
DASH-016,,docs/qa/feature-user-story-status.csv,Dashboard,Logs page,/logs,src/ctx/monitor/routes.py,High,As a user I can inspect logs,Logs render audit/log files or clear empty state,Monitor running,GET /logs,Manual/Documented,Tested Pass,GET /logs returned 200 in 132ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 75 |
DASH-017,,docs/qa/feature-user-story-status.csv,Dashboard,Live events,/events and /live,src/ctx/monitor/routes.py,High,As a user I can tail live events,Live page connects SSE and shows clear empty/disconnected states,Monitor running,GET /events and /api/events.stream,Manual/Documented,Tested Pass,GET /live returned 200 in 87ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
@@ -80,7 +81,7 @@ API-002,,docs/qa/feature-user-story-status.csv,Dashboard API,Manifest API,/api/m
|
|
| 80 |
API-003,,docs/qa/feature-user-story-status.csv,Dashboard API,Status API,/api/status.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch health JSON,Endpoint returns graph/wiki/cache health with correct status code,Monitor running,GET /api/status.json,Manual/Documented,Tested Pass,GET /api/status.json returned 200 in 4303ms after restart; functional but slower than core APIs.,,,,,,2026-06-23,API/MCP Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 81 |
API-004,,docs/qa/feature-user-story-status.csv,Dashboard API,KPI API,/api/kpi.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch KPI JSON,Endpoint returns bounded KPI payload quickly,Monitor running,GET /api/kpi.json,Manual/Documented,Tested Pass,GET /api/kpi.json returned 200 in 105ms after restart.,,,,,,2026-06-23,API/MCP Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 82 |
API-005,,docs/qa/feature-user-story-status.csv,Dashboard API,Grades API,/api/grades.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch grades JSON,Endpoint returns score and grade payload with explanations,Monitor running,GET /api/grades.json,Manual/Documented,Retested Pass,Initial dashboard sweep: GET /api/grades.json returned 200 but took 16833ms for a tiny payload.,CTX-AZ-005,Grades API ignored cached KPI grade_counts and rescanned all quality sidecars on demand.,GET /api/grades.json,Fixed,"After routing through cached KPI summary, GET /api/grades.json returned 200 in 92ms after restart.",2026-06-23,API/MCP Lane,Fallback full sidecar scan remains for missing KPI summary.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 83 |
-
API-006,,docs/qa/feature-user-story-status.csv,Dashboard API,Runtime API,/api/runtime.json,src/ctx/monitor/
|
| 84 |
API-007,,docs/qa/feature-user-story-status.csv,Dashboard API,Entity search API,/api/entities/search.json,src/ctx/monitor/routes.py,High,As a dashboard client I can search entities,Endpoint supports live query type filters and useful fuzzy results,Monitor running,GET /api/entities/search.json?q=review&type=agent,Manual/Documented,Tested Pass,PASS: endpoint returned 200 in 28ms with agent review results,,,,,,2026-06-23,API/MCP Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 85 |
API-008,,docs/qa/feature-user-story-status.csv,Dashboard API,Entity detail API,/api/entity/<slug>.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch entity details,Endpoint returns canonical entity docs frontmatter and graph sidecar,Monitor running,GET /api/entity/github.json?type=mcp-server,Manual/Documented,Tested Pass,GET /api/entity/github.json?type=mcp-server returned 200 in 27ms after restart.,,,,,,2026-06-23,API/MCP Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 86 |
API-009,,docs/qa/feature-user-story-status.csv,Dashboard API,Graph neighborhood API,/api/graph/<slug>.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch a graph neighborhood,Endpoint returns bounded nodes edges scores and reasons fast after runtime install,Monitor running,GET /api/graph/github.json?type=skill&limit=20,Manual/Documented,Tested Pass,PASS: endpoint returned 200 in 2295ms with nodes/edges JSON,,,,,,2026-06-23,API/MCP Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
@@ -166,7 +167,7 @@ DASH-PAGE-009,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Docs,/docs
|
|
| 166 |
DASH-PAGE-010,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Config,/config,src/ctx/monitor/pages/config.py,High,As a dashboard user I can inspect and edit ctx configuration,Config page shows required settings descriptions examples defaults and validates saves or clears through the config API,ctx-monitor running with mutation token,Open /config and validate required fields defaults save clear and error states,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /config, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 167 |
DASH-PAGE-011,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Status,/status,src/ctx/monitor/pages/ops.py,High,As a dashboard user I can inspect system status,Status page shows graph wiki config backup and queue health with actionable error text,ctx-monitor running,Open /status and verify status sections and stale artifact messages,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /status, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 168 |
DASH-PAGE-012,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,KPI,/kpi,src/ctx/monitor/pages/ops.py,High,As a dashboard user I can inspect dashboard KPIs,KPI page shows usage quality load and recommendation metrics with readable number formatting,ctx-monitor running,Open /kpi and verify metric cards charts and empty states,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /kpi, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 169 |
-
DASH-PAGE-013,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Runtime,/runtime,src/ctx/monitor/pages/
|
| 170 |
DASH-PAGE-014,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Sessions,/sessions,src/ctx/monitor/pages/activity.py,High,As a dashboard user I can browse ctx sessions,Sessions page lists sessions links details and handles empty history cleanly,ctx-monitor running with or without sessions,Open /sessions and verify list empty state and detail links,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /sessions, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 171 |
DASH-PAGE-015,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Logs,/logs,src/ctx/monitor/pages/activity.py,High,As a dashboard user I can inspect audit logs,Logs page tails audit JSONL entries and handles missing logs without a blank page,ctx-monitor running,Open /logs and verify log rows empty state and formatting,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /logs, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 172 |
DASH-PAGE-016,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Live Events,/events,src/ctx/monitor/pages/activity.py,Medium,As a dashboard user I can watch live events,Live page connects to server-sent events and shows either audit events or a clear waiting state,ctx-monitor running,Open /events and verify SSE connection and empty state,Browser/User Story,Retested Pass,FAIL: /api/events.stream did not send initial bytes within 10 seconds so the Live page could remain blank.,,,,,PASS: /events returned HTTP 200 and /api/events.stream returned : connected promptly after the SSE fix.,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
@@ -188,7 +189,7 @@ DASH-API-003,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Status API,/
|
|
| 188 |
DASH-API-004,,docs/qa/dashboard-user-story-status.csv,Dashboard API,KPI API,/api/kpi.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch KPI data,API returns metric payloads that match the KPI page,ctx-monitor running,GET /api/kpi.json and compare with page expectations,Manual/Documented,Tested Pass,PASS: /api/kpi.json returned HTTP 200 JSON with generated_at total and grade summary keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 189 |
DASH-API-005,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Grades API,/api/grades.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch grade summaries,API returns quality grade summaries for skills agents MCPs and harnesses,ctx-monitor running,GET /api/grades.json and validate JSON shape,Manual/Documented,Tested Pass,PASS: /api/grades.json returned HTTP 200 JSON with grades and total keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 190 |
DASH-API-006,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Sidecars API,/api/sidecars.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch searchable card data,API supports q type grade floor and limit filters with bounded output,ctx-monitor running,GET /api/sidecars.json?q=review&type=agent&limit=5,Manual/Documented,Tested Pass,PASS: /api/sidecars.json?q=review&type=agent&limit=5 returned HTTP 200 JSON with items total and pagination keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 191 |
-
DASH-API-007,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Runtime API,/api/runtime.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch runtime diagnostics,API returns
|
| 192 |
DASH-API-008,,docs/qa/dashboard-user-story-status.csv,Dashboard API,SkillSpector API,/api/skillspector.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch SkillSpector findings,API returns audit records filtered by severity and query,ctx-monitor running,GET /api/skillspector.json?severity=HIGH&q=prompt,Manual/Documented,Tested Pass,PASS: /api/skillspector.json?severity=HIGH&q=prompt returned HTTP 200 JSON with summary filters and records keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 193 |
DASH-API-009,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Config API,/api/config.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch effective config,API returns defaults overrides required metadata and no secrets,ctx-monitor running,GET /api/config.json and validate required fields,Manual/Documented,Tested Pass,PASS: /api/config.json returned HTTP 200 JSON with defaults user effective and path keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 194 |
DASH-API-010,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Entity Search API,/api/entities/search.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can search entities for autocomplete,API returns typed entity suggestions for search terms and rejects unsafe queries cleanly,ctx-monitor running,GET /api/entities/search.json?q=github&type=skill,Manual/Documented,Tested Pass,PASS: /api/entities/search.json?q=github&type=skill&limit=5 returned HTTP 200 JSON with results and total keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
@@ -202,7 +203,7 @@ DASH-POST-003,,docs/qa/dashboard-user-story-status.csv,Dashboard Mutation,Config
|
|
| 202 |
DASH-POST-004,,docs/qa/dashboard-user-story-status.csv,Dashboard Mutation,Entity Upsert API,/api/entity/upsert,src/ctx/monitor/api/mutations.py,High,As a dashboard user I can add or update entities manually,POST validates type slug and body runs entity-specific safety gates and queues graph refresh,ctx-monitor running with mutation token and temp wiki,POST /api/entity/upsert against temp wiki and verify entity page plus queue,Automated Test,Tested Pass,"PASS: focused pytest covered /api/entity/upsert validation, entity write, and queue behavior.",,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 203 |
DASH-POST-005,,docs/qa/dashboard-user-story-status.csv,Dashboard Mutation,Entity Delete API,/api/entity/delete,src/ctx/monitor/api/mutations.py,High,As a dashboard user I can delete dashboard-managed entities safely,POST validates mutation token safe slug and entity ownership before deleting or tombstoning,ctx-monitor running with mutation token and temp wiki,POST /api/entity/delete against temp wiki and verify no unrelated files removed,Automated Test,Tested Pass,PASS: focused pytest covered /api/entity/delete validation and safe deletion behavior.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 204 |
B-API-001,PYAPI-001,expert-lane/api-mcp-harness,Python API,Package exports,ctx package exports,src/ctx/__init__.py; src/ctx/api.py,High,"As a Python caller, I can import stable ctx helpers.","ctx re-exports public recommendation, wiki, graph, and list helpers without breaking import compatibility.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_public_api.py src/tests/test_harness_ctx_core.py src/tests/test_recommendation_surfaces_golden.py,Automated Test,Tested Pass,"PASS: /tmp/ctx-verify-venv/bin/python -m pytest -q --no-cov src/tests/test_public_api.py src/tests/test_harness_ctx_core.py src/tests/test_recommendation_surfaces_golden.py src/tests/test_enterprise_telemetry.py src/tests/test_mcp_server.py src/tests/test_mcp_router.py src/tests/test_mcp_live_compat.py src/tests/test_mcp_install.py -> 383 passed, 1 skipped; package export/signature/API behavior covered.",,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Child row from API/MCP lane; ctx_core_tool_names/recommendation_graph helpers are not package re-exported.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
| 205 |
-
B-API-002,PYAPI-001,expert-lane/api-mcp-harness,Python API,Recommendation API,"recommend_bundle(query, top_k)",src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py,High,"As an app, I can get ctx capability recommendations.","recommend_bundle returns skill, agent, and MCP recommendations and
|
| 206 |
B-API-003,PYAPI-001,expert-lane/api-mcp-harness,Python API,Graph API,"graph_query(seeds, max_hops, top_n)",src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py,High,"As an app, I can explore nearby ctx entities.","graph_query returns bounded graph neighbors for skill, agent, MCP, and harness seeds.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_harness_ctx_core.py,Automated Test,Tested Pass,"PASS: graph_query public/core behavior covered by test_public_api.py and test_harness_ctx_core.py in API/MCP slice -> 383 passed, 1 skipped.",,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Invalid or missing graph state collapses to an empty result for library callers.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
| 207 |
B-API-004,PYAPI-001,expert-lane/api-mcp-harness,Python API,Wiki API,wiki_search/wiki_get,src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py,High,"As an app, I can inspect wiki entities.","Search and get calls return slug, frontmatter, body, and type-aware entity details.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_harness_ctx_core.py,Automated Test,Tested Pass,"PASS: wiki_search/wiki_get public/core behavior covered by test_public_api.py and test_harness_ctx_core.py in API/MCP slice -> 383 passed, 1 skipped.",,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Slug/type ambiguity returns None rather than raising.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
| 208 |
B-API-005,PYAPI-001,expert-lane/api-mcp-harness,Python API,Catalog API,list_all_entities/default_wiki_dir,src/ctx/api.py; src/ctx/identity.py,Medium,"As tooling, I can enumerate installed catalog entities.","The API lists recommendable skills, agents, MCPs, and harnesses and resolves the configured wiki directory.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_harness_recommendations.py,Automated Test,Tested Pass,PASS: /tmp/ctx-verify-venv/bin/python -m pytest -q --no-cov src/tests/test_harness_recommendations.py -> 15 passed; catalog/harness recommendation enumeration covered.,,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Depends on local wiki/config presence.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
|
@@ -282,3 +283,12 @@ PKG-001,CLI-011,expert-lane/cli-package-inventory,Package CLI,Skill lifecycle he
|
|
| 282 |
PKG-002,CLI-029,expert-lane/cli-package-inventory,Package CLI,Toolbox satellite modules,python -m intent_interview; python -m behavior_miner; python -m council_runner; python -m toolbox_verdict,src/intent_interview.py; src/behavior_miner.py; src/council_runner.py; src/toolbox_verdict.py,Medium,"As a toolbox user, I can interview intent, mine behavior, plan councils, and record verdicts.",Documented toolbox module commands should match the parser verbs exposed by the code.,Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_intent_interview.py src/tests/test_behavior_miner.py src/tests/test_council_runner.py src/tests/test_toolbox_verdict.py,Automated Test,Retested Pass,FAIL: expert-lane inventory found toolbox docs listing stale behavior_miner/council_runner verbs.,QA-CLI-001,Toolbox docs may mention stale behavior_miner/council_runner verbs that no longer match parsers.,Compare docs/toolbox/behavior-miner.md and docs/toolbox/council-runner.md against argparse verbs in src/behavior_miner.py and src/council_runner.py.,Fixed by aligning docs with live argparse verbs and current profile/run-plan data shapes.,PASS: behavior_miner and council_runner help commands show documented verbs; focused toolbox tests 138 passed; MkDocs strict build passed.,2026-06-30,CLI Lane,CLI lane found possible docs drift for behavior_miner and council_runner verbs.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: docs-only correction; code already exposed the smaller tested command surface.,Validated by completed goal-loop and no-mistakes gate
|
| 283 |
META-001,CLI-001,expert-lane/cli-package-inventory,Package Entry Point,python -m ctx package entrypoint,src/ctx/__main__.py,src/ctx package,Medium,"As a package user, I can launch the flagship ctx harness with python -m ctx.",python -m ctx should delegate to the same behavior as the ctx console script or be explicitly documented as unsupported.,Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_package_scaffold.py src/tests/test_harness_cli_run.py,Automated Test,Retested Pass,FAIL: expert-lane inventory found no src/ctx/__main__.py for python -m ctx.,QA-CLI-002,python -m ctx currently has no package __main__.py entrypoint.,Run python -m ctx --help from an editable install or source checkout; Python cannot execute package ctx without __main__.py.,Fixed by adding a tiny __main__.py that delegates to ctx.cli.run.main.,PASS: PYTHONPATH=src python -m ctx --help exits 0 and shows run/resume/sessions; package scaffold test covers the invocation.,2026-06-30,CLI Lane,CLI lane found no src/ctx/__main__.py despite the flagship ctx console script.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,"Ponytail: one small delegation shim, no duplicate CLI implementation.",Validated by completed goal-loop and no-mistakes gate
|
| 284 |
QA-USE-001,B-ADAPT-001,expert-lane/cli-package-inventory,Hooks,Usage tracker temp wiki and log path precedence,python -m usage_tracker --sync,src/usage_tracker.py; src/tests/test_usage_tracker.py,High,"As a hook/test harness user, I can point usage tracking at an explicit wiki or log path without ambient local wiki packs hijacking the write.","Explicit wiki_dir, ENTITIES_DIR, and LOG_PATH targets are honored before the default packed wiki fallback is considered.",Repo checkout with Python 3.11+ dev environment and a default ~/.claude/skill-wiki/wiki-packs directory present.,python -m pytest -q src/tests/test_usage_tracker.py,Automated Test,Retested Pass,FAIL: full pytest and isolated test_usage_tracker.py failed because default wiki-packs shadowed monkeypatched ENTITIES_DIR and LOG_PATH.,QA-USE-001,usage_tracker default packed-wiki fallback ignored explicit module-level temp paths when local default wiki-packs existed.,"With ~/.claude/skill-wiki/wiki-packs present, run python -m pytest -q src/tests/test_usage_tracker.py before the fix.",Fixed by making monkeypatched ENTITIES_DIR/LOG_PATH take precedence over default packed-wiki fallback when wiki_dir is not explicitly passed.,PASS: python -m pytest -q src/tests/test_usage_tracker.py -> 42 passed; ruff check src/usage_tracker.py -> passed.,2026-06-30,CLI Lane,Found by current full-suite goal loop after Phase 2 fixes.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: small precedence guard; no rewrite of packed-wiki logic.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
CLI-049,,docs/qa/feature-user-story-status.csv,CLI,LoopFlow and agent-loop adapter,python -m ctx.adapters.loopflow,src/ctx/adapters/loopflow.py and src/tests/test_loopflow_adapter.py,High,As a DSL runner or custom agent-loop author I can ask ctx for scoped planning capabilities before each loop plan,Adapter emits a JSON contract with permission-gated skills agents MCPs ctx MCP server metadata and gated harness recommendations only when a user-owned/API/local model is declared,Graph/wiki available or recommendation functions mocked,python -m pytest src/tests/test_loopflow_adapter.py -q,Automated Test,Tested Pass,test_loopflow_adapter.py covers loop-file parsing permission filtering MCP tool metadata harness gating shell-quoted harness install commands CLI JSON output and empty permission fail-closed behavior.,,,,,,2026-06-30,CLI Lane,Tracks the module entry point documented in docs/harness/attaching-to-hosts.md.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 51 |
HOOK-001,,docs/qa/feature-user-story-status.csv,Hooks,Backup PostToolUse runtime hook,hooks/backup_on_change.py,hooks/backup_on_change.py and src/tests/test_quality_hook.py,Medium,As a Claude Code user I can snapshot tracked config changes from a PostToolUse hook,The hook reads stdin JSON detects tracked files runs snapshot-if-changed and always exits 0 so edits are not blocked,Temp Claude home and tracked config fixture needed,python -m pytest src/tests/test_quality_hook.py -q,Automated Test,Tested Pass,test_quality_hook.py covers root backup hook stdin parsing tracked-file dispatch snapshot reason shaping and nonblocking exit even when snapshot returns nonzero.,,,,,,2026-06-30,Core/Docs Lane,Validated in Phase 2 runtime hook behavior slice without increasing the test inventory count.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 52 |
HOOK-002,,docs/qa/feature-user-story-status.csv,Hooks,Quality Stop runtime hook,hooks/quality_on_session_end.py,hooks/quality_on_session_end.py and src/tests/test_quality_hook.py,Medium,As a Claude Code user I can refresh touched skill quality on session stop without blocking shutdown,The hook reads event state recomputes bounded touched slugs writes audit state and always exits 0 on advisory failures,Temp Claude home and skill event fixture needed,python -m pytest src/tests/test_quality_hook.py -q,Automated Test,Tested Pass,test_quality_hook.py covers touched slug selection state cutoff max slug cap missing file behavior and main nonblocking exit when recompute fails.,,,,,,2026-06-30,Core/Docs Lane,Validated in Phase 2 runtime hook behavior slice without increasing the test inventory count.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 53 |
+
PYAPI-001,,docs/qa/feature-user-story-status.csv,Python API,Public Python API,ctx.api and ctx top-level re-exports,src/ctx/api.py and src/ctx/__init__.py,High,As a harness author I can import ctx from Python without depending on internal modules,recommend_bundle recommend_related graph_query wiki_search wiki_get list_all_entities default_wiki_dir and CtxCoreToolbox keep stable signatures safe defaults and top-level re-exports,Runtime wiki or synthetic fixture available,pytest src/tests/test_public_api.py -q,Automated Test,Tested Pass,test_public_api.py covers __all__ exports top-level re-exports signatures happy paths empty paths and telemetry privacy payloads.,,,,,,2026-07-02,API/MCP Lane,Added during canonical feature inventory gap pass and updated when related recommendations became public API.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 54 |
+
MCP-001,,docs/qa/feature-user-story-status.csv,MCP/Core Tools,Read/query tool catalog,"ctx__recommend_bundle, ctx__recommend_related, ctx__graph_query, ctx__wiki_search, ctx__wiki_get",src/ctx/adapters/generic/ctx_core_tools.py and src/ctx/mcp_server/server.py,High,As an MCP or generic harness client I can call ctx read tools consistently,Read tools return recommendations related suggestions graph neighborhoods wiki search and wiki entity payloads through both generic toolbox and MCP stdio surfaces,Synthetic graph/wiki fixture available,pytest src/tests/test_harness_ctx_core.py src/tests/test_mcp_server.py -q,Automated Test,Tested Pass,test_harness_ctx_core.py and test_mcp_server.py pin the read tool names schemas dispatch success paths and JSON-RPC tools/list exposure.,,,,,,2026-07-02,API/MCP Lane,Canonical tracker row for the first-class ctx-core read tools including related recommendations.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 55 |
+
MCP-002,,docs/qa/feature-user-story-status.csv,MCP/Core Tools,Lifecycle and session tool catalog,"ctx__observe_dev_event, ctx__load_entity, ctx__mark_entity_used, ctx__record_validation, ctx__record_escalation, ctx__unload_entity, ctx__session_end, ctx__session_state",src/ctx/adapters/generic/ctx_core_tools.py and ctx.runtime_lifecycle.record,High,As an MCP or generic harness client I can record runtime lifecycle evidence,Lifecycle tools append privacy-safe runtime events enforce bound session IDs hash telemetry identifiers and expose local session state with caller-facing slugs for usability,Temp runtime lifecycle directory available,pytest src/tests/test_harness_ctx_core.py src/tests/test_mcp_server.py -q,Automated Test,Tested Pass,test_harness_ctx_core.py covers lifecycle append order bound session enforcement telemetry hashing and test_mcp_server.py covers lifecycle tools/call round-trip.,,,,,,2026-07-02,API/MCP Lane,Canonical tracker row for lifecycle/session tools exposed in the MCP/core toolbox catalog.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 56 |
MCP-003,,docs/qa/feature-user-story-status.csv,MCP Router,Trusted third-party MCP attachment,McpClient and McpRouter,src/ctx/adapters/generic/tools/mcp_router.py,High,As a generic harness user I can attach trusted third-party MCP servers safely,Router starts MCP subprocesses with isolated environment namespaces tools handles timeouts and redacts secrets from errors,Fake MCP server fixture available,pytest src/tests/test_mcp_router.py -q,Automated Test,Tested Pass,test_mcp_router.py covers client start stop tool listing calls namespace routing timeout crash handling environment isolation and stderr secret redaction.,,,,,,2026-06-29,API/MCP Lane,Added because third-party MCP attachment is user-facing host functionality not just internal plumbing.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 57 |
MCP-004,,docs/qa/feature-user-story-status.csv,MCP/Core Tools,Response format negotiation,output_format and _response_format,src/ctx/adapters/generic/ctx_core_tools.py,High,As a tool caller I can request JSON or GCF output from read tools,Read tool schemas expose optional output_format and _response_format aliases and fall back to JSON errors when GCF codec is unavailable,Generic toolbox fixture available,pytest src/tests/test_harness_ctx_core.py -q,Automated Test,Tested Pass,test_harness_ctx_core.py covers optional schema fields JSON default GCF opt-in public alias and codec-missing fallback.,,,,,,2026-06-29,API/MCP Lane,Tracks a schema-visible behavior exposed to MCP/tool clients.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 58 |
DASH-001,,docs/qa/feature-user-story-status.csv,Dashboard,Home page,/,src/ctx/monitor/routes.py,High,As a user I can land on a useful dashboard home,Home shows current counts and high-value entry points without stale numbers,Monitor running,GET /,Manual/Documented,Tested Pass,GET / returned 200 in 1506ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 62 |
DASH-005,,docs/qa/feature-user-story-status.csv,Dashboard,Wiki index/catalog,"/wiki, /catalog, and /catalog/",src/ctx/monitor/routes.py,Medium,As a user I can search entity catalog,Wiki/catalog supports autocomplete-like search and tiles for skill agent MCP harness,Monitor running,GET /catalog?type=agent&q=review,Manual/Documented,Retested Pass,FAIL: live route timed out after 60018ms before fix,CTX-AZ-001,/catalog with query rebuilt too much server-side catalog state while /api/entities/search was fast,GET /catalog?type=agent&q=review,Fixed by using bounded search results for queried wiki/catalog render,PASS: live route 200 in 1422ms after monitor restart; focused tests 4 passed,2026-06-23,Dashboard/Docs Lane,Regression covered by test_render_wiki_index_query_uses_bounded_search,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 63 |
DASH-006,,docs/qa/feature-user-story-status.csv,Dashboard,Wiki entity page,/wiki/<slug>,src/ctx/monitor/routes.py,High,As a user I can inspect a full entity page,Entity page has Overview Subgraph Quality tabs and rendered markdown/frontmatter,Monitor running,GET /wiki/github?type=mcp-server,Manual/Documented,Tested Pass,GET /wiki/github?type=mcp-server returned 200 in 2705ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 64 |
DASH-007,,docs/qa/feature-user-story-status.csv,Dashboard,Graph page,/graph,src/ctx/monitor/routes.py,Medium,As a user I can explore graph interactively,Graph loads live search results click-to-focus double-click-back filters match histogram and useful inspector,Monitor running,GET /graph then interact,Manual/Documented,Retested Pass,PASS: /graph returned 200 in 31ms after monitor restart,,,,,PASS: Playwright test_ctx_monitor_browser.py::test_graph_page_uses_builtin_svg_renderer covered renderer click focus double-click back filters histogram live search type shapes and inspector.,2026-06-23,Dashboard/Docs Lane,Browser interaction pass completed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 65 |
+
DASH-PAGE-006A,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Recommend,/recommend,src/ctx/monitor/pages/recommend.py,High,As a dashboard user I can choose and refine ctx recommendations,Recommend page renders query top-k selected and rejected controls plus recommendation state TLDR reason and related suggestions,ctx-monitor running with recommendation fixture,Open /recommend?q=python&top_k=3 and test select all select none selected rejected and related output,Browser/User Story,Tested Pass,"PASS: focused pytest covers /recommend route navigation selected checkbox parsing TLDR reason rendering and related suggestion rows.",,,,,,2026-07-02,Dashboard/Docs Lane,Phase 5B dashboard recommendation slice; deeper live browser pass remains part of the final feature loop.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 66 |
DASH-020,,docs/qa/feature-user-story-status.csv,Dashboard,Graph live search type preservation,/graph focus search,src/ctx/monitor/pages/graph_client.py,Medium,As a dashboard user searching duplicate graph slugs I can keep the selected entity type,Live search sends the selected focus type to /api/entities/search.json so duplicate slugs resolve to the intended skill agent MCP server or harness,Monitor running with graph search data,pytest src/tests/test_ctx_monitor.py::test_render_graph_focus_controls_preserve_type -q,Automated Test,Retested Pass,FAIL: graph live search fetched /api/entities/search.json without type even when focus-type was selected.,DASH-UX-004,Graph live search ignored the selected focus entity type and could suggest the wrong duplicate slug type,pytest src/tests/test_ctx_monitor.py::test_render_graph_focus_controls_preserve_type -q,Fixed by appending selectedFocusType to the live entity search request,PASS: focused graph render test pins selected type in live search URL generation.,2026-06-29,Dashboard/Docs Lane,Added from dashboard/graph expert lane UX finding.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 67 |
DASH-008,,docs/qa/feature-user-story-status.csv,Dashboard,Manage page,/manage,src/ctx/monitor/routes.py,High,As a user I can manage entities,Manage supports search upload/upsert delete/manual edit with safety prompts,Monitor running,GET /manage,Manual/Documented,Tested Pass,GET /manage returned 200 in 261ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 68 |
DASH-009,,docs/qa/feature-user-story-status.csv,Dashboard,Harness setup,/harness,src/ctx/monitor/routes.py,High,As a local/API model user I can use a harness wizard,Harness Setup interviews model and goals recommends matching harness or no-fit PRD,Monitor running,GET /harness,Manual/Documented,Tested Pass,GET /harness returned 200 in 23ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 70 |
DASH-011,,docs/qa/feature-user-story-status.csv,Dashboard,Config page,/config,src/ctx/monitor/routes.py,High,As a user I can view/edit important config,Config shows explanations defaults required fields validation and safe save,Monitor running,GET /config and POST /api/config,Manual/Documented,Tested Pass,GET /config returned 200 in 12ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 71 |
DASH-012,,docs/qa/feature-user-story-status.csv,Dashboard,Status page,/status,src/ctx/monitor/routes.py,High,As a user I can see system health,Status reports graph/wiki/cache/session health with actionable errors,Monitor running,GET /status,Manual/Documented,Tested Pass,GET /status returned 200 in 3750ms after restart; functional but slower than core pages.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 72 |
DASH-013,,docs/qa/feature-user-story-status.csv,Dashboard,KPI page,/kpi,src/ctx/monitor/routes.py,High,As a user I can inspect recommendation effectiveness,KPIs show usage score quality and lifecycle trends without slow unbounded render,Monitor running,GET /kpi,Manual/Documented,Tested Pass,GET /kpi returned 200 in 107ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 73 |
+
DASH-014,,docs/qa/feature-user-story-status.csv,Dashboard,Runtime page,/runtime,src/ctx/monitor/pages/activity.py and src/ctx/monitor/services/runtime.py,High,As a user I can inspect runtime lifecycle artifacts,Runtime shows validation escalation tool-selection token-usage and recent usage metadata without raw evidence strings,Monitor running,GET /runtime and focused runtime lifecycle tests,Automated Test,Retested Pass,PASS: runtime lifecycle tests cover token usage and privacy-safe recent usage metadata.,,,,,,2026-07-02,Dashboard/Docs Lane,Retested in the tool-selection/token-history canonical loop.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: privacy-safe runtime metadata only; no broader behavior change.,Validated by focused runtime lifecycle tests; no-mistakes deferred until after canonical feature loop
|
| 74 |
DASH-015,,docs/qa/feature-user-story-status.csv,Dashboard,Sessions page,/sessions,src/ctx/monitor/routes.py,High,As a user I can inspect sessions,Sessions page lists transcripts and details without leaking secrets,Monitor running,GET /sessions,Manual/Documented,Tested Pass,GET /sessions returned 200 in 269ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 75 |
DASH-016,,docs/qa/feature-user-story-status.csv,Dashboard,Logs page,/logs,src/ctx/monitor/routes.py,High,As a user I can inspect logs,Logs render audit/log files or clear empty state,Monitor running,GET /logs,Manual/Documented,Tested Pass,GET /logs returned 200 in 132ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 76 |
DASH-017,,docs/qa/feature-user-story-status.csv,Dashboard,Live events,/events and /live,src/ctx/monitor/routes.py,High,As a user I can tail live events,Live page connects SSE and shows clear empty/disconnected states,Monitor running,GET /events and /api/events.stream,Manual/Documented,Tested Pass,GET /live returned 200 in 87ms after restart.,,,,,,2026-06-23,Dashboard/Docs Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 81 |
API-003,,docs/qa/feature-user-story-status.csv,Dashboard API,Status API,/api/status.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch health JSON,Endpoint returns graph/wiki/cache health with correct status code,Monitor running,GET /api/status.json,Manual/Documented,Tested Pass,GET /api/status.json returned 200 in 4303ms after restart; functional but slower than core APIs.,,,,,,2026-06-23,API/MCP Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 82 |
API-004,,docs/qa/feature-user-story-status.csv,Dashboard API,KPI API,/api/kpi.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch KPI JSON,Endpoint returns bounded KPI payload quickly,Monitor running,GET /api/kpi.json,Manual/Documented,Tested Pass,GET /api/kpi.json returned 200 in 105ms after restart.,,,,,,2026-06-23,API/MCP Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 83 |
API-005,,docs/qa/feature-user-story-status.csv,Dashboard API,Grades API,/api/grades.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch grades JSON,Endpoint returns score and grade payload with explanations,Monitor running,GET /api/grades.json,Manual/Documented,Retested Pass,Initial dashboard sweep: GET /api/grades.json returned 200 but took 16833ms for a tiny payload.,CTX-AZ-005,Grades API ignored cached KPI grade_counts and rescanned all quality sidecars on demand.,GET /api/grades.json,Fixed,"After routing through cached KPI summary, GET /api/grades.json returned 200 in 92ms after restart.",2026-06-23,API/MCP Lane,Fallback full sidecar scan remains for missing KPI summary.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 84 |
+
API-006,,docs/qa/feature-user-story-status.csv,Dashboard API,Runtime API,/api/runtime.json,src/ctx/monitor/api/readonly.py and src/ctx/monitor/services/runtime.py,High,As a dashboard client I can fetch runtime JSON,Endpoint returns lifecycle selection token usage and recent usage metadata without raw evidence strings,Monitor running,GET /api/runtime.json and scan for raw evidence strings,Automated Test,Retested Pass,PASS: runtime lifecycle test asserts private evidence text is absent from recent_tool_usage.,,,,,,2026-07-02,API/MCP Lane,Retested in the tool-selection/token-history canonical loop.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: privacy-safe runtime metadata only; no broader behavior change.,Validated by focused runtime lifecycle tests; no-mistakes deferred until after canonical feature loop
|
| 85 |
API-007,,docs/qa/feature-user-story-status.csv,Dashboard API,Entity search API,/api/entities/search.json,src/ctx/monitor/routes.py,High,As a dashboard client I can search entities,Endpoint supports live query type filters and useful fuzzy results,Monitor running,GET /api/entities/search.json?q=review&type=agent,Manual/Documented,Tested Pass,PASS: endpoint returned 200 in 28ms with agent review results,,,,,,2026-06-23,API/MCP Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 86 |
API-008,,docs/qa/feature-user-story-status.csv,Dashboard API,Entity detail API,/api/entity/<slug>.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch entity details,Endpoint returns canonical entity docs frontmatter and graph sidecar,Monitor running,GET /api/entity/github.json?type=mcp-server,Manual/Documented,Tested Pass,GET /api/entity/github.json?type=mcp-server returned 200 in 27ms after restart.,,,,,,2026-06-23,API/MCP Lane,Dashboard route sweep; no mutation performed.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 87 |
API-009,,docs/qa/feature-user-story-status.csv,Dashboard API,Graph neighborhood API,/api/graph/<slug>.json,src/ctx/monitor/routes.py,High,As a dashboard client I can fetch a graph neighborhood,Endpoint returns bounded nodes edges scores and reasons fast after runtime install,Monitor running,GET /api/graph/github.json?type=skill&limit=20,Manual/Documented,Tested Pass,PASS: endpoint returned 200 in 2295ms with nodes/edges JSON,,,,,,2026-06-23,API/MCP Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 167 |
DASH-PAGE-010,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Config,/config,src/ctx/monitor/pages/config.py,High,As a dashboard user I can inspect and edit ctx configuration,Config page shows required settings descriptions examples defaults and validates saves or clears through the config API,ctx-monitor running with mutation token,Open /config and validate required fields defaults save clear and error states,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /config, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 168 |
DASH-PAGE-011,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Status,/status,src/ctx/monitor/pages/ops.py,High,As a dashboard user I can inspect system status,Status page shows graph wiki config backup and queue health with actionable error text,ctx-monitor running,Open /status and verify status sections and stale artifact messages,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /status, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 169 |
DASH-PAGE-012,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,KPI,/kpi,src/ctx/monitor/pages/ops.py,High,As a dashboard user I can inspect dashboard KPIs,KPI page shows usage quality load and recommendation metrics with readable number formatting,ctx-monitor running,Open /kpi and verify metric cards charts and empty states,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /kpi, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 170 |
+
DASH-PAGE-013,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Runtime,/runtime,src/ctx/monitor/pages/activity.py and src/ctx/monitor/services/runtime.py,High,As a dashboard user I can inspect runtime lifecycle state,Runtime page shows validations escalations tool selection token usage and recent usage metadata without raw evidence strings or secrets,ctx-monitor running,Open /runtime and verify lifecycle state token usage and no raw evidence leakage,Browser/User Story,Retested Pass,PASS: focused runtime monitor tests cover tool selection token usage and privacy-safe recent usage metadata.,,,,,,2026-07-02,Dashboard/Docs Lane,Retested in the tool-selection/token-history canonical loop.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: privacy-safe runtime metadata only; no broader behavior change.,Validated by focused runtime lifecycle tests; no-mistakes deferred until after canonical feature loop
|
| 171 |
DASH-PAGE-014,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Sessions,/sessions,src/ctx/monitor/pages/activity.py,High,As a dashboard user I can browse ctx sessions,Sessions page lists sessions links details and handles empty history cleanly,ctx-monitor running with or without sessions,Open /sessions and verify list empty state and detail links,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /sessions, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 172 |
DASH-PAGE-015,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Logs,/logs,src/ctx/monitor/pages/activity.py,High,As a dashboard user I can inspect audit logs,Logs page tails audit JSONL entries and handles missing logs without a blank page,ctx-monitor running,Open /logs and verify log rows empty state and formatting,Browser/User Story,Tested Pass,"PASS: live Playwright page probe opened /logs, found expected page markers, and detected no traceback or server-error text; dashboard_smoke also returned HTTP 200.",,,,,,2026-06-25,Dashboard/Docs Lane,Deeper controls are tracked in dedicated function/API/mutation rows.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 173 |
DASH-PAGE-016,,docs/qa/dashboard-user-story-status.csv,Dashboard Page,Live Events,/events,src/ctx/monitor/pages/activity.py,Medium,As a dashboard user I can watch live events,Live page connects to server-sent events and shows either audit events or a clear waiting state,ctx-monitor running,Open /events and verify SSE connection and empty state,Browser/User Story,Retested Pass,FAIL: /api/events.stream did not send initial bytes within 10 seconds so the Live page could remain blank.,,,,,PASS: /events returned HTTP 200 and /api/events.stream returned : connected promptly after the SSE fix.,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 189 |
DASH-API-004,,docs/qa/dashboard-user-story-status.csv,Dashboard API,KPI API,/api/kpi.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch KPI data,API returns metric payloads that match the KPI page,ctx-monitor running,GET /api/kpi.json and compare with page expectations,Manual/Documented,Tested Pass,PASS: /api/kpi.json returned HTTP 200 JSON with generated_at total and grade summary keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 190 |
DASH-API-005,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Grades API,/api/grades.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch grade summaries,API returns quality grade summaries for skills agents MCPs and harnesses,ctx-monitor running,GET /api/grades.json and validate JSON shape,Manual/Documented,Tested Pass,PASS: /api/grades.json returned HTTP 200 JSON with grades and total keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 191 |
DASH-API-006,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Sidecars API,/api/sidecars.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch searchable card data,API supports q type grade floor and limit filters with bounded output,ctx-monitor running,GET /api/sidecars.json?q=review&type=agent&limit=5,Manual/Documented,Tested Pass,PASS: /api/sidecars.json?q=review&type=agent&limit=5 returned HTTP 200 JSON with items total and pagination keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 192 |
+
DASH-API-007,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Runtime API,/api/runtime.json,src/ctx/monitor/api/readonly.py and src/ctx/monitor/services/runtime.py,High,As a dashboard client I can fetch runtime lifecycle diagnostics,API returns validation escalation selection token usage and recent usage metadata without raw evidence strings or secrets,ctx-monitor running,GET /api/runtime.json and scan for secret-like fields plus raw evidence strings,Automated Test,Retested Pass,PASS: focused runtime monitor test asserts recent_tool_usage exposes evidence_present/evidence_length and not the raw evidence value.,,,,,,2026-07-02,Dashboard/Docs Lane,,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: privacy-safe runtime metadata only; no broader behavior change.,Validated by focused runtime lifecycle tests; no-mistakes deferred until after canonical feature loop
|
| 193 |
DASH-API-008,,docs/qa/dashboard-user-story-status.csv,Dashboard API,SkillSpector API,/api/skillspector.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch SkillSpector findings,API returns audit records filtered by severity and query,ctx-monitor running,GET /api/skillspector.json?severity=HIGH&q=prompt,Manual/Documented,Tested Pass,PASS: /api/skillspector.json?severity=HIGH&q=prompt returned HTTP 200 JSON with summary filters and records keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 194 |
DASH-API-009,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Config API,/api/config.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can fetch effective config,API returns defaults overrides required metadata and no secrets,ctx-monitor running,GET /api/config.json and validate required fields,Manual/Documented,Tested Pass,PASS: /api/config.json returned HTTP 200 JSON with defaults user effective and path keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 195 |
DASH-API-010,,docs/qa/dashboard-user-story-status.csv,Dashboard API,Entity Search API,/api/entities/search.json,src/ctx/monitor/api/readonly.py,High,As a dashboard client I can search entities for autocomplete,API returns typed entity suggestions for search terms and rejects unsafe queries cleanly,ctx-monitor running,GET /api/entities/search.json?q=github&type=skill,Manual/Documented,Tested Pass,PASS: /api/entities/search.json?q=github&type=skill&limit=5 returned HTTP 200 JSON with results and total keys.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 203 |
DASH-POST-004,,docs/qa/dashboard-user-story-status.csv,Dashboard Mutation,Entity Upsert API,/api/entity/upsert,src/ctx/monitor/api/mutations.py,High,As a dashboard user I can add or update entities manually,POST validates type slug and body runs entity-specific safety gates and queues graph refresh,ctx-monitor running with mutation token and temp wiki,POST /api/entity/upsert against temp wiki and verify entity page plus queue,Automated Test,Tested Pass,"PASS: focused pytest covered /api/entity/upsert validation, entity write, and queue behavior.",,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 204 |
DASH-POST-005,,docs/qa/dashboard-user-story-status.csv,Dashboard Mutation,Entity Delete API,/api/entity/delete,src/ctx/monitor/api/mutations.py,High,As a dashboard user I can delete dashboard-managed entities safely,POST validates mutation token safe slug and entity ownership before deleting or tombstoning,ctx-monitor running with mutation token and temp wiki,POST /api/entity/delete against temp wiki and verify no unrelated files removed,Automated Test,Tested Pass,PASS: focused pytest covered /api/entity/delete validation and safe deletion behavior.,,,,,,2026-06-25,Dashboard/Docs Lane,,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: no fix needed unless retest produces a concrete regression.,Validated by completed goal-loop and no-mistakes gate
|
| 205 |
B-API-001,PYAPI-001,expert-lane/api-mcp-harness,Python API,Package exports,ctx package exports,src/ctx/__init__.py; src/ctx/api.py,High,"As a Python caller, I can import stable ctx helpers.","ctx re-exports public recommendation, wiki, graph, and list helpers without breaking import compatibility.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_public_api.py src/tests/test_harness_ctx_core.py src/tests/test_recommendation_surfaces_golden.py,Automated Test,Tested Pass,"PASS: /tmp/ctx-verify-venv/bin/python -m pytest -q --no-cov src/tests/test_public_api.py src/tests/test_harness_ctx_core.py src/tests/test_recommendation_surfaces_golden.py src/tests/test_enterprise_telemetry.py src/tests/test_mcp_server.py src/tests/test_mcp_router.py src/tests/test_mcp_live_compat.py src/tests/test_mcp_install.py -> 383 passed, 1 skipped; package export/signature/API behavior covered.",,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Child row from API/MCP lane; ctx_core_tool_names/recommendation_graph helpers are not package re-exported.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
| 206 |
+
B-API-002,PYAPI-001,expert-lane/api-mcp-harness,Python API,Recommendation API,"recommend_bundle(query, top_k); recommend_related(...)",src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py,High,"As an app, I can get ctx capability recommendations.","recommend_bundle returns skill, agent, and MCP recommendations and recommend_related returns graph-backed suggestions after partial selection while mapping structured errors to empty results.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_recommendation_surfaces_golden.py src/tests/test_harness_ctx_core.py,Automated Test,Tested Pass,"PASS: recommendation public/core surfaces covered by test_public_api.py, test_recommendation_surfaces_golden.py, and test_harness_ctx_core.py in API/MCP slice -> 383 passed, 1 skipped.",,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-02,API/MCP Lane,Harnesses remain companion metadata rather than primary recommendations; related recommendations use selected and rejected IDs.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
| 207 |
B-API-003,PYAPI-001,expert-lane/api-mcp-harness,Python API,Graph API,"graph_query(seeds, max_hops, top_n)",src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py,High,"As an app, I can explore nearby ctx entities.","graph_query returns bounded graph neighbors for skill, agent, MCP, and harness seeds.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_harness_ctx_core.py,Automated Test,Tested Pass,"PASS: graph_query public/core behavior covered by test_public_api.py and test_harness_ctx_core.py in API/MCP slice -> 383 passed, 1 skipped.",,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Invalid or missing graph state collapses to an empty result for library callers.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
| 208 |
B-API-004,PYAPI-001,expert-lane/api-mcp-harness,Python API,Wiki API,wiki_search/wiki_get,src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py,High,"As an app, I can inspect wiki entities.","Search and get calls return slug, frontmatter, body, and type-aware entity details.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_harness_ctx_core.py,Automated Test,Tested Pass,"PASS: wiki_search/wiki_get public/core behavior covered by test_public_api.py and test_harness_ctx_core.py in API/MCP slice -> 383 passed, 1 skipped.",,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Slug/type ambiguity returns None rather than raising.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
| 209 |
B-API-005,PYAPI-001,expert-lane/api-mcp-harness,Python API,Catalog API,list_all_entities/default_wiki_dir,src/ctx/api.py; src/ctx/identity.py,Medium,"As tooling, I can enumerate installed catalog entities.","The API lists recommendable skills, agents, MCPs, and harnesses and resolves the configured wiki directory.",Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_harness_recommendations.py,Automated Test,Tested Pass,PASS: /tmp/ctx-verify-venv/bin/python -m pytest -q --no-cov src/tests/test_harness_recommendations.py -> 15 passed; catalog/harness recommendation enumeration covered.,,,,,"PASS: API/MCP validation slice on 2026-07-01: 383 passed, 1 opt-in live MCP skip; harness recommendation slice: 15 passed; explicit live MCP compatibility check: 8 passed, 1 opt-in skip.",2026-07-01,API/MCP Lane,Depends on local wiki/config presence.,Reviewed by no-mistakes,no-mistakes run 01KWF5NJXTAFH6FVTR96PS2B2B reached checks-passed on PR #210 before this tracker slice; OpenCodeReview LLM endpoint remains unavailable.,"Ponytail: validate first, then make the smallest behavior-preserving fix only if the repro is confirmed.",Validated by completed goal-loop and no-mistakes gate
|
|
|
|
| 283 |
PKG-002,CLI-029,expert-lane/cli-package-inventory,Package CLI,Toolbox satellite modules,python -m intent_interview; python -m behavior_miner; python -m council_runner; python -m toolbox_verdict,src/intent_interview.py; src/behavior_miner.py; src/council_runner.py; src/toolbox_verdict.py,Medium,"As a toolbox user, I can interview intent, mine behavior, plan councils, and record verdicts.",Documented toolbox module commands should match the parser verbs exposed by the code.,Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_intent_interview.py src/tests/test_behavior_miner.py src/tests/test_council_runner.py src/tests/test_toolbox_verdict.py,Automated Test,Retested Pass,FAIL: expert-lane inventory found toolbox docs listing stale behavior_miner/council_runner verbs.,QA-CLI-001,Toolbox docs may mention stale behavior_miner/council_runner verbs that no longer match parsers.,Compare docs/toolbox/behavior-miner.md and docs/toolbox/council-runner.md against argparse verbs in src/behavior_miner.py and src/council_runner.py.,Fixed by aligning docs with live argparse verbs and current profile/run-plan data shapes.,PASS: behavior_miner and council_runner help commands show documented verbs; focused toolbox tests 138 passed; MkDocs strict build passed.,2026-06-30,CLI Lane,CLI lane found possible docs drift for behavior_miner and council_runner verbs.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: docs-only correction; code already exposed the smaller tested command surface.,Validated by completed goal-loop and no-mistakes gate
|
| 284 |
META-001,CLI-001,expert-lane/cli-package-inventory,Package Entry Point,python -m ctx package entrypoint,src/ctx/__main__.py,src/ctx package,Medium,"As a package user, I can launch the flagship ctx harness with python -m ctx.",python -m ctx should delegate to the same behavior as the ctx console script or be explicitly documented as unsupported.,Repo checkout with Python 3.11+ dev environment.,python -m pytest -q src/tests/test_package_scaffold.py src/tests/test_harness_cli_run.py,Automated Test,Retested Pass,FAIL: expert-lane inventory found no src/ctx/__main__.py for python -m ctx.,QA-CLI-002,python -m ctx currently has no package __main__.py entrypoint.,Run python -m ctx --help from an editable install or source checkout; Python cannot execute package ctx without __main__.py.,Fixed by adding a tiny __main__.py that delegates to ctx.cli.run.main.,PASS: PYTHONPATH=src python -m ctx --help exits 0 and shows run/resume/sessions; package scaffold test covers the invocation.,2026-06-30,CLI Lane,CLI lane found no src/ctx/__main__.py despite the flagship ctx console script.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,"Ponytail: one small delegation shim, no duplicate CLI implementation.",Validated by completed goal-loop and no-mistakes gate
|
| 285 |
QA-USE-001,B-ADAPT-001,expert-lane/cli-package-inventory,Hooks,Usage tracker temp wiki and log path precedence,python -m usage_tracker --sync,src/usage_tracker.py; src/tests/test_usage_tracker.py,High,"As a hook/test harness user, I can point usage tracking at an explicit wiki or log path without ambient local wiki packs hijacking the write.","Explicit wiki_dir, ENTITIES_DIR, and LOG_PATH targets are honored before the default packed wiki fallback is considered.",Repo checkout with Python 3.11+ dev environment and a default ~/.claude/skill-wiki/wiki-packs directory present.,python -m pytest -q src/tests/test_usage_tracker.py,Automated Test,Retested Pass,FAIL: full pytest and isolated test_usage_tracker.py failed because default wiki-packs shadowed monkeypatched ENTITIES_DIR and LOG_PATH.,QA-USE-001,usage_tracker default packed-wiki fallback ignored explicit module-level temp paths when local default wiki-packs existed.,"With ~/.claude/skill-wiki/wiki-packs present, run python -m pytest -q src/tests/test_usage_tracker.py before the fix.",Fixed by making monkeypatched ENTITIES_DIR/LOG_PATH take precedence over default packed-wiki fallback when wiki_dir is not explicitly passed.,PASS: python -m pytest -q src/tests/test_usage_tracker.py -> 42 passed; ruff check src/usage_tracker.py -> passed.,2026-06-30,CLI Lane,Found by current full-suite goal loop after Phase 2 fixes.,Reviewed by no-mistakes,Historical tracker import; current canonical row is covered by completed goal-loop review and no-mistakes gate.,Ponytail: small precedence guard; no rewrite of packed-wiki logic.,Validated by completed goal-loop and no-mistakes gate
|
| 286 |
+
US-001,B-REC-001,qa/tool-selection-token-history/tracker.csv,API/CLI/UI,Tool recommendation selection,ctx-recommend; ctx.api.recommend_bundle; ctx__recommend_bundle; /recommend,src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/cli/recommend.py; src/ctx/monitor/pages/recommend.py,High,"As a programmer or AI engineer, I can select which recommended tools to use.","UI/CLI/API expose selectable state for every suggested skill, agent, MCP server, and harness where supported; select all, none, and subset flows are explicit.",Repo checkout with Python 3.11+ dev environment and graph/wiki recommendation fixture.,pytest src/tests/test_recommendations.py src/tests/test_recommend_cli.py src/tests/test_ctx_monitor.py -q,Automated Test,Retested Pass,"Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19); supporting tracker US-001 retested pass.",,,,,,2026-07-02,API/MCP Lane,Canonical projection of tool-selection/token-history tracker row US-001.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 287 |
+
US-002,B-REC-001,qa/tool-selection-token-history/tracker.csv,API/CLI/UI,TLDR descriptions,ctx-recommend; ctx.api.recommend_bundle; ctx__recommend_bundle; /recommend,src/ctx/core/resolve/recommendations.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/cli/recommend.py; src/ctx/monitor/pages/recommend.py,High,"As a user, I can read a concise TLDR for each suggested tool before selecting it.",Each recommendation has a short description plus relevance reason; fallback uses safe existing metadata when description is absent.,Repo checkout with Python 3.11+ dev environment and graph/wiki recommendation fixture.,pytest src/tests/test_recommendations.py src/tests/test_recommendation_surfaces_golden.py -q,Automated Test,Retested Pass,"Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19); supporting tracker US-002 retested pass.",,,,,,2026-07-02,API/MCP Lane,Canonical projection of tool-selection/token-history tracker row US-002.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 288 |
+
US-003,B-API-002,qa/tool-selection-token-history/tracker.csv,Knowledge Graph,Related recommendations after partial selection,ctx.api.recommend_related; ctx__recommend_related; ctx-recommend --related-top-n; /recommend,src/ctx/core/resolve/recommendations.py; src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/monitor/pages/recommend.py,High,"As a user, if I select only some suggestions, ctx proposes related tools.","Related rows are generated from graph/category/tag neighbors, exclude selected/rejected/unavailable/deprecated rows, and include reason text.",Repo checkout with Python 3.11+ dev environment and graph/wiki recommendation fixture.,pytest src/tests/test_recommendations.py src/tests/test_harness_recommendations.py -q,Automated Test,Retested Pass,"Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19); supporting tracker US-003 retested pass.",,,,,,2026-07-02,API/MCP Lane,Canonical projection of tool-selection/token-history tracker row US-003.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 289 |
+
US-004,B-HAR-009,qa/tool-selection-token-history/tracker.csv,Runtime Lifecycle,Tool activation tracking,ctx__load_entity; ctx__mark_entity_used; ctx__session_state,src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/adapters/generic/ctx_core_tools.py,Critical,"As a user, selected tool activation is recorded with session/system context.","Activation records include entity id/name/type, timestamp, privacy-safe session context, user-selected vs system-selected source, and source context.",Repo checkout with Python 3.11+ dev environment and temp runtime lifecycle directory.,pytest src/tests/test_harness_ctx_core.py -q,Automated Test,Retested Pass,Phase 7 focused harness-core retest passed (70 passed); full pytest and ci_preflight also passed.,,,,,,2026-07-02,Telemetry/Release Lane,Canonical projection of tool-selection/token-history tracker row US-004.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 290 |
+
US-005,LANE-D-006,qa/tool-selection-token-history/tracker.csv,Telemetry,Token usage KPI,ctx__mark_entity_used.token_usage; /runtime; /api/runtime.json,src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/telemetry/__init__.py; src/ctx/cli/run.py; src/ctx/monitor/services/runtime.py,Critical,"As a user, I can see token usage per selected and activated tool.",Exact input/output/total tokens are recorded only with per-tool correlation; session totals stay session-level; estimated/unavailable values are labeled honestly with reason; API/dashboard expose the data.,Repo checkout with Python 3.11+ dev environment and temp runtime lifecycle directory.,pytest src/tests/test_enterprise_telemetry.py src/tests/test_harness_cli_run.py -q,Automated Test,Retested Pass,"Phase 7 telemetry enterprise gate passed (67 passed, 65 deselected); full pytest and ci_preflight also passed.",,,,,,2026-07-02,Telemetry/Release Lane,Canonical projection of tool-selection/token-history tracker row US-005.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 291 |
+
US-006,LANE-D-006,qa/tool-selection-token-history/tracker.csv,Persistence,Historical usage,runtime lifecycle session_state; /runtime; /api/runtime.json,src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/monitor/services/runtime.py,High,"As a user, I can view historical token usage per tool over time.","Usage history persists across sessions and can be aggregated by tool, type, session, and source.",Repo checkout with Python 3.11+ dev environment and temp runtime lifecycle directory.,pytest src/tests/test_harness_ctx_core.py src/tests/test_ctx_monitor.py -q,Automated Test,Retested Pass,"Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19); supporting tracker US-006 retested pass.",,,,,,2026-07-02,Telemetry/Release Lane,Canonical projection of tool-selection/token-history tracker row US-006.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 292 |
+
US-007,DASH-PAGE-006A,qa/tool-selection-token-history/tracker.csv,Dashboard,Dashboard support,/recommend; /runtime; /api/runtime.json,src/ctx/monitor/services/runtime.py; src/ctx/monitor/pages/ops.py; src/ctx/monitor/pages/recommend.py; src/ctx/monitor/api/readonly.py,High,"As a user/admin, I can see tool-selection and token-history KPIs in the dashboard.","Dashboard shows totals, recent usage, history, user-vs-system selected source, and empty/error/unavailable states.",ctx-monitor route fixture or browser-capable dev environment.,pytest src/tests/test_ctx_monitor.py src/tests/test_monitor_testing_api.py src/tests/test_dashboard_smoke.py -q,Automated Test,Retested Pass,Phase 7 browser monitor security gate passed (11 passed); ci_preflight --profile pr passed 19/19.,,,,,,2026-07-02,Dashboard/Docs Lane,Canonical projection of tool-selection/token-history tracker row US-007.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 293 |
+
US-008,PYAPI-001,qa/tool-selection-token-history/tracker.csv,Parity,API/CLI/UI parity,ctx.api; ctx-recommend; CtxCoreToolbox; ctx-mcp-server; LoopFlow adapter; /recommend,src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/mcp_server/server.py; src/ctx/adapters/loopflow.py; docs,High,"As a user, behavior is consistent across API, CLI, MCP/core toolbox, LoopFlow, and dashboard.",Shared semantics are reused; differences are documented only where necessary.,Repo checkout with Python 3.11+ dev environment and graph/wiki recommendation fixture.,pytest src/tests/test_public_api.py src/tests/test_mcp_server.py src/tests/test_loopflow_adapter.py -q,Automated Test,Retested Pass,"Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19); supporting tracker US-008 retested pass.",,,,,,2026-07-02,API/MCP Lane,Canonical projection of tool-selection/token-history tracker row US-008.,Pending no-mistakes,Awaiting final no-mistakes run after canonical feature loop.,Ponytail: no fix needed unless final no-mistakes finds a concrete regression.,Validated by Phase 7 gates; no-mistakes deferred until after canonical feature loop
|
| 294 |
+
QA-001,LANE-D-039,qa/tool-selection-token-history/tracker.csv,QA,Regression suite,src/tests; scripts/ci_preflight.py; no-mistakes gate,src/tests; scripts/ci_preflight.py; qa/tool-selection-token-history/tracker.csv,Critical,"As a maintainer, I can ship without breaking existing recommendation/telemetry/dashboard behavior.","Focused milestone tests, ruff, mypy, full pytest, ci_preflight, and no-mistakes pass.",Repo checkout with Python 3.11+ dev environment and no-mistakes remote available.,python scripts/ci_preflight.py --profile pr; no-mistakes axi run --intent ...,Automated Test,Needs Validation,"Phase 7 passed ruff format/check, mypy, full pytest (4431 passed, 2 skipped), ci_preflight --profile pr (19/19), stats check, docs build, and public tracker tests; no-mistakes remains deferred until after the canonical feature loop.",,,,,,2026-07-02,Telemetry/Release Lane,Canonical projection of tool-selection/token-history tracker row QA-001.,Pending no-mistakes,Final no-mistakes gate has not run yet by user instruction; run after canonical feature loop completes.,Ponytail: no code fix pending; execute final gate after tracker/test loop.,Pending no-mistakes after canonical feature loop
|
qa/tool-selection-token-history/Plan.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tool Selection And Token History Plan
|
| 2 |
+
|
| 3 |
+
Date: 2026-07-02
|
| 4 |
+
|
| 5 |
+
## Phase 0: Planning And Architecture Map
|
| 6 |
+
|
| 7 |
+
Scope: planning artifacts only.
|
| 8 |
+
|
| 9 |
+
Files:
|
| 10 |
+
|
| 11 |
+
- `qa/tool-selection-token-history/SPEC.md`
|
| 12 |
+
- `qa/tool-selection-token-history/Plan.md`
|
| 13 |
+
- `qa/tool-selection-token-history/tracker.csv`
|
| 14 |
+
|
| 15 |
+
Validation:
|
| 16 |
+
|
| 17 |
+
```sh
|
| 18 |
+
/tmp/ctx-verify-venv/bin/python - <<'PY'
|
| 19 |
+
import csv
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
path = Path("qa/tool-selection-token-history/tracker.csv")
|
| 22 |
+
rows = list(csv.DictReader(path.open(newline="", encoding="utf-8")))
|
| 23 |
+
required = {
|
| 24 |
+
"ID", "Workstream", "Feature", "User Story", "Expected Behavior",
|
| 25 |
+
"Files/Modules", "Test Command", "Status", "Severity", "Attempts",
|
| 26 |
+
"Last Checked", "Notes",
|
| 27 |
+
}
|
| 28 |
+
assert rows
|
| 29 |
+
assert set(rows[0]) == required
|
| 30 |
+
assert {row["ID"] for row in rows} >= {f"US-{i:03d}" for i in range(1, 9)}
|
| 31 |
+
print(f"tracker rows: {len(rows)}")
|
| 32 |
+
PY
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Success criteria:
|
| 36 |
+
|
| 37 |
+
- Spec names observed code paths and missing pieces.
|
| 38 |
+
- Plan breaks implementation into bounded milestones.
|
| 39 |
+
- Tracker has all core user stories.
|
| 40 |
+
|
| 41 |
+
## Phase 1: Shared Recommendation Selection Contract
|
| 42 |
+
|
| 43 |
+
Scope: backend/core only, no dashboard changes.
|
| 44 |
+
|
| 45 |
+
Candidate files:
|
| 46 |
+
|
| 47 |
+
- `src/ctx/core/resolve/recommendations.py`
|
| 48 |
+
- `src/ctx/adapters/generic/ctx_core_tools.py`
|
| 49 |
+
- `src/ctx/api.py`
|
| 50 |
+
- `src/tests/test_recommendations.py`
|
| 51 |
+
- `src/tests/test_public_api.py`
|
| 52 |
+
|
| 53 |
+
Work:
|
| 54 |
+
|
| 55 |
+
- Add stable row enrichment helpers for recommendation id, TL;DR, reason, selected/default state, and entity identity.
|
| 56 |
+
- Preserve old `recommend_bundle()` list-return compatibility.
|
| 57 |
+
- Add explicit enriched API/toolbox operation or opt-in argument rather than changing all callers silently.
|
| 58 |
+
|
| 59 |
+
Validation:
|
| 60 |
+
|
| 61 |
+
```sh
|
| 62 |
+
/tmp/ctx-verify-venv/bin/python -m pytest -q -p no:cacheprovider src/tests/test_recommendations.py src/tests/test_public_api.py src/tests/test_recommendation_surfaces_golden.py
|
| 63 |
+
/tmp/ctx-verify-venv/bin/python -m ruff check src/ctx/core/resolve/recommendations.py src/ctx/adapters/generic/ctx_core_tools.py src/ctx/api.py
|
| 64 |
+
/tmp/ctx-verify-venv/bin/python -m mypy src
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
## Phase 2: Related Recommendations
|
| 68 |
+
|
| 69 |
+
Scope: graph/backend, then API/LoopFlow exposure.
|
| 70 |
+
|
| 71 |
+
Candidate files:
|
| 72 |
+
|
| 73 |
+
- `src/ctx/core/resolve/recommendations.py`
|
| 74 |
+
- `src/ctx/adapters/generic/ctx_core_tools.py`
|
| 75 |
+
- `src/ctx/api.py`
|
| 76 |
+
- `src/ctx/adapters/loopflow.py`
|
| 77 |
+
- `src/tests/test_recommendations.py`
|
| 78 |
+
- `src/tests/test_loopflow_adapter.py`
|
| 79 |
+
|
| 80 |
+
Work:
|
| 81 |
+
|
| 82 |
+
- Add a related recommendation function based on selected seeds, graph neighbors, categories/tags, or existing `graph_query`.
|
| 83 |
+
- Exclude selected and rejected identities.
|
| 84 |
+
- Explain reasons with shared tags/graph-neighbor evidence.
|
| 85 |
+
- Expose through API/core toolbox and LoopFlow/agent-loop payloads.
|
| 86 |
+
|
| 87 |
+
Validation:
|
| 88 |
+
|
| 89 |
+
```sh
|
| 90 |
+
/tmp/ctx-verify-venv/bin/python -m pytest -q -p no:cacheprovider src/tests/test_recommendations.py src/tests/test_loopflow_adapter.py src/tests/test_harness_recommendations.py
|
| 91 |
+
/tmp/ctx-verify-venv/bin/python -m ruff check src/ctx/core/resolve/recommendations.py src/ctx/adapters/generic/ctx_core_tools.py src/ctx/api.py src/ctx/adapters/loopflow.py
|
| 92 |
+
/tmp/ctx-verify-venv/bin/python -m mypy src
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
## Phase 3: Activation And Token Usage Persistence
|
| 96 |
+
|
| 97 |
+
Scope: runtime lifecycle store plus telemetry metrics.
|
| 98 |
+
|
| 99 |
+
Candidate files:
|
| 100 |
+
|
| 101 |
+
- `src/ctx/adapters/generic/runtime_lifecycle.py`
|
| 102 |
+
- `src/ctx/adapters/generic/ctx_core_tools.py`
|
| 103 |
+
- `src/ctx/telemetry/__init__.py`
|
| 104 |
+
- `src/tests/test_harness_ctx_core.py`
|
| 105 |
+
- `src/tests/test_enterprise_telemetry.py`
|
| 106 |
+
|
| 107 |
+
Work:
|
| 108 |
+
|
| 109 |
+
- Add selection/activation metadata to lifecycle records.
|
| 110 |
+
- Add token usage record support with exact/estimated/unavailable measurement.
|
| 111 |
+
- Preserve local runtime history even when telemetry export is disabled; do not make required activation history depend on exporters.
|
| 112 |
+
- Emit OTel-style counters/histograms for usage when metrics are enabled.
|
| 113 |
+
- Reuse existing sanitization and safe session/entity validation.
|
| 114 |
+
|
| 115 |
+
Validation:
|
| 116 |
+
|
| 117 |
+
```sh
|
| 118 |
+
/tmp/ctx-verify-venv/bin/python -m pytest -q -p no:cacheprovider src/tests/test_harness_ctx_core.py src/tests/test_enterprise_telemetry.py
|
| 119 |
+
/tmp/ctx-verify-venv/bin/python -m ruff check src/ctx/adapters/generic/runtime_lifecycle.py src/ctx/adapters/generic/ctx_core_tools.py src/ctx/telemetry/__init__.py
|
| 120 |
+
/tmp/ctx-verify-venv/bin/python -m mypy src
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
## Phase 4: CLI And Loop Runtime Integration
|
| 124 |
+
|
| 125 |
+
Scope: user-facing CLI and ctx run attribution where exact usage exists.
|
| 126 |
+
|
| 127 |
+
Candidate files:
|
| 128 |
+
|
| 129 |
+
- `src/ctx/cli/recommend.py`
|
| 130 |
+
- `src/ctx/cli/run.py`
|
| 131 |
+
- `src/ctx/adapters/generic/state.py`
|
| 132 |
+
- `src/tests/test_recommend_cli.py`
|
| 133 |
+
- `src/tests/test_harness_cli_run.py`
|
| 134 |
+
|
| 135 |
+
Work:
|
| 136 |
+
|
| 137 |
+
- Add explicit selection mode to `ctx-recommend`.
|
| 138 |
+
- Add JSON contract for selected/rejected/related recommendations.
|
| 139 |
+
- Attribute exact usage to activated ctx entities only when the host/provider or session log provides unambiguous per-tool correlation.
|
| 140 |
+
- Keep aggregate run usage as session-level history and label unavailable per-tool attribution honestly.
|
| 141 |
+
|
| 142 |
+
Validation:
|
| 143 |
+
|
| 144 |
+
```sh
|
| 145 |
+
/tmp/ctx-verify-venv/bin/python -m pytest -q -p no:cacheprovider src/tests/test_recommend_cli.py src/tests/test_harness_cli_run.py src/tests/test_harness_state.py
|
| 146 |
+
/tmp/ctx-verify-venv/bin/python -m ruff check src/ctx/cli/recommend.py src/ctx/cli/run.py src/ctx/adapters/generic/state.py
|
| 147 |
+
/tmp/ctx-verify-venv/bin/python -m mypy src
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
## Phase 5: Dashboard And API Views
|
| 151 |
+
|
| 152 |
+
Scope: monitor pages/services/API only.
|
| 153 |
+
|
| 154 |
+
Candidate files:
|
| 155 |
+
|
| 156 |
+
- `src/ctx/monitor/services/runtime.py`
|
| 157 |
+
- `src/ctx/monitor/pages/activity.py`
|
| 158 |
+
- `src/ctx/monitor/pages/ops.py`
|
| 159 |
+
- `src/ctx/monitor/api/readonly.py`
|
| 160 |
+
- `src/ctx/monitor/routes.py`
|
| 161 |
+
- `src/tests/test_ctx_monitor.py`
|
| 162 |
+
- `src/tests/test_monitor_testing_api.py`
|
| 163 |
+
- `src/tests/test_dashboard_smoke.py`
|
| 164 |
+
|
| 165 |
+
Work:
|
| 166 |
+
|
| 167 |
+
- Add aggregation service for per-tool usage history.
|
| 168 |
+
- Add JSON API for usage KPIs/history.
|
| 169 |
+
- Add dashboard view or embed in Runtime/KPIs with populated, empty, unavailable, and error states.
|
| 170 |
+
- Aggregate token metadata only; never render raw transcripts, raw tool arguments, raw tool outputs, or raw recommendation queries.
|
| 171 |
+
- Keep monitor UI consistent with existing cards/tables/native controls.
|
| 172 |
+
|
| 173 |
+
Validation:
|
| 174 |
+
|
| 175 |
+
```sh
|
| 176 |
+
/tmp/ctx-verify-venv/bin/python -m pytest -q -p no:cacheprovider src/tests/test_ctx_monitor.py src/tests/test_monitor_testing_api.py src/tests/test_dashboard_smoke.py
|
| 177 |
+
/tmp/ctx-verify-venv/bin/python -m ruff check src/ctx/monitor/services/runtime.py src/ctx/monitor/pages/activity.py src/ctx/monitor/pages/ops.py src/ctx/monitor/api/readonly.py src/ctx/monitor/routes.py
|
| 178 |
+
/tmp/ctx-verify-venv/bin/python -m mypy src
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
## Phase 6: Docs And Tracker Sync
|
| 182 |
+
|
| 183 |
+
Scope: docs and QA status.
|
| 184 |
+
|
| 185 |
+
Candidate files:
|
| 186 |
+
|
| 187 |
+
- `docs/dashboard.md`
|
| 188 |
+
- `docs/telemetry.md`
|
| 189 |
+
- `docs/harness/attaching-to-hosts.md`
|
| 190 |
+
- `docs/harness/loopflow-adapter-demo.md`
|
| 191 |
+
- `qa/tool-selection-token-history/tracker.csv`
|
| 192 |
+
- `qa/feature_status.csv`
|
| 193 |
+
|
| 194 |
+
Validation:
|
| 195 |
+
|
| 196 |
+
```sh
|
| 197 |
+
/tmp/ctx-verify-venv/bin/python -m pytest -q -p no:cacheprovider src/tests/test_feature_user_story_tracker.py src/tests/test_dashboard_user_story_tracker.py
|
| 198 |
+
/tmp/ctx-verify-venv/bin/python -m mkdocs build --strict
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
## Phase 7: Final Quality Gate
|
| 202 |
+
|
| 203 |
+
Validation:
|
| 204 |
+
|
| 205 |
+
```sh
|
| 206 |
+
/tmp/ctx-verify-venv/bin/python -m ruff format --check src hooks scripts
|
| 207 |
+
/tmp/ctx-verify-venv/bin/python -m ruff check src hooks scripts
|
| 208 |
+
/tmp/ctx-verify-venv/bin/python -m mypy src
|
| 209 |
+
/tmp/ctx-verify-venv/bin/python -m pytest -q
|
| 210 |
+
/tmp/ctx-verify-venv/bin/python scripts/ci_preflight.py --profile pr
|
| 211 |
+
no-mistakes axi run --intent "Implement interactive tool selection, related-tool recommendations, activation tracking, and per-tool token usage history across ctx API, CLI, MCP/core toolbox, LoopFlow adapter, and dashboard while preserving enterprise privacy and existing recommendation compatibility."
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
Success criteria:
|
| 215 |
+
|
| 216 |
+
- All tracker rows are `Pass` or explicitly `Blocked`.
|
| 217 |
+
- Focused tests pass for each milestone.
|
| 218 |
+
- Full pytest and CI preflight pass.
|
| 219 |
+
- no-mistakes reaches `checks-passed` or `passed`.
|
| 220 |
+
|
| 221 |
+
## CTO Parallelization Rules
|
| 222 |
+
|
| 223 |
+
- Keep planning and orchestration in the main branch workspace.
|
| 224 |
+
- Use read-only explorer agents for module maps.
|
| 225 |
+
- Use worker agents only after Phase 0 when write sets are disjoint.
|
| 226 |
+
- Do not let workers edit the same file in parallel.
|
| 227 |
+
- Commit after each milestone that passes its validation.
|
qa/tool-selection-token-history/SPEC.md
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tool Selection And Token History Spec
|
| 2 |
+
|
| 3 |
+
Date: 2026-07-02
|
| 4 |
+
|
| 5 |
+
## Objective
|
| 6 |
+
|
| 7 |
+
Add interactive recommendation selection, related-tool recommendations, activation tracking, and per-tool token usage history across the Python API, MCP/core toolbox, CLI, LoopFlow/agent-loop adapter, and local monitor dashboard.
|
| 8 |
+
|
| 9 |
+
The target user is a programmer or AI engineer who receives ctx recommendations for skills, agents, MCP servers, and harnesses. They must be able to understand the recommendations quickly, choose what to activate, get related suggestions after partial selection, and inspect token KPIs over time for selected/activated tools.
|
| 10 |
+
|
| 11 |
+
## Existing Context Suggestion Flow
|
| 12 |
+
|
| 13 |
+
Observed entry points:
|
| 14 |
+
|
| 15 |
+
- `src/ctx/api.py` exposes `recommend_bundle(query, top_k=5)` and `recommend_related(selected, rejected=None, max_hops=2, top_n=5)` as the public Python API. They wrap the shared ctx-core tools and return lists of recommendation dicts.
|
| 16 |
+
- `src/ctx/adapters/generic/ctx_core_tools.py` exposes `ctx__recommend_bundle`, `ctx__recommend_related`, `ctx__graph_query`, `ctx__wiki_search`, `ctx__wiki_get`, and runtime lifecycle/session tools through `CtxCoreToolbox`.
|
| 17 |
+
- `src/ctx/core/resolve/recommendations.py` provides `recommend_by_tags(...)`, which ranks graph entities by slug-token, tag overlap, graph degree, explicit entity match, optional semantic query score, and external catalog fallback.
|
| 18 |
+
- `src/ctx/cli/recommend.py` provides `ctx-recommend`; text mode renders enriched rows plus related rows when `--selected` is passed, and `--json` emits `{"query": ..., "results": [...]}` with a `selection` object when selected or rejected IDs are supplied.
|
| 19 |
+
- `src/ctx/mcp_server/server.py` exposes the shared toolbox through MCP `tools/list` and `tools/call`.
|
| 20 |
+
- `src/ctx/adapters/loopflow.py` emits permission-gated LoopFlow/agent-loop adapter payloads containing grouped `skills`, `agents`, `mcps`, `harnesses`, and ctx MCP metadata.
|
| 21 |
+
|
| 22 |
+
Current recommendation result shape is list-oriented. Rows may include `id`, `name`, `type`, `score`, `normalized_score`, `matching_tags`, `tldr`, `reason`, `selected`, `selection_state`, `external`, `source_catalog`, `status`, `source`, `skill_id`, `installs`, `detail_url`, `install_command`, `category`, `invoke_command`, and `security_review`.
|
| 23 |
+
|
| 24 |
+
## Existing Tool Model
|
| 25 |
+
|
| 26 |
+
Supported recommendable entity types are shared through `ctx.core.entity_types.RECOMMENDABLE_ENTITY_TYPES`; current flows use:
|
| 27 |
+
|
| 28 |
+
- `skill`
|
| 29 |
+
- `agent`
|
| 30 |
+
- `mcp-server`
|
| 31 |
+
- `harness`
|
| 32 |
+
|
| 33 |
+
The current `ctx__recommend_bundle` core tool recommends `skill`, `agent`, and `mcp-server`. Harnesses are recommended as companion rows when model/provider context exists, and LoopFlow can request harness recommendations when `own_llm`, `model_provider`, or `model` is supplied.
|
| 34 |
+
|
| 35 |
+
## Existing Knowledge Graph Model
|
| 36 |
+
|
| 37 |
+
The recommendation graph is loaded by `CtxCoreToolbox._ensure_graph()` from the llm-wiki graph artifact. `recommend_by_tags(...)` uses:
|
| 38 |
+
|
| 39 |
+
- query-derived tags from `query_to_tags`
|
| 40 |
+
- node labels and slug tokens
|
| 41 |
+
- node tags and matching tags
|
| 42 |
+
- graph degree
|
| 43 |
+
- optional semantic-cache query scoring
|
| 44 |
+
- status and `never_load` filtering
|
| 45 |
+
- external skill catalog fallback when available
|
| 46 |
+
|
| 47 |
+
Related-tool recommendations should reuse this graph. For selected rows, the minimal stable path is to call or share `ctx__graph_query` / graph-neighbor logic using selected entity names as seeds, then filter out selected and rejected identities.
|
| 48 |
+
|
| 49 |
+
## Existing Token Accounting Model
|
| 50 |
+
|
| 51 |
+
Observed exact usage exists at the generic harness level:
|
| 52 |
+
|
| 53 |
+
- `src/ctx/adapters/generic/providers/base.py` defines `Usage(input_tokens, output_tokens, cost_usd)`.
|
| 54 |
+
- `src/ctx/adapters/generic/loop.py` sums `CompletionResponse.usage` into `LoopResult.usage`.
|
| 55 |
+
- `src/ctx/cli/run.py` emits aggregate run usage in JSON and stderr output.
|
| 56 |
+
- `src/ctx/adapters/generic/state.py` persists per-model-response usage and reconstructs session totals on resume.
|
| 57 |
+
|
| 58 |
+
Observed lifecycle/telemetry persistence:
|
| 59 |
+
|
| 60 |
+
- `src/ctx/adapters/generic/runtime_lifecycle.py` persists host-neutral lifecycle events under `~/.ctx/runtime/events.jsonl` or `CTX_RUNTIME_LIFECYCLE_DIR/events.jsonl`.
|
| 61 |
+
- `RuntimeLifecycleStore` already records `load_entity`, `mark_entity_used`, `unload_entity`, `record_validation`, `record_escalation`, and `session_state`.
|
| 62 |
+
- `src/ctx/telemetry/__init__.py` provides privacy-safe local event and metric spools, `record_event`, `record_counter`, `record_histogram`, `read_events`, and `read_metrics`.
|
| 63 |
+
- Legacy `src/skill_telemetry.py` records load/unload events for skills, agents, and MCP servers under `~/.claude/skill-events.jsonl`.
|
| 64 |
+
|
| 65 |
+
Implemented pieces and remaining caveats:
|
| 66 |
+
|
| 67 |
+
- Recommendation rows expose the shared selection-state contract.
|
| 68 |
+
- User-selected vs system-selected activation flags persist in the runtime lifecycle ledger.
|
| 69 |
+
- Per-tool token attribution is stored when the host can provide exact, estimated, or unavailable evidence.
|
| 70 |
+
- Dashboard/API aggregation of per-tool token history is implemented through the Runtime page and `/api/runtime.json`; final-loop validation covers the browser/API privacy contract.
|
| 71 |
+
- Exact token counts are available for ctx generic harness runs, but not necessarily for arbitrary external MCP/host tool invocations. Unavailable or estimated states must be explicit.
|
| 72 |
+
- Exact token counts are currently provider/session-level, not per-tool. A per-tool usage row may be marked `exact` only when the host/provider supplies usage for that specific tool or when the model/tool boundary is unambiguous and recorded with correlation evidence. Session totals must not be split across tools as if they were exact.
|
| 73 |
+
|
| 74 |
+
## Required UX Behavior
|
| 75 |
+
|
| 76 |
+
Dashboard and any browser UI must:
|
| 77 |
+
|
| 78 |
+
- Show a selectable control for each recommendation.
|
| 79 |
+
- Display a short TL;DR description and relevance reason for each row.
|
| 80 |
+
- Make selected, rejected, and suggested-related states clear.
|
| 81 |
+
- Support select all, select none, and subset selection where the surface allows selection.
|
| 82 |
+
- Show related recommendations after partial selection.
|
| 83 |
+
- Show per-tool usage KPIs and history with empty, unavailable, and error states.
|
| 84 |
+
- Reuse existing monitor page, table, card, and checkbox styling rather than introducing a new frontend framework.
|
| 85 |
+
|
| 86 |
+
## Required CLI Behavior
|
| 87 |
+
|
| 88 |
+
CLI must:
|
| 89 |
+
|
| 90 |
+
- Keep existing `ctx-recommend` behavior compatible by default.
|
| 91 |
+
- Add an explicit selection mode for users who want to choose recommendations.
|
| 92 |
+
- Offer a non-interactive JSON mode exposing the same selection and related-recommendation semantics.
|
| 93 |
+
- Show TL;DR descriptions and relevance reasons.
|
| 94 |
+
- Record activation/selection only when the user confirms or when a caller explicitly passes selected identities.
|
| 95 |
+
- Clearly label session usage as session-scoped and per-tool attribution as exact, estimated, or unavailable when usage evidence is recorded.
|
| 96 |
+
|
| 97 |
+
## Required API And Backend Behavior
|
| 98 |
+
|
| 99 |
+
Shared backend behavior must:
|
| 100 |
+
|
| 101 |
+
- Add a canonical recommendation row enrichment with `id`, `name`, `type`, `tldr`, `reason`, `selected`, and `selection_state` where appropriate.
|
| 102 |
+
- Add a related recommendation operation that accepts selected and rejected identities and returns filtered related rows.
|
| 103 |
+
- Add activation tracking that records entity id/name/type, time, privacy-safe session/user/system context, selected-vs-system source, and optional source context.
|
| 104 |
+
- Add token usage recording that accepts exact usage when available and unavailable/estimated metadata otherwise.
|
| 105 |
+
- Keep run/session token totals distinct from per-tool token rows when attribution is unavailable.
|
| 106 |
+
- Preserve old `recommend_bundle` list return semantics for Python callers unless a new explicit API asks for enriched state.
|
| 107 |
+
|
| 108 |
+
## Required Dashboard Behavior
|
| 109 |
+
|
| 110 |
+
Dashboard must:
|
| 111 |
+
|
| 112 |
+
- Surface selectable recommendation rows or a dedicated recommendation-selection view.
|
| 113 |
+
- Show per-tool token totals and recent usage.
|
| 114 |
+
- Show history grouped by tool and user/session/system context where available.
|
| 115 |
+
- Distinguish user-selected and system-selected activations.
|
| 116 |
+
- Reuse `/kpi`, `/runtime`, `/sessions`, or a nearby monitor page pattern instead of creating a separate app.
|
| 117 |
+
- Expose JSON API endpoints for dashboard data.
|
| 118 |
+
|
| 119 |
+
## Data Model
|
| 120 |
+
|
| 121 |
+
Preferred persisted record shape for activation and usage:
|
| 122 |
+
|
| 123 |
+
- `action`: `load_requested`, `used`, `unload_requested`, `validation`, `escalation`, `session_end`, or compatible lifecycle action.
|
| 124 |
+
- `session_id`: safe host-generated id; use existing validation and hashed telemetry identifiers.
|
| 125 |
+
- `entity_type`: one of `skill`, `agent`, `mcp-server`, `harness`.
|
| 126 |
+
- `slug` or `name`: safe entity identity.
|
| 127 |
+
- `selection_source`: `user`, `system`, `host`, or `unknown`.
|
| 128 |
+
- `selected`: boolean where relevant.
|
| 129 |
+
- `source_context`: bounded sanitized object.
|
| 130 |
+
- `token_usage`: object with `input_tokens`, `output_tokens`, `total_tokens`, optional `cost_usd`, `provider`, `model`, `attribution`: `exact`, `estimated`, or `unavailable`, and optional `attribution_reason`.
|
| 131 |
+
- `correlation_id`: optional safe id linking model responses, tool calls, and lifecycle records when attribution is exact.
|
| 132 |
+
- `created_at` and `created_at_epoch`.
|
| 133 |
+
|
| 134 |
+
Implementation decision: extend `RuntimeLifecycleStore` with selection and token usage fields because it already owns session/entity history.
|
| 135 |
+
|
| 136 |
+
Persistence note: `RuntimeLifecycleStore` keeps local lifecycle history independent of telemetry/export disablement. Enterprise privacy keeps exporters opt-in, while local runtime history remains available for dashboard/API aggregation.
|
| 137 |
+
|
| 138 |
+
## Security And Privacy
|
| 139 |
+
|
| 140 |
+
- Telemetry must never write raw prompts, raw paths, tool arguments, stdout, stderr, secrets, or tokens.
|
| 141 |
+
- Session IDs may be stored in the runtime lifecycle ledger because the existing store already validates bounded safe IDs; exported telemetry should continue to use hashed session IDs.
|
| 142 |
+
- Payloads must pass existing telemetry/lifecycle sanitizers.
|
| 143 |
+
- Local-only defaults remain unchanged; exporters may carry only sanitized OTel-compatible metrics/events.
|
| 144 |
+
- Token history must not fabricate exact values. Use `unavailable` when the host cannot provide usage.
|
| 145 |
+
- Dashboard/API token history must aggregate usage metadata only. It must not dump raw session transcripts, raw tool arguments, raw tool results, or raw recommendation queries.
|
| 146 |
+
|
| 147 |
+
## Accessibility
|
| 148 |
+
|
| 149 |
+
- Browser controls must use native checkbox/select/button controls where possible.
|
| 150 |
+
- Dynamic related-recommendation and dashboard states must have text equivalents.
|
| 151 |
+
- Tables and forms must preserve existing monitor layout semantics.
|
| 152 |
+
- Keyboard-only operation must work for CLI and dashboard forms.
|
| 153 |
+
|
| 154 |
+
## Acceptance Criteria
|
| 155 |
+
|
| 156 |
+
- US-001: UI/CLI/API expose selectable recommendation state for skills, agents, MCP servers, and harnesses where those are recommended.
|
| 157 |
+
- US-002: Each recommendation exposes a short TL;DR description and relevance reason.
|
| 158 |
+
- US-003: Selecting fewer than all recommendations can return filtered related recommendations that exclude selected and rejected tools.
|
| 159 |
+
- US-004: Activations persist with entity identity, timestamp, privacy-safe session context, source, and source context.
|
| 160 |
+
- US-005: Per-tool token usage is recorded as exact, estimated, or unavailable and exposed through API/dashboard.
|
| 161 |
+
- US-006: Historical usage persists across sessions and can be aggregated by tool.
|
| 162 |
+
- US-007: Dashboard renders token KPIs/history with empty, unavailable, error, and populated states.
|
| 163 |
+
- US-008: API, CLI, MCP/core toolbox, LoopFlow/agent-loop adapter, and dashboard share semantics.
|
| 164 |
+
- Existing recommendation, graph, CLI, MCP, LoopFlow, telemetry, and dashboard tests continue to pass.
|
| 165 |
+
- Final no-mistakes gate passes after implementation is committed.
|
| 166 |
+
|
| 167 |
+
## Non-Goals
|
| 168 |
+
|
| 169 |
+
- Do not introduce a new web framework or dashboard app.
|
| 170 |
+
- Do not change the default local-only privacy posture.
|
| 171 |
+
- Do not require paid APIs or external observability backends for local functionality.
|
| 172 |
+
- Do not rewrite graph ranking.
|
| 173 |
+
- Do not fabricate exact token usage for hosts that do not expose it.
|
| 174 |
+
- Do not break existing `recommend_bundle` list-return compatibility.
|
qa/tool-selection-token-history/tracker.csv
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ID,Workstream,Feature,User Story,Expected Behavior,Files/Modules,Test Command,Status,Severity,Attempts,Last Checked,Notes
|
| 2 |
+
US-001,API/CLI/UI,Tool recommendation selection,"As a programmer or AI engineer, I can select which recommended tools to use.","UI/CLI/API expose selectable state for every suggested skill, agent, MCP server, and harness where supported; select all, none, and subset flows are explicit.","src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/cli/recommend.py; src/ctx/monitor pages","pytest src/tests/test_recommendations.py src/tests/test_recommend_cli.py src/tests/test_ctx_monitor.py -q",Retested Pass,High,4,2026-07-02,"Phase 1 adds API/core recommendation id, selected=false, and selection_state=suggested; Phase 4A adds CLI --selected/--rejected IDs and related-selection flow; Phase 5B adds dashboard /recommend controls for select all, select none, subset selection, selected IDs, and rejected IDs; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 3 |
+
US-002,API/CLI/UI,TLDR descriptions,"As a user, I can read a concise TLDR for each suggested tool before selecting it.","Each recommendation has a short description plus relevance reason; fallback uses safe existing metadata when description is absent.","src/ctx/core/resolve/recommendations.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/cli/recommend.py","pytest src/tests/test_recommendations.py src/tests/test_recommendation_surfaces_golden.py -q",Retested Pass,High,4,2026-07-02,"Phase 1 adds API/core tldr and reason fallbacks from existing row metadata; Phase 4A renders CLI tldr/reason; Phase 5B renders TLDR and reason text on the dashboard /recommend page; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 4 |
+
US-003,Knowledge Graph,Related recommendations after partial selection,"As a user, if I select only some suggestions, ctx proposes related tools.","Related rows are generated from graph/category/tag neighbors, exclude selected/rejected/unavailable/deprecated rows, and include reason text.","src/ctx/core/resolve/recommendations.py; src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py","pytest src/tests/test_recommendations.py src/tests/test_harness_recommendations.py -q",Retested Pass,High,6,2026-07-02,"Phase 2A adds ctx__recommend_related; Phase 2B1 adds public ctx.recommend_related with redacted selection telemetry; Phase 2B2 adds LoopFlow/agent-loop related_recommendations; Phase 4A adds CLI related recommendations; Phase 5B adds dashboard related suggestions for partial selections; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 5 |
+
US-004,Runtime Lifecycle,Tool activation tracking,"As a user, selected tool activation is recorded with session/system context.","Activation records include entity id/name/type, timestamp, privacy-safe session context, user-selected vs system-selected source, and source context.","src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/adapters/generic/ctx_core_tools.py","pytest src/tests/test_harness_ctx_core.py -q",Retested Pass,Critical,2,2026-07-02,"Phase 3A adds selected, selection_source, and sanitized source_context to load_entity/session_state and keeps local lifecycle history when telemetry is disabled; Phase 7 passed focused harness-core retest (70 passed), full pytest (4431 passed, 2 skipped), and ci_preflight --profile pr (19/19)."
|
| 6 |
+
US-005,Telemetry,Token usage KPI,"As a user, I can see token usage per selected and activated tool.","Exact input/output/total tokens are recorded only with per-tool correlation; session totals stay session-level; estimated/unavailable values are labeled honestly with reason; API/dashboard expose the data.","src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/telemetry/__init__.py; src/ctx/cli/run.py","pytest src/tests/test_enterprise_telemetry.py src/tests/test_harness_cli_run.py -q",Retested Pass,Critical,4,2026-07-02,"Phase 3B adds token_usage to mark_entity_used with exact/estimated/unavailable attribution and emits OTel-style usage counters/histograms when metrics are enabled; Phase 4B labels ctx run usage as session-scoped/unavailable for per-tool attribution; Phase 5A exposes token totals/attribution on /runtime and /api/runtime.json; Phase 7 telemetry enterprise gate passed (67 passed, 65 deselected)."
|
| 7 |
+
US-006,Persistence,Historical usage,"As a user, I can view historical token usage per tool over time.","Usage history persists across sessions and can be aggregated by tool, type, session, and source.","src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/monitor/services/runtime.py","pytest src/tests/test_harness_ctx_core.py src/tests/test_ctx_monitor.py -q",Retested Pass,High,3,2026-07-02,"Phase 3B persists per-entity token_usage summaries in runtime session_state; Phase 5A aggregates lifecycle history by selection source, active loads, token totals, attribution, and recent tool usage for dashboard/API consumers; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 8 |
+
US-007,Dashboard,Dashboard support,"As a user/admin, I can see tool-selection and token-history KPIs in the dashboard.","Dashboard shows totals, recent usage, history, user-vs-system selected source, and empty/error/unavailable states.","src/ctx/monitor/services/runtime.py; src/ctx/monitor/pages/activity.py; src/ctx/monitor/pages/ops.py; src/ctx/monitor/api/readonly.py","pytest src/tests/test_ctx_monitor.py src/tests/test_monitor_testing_api.py src/tests/test_dashboard_smoke.py -q",Retested Pass,High,3,2026-07-02,"Phase 5A extends the existing Runtime page/API with tool-selection totals, source split, token totals, attribution counts, and recent usage; Phase 5B adds dashboard recommendation selection and related-suggestion controls; Phase 7 browser monitor security gate passed (11 passed) and ci_preflight --profile pr passed 19/19."
|
| 9 |
+
US-008,Parity,API/CLI/UI parity,"As a user, behavior is consistent across API, CLI, MCP/core toolbox, LoopFlow, and dashboard.","Shared semantics are reused; differences are documented only where necessary.","src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/mcp_server/server.py; src/ctx/adapters/loopflow.py; docs","pytest src/tests/test_public_api.py src/tests/test_mcp_server.py src/tests/test_loopflow_adapter.py -q",Retested Pass,High,8,2026-07-02,"Phase 1 preserves recommend_bundle; Phase 2 adds MCP/core, Python API, and LoopFlow related recommendations; Phase 4A adds CLI parity for IDs, TLDR, reasons, selected/rejected inputs, and related rows; Phase 5A adds runtime dashboard/API parity for persisted selection and token usage; Phase 5B adds dashboard recommendation parity; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 10 |
+
QA-001,QA,Regression suite,"As a maintainer, I can ship without breaking existing recommendation/telemetry/dashboard behavior.","Focused milestone tests, ruff, mypy, full pytest, ci_preflight, and no-mistakes pass.","src/tests; scripts/ci_preflight.py; no-mistakes gate","python scripts/ci_preflight.py --profile pr; no-mistakes axi run --intent ...",Needs Validation,Critical,11,2026-07-02,"Phase 2 slices passed; Phase 3A passed: 142 passed; Phase 3B usage persistence/metrics slice passed: 70 passed plus ruff, format, and mypy; Phase 4A CLI selection slice passed: 6 passed plus ruff, format, and mypy; Phase 4B runtime attribution slice passed: 72 passed plus ruff, format, and mypy; Phase 5A dashboard slice passed: 3 focused tests, 8 runtime monitor tests, 5 dashboard smoke/API tests plus ruff, format, and mypy; Phase 5B dashboard recommendation slice passed: 4 focused tests, full monitor 180 passed, ruff, format, and mypy; Phase 7 passed ruff format/check, mypy, full pytest (4431 passed, 2 skipped), ci_preflight --profile pr (19/19), stats check, docs build, and public tracker tests; no-mistakes remains deferred until after the canonical feature loop."
|
src/ctx/__init__.py
CHANGED
|
@@ -49,6 +49,7 @@ from ctx.api import (
|
|
| 49 |
graph_query,
|
| 50 |
list_all_entities,
|
| 51 |
recommend_bundle,
|
|
|
|
| 52 |
wiki_get,
|
| 53 |
wiki_search,
|
| 54 |
)
|
|
@@ -60,6 +61,7 @@ __all__ = [
|
|
| 60 |
"graph_query",
|
| 61 |
"list_all_entities",
|
| 62 |
"recommend_bundle",
|
|
|
|
| 63 |
"wiki_get",
|
| 64 |
"wiki_search",
|
| 65 |
"__version__",
|
|
|
|
| 49 |
graph_query,
|
| 50 |
list_all_entities,
|
| 51 |
recommend_bundle,
|
| 52 |
+
recommend_related,
|
| 53 |
wiki_get,
|
| 54 |
wiki_search,
|
| 55 |
)
|
|
|
|
| 61 |
"graph_query",
|
| 62 |
"list_all_entities",
|
| 63 |
"recommend_bundle",
|
| 64 |
+
"recommend_related",
|
| 65 |
"wiki_get",
|
| 66 |
"wiki_search",
|
| 67 |
"__version__",
|
src/ctx/adapters/generic/ctx_core_tools.py
CHANGED
|
@@ -2,9 +2,9 @@
|
|
| 2 |
|
| 3 |
This is the integration point that makes the alive skill system
|
| 4 |
available to ANY LLM running through the generic harness. The
|
| 5 |
-
toolbox wraps
|
| 6 |
-
|
| 7 |
-
|
| 8 |
|
| 9 |
Tools exposed (all namespaced under the ``ctx__`` prefix, matching
|
| 10 |
the MCP router's separator convention so the harness can route to
|
|
@@ -13,7 +13,12 @@ MCP servers):
|
|
| 13 |
|
| 14 |
ctx__recommend_bundle(query, top_k=5)
|
| 15 |
Free-text → top-K cross-type bundle (skill + agent + MCP).
|
| 16 |
-
Tokenizes the query into tags, walks the graph
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
ctx__graph_query(seeds, max_hops=2, top_n=10)
|
| 19 |
Direct graph walk from a list of seed entity names.
|
|
@@ -28,9 +33,11 @@ MCP servers):
|
|
| 28 |
Fetch a single entity page by slug — returns its full
|
| 29 |
frontmatter + body for the model to reason about.
|
| 30 |
|
| 31 |
-
Load/unload tools are explicit lifecycle records, not filesystem
|
| 32 |
auto-installs. The host remains responsible for asking the user and
|
| 33 |
-
deciding how to place selected entities into context.
|
|
|
|
|
|
|
| 34 |
|
| 35 |
Plan 001 Phase H6.
|
| 36 |
"""
|
|
@@ -65,6 +72,23 @@ _logger = logging.getLogger(__name__)
|
|
| 65 |
# anything else falls back to its normal tool_executor.
|
| 66 |
_NAMESPACE = f"ctx{TOOL_SEPARATOR}"
|
| 67 |
_FILE_SIGNATURE_SAMPLE_BYTES = 64 * 1024
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
SUPPORTED_RESPONSE_FORMATS = ("json", "gcf")
|
| 69 |
_RESPONSE_FORMAT_PROPERTY = {
|
| 70 |
"type": "string",
|
|
@@ -156,6 +180,11 @@ def _safe_tool_payload(local_name: str, args: Mapping[str, Any]) -> dict[str, An
|
|
| 156 |
if isinstance(seeds, (list, tuple)):
|
| 157 |
payload["ctx.seeds.count"] = len(seeds)
|
| 158 |
payload["ctx.seeds.hash"] = _hash_json_value(list(seeds))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
slug = args.get("slug")
|
| 160 |
if isinstance(slug, str):
|
| 161 |
payload["ctx.slug.hash"] = hash_identifier(slug)
|
|
@@ -230,6 +259,7 @@ def _record_core_tool_event(
|
|
| 230 |
|
| 231 |
_CORE_EVENT_NAMES = {
|
| 232 |
"recommend_bundle": "ctx.core.recommend_bundle",
|
|
|
|
| 233 |
"graph_query": "ctx.core.graph_query",
|
| 234 |
"wiki_search": "ctx.core.wiki_search",
|
| 235 |
"wiki_get": "ctx.core.wiki_get",
|
|
@@ -374,6 +404,48 @@ class CtxCoreToolbox:
|
|
| 374 |
"required": ["seeds"],
|
| 375 |
},
|
| 376 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
ToolDefinition(
|
| 378 |
name=f"{_NAMESPACE}wiki_search",
|
| 379 |
description=(
|
|
@@ -452,6 +524,8 @@ class CtxCoreToolbox:
|
|
| 452 |
try:
|
| 453 |
if local_name == "recommend_bundle":
|
| 454 |
result = self._dispatch_recommend(args)
|
|
|
|
|
|
|
| 455 |
elif local_name == "graph_query":
|
| 456 |
result = self._dispatch_graph_query(args)
|
| 457 |
elif local_name == "wiki_search":
|
|
@@ -555,25 +629,27 @@ class CtxCoreToolbox:
|
|
| 555 |
semantic_cache_dir=semantic_cache_dir,
|
| 556 |
)
|
| 557 |
results = [
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
|
|
|
|
|
|
| 577 |
for r in raw
|
| 578 |
]
|
| 579 |
model_provider = _optional_str(args.get("model_provider"))
|
|
@@ -598,6 +674,79 @@ class CtxCoreToolbox:
|
|
| 598 |
_response_format_from_args(args),
|
| 599 |
)
|
| 600 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 601 |
def _dispatch_graph_query(self, args: dict[str, Any]) -> str:
|
| 602 |
seeds_raw = args.get("seeds") or []
|
| 603 |
if not isinstance(seeds_raw, list) or not seeds_raw:
|
|
@@ -753,6 +902,9 @@ class CtxCoreToolbox:
|
|
| 753 |
security_scan=(
|
| 754 |
_dict_arg(args.get("security_scan")) if "security_scan" in args else None
|
| 755 |
),
|
|
|
|
|
|
|
|
|
|
| 756 |
)
|
| 757 |
elif name == "mark_entity_used":
|
| 758 |
result = self._lifecycle.mark_entity_used(
|
|
@@ -760,6 +912,9 @@ class CtxCoreToolbox:
|
|
| 760 |
entity_type=str(args.get("entity_type") or ""),
|
| 761 |
slug=str(args.get("slug") or ""),
|
| 762 |
evidence=str(args.get("evidence") or "") or None,
|
|
|
|
|
|
|
|
|
|
| 763 |
)
|
| 764 |
elif name == "unload_entity":
|
| 765 |
result = self._lifecycle.unload_entity(
|
|
@@ -1086,6 +1241,244 @@ def _optional_str(raw: Any) -> str | None:
|
|
| 1086 |
return value or None
|
| 1087 |
|
| 1088 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1089 |
def _recommend_companion_harnesses(
|
| 1090 |
query: str,
|
| 1091 |
*,
|
|
@@ -1171,6 +1564,28 @@ def _lifecycle_tool_definitions(
|
|
| 1171 |
"entity_type": entity_type,
|
| 1172 |
"slug": slug,
|
| 1173 |
"reason": {"type": "string"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1174 |
"security_scan": {
|
| 1175 |
"type": "object",
|
| 1176 |
"description": (
|
|
@@ -1194,6 +1609,28 @@ def _lifecycle_tool_definitions(
|
|
| 1194 |
"entity_type": entity_type,
|
| 1195 |
"slug": slug,
|
| 1196 |
"evidence": {"type": "string"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1197 |
},
|
| 1198 |
"required": ["session_id", "entity_type", "slug"],
|
| 1199 |
},
|
|
@@ -1333,6 +1770,10 @@ def _float_arg(raw: Any) -> float:
|
|
| 1333 |
return 0.0
|
| 1334 |
|
| 1335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1336 |
def _excerpt(body: str, max_chars: int) -> str:
|
| 1337 |
"""Short preview of a page body: first non-empty line, trimmed.
|
| 1338 |
|
|
|
|
| 2 |
|
| 3 |
This is the integration point that makes the alive skill system
|
| 4 |
available to ANY LLM running through the generic harness. The
|
| 5 |
+
toolbox wraps ctx-core recommendation, graph/wiki, and runtime
|
| 6 |
+
lifecycle surfaces as ``ToolDefinition``/dispatcher pairs that slot
|
| 7 |
+
into ``run_loop``.
|
| 8 |
|
| 9 |
Tools exposed (all namespaced under the ``ctx__`` prefix, matching
|
| 10 |
the MCP router's separator convention so the harness can route to
|
|
|
|
| 13 |
|
| 14 |
ctx__recommend_bundle(query, top_k=5)
|
| 15 |
Free-text → top-K cross-type bundle (skill + agent + MCP).
|
| 16 |
+
Tokenizes the query into tags, walks the graph, and returns
|
| 17 |
+
enriched rows with id, tldr, reason, and selection metadata.
|
| 18 |
+
|
| 19 |
+
ctx__recommend_related(selected, rejected=None, max_hops=2, top_n=5)
|
| 20 |
+
Selected/rejected recommendation IDs → graph-related rows.
|
| 21 |
+
Excludes selected, rejected, unavailable, and deprecated nodes.
|
| 22 |
|
| 23 |
ctx__graph_query(seeds, max_hops=2, top_n=10)
|
| 24 |
Direct graph walk from a list of seed entity names.
|
|
|
|
| 33 |
Fetch a single entity page by slug — returns its full
|
| 34 |
frontmatter + body for the model to reason about.
|
| 35 |
|
| 36 |
+
Load/unload/use tools are explicit lifecycle records, not filesystem
|
| 37 |
auto-installs. The host remains responsible for asking the user and
|
| 38 |
+
deciding how to place selected entities into context. Per-entity
|
| 39 |
+
token usage is recorded only when the host supplies explicit
|
| 40 |
+
``ctx__mark_entity_used.token_usage`` attribution.
|
| 41 |
|
| 42 |
Plan 001 Phase H6.
|
| 43 |
"""
|
|
|
|
| 72 |
# anything else falls back to its normal tool_executor.
|
| 73 |
_NAMESPACE = f"ctx{TOOL_SEPARATOR}"
|
| 74 |
_FILE_SIGNATURE_SAMPLE_BYTES = 64 * 1024
|
| 75 |
+
_RECOMMENDATION_ENTITY_TYPE_ALIASES = {
|
| 76 |
+
"agent": "agent",
|
| 77 |
+
"harness": "harness",
|
| 78 |
+
"mcp": "mcp-server",
|
| 79 |
+
"mcp-server": "mcp-server",
|
| 80 |
+
"mcp-servers": "mcp-server",
|
| 81 |
+
"skill": "skill",
|
| 82 |
+
}
|
| 83 |
+
_RELATED_BLOCKED_STATUSES = {
|
| 84 |
+
"archived",
|
| 85 |
+
"deleted",
|
| 86 |
+
"deprecated",
|
| 87 |
+
"disabled",
|
| 88 |
+
"removed",
|
| 89 |
+
"stale",
|
| 90 |
+
"unavailable",
|
| 91 |
+
}
|
| 92 |
SUPPORTED_RESPONSE_FORMATS = ("json", "gcf")
|
| 93 |
_RESPONSE_FORMAT_PROPERTY = {
|
| 94 |
"type": "string",
|
|
|
|
| 180 |
if isinstance(seeds, (list, tuple)):
|
| 181 |
payload["ctx.seeds.count"] = len(seeds)
|
| 182 |
payload["ctx.seeds.hash"] = _hash_json_value(list(seeds))
|
| 183 |
+
for key in ("selected", "rejected"):
|
| 184 |
+
values = args.get(key)
|
| 185 |
+
if isinstance(values, (list, tuple)):
|
| 186 |
+
payload[f"ctx.selection.{key}.count"] = len(values)
|
| 187 |
+
payload[f"ctx.selection.{key}.hash"] = _hash_json_value(list(values))
|
| 188 |
slug = args.get("slug")
|
| 189 |
if isinstance(slug, str):
|
| 190 |
payload["ctx.slug.hash"] = hash_identifier(slug)
|
|
|
|
| 259 |
|
| 260 |
_CORE_EVENT_NAMES = {
|
| 261 |
"recommend_bundle": "ctx.core.recommend_bundle",
|
| 262 |
+
"recommend_related": "ctx.core.recommend_related",
|
| 263 |
"graph_query": "ctx.core.graph_query",
|
| 264 |
"wiki_search": "ctx.core.wiki_search",
|
| 265 |
"wiki_get": "ctx.core.wiki_get",
|
|
|
|
| 404 |
"required": ["seeds"],
|
| 405 |
},
|
| 406 |
),
|
| 407 |
+
ToolDefinition(
|
| 408 |
+
name=f"{_NAMESPACE}recommend_related",
|
| 409 |
+
description=(
|
| 410 |
+
"Recommend related skills / agents / MCP servers after "
|
| 411 |
+
"the user selected a subset of an initial bundle. "
|
| 412 |
+
"Filters out selected and rejected recommendation IDs."
|
| 413 |
+
),
|
| 414 |
+
parameters={
|
| 415 |
+
"type": "object",
|
| 416 |
+
"properties": {
|
| 417 |
+
"selected": {
|
| 418 |
+
"type": "array",
|
| 419 |
+
"items": {"type": "string"},
|
| 420 |
+
"description": (
|
| 421 |
+
"Selected recommendation IDs or names, such as "
|
| 422 |
+
"'skill:fastapi-pro' or 'fastapi-pro'."
|
| 423 |
+
),
|
| 424 |
+
"minItems": 1,
|
| 425 |
+
},
|
| 426 |
+
"rejected": {
|
| 427 |
+
"type": "array",
|
| 428 |
+
"items": {"type": "string"},
|
| 429 |
+
"description": "Rejected recommendation IDs or names to exclude.",
|
| 430 |
+
},
|
| 431 |
+
"max_hops": {
|
| 432 |
+
"type": "integer",
|
| 433 |
+
"description": "Graph walk depth. Default 2.",
|
| 434 |
+
"minimum": 1,
|
| 435 |
+
"maximum": 4,
|
| 436 |
+
},
|
| 437 |
+
"top_n": {
|
| 438 |
+
"type": "integer",
|
| 439 |
+
"description": "How many related recommendations. Default 5.",
|
| 440 |
+
"minimum": 1,
|
| 441 |
+
"maximum": 50,
|
| 442 |
+
},
|
| 443 |
+
"output_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 444 |
+
"_response_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 445 |
+
},
|
| 446 |
+
"required": ["selected"],
|
| 447 |
+
},
|
| 448 |
+
),
|
| 449 |
ToolDefinition(
|
| 450 |
name=f"{_NAMESPACE}wiki_search",
|
| 451 |
description=(
|
|
|
|
| 524 |
try:
|
| 525 |
if local_name == "recommend_bundle":
|
| 526 |
result = self._dispatch_recommend(args)
|
| 527 |
+
elif local_name == "recommend_related":
|
| 528 |
+
result = self._dispatch_recommend_related(args)
|
| 529 |
elif local_name == "graph_query":
|
| 530 |
result = self._dispatch_graph_query(args)
|
| 531 |
elif local_name == "wiki_search":
|
|
|
|
| 629 |
semantic_cache_dir=semantic_cache_dir,
|
| 630 |
)
|
| 631 |
results = [
|
| 632 |
+
_with_recommendation_selection_metadata(
|
| 633 |
+
{
|
| 634 |
+
"name": r["name"],
|
| 635 |
+
"type": r["type"],
|
| 636 |
+
"score": r["score"],
|
| 637 |
+
"normalized_score": r.get("normalized_score"),
|
| 638 |
+
"matching_tags": r.get("matching_tags", []),
|
| 639 |
+
"external": r.get("external", False),
|
| 640 |
+
"external_catalog": r.get("external_catalog"),
|
| 641 |
+
"source_catalog": r.get("source_catalog"),
|
| 642 |
+
"status": r.get("status"),
|
| 643 |
+
"source": r.get("source"),
|
| 644 |
+
"skill_id": r.get("skill_id"),
|
| 645 |
+
"installs": r.get("installs"),
|
| 646 |
+
"detail_url": r.get("detail_url"),
|
| 647 |
+
"install_command": r.get("install_command"),
|
| 648 |
+
"category": r.get("category"),
|
| 649 |
+
"invoke_command": r.get("invoke_command"),
|
| 650 |
+
"security_review": r.get("security_review"),
|
| 651 |
+
}
|
| 652 |
+
)
|
| 653 |
for r in raw
|
| 654 |
]
|
| 655 |
model_provider = _optional_str(args.get("model_provider"))
|
|
|
|
| 674 |
_response_format_from_args(args),
|
| 675 |
)
|
| 676 |
|
| 677 |
+
def _dispatch_recommend_related(self, args: dict[str, Any]) -> str:
|
| 678 |
+
selected_raw = args.get("selected") or []
|
| 679 |
+
if not isinstance(selected_raw, list) or not selected_raw:
|
| 680 |
+
return json.dumps({"error": "selected must be a non-empty list", "results": []})
|
| 681 |
+
selected = _recommendation_selection_values(selected_raw)
|
| 682 |
+
if not selected:
|
| 683 |
+
return json.dumps(
|
| 684 |
+
{
|
| 685 |
+
"error": "selected must contain recommendation IDs or names",
|
| 686 |
+
"results": [],
|
| 687 |
+
}
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
rejected_raw = args.get("rejected") or []
|
| 691 |
+
rejected = (
|
| 692 |
+
_recommendation_selection_values(rejected_raw) if isinstance(rejected_raw, list) else []
|
| 693 |
+
)
|
| 694 |
+
excluded = _recommendation_selection_keys(selected + rejected)
|
| 695 |
+
max_hops = _clamp_int(args.get("max_hops"), default=2, lo=1, hi=4)
|
| 696 |
+
top_n = _clamp_int(args.get("top_n"), default=5, lo=1, hi=50)
|
| 697 |
+
|
| 698 |
+
graph = self._ensure_graph()
|
| 699 |
+
if graph.number_of_nodes() == 0:
|
| 700 |
+
return json.dumps(
|
| 701 |
+
{
|
| 702 |
+
"error": "knowledge graph not available; run ctx-wiki-graphify",
|
| 703 |
+
"results": [],
|
| 704 |
+
}
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
seed_ids = _recommendation_selection_node_ids(graph, selected)
|
| 708 |
+
raw = _resolve_related_recommendation_rows(
|
| 709 |
+
graph,
|
| 710 |
+
seed_ids,
|
| 711 |
+
max_hops=max_hops,
|
| 712 |
+
top_n=min(50, top_n + len(excluded) + 5),
|
| 713 |
+
)
|
| 714 |
+
results: list[dict[str, Any]] = []
|
| 715 |
+
for r in raw:
|
| 716 |
+
candidate_keys = _recommendation_selection_keys(
|
| 717 |
+
[_recommendation_identity(r), str(r.get("name") or "")]
|
| 718 |
+
)
|
| 719 |
+
if candidate_keys & excluded:
|
| 720 |
+
continue
|
| 721 |
+
shared_tags = r.get("shared_tags", [])
|
| 722 |
+
row = _with_recommendation_selection_metadata(
|
| 723 |
+
{
|
| 724 |
+
"name": r["name"],
|
| 725 |
+
"type": r["type"],
|
| 726 |
+
"score": r["score"],
|
| 727 |
+
"normalized_score": r.get("normalized_score"),
|
| 728 |
+
"matching_tags": shared_tags,
|
| 729 |
+
"shared_tags": shared_tags,
|
| 730 |
+
"status": r.get("status"),
|
| 731 |
+
"via": r.get("via", []),
|
| 732 |
+
}
|
| 733 |
+
)
|
| 734 |
+
row["selection_state"] = "suggested_related"
|
| 735 |
+
row["related_to"] = r.get("via", [])
|
| 736 |
+
row["reason"] = _related_recommendation_reason(row)
|
| 737 |
+
results.append(row)
|
| 738 |
+
if len(results) >= top_n:
|
| 739 |
+
break
|
| 740 |
+
|
| 741 |
+
return _encode_response(
|
| 742 |
+
{
|
| 743 |
+
"selected": selected,
|
| 744 |
+
"rejected": rejected,
|
| 745 |
+
"results": results,
|
| 746 |
+
},
|
| 747 |
+
_response_format_from_args(args),
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
def _dispatch_graph_query(self, args: dict[str, Any]) -> str:
|
| 751 |
seeds_raw = args.get("seeds") or []
|
| 752 |
if not isinstance(seeds_raw, list) or not seeds_raw:
|
|
|
|
| 902 |
security_scan=(
|
| 903 |
_dict_arg(args.get("security_scan")) if "security_scan" in args else None
|
| 904 |
),
|
| 905 |
+
selected=_optional_bool(args.get("selected")),
|
| 906 |
+
selection_source=str(args.get("selection_source") or "") or None,
|
| 907 |
+
source_context=_dict_arg(args.get("source_context")),
|
| 908 |
)
|
| 909 |
elif name == "mark_entity_used":
|
| 910 |
result = self._lifecycle.mark_entity_used(
|
|
|
|
| 912 |
entity_type=str(args.get("entity_type") or ""),
|
| 913 |
slug=str(args.get("slug") or ""),
|
| 914 |
evidence=str(args.get("evidence") or "") or None,
|
| 915 |
+
token_usage=(
|
| 916 |
+
_dict_arg(args.get("token_usage")) if "token_usage" in args else None
|
| 917 |
+
),
|
| 918 |
)
|
| 919 |
elif name == "unload_entity":
|
| 920 |
result = self._lifecycle.unload_entity(
|
|
|
|
| 1241 |
return value or None
|
| 1242 |
|
| 1243 |
|
| 1244 |
+
def _clip_recommendation_text(value: str, *, max_chars: int = 160) -> str:
|
| 1245 |
+
text = " ".join(value.split())
|
| 1246 |
+
if len(text) <= max_chars:
|
| 1247 |
+
return text
|
| 1248 |
+
return text[: max_chars - 1].rstrip() + "..."
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
def _recommendation_identity(row: Mapping[str, Any]) -> str:
|
| 1252 |
+
entity_type = str(row.get("type") or "tool").strip() or "tool"
|
| 1253 |
+
name = str(row.get("name") or "unknown").strip() or "unknown"
|
| 1254 |
+
return f"{entity_type}:{name}"
|
| 1255 |
+
|
| 1256 |
+
|
| 1257 |
+
def _recommendation_tags(row: Mapping[str, Any]) -> list[str]:
|
| 1258 |
+
raw = row.get("matching_tags", [])
|
| 1259 |
+
if not isinstance(raw, list):
|
| 1260 |
+
return []
|
| 1261 |
+
return [str(tag).strip() for tag in raw if str(tag).strip()]
|
| 1262 |
+
|
| 1263 |
+
|
| 1264 |
+
def _recommendation_tldr(row: Mapping[str, Any]) -> str:
|
| 1265 |
+
description = (
|
| 1266 |
+
_optional_str(row.get("description"))
|
| 1267 |
+
or _optional_str(row.get("summary"))
|
| 1268 |
+
or _optional_str(row.get("title"))
|
| 1269 |
+
)
|
| 1270 |
+
if description:
|
| 1271 |
+
return _clip_recommendation_text(description)
|
| 1272 |
+
|
| 1273 |
+
entity_type = str(row.get("type") or "tool").strip() or "tool"
|
| 1274 |
+
category = _optional_str(row.get("category"))
|
| 1275 |
+
tags = _recommendation_tags(row)
|
| 1276 |
+
if tags:
|
| 1277 |
+
prefix = f"{category} {entity_type}" if category else entity_type
|
| 1278 |
+
return _clip_recommendation_text(f"{prefix} matching {', '.join(tags[:4])}.")
|
| 1279 |
+
|
| 1280 |
+
catalog = _optional_str(row.get("source_catalog")) or _optional_str(row.get("external_catalog"))
|
| 1281 |
+
if bool(row.get("external")) and catalog:
|
| 1282 |
+
return _clip_recommendation_text(f"External {entity_type} from {catalog}.")
|
| 1283 |
+
return _clip_recommendation_text(f"{entity_type} recommendation.")
|
| 1284 |
+
|
| 1285 |
+
|
| 1286 |
+
def _recommendation_reason(row: Mapping[str, Any]) -> str:
|
| 1287 |
+
parts: list[str] = []
|
| 1288 |
+
tags = _recommendation_tags(row)
|
| 1289 |
+
if tags:
|
| 1290 |
+
parts.append(f"matches tags {', '.join(tags[:6])}")
|
| 1291 |
+
category = _optional_str(row.get("category"))
|
| 1292 |
+
if category:
|
| 1293 |
+
parts.append(f"category {category}")
|
| 1294 |
+
source = _optional_str(row.get("source_catalog")) or _optional_str(row.get("source"))
|
| 1295 |
+
if source:
|
| 1296 |
+
parts.append(f"source {source}")
|
| 1297 |
+
normalized_score = row.get("normalized_score")
|
| 1298 |
+
if isinstance(normalized_score, (int, float)):
|
| 1299 |
+
parts.append(f"normalized score {float(normalized_score):.3f}")
|
| 1300 |
+
if not parts:
|
| 1301 |
+
return "Ranked by ctx recommendation graph."
|
| 1302 |
+
return _clip_recommendation_text("; ".join(parts), max_chars=220)
|
| 1303 |
+
|
| 1304 |
+
|
| 1305 |
+
def _with_recommendation_selection_metadata(row: Mapping[str, Any]) -> dict[str, Any]:
|
| 1306 |
+
enriched = dict(row)
|
| 1307 |
+
enriched["id"] = _recommendation_identity(row)
|
| 1308 |
+
enriched["tldr"] = _recommendation_tldr(row)
|
| 1309 |
+
enriched["reason"] = _recommendation_reason(row)
|
| 1310 |
+
enriched["selected"] = False
|
| 1311 |
+
enriched["selection_state"] = "suggested"
|
| 1312 |
+
return enriched
|
| 1313 |
+
|
| 1314 |
+
|
| 1315 |
+
def _recommendation_selection_values(values: list[Any]) -> list[str]:
|
| 1316 |
+
selected: list[str] = []
|
| 1317 |
+
seen: set[str] = set()
|
| 1318 |
+
for value in values:
|
| 1319 |
+
if isinstance(value, Mapping):
|
| 1320 |
+
raw = value.get("id") or (
|
| 1321 |
+
f"{value.get('type')}:{value.get('name')}"
|
| 1322 |
+
if value.get("type") and value.get("name")
|
| 1323 |
+
else value.get("name")
|
| 1324 |
+
)
|
| 1325 |
+
else:
|
| 1326 |
+
raw = value
|
| 1327 |
+
if not isinstance(raw, str):
|
| 1328 |
+
continue
|
| 1329 |
+
item = raw.strip()
|
| 1330 |
+
if not item:
|
| 1331 |
+
continue
|
| 1332 |
+
key = _recommendation_selection_key(item)
|
| 1333 |
+
if key in seen:
|
| 1334 |
+
continue
|
| 1335 |
+
seen.add(key)
|
| 1336 |
+
selected.append(item)
|
| 1337 |
+
return selected
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def _recommendation_selection_keys(values: list[str]) -> set[str]:
|
| 1341 |
+
keys: set[str] = set()
|
| 1342 |
+
for value in values:
|
| 1343 |
+
item = str(value or "").strip().lower()
|
| 1344 |
+
if not item:
|
| 1345 |
+
continue
|
| 1346 |
+
keys.add(_recommendation_selection_key(item))
|
| 1347 |
+
return keys
|
| 1348 |
+
|
| 1349 |
+
|
| 1350 |
+
def _recommendation_selection_key(value: str) -> str:
|
| 1351 |
+
entity_type, name = _recommendation_selection_parts(value)
|
| 1352 |
+
if entity_type is not None:
|
| 1353 |
+
return f"{entity_type}:{name.lower()}"
|
| 1354 |
+
return name.lower()
|
| 1355 |
+
|
| 1356 |
+
|
| 1357 |
+
def _recommendation_selection_parts(value: str) -> tuple[str | None, str]:
|
| 1358 |
+
item = str(value or "").strip()
|
| 1359 |
+
if ":" not in item:
|
| 1360 |
+
return None, item
|
| 1361 |
+
raw_type, raw_name = item.split(":", 1)
|
| 1362 |
+
entity_type = _RECOMMENDATION_ENTITY_TYPE_ALIASES.get(raw_type.strip().lower())
|
| 1363 |
+
name = raw_name.strip()
|
| 1364 |
+
if entity_type is None or not name:
|
| 1365 |
+
return None, item
|
| 1366 |
+
return entity_type, name
|
| 1367 |
+
|
| 1368 |
+
|
| 1369 |
+
def _recommendation_selection_node_ids(graph: Any, values: list[str]) -> set[str]:
|
| 1370 |
+
node_ids: set[str] = set()
|
| 1371 |
+
for value in values:
|
| 1372 |
+
entity_type, name = _recommendation_selection_parts(value)
|
| 1373 |
+
if not name:
|
| 1374 |
+
continue
|
| 1375 |
+
if entity_type is not None:
|
| 1376 |
+
node_id = f"{entity_type}:{name}"
|
| 1377 |
+
if node_id in graph:
|
| 1378 |
+
node_ids.add(node_id)
|
| 1379 |
+
continue
|
| 1380 |
+
for candidate_type in RECOMMENDABLE_ENTITY_TYPES:
|
| 1381 |
+
node_id = f"{candidate_type}:{name}"
|
| 1382 |
+
if node_id in graph:
|
| 1383 |
+
node_ids.add(node_id)
|
| 1384 |
+
return node_ids
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
def _resolve_related_recommendation_rows(
|
| 1388 |
+
graph: Any,
|
| 1389 |
+
seed_ids: set[str],
|
| 1390 |
+
*,
|
| 1391 |
+
max_hops: int,
|
| 1392 |
+
top_n: int,
|
| 1393 |
+
) -> list[dict[str, Any]]:
|
| 1394 |
+
if not seed_ids:
|
| 1395 |
+
return []
|
| 1396 |
+
scores: dict[str, float] = {}
|
| 1397 |
+
via: dict[str, list[str]] = {}
|
| 1398 |
+
shared_tags_map: dict[str, list[str]] = {}
|
| 1399 |
+
visited = set(seed_ids)
|
| 1400 |
+
frontier = list(seed_ids)
|
| 1401 |
+
|
| 1402 |
+
for hop in range(max_hops):
|
| 1403 |
+
next_frontier: list[str] = []
|
| 1404 |
+
decay = 1.0 / (hop + 1)
|
| 1405 |
+
for node_id in frontier:
|
| 1406 |
+
for neighbor in graph.neighbors(node_id):
|
| 1407 |
+
if neighbor in seed_ids or not _related_node_is_recommendable(graph, neighbor):
|
| 1408 |
+
continue
|
| 1409 |
+
edge_data = graph[node_id][neighbor]
|
| 1410 |
+
try:
|
| 1411 |
+
weight = float(edge_data.get("weight", 1)) * decay
|
| 1412 |
+
except (TypeError, ValueError):
|
| 1413 |
+
weight = decay
|
| 1414 |
+
scores[neighbor] = scores.get(neighbor, 0.0) + weight
|
| 1415 |
+
seed_label = node_id.split(":", 1)[-1]
|
| 1416 |
+
via.setdefault(neighbor, [])
|
| 1417 |
+
if seed_label not in via[neighbor]:
|
| 1418 |
+
via[neighbor].append(seed_label)
|
| 1419 |
+
shared_tags_map.setdefault(neighbor, [])
|
| 1420 |
+
for tag in edge_data.get("shared_tags", []):
|
| 1421 |
+
if tag not in shared_tags_map[neighbor]:
|
| 1422 |
+
shared_tags_map[neighbor].append(tag)
|
| 1423 |
+
if neighbor not in visited:
|
| 1424 |
+
visited.add(neighbor)
|
| 1425 |
+
next_frontier.append(neighbor)
|
| 1426 |
+
frontier = next_frontier
|
| 1427 |
+
|
| 1428 |
+
ranked = sorted(scores.items(), key=lambda item: (-item[1], item[0]))[:top_n]
|
| 1429 |
+
max_score = max((score for _, score in ranked), default=0.0) or 1.0
|
| 1430 |
+
results: list[dict[str, Any]] = []
|
| 1431 |
+
for node_id, score in ranked:
|
| 1432 |
+
node_data = graph.nodes.get(node_id, {})
|
| 1433 |
+
entity_type = str(node_data.get("type") or node_id.split(":", 1)[0])
|
| 1434 |
+
name = str(node_data.get("label") or node_id.split(":", 1)[-1])
|
| 1435 |
+
results.append(
|
| 1436 |
+
{
|
| 1437 |
+
"name": name,
|
| 1438 |
+
"type": entity_type,
|
| 1439 |
+
"score": round(score, 2),
|
| 1440 |
+
"normalized_score": round(score / max_score, 4),
|
| 1441 |
+
"shared_tags": shared_tags_map.get(node_id, [])[:8],
|
| 1442 |
+
"via": via.get(node_id, [])[:4],
|
| 1443 |
+
"status": node_data.get("status"),
|
| 1444 |
+
}
|
| 1445 |
+
)
|
| 1446 |
+
return results
|
| 1447 |
+
|
| 1448 |
+
|
| 1449 |
+
def _related_node_is_recommendable(graph: Any, node_id: str) -> bool:
|
| 1450 |
+
node_data = graph.nodes.get(node_id, {})
|
| 1451 |
+
entity_type = str(node_data.get("type") or node_id.split(":", 1)[0])
|
| 1452 |
+
if entity_type not in RECOMMENDABLE_ENTITY_TYPES:
|
| 1453 |
+
return False
|
| 1454 |
+
status = str(node_data.get("status") or "").strip().lower()
|
| 1455 |
+
if status in _RELATED_BLOCKED_STATUSES:
|
| 1456 |
+
return False
|
| 1457 |
+
return not _truthy_recommendation_flag(node_data.get("never_load"))
|
| 1458 |
+
|
| 1459 |
+
|
| 1460 |
+
def _truthy_recommendation_flag(value: object) -> bool:
|
| 1461 |
+
if isinstance(value, str):
|
| 1462 |
+
return value.strip().lower() in {"1", "true", "yes", "y", "on"}
|
| 1463 |
+
return bool(value)
|
| 1464 |
+
|
| 1465 |
+
|
| 1466 |
+
def _related_recommendation_reason(row: Mapping[str, Any]) -> str:
|
| 1467 |
+
parts: list[str] = []
|
| 1468 |
+
via = row.get("via", [])
|
| 1469 |
+
if isinstance(via, list) and via:
|
| 1470 |
+
parts.append(f"related via {', '.join(str(v) for v in via[:4])}")
|
| 1471 |
+
tags = _recommendation_tags(row)
|
| 1472 |
+
if tags:
|
| 1473 |
+
parts.append(f"shares tags {', '.join(tags[:6])}")
|
| 1474 |
+
normalized_score = row.get("normalized_score")
|
| 1475 |
+
if isinstance(normalized_score, (int, float)):
|
| 1476 |
+
parts.append(f"normalized score {float(normalized_score):.3f}")
|
| 1477 |
+
if not parts:
|
| 1478 |
+
return "Related by ctx recommendation graph."
|
| 1479 |
+
return _clip_recommendation_text("; ".join(parts), max_chars=220)
|
| 1480 |
+
|
| 1481 |
+
|
| 1482 |
def _recommend_companion_harnesses(
|
| 1483 |
query: str,
|
| 1484 |
*,
|
|
|
|
| 1564 |
"entity_type": entity_type,
|
| 1565 |
"slug": slug,
|
| 1566 |
"reason": {"type": "string"},
|
| 1567 |
+
"selected": {
|
| 1568 |
+
"type": "boolean",
|
| 1569 |
+
"description": (
|
| 1570 |
+
"True when the entity was explicitly selected from "
|
| 1571 |
+
"ctx recommendations. Defaults to true for user loads."
|
| 1572 |
+
),
|
| 1573 |
+
},
|
| 1574 |
+
"selection_source": {
|
| 1575 |
+
"type": "string",
|
| 1576 |
+
"enum": ["user", "system", "host", "unknown"],
|
| 1577 |
+
"description": (
|
| 1578 |
+
"Who selected or activated the entity: user, system, "
|
| 1579 |
+
"host, or unknown. Default user."
|
| 1580 |
+
),
|
| 1581 |
+
},
|
| 1582 |
+
"source_context": {
|
| 1583 |
+
"type": "object",
|
| 1584 |
+
"description": (
|
| 1585 |
+
"Optional privacy-sanitized context such as the "
|
| 1586 |
+
"recommendation surface or workflow that caused activation."
|
| 1587 |
+
),
|
| 1588 |
+
},
|
| 1589 |
"security_scan": {
|
| 1590 |
"type": "object",
|
| 1591 |
"description": (
|
|
|
|
| 1609 |
"entity_type": entity_type,
|
| 1610 |
"slug": slug,
|
| 1611 |
"evidence": {"type": "string"},
|
| 1612 |
+
"token_usage": {
|
| 1613 |
+
"type": "object",
|
| 1614 |
+
"description": (
|
| 1615 |
+
"Optional per-tool usage evidence. Only pass exact "
|
| 1616 |
+
"token counts when the host/provider can attribute "
|
| 1617 |
+
"them to this entity; otherwise set attribution to "
|
| 1618 |
+
"estimated or unavailable."
|
| 1619 |
+
),
|
| 1620 |
+
"properties": {
|
| 1621 |
+
"attribution": {
|
| 1622 |
+
"type": "string",
|
| 1623 |
+
"enum": ["exact", "estimated", "unavailable"],
|
| 1624 |
+
},
|
| 1625 |
+
"input_tokens": {"type": "integer", "minimum": 0},
|
| 1626 |
+
"output_tokens": {"type": "integer", "minimum": 0},
|
| 1627 |
+
"total_tokens": {"type": "integer", "minimum": 0},
|
| 1628 |
+
"cost_usd": {"type": "number", "minimum": 0},
|
| 1629 |
+
"attribution_reason": {"type": "string"},
|
| 1630 |
+
"provider": {"type": "string"},
|
| 1631 |
+
"model": {"type": "string"},
|
| 1632 |
+
},
|
| 1633 |
+
},
|
| 1634 |
},
|
| 1635 |
"required": ["session_id", "entity_type", "slug"],
|
| 1636 |
},
|
|
|
|
| 1770 |
return 0.0
|
| 1771 |
|
| 1772 |
|
| 1773 |
+
def _optional_bool(raw: Any) -> bool | None:
|
| 1774 |
+
return raw if isinstance(raw, bool) else None
|
| 1775 |
+
|
| 1776 |
+
|
| 1777 |
def _excerpt(body: str, max_chars: int) -> str:
|
| 1778 |
"""Short preview of a page body: first non-empty line, trimmed.
|
| 1779 |
|
src/ctx/adapters/generic/runtime_lifecycle.py
CHANGED
|
@@ -15,7 +15,9 @@ from ctx.core.wiki.wiki_utils import validate_skill_name
|
|
| 15 |
from ctx.telemetry import (
|
| 16 |
ensure_private_event_file,
|
| 17 |
hash_identifier,
|
|
|
|
| 18 |
record_event,
|
|
|
|
| 19 |
sanitize_payload,
|
| 20 |
telemetry_span,
|
| 21 |
telemetry_enabled,
|
|
@@ -27,6 +29,9 @@ _SESSION_RE = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")
|
|
| 27 |
_ENTITY_TYPES = set(RECOMMENDABLE_ENTITY_TYPES)
|
| 28 |
_VALIDATION_STATUSES = {"passed", "failed", "skipped", "error"}
|
| 29 |
_ESCALATION_STATUSES = {"open", "resolved", "ignored"}
|
|
|
|
|
|
|
|
|
|
| 30 |
_SECURITY_SCAN_STATUSES = {
|
| 31 |
"passed",
|
| 32 |
"findings",
|
|
@@ -69,9 +74,17 @@ class RuntimeLifecycleStore:
|
|
| 69 |
slug: str,
|
| 70 |
reason: str | None = None,
|
| 71 |
security_scan: dict[str, Any] | None = None,
|
|
|
|
|
|
|
|
|
|
| 72 |
) -> dict[str, Any]:
|
| 73 |
entity_type = _validate_entity_type(entity_type)
|
| 74 |
slug = _validate_slug(slug)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
return self._record(
|
| 76 |
action="load_requested",
|
| 77 |
session_id=session_id,
|
|
@@ -83,6 +96,9 @@ class RuntimeLifecycleStore:
|
|
| 83 |
entity_type=entity_type,
|
| 84 |
slug=slug,
|
| 85 |
),
|
|
|
|
|
|
|
|
|
|
| 86 |
)
|
| 87 |
|
| 88 |
def mark_entity_used(
|
|
@@ -92,14 +108,17 @@ class RuntimeLifecycleStore:
|
|
| 92 |
entity_type: str,
|
| 93 |
slug: str,
|
| 94 |
evidence: str | None = None,
|
|
|
|
| 95 |
) -> dict[str, Any]:
|
| 96 |
-
|
| 97 |
action="used",
|
| 98 |
session_id=session_id,
|
| 99 |
entity_type=entity_type,
|
| 100 |
slug=slug,
|
| 101 |
evidence=evidence,
|
|
|
|
| 102 |
)
|
|
|
|
| 103 |
|
| 104 |
def unload_entity(
|
| 105 |
self,
|
|
@@ -216,11 +235,15 @@ class RuntimeLifecycleStore:
|
|
| 216 |
"loaded_at_epoch": float(event.get("created_at_epoch") or 0),
|
| 217 |
"reason": event.get("reason"),
|
| 218 |
"security_scan": event.get("security_scan"),
|
|
|
|
|
|
|
|
|
|
| 219 |
"used": False,
|
| 220 |
"use_count": 0,
|
| 221 |
"last_used_at": None,
|
| 222 |
"evidence": [],
|
| 223 |
"dev_event_epoch": latest_dev_event_epoch,
|
|
|
|
| 224 |
}
|
| 225 |
elif action == "used" and key in loaded:
|
| 226 |
loaded[key]["used"] = True
|
|
@@ -228,6 +251,9 @@ class RuntimeLifecycleStore:
|
|
| 228 |
loaded[key]["last_used_at"] = event.get("created_at")
|
| 229 |
if event.get("evidence"):
|
| 230 |
loaded[key]["evidence"].append(event["evidence"])
|
|
|
|
|
|
|
|
|
|
| 231 |
elif action == "unload_requested":
|
| 232 |
current = loaded.pop(key, None)
|
| 233 |
unloaded.append(
|
|
@@ -273,12 +299,6 @@ class RuntimeLifecycleStore:
|
|
| 273 |
event["session_id"] = session_id
|
| 274 |
event["created_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 275 |
event["created_at_epoch"] = time.time()
|
| 276 |
-
if not telemetry_enabled():
|
| 277 |
-
return {
|
| 278 |
-
"ok": True,
|
| 279 |
-
"events_path": str(self.events_path),
|
| 280 |
-
"recorded": False,
|
| 281 |
-
}
|
| 282 |
event = _sanitize_lifecycle_event(event)
|
| 283 |
path = self.events_path
|
| 284 |
reject_symlink_path(path)
|
|
@@ -315,7 +335,13 @@ def _sanitize_lifecycle_event(event: dict[str, Any]) -> dict[str, Any]:
|
|
| 315 |
redacted = dict(event)
|
| 316 |
payload = redacted.get("payload")
|
| 317 |
if isinstance(payload, dict):
|
| 318 |
-
redacted["payload"] = sanitize_payload(payload)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
cwd = redacted.pop("cwd", None)
|
| 320 |
if isinstance(cwd, str) and cwd:
|
| 321 |
redacted["cwd_hash"] = hash_identifier(cwd)
|
|
@@ -330,6 +356,16 @@ def _validate_session_id(raw: str) -> str:
|
|
| 330 |
|
| 331 |
|
| 332 |
def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
payload: dict[str, Any] = {
|
| 334 |
"ctx.lifecycle.action": str(event.get("action") or ""),
|
| 335 |
"ctx.payload.present": bool(event.get("payload")),
|
|
@@ -344,9 +380,19 @@ def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
|
| 344 |
status = event.get("status")
|
| 345 |
if isinstance(status, str) and status:
|
| 346 |
payload["ctx.status"] = status
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
security_scan = event.get("security_scan")
|
| 348 |
if isinstance(security_scan, dict):
|
| 349 |
payload["ctx.security_scan.status"] = str(security_scan.get("status") or "")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
try:
|
| 351 |
with telemetry_span():
|
| 352 |
record_event(
|
|
@@ -361,6 +407,50 @@ def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
|
| 361 |
pass
|
| 362 |
|
| 363 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
def _validate_entity_type(raw: str) -> str:
|
| 365 |
value = raw.strip()
|
| 366 |
if value not in _ENTITY_TYPES:
|
|
@@ -400,6 +490,84 @@ def _validation_state(event: dict[str, Any]) -> dict[str, Any]:
|
|
| 400 |
}
|
| 401 |
|
| 402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
def _security_scan_state(
|
| 404 |
raw: dict[str, Any] | None,
|
| 405 |
*,
|
|
|
|
| 15 |
from ctx.telemetry import (
|
| 16 |
ensure_private_event_file,
|
| 17 |
hash_identifier,
|
| 18 |
+
record_counter,
|
| 19 |
record_event,
|
| 20 |
+
record_histogram,
|
| 21 |
sanitize_payload,
|
| 22 |
telemetry_span,
|
| 23 |
telemetry_enabled,
|
|
|
|
| 29 |
_ENTITY_TYPES = set(RECOMMENDABLE_ENTITY_TYPES)
|
| 30 |
_VALIDATION_STATUSES = {"passed", "failed", "skipped", "error"}
|
| 31 |
_ESCALATION_STATUSES = {"open", "resolved", "ignored"}
|
| 32 |
+
_SELECTION_SOURCES = {"user", "system", "host", "unknown"}
|
| 33 |
+
_TOKEN_ATTRIBUTIONS = {"exact", "estimated", "unavailable"}
|
| 34 |
+
_LIFECYCLE_SANITIZER_CONFIG = {"enabled": True, "mode": "local_redacted"}
|
| 35 |
_SECURITY_SCAN_STATUSES = {
|
| 36 |
"passed",
|
| 37 |
"findings",
|
|
|
|
| 74 |
slug: str,
|
| 75 |
reason: str | None = None,
|
| 76 |
security_scan: dict[str, Any] | None = None,
|
| 77 |
+
selected: bool | None = None,
|
| 78 |
+
selection_source: str | None = None,
|
| 79 |
+
source_context: dict[str, Any] | None = None,
|
| 80 |
) -> dict[str, Any]:
|
| 81 |
entity_type = _validate_entity_type(entity_type)
|
| 82 |
slug = _validate_slug(slug)
|
| 83 |
+
source = _validate_choice(
|
| 84 |
+
selection_source or "user",
|
| 85 |
+
_SELECTION_SOURCES,
|
| 86 |
+
"selection_source",
|
| 87 |
+
)
|
| 88 |
return self._record(
|
| 89 |
action="load_requested",
|
| 90 |
session_id=session_id,
|
|
|
|
| 96 |
entity_type=entity_type,
|
| 97 |
slug=slug,
|
| 98 |
),
|
| 99 |
+
selected=(source == "user" if selected is None else bool(selected)),
|
| 100 |
+
selection_source=source,
|
| 101 |
+
source_context=source_context or {},
|
| 102 |
)
|
| 103 |
|
| 104 |
def mark_entity_used(
|
|
|
|
| 108 |
entity_type: str,
|
| 109 |
slug: str,
|
| 110 |
evidence: str | None = None,
|
| 111 |
+
token_usage: dict[str, Any] | None = None,
|
| 112 |
) -> dict[str, Any]:
|
| 113 |
+
event = self._record(
|
| 114 |
action="used",
|
| 115 |
session_id=session_id,
|
| 116 |
entity_type=entity_type,
|
| 117 |
slug=slug,
|
| 118 |
evidence=evidence,
|
| 119 |
+
token_usage=_token_usage_state(token_usage),
|
| 120 |
)
|
| 121 |
+
return event
|
| 122 |
|
| 123 |
def unload_entity(
|
| 124 |
self,
|
|
|
|
| 235 |
"loaded_at_epoch": float(event.get("created_at_epoch") or 0),
|
| 236 |
"reason": event.get("reason"),
|
| 237 |
"security_scan": event.get("security_scan"),
|
| 238 |
+
"selected": bool(event.get("selected", False)),
|
| 239 |
+
"selection_source": event.get("selection_source") or "unknown",
|
| 240 |
+
"source_context": event.get("source_context") or {},
|
| 241 |
"used": False,
|
| 242 |
"use_count": 0,
|
| 243 |
"last_used_at": None,
|
| 244 |
"evidence": [],
|
| 245 |
"dev_event_epoch": latest_dev_event_epoch,
|
| 246 |
+
"token_usage": _empty_token_usage_summary(),
|
| 247 |
}
|
| 248 |
elif action == "used" and key in loaded:
|
| 249 |
loaded[key]["used"] = True
|
|
|
|
| 251 |
loaded[key]["last_used_at"] = event.get("created_at")
|
| 252 |
if event.get("evidence"):
|
| 253 |
loaded[key]["evidence"].append(event["evidence"])
|
| 254 |
+
token_usage = event.get("token_usage")
|
| 255 |
+
if isinstance(token_usage, dict):
|
| 256 |
+
_merge_token_usage(loaded[key]["token_usage"], token_usage)
|
| 257 |
elif action == "unload_requested":
|
| 258 |
current = loaded.pop(key, None)
|
| 259 |
unloaded.append(
|
|
|
|
| 299 |
event["session_id"] = session_id
|
| 300 |
event["created_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 301 |
event["created_at_epoch"] = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
event = _sanitize_lifecycle_event(event)
|
| 303 |
path = self.events_path
|
| 304 |
reject_symlink_path(path)
|
|
|
|
| 335 |
redacted = dict(event)
|
| 336 |
payload = redacted.get("payload")
|
| 337 |
if isinstance(payload, dict):
|
| 338 |
+
redacted["payload"] = sanitize_payload(payload, config=_LIFECYCLE_SANITIZER_CONFIG)
|
| 339 |
+
source_context = redacted.get("source_context")
|
| 340 |
+
if isinstance(source_context, dict):
|
| 341 |
+
redacted["source_context"] = sanitize_payload(
|
| 342 |
+
source_context,
|
| 343 |
+
config=_LIFECYCLE_SANITIZER_CONFIG,
|
| 344 |
+
)
|
| 345 |
cwd = redacted.pop("cwd", None)
|
| 346 |
if isinstance(cwd, str) and cwd:
|
| 347 |
redacted["cwd_hash"] = hash_identifier(cwd)
|
|
|
|
| 356 |
|
| 357 |
|
| 358 |
def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
| 359 |
+
token_usage = event.get("token_usage")
|
| 360 |
+
usage_attribution: str | None = None
|
| 361 |
+
if isinstance(token_usage, dict):
|
| 362 |
+
usage_attribution = str(token_usage.get("attribution") or "unavailable")
|
| 363 |
+
total_tokens = token_usage.get("total_tokens")
|
| 364 |
+
_record_token_usage_metrics(
|
| 365 |
+
event,
|
| 366 |
+
attribution=usage_attribution,
|
| 367 |
+
total_tokens=total_tokens if isinstance(total_tokens, int) else None,
|
| 368 |
+
)
|
| 369 |
payload: dict[str, Any] = {
|
| 370 |
"ctx.lifecycle.action": str(event.get("action") or ""),
|
| 371 |
"ctx.payload.present": bool(event.get("payload")),
|
|
|
|
| 380 |
status = event.get("status")
|
| 381 |
if isinstance(status, str) and status:
|
| 382 |
payload["ctx.status"] = status
|
| 383 |
+
selection_source = event.get("selection_source")
|
| 384 |
+
if isinstance(selection_source, str) and selection_source:
|
| 385 |
+
payload["ctx.selection.source"] = selection_source
|
| 386 |
+
selected = event.get("selected")
|
| 387 |
+
if isinstance(selected, bool):
|
| 388 |
+
payload["ctx.selection.selected"] = selected
|
| 389 |
security_scan = event.get("security_scan")
|
| 390 |
if isinstance(security_scan, dict):
|
| 391 |
payload["ctx.security_scan.status"] = str(security_scan.get("status") or "")
|
| 392 |
+
if usage_attribution is not None:
|
| 393 |
+
payload["ctx.usage.attribution"] = usage_attribution
|
| 394 |
+
if not telemetry_enabled():
|
| 395 |
+
return
|
| 396 |
try:
|
| 397 |
with telemetry_span():
|
| 398 |
record_event(
|
|
|
|
| 407 |
pass
|
| 408 |
|
| 409 |
|
| 410 |
+
def _record_token_usage_metrics(
|
| 411 |
+
event: dict[str, Any],
|
| 412 |
+
*,
|
| 413 |
+
attribution: str,
|
| 414 |
+
total_tokens: int | None,
|
| 415 |
+
) -> None:
|
| 416 |
+
attrs: dict[str, Any] = {
|
| 417 |
+
"ctx.lifecycle.action": str(event.get("action") or ""),
|
| 418 |
+
"ctx.usage.attribution": attribution,
|
| 419 |
+
}
|
| 420 |
+
entity_type = event.get("entity_type")
|
| 421 |
+
if isinstance(entity_type, str) and entity_type:
|
| 422 |
+
attrs["ctx.entity.type"] = entity_type
|
| 423 |
+
session_id = str(event.get("session_id") or "") or None
|
| 424 |
+
try:
|
| 425 |
+
record_counter(
|
| 426 |
+
"ctx.tool_usage.records",
|
| 427 |
+
value=1,
|
| 428 |
+
unit="1",
|
| 429 |
+
attributes=attrs,
|
| 430 |
+
source="ctx-runtime-lifecycle",
|
| 431 |
+
session_id=session_id,
|
| 432 |
+
)
|
| 433 |
+
if total_tokens is not None:
|
| 434 |
+
record_counter(
|
| 435 |
+
"ctx.tool_usage.tokens",
|
| 436 |
+
value=total_tokens,
|
| 437 |
+
unit="tokens",
|
| 438 |
+
attributes=attrs,
|
| 439 |
+
source="ctx-runtime-lifecycle",
|
| 440 |
+
session_id=session_id,
|
| 441 |
+
)
|
| 442 |
+
record_histogram(
|
| 443 |
+
"ctx.tool_usage.tokens_per_record",
|
| 444 |
+
value=total_tokens,
|
| 445 |
+
unit="tokens",
|
| 446 |
+
attributes=attrs,
|
| 447 |
+
source="ctx-runtime-lifecycle",
|
| 448 |
+
session_id=session_id,
|
| 449 |
+
)
|
| 450 |
+
except Exception: # noqa: BLE001 - metrics must not break lifecycle writes.
|
| 451 |
+
pass
|
| 452 |
+
|
| 453 |
+
|
| 454 |
def _validate_entity_type(raw: str) -> str:
|
| 455 |
value = raw.strip()
|
| 456 |
if value not in _ENTITY_TYPES:
|
|
|
|
| 490 |
}
|
| 491 |
|
| 492 |
|
| 493 |
+
def _token_usage_state(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
| 494 |
+
if not raw:
|
| 495 |
+
return None
|
| 496 |
+
attribution = _validate_choice(
|
| 497 |
+
str(raw.get("attribution") or "unavailable"),
|
| 498 |
+
_TOKEN_ATTRIBUTIONS,
|
| 499 |
+
"token_usage.attribution",
|
| 500 |
+
)
|
| 501 |
+
input_tokens = _nonnegative_int(raw.get("input_tokens"), "token_usage.input_tokens")
|
| 502 |
+
output_tokens = _nonnegative_int(raw.get("output_tokens"), "token_usage.output_tokens")
|
| 503 |
+
total_tokens = _nonnegative_int(raw.get("total_tokens"), "token_usage.total_tokens")
|
| 504 |
+
if total_tokens is None and (input_tokens is not None or output_tokens is not None):
|
| 505 |
+
total_tokens = int(input_tokens or 0) + int(output_tokens or 0)
|
| 506 |
+
cost_usd = _nonnegative_float(raw.get("cost_usd"), "token_usage.cost_usd")
|
| 507 |
+
return {
|
| 508 |
+
"attribution": attribution,
|
| 509 |
+
"input_tokens": input_tokens,
|
| 510 |
+
"output_tokens": output_tokens,
|
| 511 |
+
"total_tokens": total_tokens,
|
| 512 |
+
"cost_usd": cost_usd,
|
| 513 |
+
"attribution_reason": str(raw.get("attribution_reason") or "").strip() or None,
|
| 514 |
+
"model": str(raw.get("model") or "").strip() or None,
|
| 515 |
+
"provider": str(raw.get("provider") or "").strip() or None,
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _empty_token_usage_summary() -> dict[str, Any]:
|
| 520 |
+
return {
|
| 521 |
+
"records": 0,
|
| 522 |
+
"input_tokens": 0,
|
| 523 |
+
"output_tokens": 0,
|
| 524 |
+
"total_tokens": 0,
|
| 525 |
+
"cost_usd": 0.0,
|
| 526 |
+
"by_attribution": {key: 0 for key in sorted(_TOKEN_ATTRIBUTIONS)},
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _merge_token_usage(summary: dict[str, Any], usage: dict[str, Any]) -> None:
|
| 531 |
+
summary["records"] = int(summary.get("records") or 0) + 1
|
| 532 |
+
attribution = str(usage.get("attribution") or "unavailable")
|
| 533 |
+
by_attribution = summary.setdefault(
|
| 534 |
+
"by_attribution",
|
| 535 |
+
{key: 0 for key in sorted(_TOKEN_ATTRIBUTIONS)},
|
| 536 |
+
)
|
| 537 |
+
by_attribution[attribution] = int(by_attribution.get(attribution) or 0) + 1
|
| 538 |
+
for key in ("input_tokens", "output_tokens", "total_tokens"):
|
| 539 |
+
value = usage.get(key)
|
| 540 |
+
if isinstance(value, int):
|
| 541 |
+
summary[key] = int(summary.get(key) or 0) + value
|
| 542 |
+
cost = usage.get("cost_usd")
|
| 543 |
+
if isinstance(cost, (int, float)):
|
| 544 |
+
summary["cost_usd"] = round(float(summary.get("cost_usd") or 0.0) + float(cost), 8)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def _nonnegative_int(raw: Any, field: str) -> int | None:
|
| 548 |
+
if raw is None or raw == "":
|
| 549 |
+
return None
|
| 550 |
+
try:
|
| 551 |
+
value = int(raw)
|
| 552 |
+
except (TypeError, ValueError) as exc:
|
| 553 |
+
raise ValueError(f"{field} must be a non-negative integer") from exc
|
| 554 |
+
if value < 0:
|
| 555 |
+
raise ValueError(f"{field} must be a non-negative integer")
|
| 556 |
+
return value
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def _nonnegative_float(raw: Any, field: str) -> float | None:
|
| 560 |
+
if raw is None or raw == "":
|
| 561 |
+
return None
|
| 562 |
+
try:
|
| 563 |
+
value = float(raw)
|
| 564 |
+
except (TypeError, ValueError) as exc:
|
| 565 |
+
raise ValueError(f"{field} must be a non-negative number") from exc
|
| 566 |
+
if value < 0:
|
| 567 |
+
raise ValueError(f"{field} must be a non-negative number")
|
| 568 |
+
return value
|
| 569 |
+
|
| 570 |
+
|
| 571 |
def _security_scan_state(
|
| 572 |
raw: dict[str, Any] | None,
|
| 573 |
*,
|
src/ctx/adapters/loopflow.py
CHANGED
|
@@ -129,8 +129,11 @@ def _build_query(
|
|
| 129 |
def _compact_row(row: dict[str, Any]) -> dict[str, Any]:
|
| 130 |
compact: dict[str, Any] = {}
|
| 131 |
for key in (
|
|
|
|
| 132 |
"name",
|
| 133 |
"type",
|
|
|
|
|
|
|
| 134 |
"score",
|
| 135 |
"normalized_score",
|
| 136 |
"fit_score",
|
|
@@ -145,6 +148,9 @@ def _compact_row(row: dict[str, Any]) -> dict[str, Any]:
|
|
| 145 |
"category",
|
| 146 |
"invoke_command",
|
| 147 |
"security_review",
|
|
|
|
|
|
|
|
|
|
| 148 |
):
|
| 149 |
value = row.get(key)
|
| 150 |
if value not in (None, "", [], {}):
|
|
@@ -185,6 +191,29 @@ def _group_bundle(
|
|
| 185 |
return grouped
|
| 186 |
|
| 187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
def _harness_command(
|
| 189 |
harnesses: list[dict[str, Any]],
|
| 190 |
*,
|
|
@@ -279,6 +308,8 @@ def recommend_for_loop(
|
|
| 279 |
model_provider: str | None = None,
|
| 280 |
model: str | None = None,
|
| 281 |
harness_requirements: dict[str, str] | None = None,
|
|
|
|
|
|
|
| 282 |
top_k: int = 5,
|
| 283 |
) -> dict[str, Any]:
|
| 284 |
"""Return a permissioned ctx adapter payload for a DSL or agent loop.
|
|
@@ -328,6 +359,19 @@ def recommend_for_loop(
|
|
| 328 |
top_k=safe_top_k,
|
| 329 |
)
|
| 330 |
capability_bundle.update(_group_bundle(rows, permissions=granted, top_k=safe_top_k))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
warnings: list[str] = []
|
| 333 |
if unknown_requirement_keys:
|
|
@@ -393,6 +437,7 @@ def recommend_for_loop(
|
|
| 393 |
"tools": mcp_server_tools,
|
| 394 |
},
|
| 395 |
"capabilities": capability_bundle,
|
|
|
|
| 396 |
"loopflow": {
|
| 397 |
"use_tools": use_tools,
|
| 398 |
"use_skills": use_skills,
|
|
@@ -425,6 +470,18 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
| 425 |
parser.add_argument("--done-when", action="append", default=[], help="Verification/check hint.")
|
| 426 |
parser.add_argument("--last-failure", default="", help="Previous failure text.")
|
| 427 |
parser.add_argument("--last-failure-file", type=Path, help="Read previous failure from a file.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
parser.add_argument(
|
| 429 |
"--permissions",
|
| 430 |
action="append",
|
|
@@ -499,6 +556,8 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 499 |
model_provider=args.model_provider,
|
| 500 |
model=args.model,
|
| 501 |
harness_requirements={key: value for key, value in requirements.items() if value},
|
|
|
|
|
|
|
| 502 |
top_k=args.top_k,
|
| 503 |
)
|
| 504 |
json.dump(payload, sys.stdout, indent=None if args.compact else 2, sort_keys=True)
|
|
|
|
| 129 |
def _compact_row(row: dict[str, Any]) -> dict[str, Any]:
|
| 130 |
compact: dict[str, Any] = {}
|
| 131 |
for key in (
|
| 132 |
+
"id",
|
| 133 |
"name",
|
| 134 |
"type",
|
| 135 |
+
"tldr",
|
| 136 |
+
"reason",
|
| 137 |
"score",
|
| 138 |
"normalized_score",
|
| 139 |
"fit_score",
|
|
|
|
| 148 |
"category",
|
| 149 |
"invoke_command",
|
| 150 |
"security_review",
|
| 151 |
+
"selected",
|
| 152 |
+
"selection_state",
|
| 153 |
+
"related_to",
|
| 154 |
):
|
| 155 |
value = row.get(key)
|
| 156 |
if value not in (None, "", [], {}):
|
|
|
|
| 191 |
return grouped
|
| 192 |
|
| 193 |
|
| 194 |
+
def _filter_related_rows(
|
| 195 |
+
rows: list[dict[str, Any]],
|
| 196 |
+
*,
|
| 197 |
+
permissions: set[str],
|
| 198 |
+
top_k: int,
|
| 199 |
+
) -> list[dict[str, Any]]:
|
| 200 |
+
filtered: list[dict[str, Any]] = []
|
| 201 |
+
seen: set[tuple[str, str]] = set()
|
| 202 |
+
for row in rows:
|
| 203 |
+
group = _ENTITY_TO_GROUP.get(str(row.get("type") or ""))
|
| 204 |
+
name = str(row.get("name") or "").strip()
|
| 205 |
+
if group is None or group not in permissions or not name:
|
| 206 |
+
continue
|
| 207 |
+
identity = (group, name)
|
| 208 |
+
if identity in seen:
|
| 209 |
+
continue
|
| 210 |
+
seen.add(identity)
|
| 211 |
+
filtered.append(_compact_row(row))
|
| 212 |
+
if len(filtered) >= top_k:
|
| 213 |
+
break
|
| 214 |
+
return filtered
|
| 215 |
+
|
| 216 |
+
|
| 217 |
def _harness_command(
|
| 218 |
harnesses: list[dict[str, Any]],
|
| 219 |
*,
|
|
|
|
| 308 |
model_provider: str | None = None,
|
| 309 |
model: str | None = None,
|
| 310 |
harness_requirements: dict[str, str] | None = None,
|
| 311 |
+
selected: list[str] | None = None,
|
| 312 |
+
rejected: list[str] | None = None,
|
| 313 |
top_k: int = 5,
|
| 314 |
) -> dict[str, Any]:
|
| 315 |
"""Return a permissioned ctx adapter payload for a DSL or agent loop.
|
|
|
|
| 359 |
top_k=safe_top_k,
|
| 360 |
)
|
| 361 |
capability_bundle.update(_group_bundle(rows, permissions=granted, top_k=safe_top_k))
|
| 362 |
+
selected_ids = [value.strip() for value in (selected or []) if value.strip()]
|
| 363 |
+
rejected_ids = [value.strip() for value in (rejected or []) if value.strip()]
|
| 364 |
+
related_recommendations: list[dict[str, Any]] = []
|
| 365 |
+
if selected_ids and granted.intersection({"skills", "agents", "mcps"}):
|
| 366 |
+
related_recommendations = _filter_related_rows(
|
| 367 |
+
ctx_api.recommend_related(
|
| 368 |
+
selected_ids,
|
| 369 |
+
rejected=rejected_ids,
|
| 370 |
+
top_n=50,
|
| 371 |
+
),
|
| 372 |
+
permissions=granted,
|
| 373 |
+
top_k=safe_top_k,
|
| 374 |
+
)
|
| 375 |
|
| 376 |
warnings: list[str] = []
|
| 377 |
if unknown_requirement_keys:
|
|
|
|
| 437 |
"tools": mcp_server_tools,
|
| 438 |
},
|
| 439 |
"capabilities": capability_bundle,
|
| 440 |
+
"related_recommendations": related_recommendations,
|
| 441 |
"loopflow": {
|
| 442 |
"use_tools": use_tools,
|
| 443 |
"use_skills": use_skills,
|
|
|
|
| 470 |
parser.add_argument("--done-when", action="append", default=[], help="Verification/check hint.")
|
| 471 |
parser.add_argument("--last-failure", default="", help="Previous failure text.")
|
| 472 |
parser.add_argument("--last-failure-file", type=Path, help="Read previous failure from a file.")
|
| 473 |
+
parser.add_argument(
|
| 474 |
+
"--selected",
|
| 475 |
+
action="append",
|
| 476 |
+
default=[],
|
| 477 |
+
help="Comma-separated selected ctx recommendation IDs or names.",
|
| 478 |
+
)
|
| 479 |
+
parser.add_argument(
|
| 480 |
+
"--rejected",
|
| 481 |
+
action="append",
|
| 482 |
+
default=[],
|
| 483 |
+
help="Comma-separated rejected ctx recommendation IDs or names.",
|
| 484 |
+
)
|
| 485 |
parser.add_argument(
|
| 486 |
"--permissions",
|
| 487 |
action="append",
|
|
|
|
| 556 |
model_provider=args.model_provider,
|
| 557 |
model=args.model,
|
| 558 |
harness_requirements={key: value for key, value in requirements.items() if value},
|
| 559 |
+
selected=_split_csv(args.selected),
|
| 560 |
+
rejected=_split_csv(args.rejected),
|
| 561 |
top_k=args.top_k,
|
| 562 |
)
|
| 563 |
json.dump(payload, sys.stdout, indent=None if args.compact else 2, sort_keys=True)
|
src/ctx/api.py
CHANGED
|
@@ -33,6 +33,9 @@ Public functions:
|
|
| 33 |
recommend_bundle(query, *, top_k=5)
|
| 34 |
Free-text → ranked skill/agent/MCP execution bundle.
|
| 35 |
|
|
|
|
|
|
|
|
|
|
| 36 |
graph_query(seeds, *, max_hops=2, top_n=10)
|
| 37 |
Walk the knowledge graph from seed entity names.
|
| 38 |
|
|
@@ -76,6 +79,7 @@ from ctx.telemetry import hash_identifier, record_event, record_exception, telem
|
|
| 76 |
|
| 77 |
__all__ = [
|
| 78 |
"recommend_bundle",
|
|
|
|
| 79 |
"graph_query",
|
| 80 |
"wiki_search",
|
| 81 |
"wiki_get",
|
|
@@ -90,6 +94,7 @@ __all__ = [
|
|
| 90 |
_default_toolbox: CtxCoreToolbox | None = None
|
| 91 |
_TOOL_EVENT_NAMES = {
|
| 92 |
"ctx__recommend_bundle": "ctx.api.recommend_bundle",
|
|
|
|
| 93 |
"ctx__graph_query": "ctx.api.graph_query",
|
| 94 |
"ctx__wiki_search": "ctx.api.wiki_search",
|
| 95 |
"ctx__wiki_get": "ctx.api.wiki_get",
|
|
@@ -130,6 +135,11 @@ def _safe_argument_payload(tool_name: str, arguments: dict[str, Any]) -> dict[st
|
|
| 130 |
if isinstance(seeds, (list, tuple)):
|
| 131 |
payload["ctx.seeds.count"] = len(seeds)
|
| 132 |
payload["ctx.seeds.hash"] = _hash_json_value(list(seeds))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
slug = arguments.get("slug")
|
| 134 |
if isinstance(slug, str):
|
| 135 |
payload["ctx.slug.hash"] = hash_identifier(slug)
|
|
@@ -251,6 +261,33 @@ def recommend_bundle(
|
|
| 251 |
return payload.get("results", []) if "error" not in payload else []
|
| 252 |
|
| 253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
def graph_query(
|
| 255 |
seeds: list[str],
|
| 256 |
*,
|
|
|
|
| 33 |
recommend_bundle(query, *, top_k=5)
|
| 34 |
Free-text → ranked skill/agent/MCP execution bundle.
|
| 35 |
|
| 36 |
+
recommend_related(selected, *, rejected=None, max_hops=2, top_n=5)
|
| 37 |
+
Selected recommendation IDs → related filtered recommendations.
|
| 38 |
+
|
| 39 |
graph_query(seeds, *, max_hops=2, top_n=10)
|
| 40 |
Walk the knowledge graph from seed entity names.
|
| 41 |
|
|
|
|
| 79 |
|
| 80 |
__all__ = [
|
| 81 |
"recommend_bundle",
|
| 82 |
+
"recommend_related",
|
| 83 |
"graph_query",
|
| 84 |
"wiki_search",
|
| 85 |
"wiki_get",
|
|
|
|
| 94 |
_default_toolbox: CtxCoreToolbox | None = None
|
| 95 |
_TOOL_EVENT_NAMES = {
|
| 96 |
"ctx__recommend_bundle": "ctx.api.recommend_bundle",
|
| 97 |
+
"ctx__recommend_related": "ctx.api.recommend_related",
|
| 98 |
"ctx__graph_query": "ctx.api.graph_query",
|
| 99 |
"ctx__wiki_search": "ctx.api.wiki_search",
|
| 100 |
"ctx__wiki_get": "ctx.api.wiki_get",
|
|
|
|
| 135 |
if isinstance(seeds, (list, tuple)):
|
| 136 |
payload["ctx.seeds.count"] = len(seeds)
|
| 137 |
payload["ctx.seeds.hash"] = _hash_json_value(list(seeds))
|
| 138 |
+
for key in ("selected", "rejected"):
|
| 139 |
+
values = arguments.get(key)
|
| 140 |
+
if isinstance(values, (list, tuple)):
|
| 141 |
+
payload[f"ctx.selection.{key}.count"] = len(values)
|
| 142 |
+
payload[f"ctx.selection.{key}.hash"] = _hash_json_value(list(values))
|
| 143 |
slug = arguments.get("slug")
|
| 144 |
if isinstance(slug, str):
|
| 145 |
payload["ctx.slug.hash"] = hash_identifier(slug)
|
|
|
|
| 261 |
return payload.get("results", []) if "error" not in payload else []
|
| 262 |
|
| 263 |
|
| 264 |
+
def recommend_related(
|
| 265 |
+
selected: list[str],
|
| 266 |
+
*,
|
| 267 |
+
rejected: list[str] | None = None,
|
| 268 |
+
max_hops: int = 2,
|
| 269 |
+
top_n: int = 5,
|
| 270 |
+
) -> list[dict[str, Any]]:
|
| 271 |
+
"""Return graph-related recommendations after a partial selection.
|
| 272 |
+
|
| 273 |
+
``selected`` and ``rejected`` accept recommendation IDs such as
|
| 274 |
+
``skill:fastapi-pro`` or bare entity names such as ``fastapi-pro``.
|
| 275 |
+
Returned rows use the same enriched recommendation contract as
|
| 276 |
+
``recommend_bundle`` and are marked ``selection_state='suggested_related'``.
|
| 277 |
+
Empty list on missing graph or invalid inputs.
|
| 278 |
+
"""
|
| 279 |
+
payload = _call(
|
| 280 |
+
"ctx__recommend_related",
|
| 281 |
+
{
|
| 282 |
+
"selected": selected,
|
| 283 |
+
"rejected": rejected or [],
|
| 284 |
+
"max_hops": max_hops,
|
| 285 |
+
"top_n": top_n,
|
| 286 |
+
},
|
| 287 |
+
)
|
| 288 |
+
return payload.get("results", []) if "error" not in payload else []
|
| 289 |
+
|
| 290 |
+
|
| 291 |
def graph_query(
|
| 292 |
seeds: list[str],
|
| 293 |
*,
|
src/ctx/cli/recommend.py
CHANGED
|
@@ -7,7 +7,7 @@ import json
|
|
| 7 |
import sys
|
| 8 |
from typing import Any
|
| 9 |
|
| 10 |
-
from ctx import recommend_bundle
|
| 11 |
from ctx_config import cfg
|
| 12 |
|
| 13 |
|
|
@@ -28,10 +28,43 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
| 28 |
help=f"Maximum results to show (default {cfg.recommendation_top_k}, max 5).",
|
| 29 |
)
|
| 30 |
parser.add_argument("--json", action="store_true", help="Emit JSON.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
return parser
|
| 32 |
|
| 33 |
|
| 34 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
name = str(row.get("name") or row.get("slug") or "")
|
| 36 |
entity_type = str(row.get("type") or row.get("entity_type") or "skill")
|
| 37 |
score = row.get("normalized_score", row.get("score", 0.0))
|
|
@@ -46,22 +79,62 @@ def _render_row(row: dict[str, Any]) -> str:
|
|
| 46 |
action_text = f" run={action}" if action else ""
|
| 47 |
category = row.get("category")
|
| 48 |
category_text = f" category={category}" if category else ""
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
def main(argv: list[str] | None = None) -> int:
|
| 53 |
args = _build_parser().parse_args(argv)
|
| 54 |
query = " ".join(args.query).strip()
|
| 55 |
top_k = max(1, min(int(args.top_k), cfg.recommendation_top_k))
|
|
|
|
|
|
|
|
|
|
| 56 |
results = recommend_bundle(query, top_k=top_k)
|
|
|
|
|
|
|
|
|
|
| 57 |
if args.json:
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
return 0
|
| 60 |
if not results:
|
| 61 |
print("No recommendations above the configured score threshold.", file=sys.stderr)
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
return 0
|
| 66 |
|
| 67 |
|
|
|
|
| 7 |
import sys
|
| 8 |
from typing import Any
|
| 9 |
|
| 10 |
+
from ctx import recommend_bundle, recommend_related
|
| 11 |
from ctx_config import cfg
|
| 12 |
|
| 13 |
|
|
|
|
| 28 |
help=f"Maximum results to show (default {cfg.recommendation_top_k}, max 5).",
|
| 29 |
)
|
| 30 |
parser.add_argument("--json", action="store_true", help="Emit JSON.")
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--selected",
|
| 33 |
+
action="append",
|
| 34 |
+
default=[],
|
| 35 |
+
help=(
|
| 36 |
+
"Selected recommendation ID/name. May be repeated or comma-separated; "
|
| 37 |
+
"enables related recommendations."
|
| 38 |
+
),
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"--rejected",
|
| 42 |
+
action="append",
|
| 43 |
+
default=[],
|
| 44 |
+
help="Rejected recommendation ID/name. May be repeated or comma-separated.",
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--related-top-n",
|
| 48 |
+
type=int,
|
| 49 |
+
default=cfg.recommendation_top_k,
|
| 50 |
+
help=f"Maximum related results to show (default {cfg.recommendation_top_k}, max 5).",
|
| 51 |
+
)
|
| 52 |
return parser
|
| 53 |
|
| 54 |
|
| 55 |
+
def _split_selection_values(values: list[str] | None) -> list[str]:
|
| 56 |
+
selections: list[str] = []
|
| 57 |
+
seen: set[str] = set()
|
| 58 |
+
for value in values or []:
|
| 59 |
+
for part in value.split(","):
|
| 60 |
+
item = part.strip()
|
| 61 |
+
if item and item not in seen:
|
| 62 |
+
selections.append(item)
|
| 63 |
+
seen.add(item)
|
| 64 |
+
return selections
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _render_row(row: dict[str, Any], *, index: int | None = None) -> str:
|
| 68 |
name = str(row.get("name") or row.get("slug") or "")
|
| 69 |
entity_type = str(row.get("type") or row.get("entity_type") or "skill")
|
| 70 |
score = row.get("normalized_score", row.get("score", 0.0))
|
|
|
|
| 79 |
action_text = f" run={action}" if action else ""
|
| 80 |
category = row.get("category")
|
| 81 |
category_text = f" category={category}" if category else ""
|
| 82 |
+
row_id = row.get("id")
|
| 83 |
+
row_id_text = f" id={row_id}" if row_id else ""
|
| 84 |
+
state = row.get("selection_state")
|
| 85 |
+
state_text = f" state={state}" if state else ""
|
| 86 |
+
related_to = row.get("related_to")
|
| 87 |
+
related_text = f" related_to={related_to}" if related_to else ""
|
| 88 |
+
prefix = f"{index:>2}. " if index is not None else ""
|
| 89 |
+
lines = [
|
| 90 |
+
(
|
| 91 |
+
f"{prefix}{entity_type:>10} {name:<40} "
|
| 92 |
+
f"score={score_text}{suffix}{category_text}{row_id_text}"
|
| 93 |
+
f"{state_text}{related_text}{action_text}"
|
| 94 |
+
)
|
| 95 |
+
]
|
| 96 |
+
tldr = row.get("tldr")
|
| 97 |
+
if tldr:
|
| 98 |
+
lines.append(f" {tldr}")
|
| 99 |
+
reason = row.get("reason")
|
| 100 |
+
if reason:
|
| 101 |
+
lines.append(f" reason={reason}")
|
| 102 |
+
return "\n".join(lines)
|
| 103 |
|
| 104 |
|
| 105 |
def main(argv: list[str] | None = None) -> int:
|
| 106 |
args = _build_parser().parse_args(argv)
|
| 107 |
query = " ".join(args.query).strip()
|
| 108 |
top_k = max(1, min(int(args.top_k), cfg.recommendation_top_k))
|
| 109 |
+
related_top_n = max(1, min(int(args.related_top_n), cfg.recommendation_top_k))
|
| 110 |
+
selected = _split_selection_values(args.selected)
|
| 111 |
+
rejected = _split_selection_values(args.rejected)
|
| 112 |
results = recommend_bundle(query, top_k=top_k)
|
| 113 |
+
related_results = (
|
| 114 |
+
recommend_related(selected, rejected=rejected, top_n=related_top_n) if selected else []
|
| 115 |
+
)
|
| 116 |
if args.json:
|
| 117 |
+
payload: dict[str, Any] = {"query": query, "results": results}
|
| 118 |
+
if selected or rejected:
|
| 119 |
+
payload["selection"] = {
|
| 120 |
+
"selected": selected,
|
| 121 |
+
"rejected": rejected,
|
| 122 |
+
"related_results": related_results,
|
| 123 |
+
}
|
| 124 |
+
print(json.dumps(payload, indent=2))
|
| 125 |
return 0
|
| 126 |
if not results:
|
| 127 |
print("No recommendations above the configured score threshold.", file=sys.stderr)
|
| 128 |
+
else:
|
| 129 |
+
for index, row in enumerate(results, start=1):
|
| 130 |
+
print(_render_row(row, index=index))
|
| 131 |
+
if selected:
|
| 132 |
+
print("\nRelated recommendations:")
|
| 133 |
+
if related_results:
|
| 134 |
+
for index, row in enumerate(related_results, start=1):
|
| 135 |
+
print(_render_row(row, index=index))
|
| 136 |
+
else:
|
| 137 |
+
print(" No related recommendations above the configured score threshold.")
|
| 138 |
return 0
|
| 139 |
|
| 140 |
|
src/ctx/cli/run.py
CHANGED
|
@@ -58,6 +58,10 @@ from ctx.telemetry import record_event, record_exception, telemetry_span
|
|
| 58 |
|
| 59 |
_logger = logging.getLogger(__name__)
|
| 60 |
_CTX_SESSION_MARKER = "ctx runtime session id:"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
_MODEL_PROFILE_NAME = "ctx-model-profile.json"
|
| 62 |
_GITHUB_MCP_CREDENTIAL_ENV = (
|
| 63 |
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
|
@@ -450,7 +454,9 @@ def _with_ctx_session_instructions(system_prompt: str, session_id: str) -> str:
|
|
| 450 |
+ "Record ctx__load_entity when the user/host chooses a recommended "
|
| 451 |
+ "skill, agent, MCP server, or harness; record ctx__mark_entity_used "
|
| 452 |
+ "when it materially helps; call ctx__unload_entity only after user "
|
| 453 |
-
+ "confirmation or an explicit skip/unload instruction.
|
|
|
|
|
|
|
| 454 |
)
|
| 455 |
|
| 456 |
|
|
@@ -586,12 +592,32 @@ def _loop_result_payload(result: Any) -> dict[str, Any]:
|
|
| 586 |
payload["ctx.iterations"] = int(getattr(result, "iterations", 0) or 0)
|
| 587 |
usage = getattr(result, "usage", None)
|
| 588 |
if usage is not None:
|
| 589 |
-
|
| 590 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
payload["ctx.usage.cost_present"] = getattr(usage, "cost_usd", None) is not None
|
| 592 |
return payload
|
| 593 |
|
| 594 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 595 |
def _loop_result_outcome(result: Any) -> tuple[str, str | None]:
|
| 596 |
stop_reason = str(getattr(result, "stop_reason", "error"))
|
| 597 |
if result is None or stop_reason in _ERROR_STOP_REASONS:
|
|
@@ -1550,6 +1576,7 @@ def _emit_result(
|
|
| 1550 |
"output_tokens": result.usage.output_tokens,
|
| 1551 |
"cost_usd": result.usage.cost_usd,
|
| 1552 |
},
|
|
|
|
| 1553 |
"detail": result.detail,
|
| 1554 |
}
|
| 1555 |
if evaluator_rounds is not None:
|
|
@@ -1559,7 +1586,8 @@ def _emit_result(
|
|
| 1559 |
if not quiet:
|
| 1560 |
print(
|
| 1561 |
f"\n[ctx] stop={result.stop_reason} iterations={result.iterations} "
|
| 1562 |
-
f"tokens={result.usage.input_tokens + result.usage.output_tokens}"
|
|
|
|
| 1563 |
file=sys.stderr,
|
| 1564 |
)
|
| 1565 |
if result.usage.cost_usd is not None:
|
|
|
|
| 58 |
|
| 59 |
_logger = logging.getLogger(__name__)
|
| 60 |
_CTX_SESSION_MARKER = "ctx runtime session id:"
|
| 61 |
+
_SESSION_USAGE_ATTRIBUTION_REASON = (
|
| 62 |
+
"ctx run provider usage is aggregated across the session; exact per-tool "
|
| 63 |
+
"token attribution requires host-supplied ctx__mark_entity_used.token_usage."
|
| 64 |
+
)
|
| 65 |
_MODEL_PROFILE_NAME = "ctx-model-profile.json"
|
| 66 |
_GITHUB_MCP_CREDENTIAL_ENV = (
|
| 67 |
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
|
|
|
| 454 |
+ "Record ctx__load_entity when the user/host chooses a recommended "
|
| 455 |
+ "skill, agent, MCP server, or harness; record ctx__mark_entity_used "
|
| 456 |
+ "when it materially helps; call ctx__unload_entity only after user "
|
| 457 |
+
+ "confirmation or an explicit skip/unload instruction. Include "
|
| 458 |
+
+ "ctx__mark_entity_used.token_usage only when exact per-entity usage "
|
| 459 |
+
+ "is available; do not allocate session totals across tools.\n"
|
| 460 |
)
|
| 461 |
|
| 462 |
|
|
|
|
| 592 |
payload["ctx.iterations"] = int(getattr(result, "iterations", 0) or 0)
|
| 593 |
usage = getattr(result, "usage", None)
|
| 594 |
if usage is not None:
|
| 595 |
+
input_tokens = int(getattr(usage, "input_tokens", 0) or 0)
|
| 596 |
+
output_tokens = int(getattr(usage, "output_tokens", 0) or 0)
|
| 597 |
+
payload["ctx.usage.input_tokens"] = input_tokens
|
| 598 |
+
payload["ctx.usage.output_tokens"] = output_tokens
|
| 599 |
+
payload["ctx.usage.total_tokens"] = input_tokens + output_tokens
|
| 600 |
+
payload["ctx.usage.scope"] = "session"
|
| 601 |
+
payload["ctx.usage.attribution"] = "unavailable"
|
| 602 |
+
payload["ctx.usage.attribution_reason"] = _SESSION_USAGE_ATTRIBUTION_REASON
|
| 603 |
payload["ctx.usage.cost_present"] = getattr(usage, "cost_usd", None) is not None
|
| 604 |
return payload
|
| 605 |
|
| 606 |
|
| 607 |
+
def _usage_attribution_summary(usage: Any) -> dict[str, Any]:
|
| 608 |
+
input_tokens = int(getattr(usage, "input_tokens", 0) or 0)
|
| 609 |
+
output_tokens = int(getattr(usage, "output_tokens", 0) or 0)
|
| 610 |
+
return {
|
| 611 |
+
"scope": "session",
|
| 612 |
+
"attribution": "unavailable",
|
| 613 |
+
"attribution_reason": _SESSION_USAGE_ATTRIBUTION_REASON,
|
| 614 |
+
"input_tokens": input_tokens,
|
| 615 |
+
"output_tokens": output_tokens,
|
| 616 |
+
"total_tokens": input_tokens + output_tokens,
|
| 617 |
+
"cost_usd": getattr(usage, "cost_usd", None),
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
|
| 621 |
def _loop_result_outcome(result: Any) -> tuple[str, str | None]:
|
| 622 |
stop_reason = str(getattr(result, "stop_reason", "error"))
|
| 623 |
if result is None or stop_reason in _ERROR_STOP_REASONS:
|
|
|
|
| 1576 |
"output_tokens": result.usage.output_tokens,
|
| 1577 |
"cost_usd": result.usage.cost_usd,
|
| 1578 |
},
|
| 1579 |
+
"usage_attribution": _usage_attribution_summary(result.usage),
|
| 1580 |
"detail": result.detail,
|
| 1581 |
}
|
| 1582 |
if evaluator_rounds is not None:
|
|
|
|
| 1586 |
if not quiet:
|
| 1587 |
print(
|
| 1588 |
f"\n[ctx] stop={result.stop_reason} iterations={result.iterations} "
|
| 1589 |
+
f"tokens={result.usage.input_tokens + result.usage.output_tokens} "
|
| 1590 |
+
"usage_scope=session per_tool_usage=unavailable",
|
| 1591 |
file=sys.stderr,
|
| 1592 |
)
|
| 1593 |
if result.usage.cost_usd is not None:
|
src/ctx/mcp_server/__init__.py
CHANGED
|
@@ -2,10 +2,20 @@
|
|
| 2 |
harness can consume its recommendations.
|
| 3 |
|
| 4 |
Tools exposed:
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
Console script: ``ctx-mcp-server``.
|
| 11 |
|
|
|
|
| 2 |
harness can consume its recommendations.
|
| 3 |
|
| 4 |
Tools exposed:
|
| 5 |
+
ctx__recommend_bundle(query, top_k=5)
|
| 6 |
+
top-K skill/agent/MCP recommendations with selection metadata
|
| 7 |
+
ctx__recommend_related(selected, rejected=None, max_hops=2, top_n=5)
|
| 8 |
+
graph-backed suggestions after a partial selection
|
| 9 |
+
ctx__graph_query(seeds, max_hops=2, top_n=10)
|
| 10 |
+
graph walk from seed entities
|
| 11 |
+
ctx__wiki_search(query, top_n=15)
|
| 12 |
+
search the llm-wiki
|
| 13 |
+
ctx__wiki_get(slug)
|
| 14 |
+
fetch a specific entity card
|
| 15 |
+
ctx__observe_dev_event / ctx__load_entity / ctx__mark_entity_used /
|
| 16 |
+
ctx__record_validation / ctx__record_escalation / ctx__unload_entity /
|
| 17 |
+
ctx__session_end / ctx__session_state
|
| 18 |
+
runtime lifecycle records and session state
|
| 19 |
|
| 20 |
Console script: ``ctx-mcp-server``.
|
| 21 |
|
src/ctx/mcp_server/server.py
CHANGED
|
@@ -22,13 +22,22 @@ Install into any MCP-aware host:
|
|
| 22 |
|
| 23 |
<host-specific config pointing at the ``ctx-mcp-server`` binary>
|
| 24 |
|
| 25 |
-
Tools exposed (same as ctx.adapters.generic.ctx_core_tools —
|
| 26 |
-
|
| 27 |
|
| 28 |
ctx__recommend_bundle(query, top_k=5)
|
|
|
|
| 29 |
ctx__graph_query(seeds, max_hops=2, top_n=10)
|
| 30 |
ctx__wiki_search(query, top_n=15)
|
| 31 |
ctx__wiki_get(slug)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
Protocol coverage mirrors H2's client implementation — the minimal
|
| 34 |
operational subset: initialize + initialized notification +
|
|
|
|
| 22 |
|
| 23 |
<host-specific config pointing at the ``ctx-mcp-server`` binary>
|
| 24 |
|
| 25 |
+
Tools exposed (same as ctx.adapters.generic.ctx_core_tools — that
|
| 26 |
+
module is the source of truth for the tool catalogue):
|
| 27 |
|
| 28 |
ctx__recommend_bundle(query, top_k=5)
|
| 29 |
+
ctx__recommend_related(selected, rejected=None, max_hops=2, top_n=5)
|
| 30 |
ctx__graph_query(seeds, max_hops=2, top_n=10)
|
| 31 |
ctx__wiki_search(query, top_n=15)
|
| 32 |
ctx__wiki_get(slug)
|
| 33 |
+
ctx__observe_dev_event(...)
|
| 34 |
+
ctx__load_entity(...)
|
| 35 |
+
ctx__mark_entity_used(...)
|
| 36 |
+
ctx__record_validation(...)
|
| 37 |
+
ctx__record_escalation(...)
|
| 38 |
+
ctx__unload_entity(...)
|
| 39 |
+
ctx__session_end(...)
|
| 40 |
+
ctx__session_state(...)
|
| 41 |
|
| 42 |
Protocol coverage mirrors H2's client implementation — the minimal
|
| 43 |
operational subset: initialize + initialized notification +
|
src/ctx/monitor/app.py
CHANGED
|
@@ -22,6 +22,7 @@ class RouteDispatchDeps:
|
|
| 22 |
render_loaded: Callable[[bool], str]
|
| 23 |
render_logs: Callable[[], str]
|
| 24 |
render_graph: Callable[[str | None, str | None], str]
|
|
|
|
| 25 |
render_manage: Callable[[bool], str]
|
| 26 |
render_harness_wizard: Callable[[], str]
|
| 27 |
render_docs: Callable[[], str]
|
|
@@ -62,6 +63,8 @@ def handle_get_route(
|
|
| 62 |
handler._send_html(deps.render_logs())
|
| 63 |
elif name == "graph":
|
| 64 |
handler._send_html(deps.render_graph(qs.get("slug"), qs.get("type")))
|
|
|
|
|
|
|
| 65 |
elif name == "manage":
|
| 66 |
handler._send_html(deps.render_manage(handler._mutations_enabled()))
|
| 67 |
elif name == "harness":
|
|
|
|
| 22 |
render_loaded: Callable[[bool], str]
|
| 23 |
render_logs: Callable[[], str]
|
| 24 |
render_graph: Callable[[str | None, str | None], str]
|
| 25 |
+
render_recommendations: Callable[[dict[str, str]], str]
|
| 26 |
render_manage: Callable[[bool], str]
|
| 27 |
render_harness_wizard: Callable[[], str]
|
| 28 |
render_docs: Callable[[], str]
|
|
|
|
| 63 |
handler._send_html(deps.render_logs())
|
| 64 |
elif name == "graph":
|
| 65 |
handler._send_html(deps.render_graph(qs.get("slug"), qs.get("type")))
|
| 66 |
+
elif name == "recommend":
|
| 67 |
+
handler._send_html(deps.render_recommendations(qs))
|
| 68 |
elif name == "manage":
|
| 69 |
handler._send_html(deps.render_manage(handler._mutations_enabled()))
|
| 70 |
elif name == "harness":
|
src/ctx/monitor/compat.py
CHANGED
|
@@ -18,19 +18,20 @@ Routes:
|
|
| 18 |
/wiki/<slug>?type=<entity> One wiki entity page (frontmatter + body)
|
| 19 |
/graph Built-in graph explorer + popular seeds
|
| 20 |
/graph?slug=<slug>&type=... Focus graph view on a specific entity
|
|
|
|
| 21 |
/manage Search/edit/delete/import catalog entities
|
| 22 |
/harness Manual harness setup for user-owned LLMs
|
| 23 |
/docs Local docs index + public docs handoff
|
| 24 |
/config Editable ctx config with defaults fallback
|
| 25 |
/status Durable queue + graph/wiki artifact state
|
| 26 |
/kpi Grade / lifecycle / category KPIs
|
| 27 |
-
/runtime Generic harness
|
| 28 |
/logs Filterable tail of ctx-audit.jsonl
|
| 29 |
/events Live SSE stream of new audit-log lines
|
| 30 |
/api/sessions.json JSON index for scripting
|
| 31 |
/api/manifest.json Raw ~/.claude/skill-manifest.json
|
| 32 |
/api/status.json Queue counts + artifact promotion metadata
|
| 33 |
-
/api/runtime.json Generic harness
|
| 34 |
/api/skillspector.json SkillSpector audit records + filters
|
| 35 |
/api/skill/<slug>.json Sidecar passthrough
|
| 36 |
/api/graph/<slug>.json Dashboard-shaped neighborhood; accepts type
|
|
@@ -68,6 +69,7 @@ from pathlib import Path
|
|
| 68 |
from typing import Any
|
| 69 |
from urllib.parse import quote
|
| 70 |
|
|
|
|
| 71 |
from ctx import dashboard_entities
|
| 72 |
from ctx.core import entity_types as core_entity_types
|
| 73 |
from ctx.core.quality.skillspector_service import render_scan_report
|
|
@@ -92,6 +94,7 @@ from ctx.monitor.pages import home as _home_page
|
|
| 92 |
from ctx.monitor.pages import loaded as _loaded_page
|
| 93 |
from ctx.monitor.pages import manage as _manage_page
|
| 94 |
from ctx.monitor.pages import ops as _ops_page
|
|
|
|
| 95 |
from ctx.monitor.pages import skills as _skills_page
|
| 96 |
from ctx.monitor.pages import skillspector as _skillspector_page
|
| 97 |
from ctx.monitor.pages import wiki as _wiki_page
|
|
@@ -1443,6 +1446,19 @@ def _render_runtime_lifecycle() -> str:
|
|
| 1443 |
)
|
| 1444 |
|
| 1445 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1446 |
def _render_logs() -> str:
|
| 1447 |
return _activity_page.render_logs(
|
| 1448 |
layout=_layout,
|
|
@@ -1513,6 +1529,7 @@ def _route_dispatch_deps() -> _monitor_app.RouteDispatchDeps:
|
|
| 1513 |
render_loaded=_render_loaded,
|
| 1514 |
render_logs=_render_logs,
|
| 1515 |
render_graph=_render_graph,
|
|
|
|
| 1516 |
render_manage=_render_manage,
|
| 1517 |
render_harness_wizard=_render_harness_wizard,
|
| 1518 |
render_docs=_render_docs,
|
|
|
|
| 18 |
/wiki/<slug>?type=<entity> One wiki entity page (frontmatter + body)
|
| 19 |
/graph Built-in graph explorer + popular seeds
|
| 20 |
/graph?slug=<slug>&type=... Focus graph view on a specific entity
|
| 21 |
+
/recommend Select ctx recommendations + related rows
|
| 22 |
/manage Search/edit/delete/import catalog entities
|
| 23 |
/harness Manual harness setup for user-owned LLMs
|
| 24 |
/docs Local docs index + public docs handoff
|
| 25 |
/config Editable ctx config with defaults fallback
|
| 26 |
/status Durable queue + graph/wiki artifact state
|
| 27 |
/kpi Grade / lifecycle / category KPIs
|
| 28 |
+
/runtime Generic harness lifecycle, selection, and token ledger
|
| 29 |
/logs Filterable tail of ctx-audit.jsonl
|
| 30 |
/events Live SSE stream of new audit-log lines
|
| 31 |
/api/sessions.json JSON index for scripting
|
| 32 |
/api/manifest.json Raw ~/.claude/skill-manifest.json
|
| 33 |
/api/status.json Queue counts + artifact promotion metadata
|
| 34 |
+
/api/runtime.json Generic harness lifecycle, selection, and token summary
|
| 35 |
/api/skillspector.json SkillSpector audit records + filters
|
| 36 |
/api/skill/<slug>.json Sidecar passthrough
|
| 37 |
/api/graph/<slug>.json Dashboard-shaped neighborhood; accepts type
|
|
|
|
| 69 |
from typing import Any
|
| 70 |
from urllib.parse import quote
|
| 71 |
|
| 72 |
+
from ctx import api as _ctx_api
|
| 73 |
from ctx import dashboard_entities
|
| 74 |
from ctx.core import entity_types as core_entity_types
|
| 75 |
from ctx.core.quality.skillspector_service import render_scan_report
|
|
|
|
| 94 |
from ctx.monitor.pages import loaded as _loaded_page
|
| 95 |
from ctx.monitor.pages import manage as _manage_page
|
| 96 |
from ctx.monitor.pages import ops as _ops_page
|
| 97 |
+
from ctx.monitor.pages import recommend as _recommend_page
|
| 98 |
from ctx.monitor.pages import skills as _skills_page
|
| 99 |
from ctx.monitor.pages import skillspector as _skillspector_page
|
| 100 |
from ctx.monitor.pages import wiki as _wiki_page
|
|
|
|
| 1446 |
)
|
| 1447 |
|
| 1448 |
|
| 1449 |
+
def _render_recommendations(qs: dict[str, str] | None = None) -> str:
|
| 1450 |
+
return _recommend_page.render_recommendations(
|
| 1451 |
+
layout=_layout,
|
| 1452 |
+
query=qs or {},
|
| 1453 |
+
recommend_bundle=lambda query, top_k: _ctx_api.recommend_bundle(query, top_k=top_k),
|
| 1454 |
+
recommend_related=lambda selected, rejected, top_n: _ctx_api.recommend_related(
|
| 1455 |
+
selected,
|
| 1456 |
+
rejected=rejected,
|
| 1457 |
+
top_n=top_n,
|
| 1458 |
+
),
|
| 1459 |
+
)
|
| 1460 |
+
|
| 1461 |
+
|
| 1462 |
def _render_logs() -> str:
|
| 1463 |
return _activity_page.render_logs(
|
| 1464 |
layout=_layout,
|
|
|
|
| 1529 |
render_loaded=_render_loaded,
|
| 1530 |
render_logs=_render_logs,
|
| 1531 |
render_graph=_render_graph,
|
| 1532 |
+
render_recommendations=_render_recommendations,
|
| 1533 |
render_manage=_render_manage,
|
| 1534 |
render_harness_wizard=_render_harness_wizard,
|
| 1535 |
render_docs=_render_docs,
|
src/ctx/monitor/pages/activity.py
CHANGED
|
@@ -161,6 +161,36 @@ def render_runtime_lifecycle(
|
|
| 161 |
"</tr>"
|
| 162 |
for event in reversed(summary["open_escalations"])
|
| 163 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
body = (
|
| 166 |
"<h1>Runtime lifecycle</h1>"
|
|
@@ -171,6 +201,35 @@ def render_runtime_lifecycle(
|
|
| 171 |
f"<br><span class='muted'>source: <code>{html.escape(summary['path'])}</code></span>"
|
| 172 |
" / <a href='/api/runtime.json'>JSON</a>"
|
| 173 |
"</div>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
"<div class='card'><strong>Recent validations</strong>"
|
| 175 |
+ (
|
| 176 |
"<table><tr><th>Created</th><th>Check</th><th>Status</th>"
|
|
|
|
| 161 |
"</tr>"
|
| 162 |
for event in reversed(summary["open_escalations"])
|
| 163 |
)
|
| 164 |
+
selection = summary.get("tool_selection") or {}
|
| 165 |
+
sources = selection.get("selection_sources") or {}
|
| 166 |
+
source_rows = "".join(
|
| 167 |
+
f"<tr><td>{html.escape(str(source))}</td><td>{html.escape(str(count))}</td></tr>"
|
| 168 |
+
for source, count in sorted(sources.items())
|
| 169 |
+
)
|
| 170 |
+
token_usage = summary.get("token_usage") or {}
|
| 171 |
+
by_attribution = token_usage.get("by_attribution") or {}
|
| 172 |
+
attribution_rows = "".join(
|
| 173 |
+
f"<tr><td>{html.escape(str(attribution))}</td><td>{html.escape(str(count))}</td></tr>"
|
| 174 |
+
for attribution, count in sorted(by_attribution.items())
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def usage_cell(row: dict[str, Any], key: str) -> str:
|
| 178 |
+
usage = row.get("token_usage")
|
| 179 |
+
if not isinstance(usage, dict):
|
| 180 |
+
return ""
|
| 181 |
+
return html.escape(str(usage.get(key) or ""))
|
| 182 |
+
|
| 183 |
+
recent_usage_rows = "".join(
|
| 184 |
+
"<tr>"
|
| 185 |
+
f"<td class='muted'>{event_cell(row, 'created_at')}</td>"
|
| 186 |
+
f"<td class='muted'>{event_cell(row, 'session_id')}</td>"
|
| 187 |
+
f"<td>{event_cell(row, 'entity_type')}</td>"
|
| 188 |
+
f"<td><code>{event_cell(row, 'slug')}</code></td>"
|
| 189 |
+
f"<td>{usage_cell(row, 'total_tokens')}</td>"
|
| 190 |
+
f"<td><span class='pill'>{usage_cell(row, 'attribution') or 'unavailable'}</span></td>"
|
| 191 |
+
"</tr>"
|
| 192 |
+
for row in reversed(summary.get("recent_tool_usage") or [])
|
| 193 |
+
)
|
| 194 |
|
| 195 |
body = (
|
| 196 |
"<h1>Runtime lifecycle</h1>"
|
|
|
|
| 201 |
f"<br><span class='muted'>source: <code>{html.escape(summary['path'])}</code></span>"
|
| 202 |
" / <a href='/api/runtime.json'>JSON</a>"
|
| 203 |
"</div>"
|
| 204 |
+
"<div class='card'><strong>Tool selection</strong>"
|
| 205 |
+
f"<p><strong>{selection.get('loaded_total', 0)}</strong> loaded / "
|
| 206 |
+
f"<strong>{selection.get('active_loaded_total', 0)}</strong> active / "
|
| 207 |
+
f"<strong>{selection.get('selected_total', 0)}</strong> selected / "
|
| 208 |
+
f"<strong>{selection.get('used_total', 0)}</strong> used</p>"
|
| 209 |
+
+ (
|
| 210 |
+
"<table><tr><th>Source</th><th>Loads</th></tr>" + source_rows + "</table>"
|
| 211 |
+
if source_rows
|
| 212 |
+
else "<p class='muted'>No tool selections recorded yet.</p>"
|
| 213 |
+
)
|
| 214 |
+
+ "</div>"
|
| 215 |
+
"<div class='card'><strong>Token usage</strong>"
|
| 216 |
+
f"<p><strong>{token_usage.get('records', 0)}</strong> records / "
|
| 217 |
+
f"<strong>{token_usage.get('total_tokens', 0)}</strong> tokens / "
|
| 218 |
+
f"<strong>${float(token_usage.get('cost_usd') or 0.0):.4f}</strong> cost</p>"
|
| 219 |
+
+ (
|
| 220 |
+
"<table><tr><th>Attribution</th><th>Records</th></tr>" + attribution_rows + "</table>"
|
| 221 |
+
if attribution_rows
|
| 222 |
+
else "<p class='muted'>No token usage records yet.</p>"
|
| 223 |
+
)
|
| 224 |
+
+ "</div>"
|
| 225 |
+
"<div class='card'><strong>Recent tool usage</strong>"
|
| 226 |
+
+ (
|
| 227 |
+
"<table><tr><th>Created</th><th>Session</th><th>Type</th><th>Slug</th>"
|
| 228 |
+
"<th>Tokens</th><th>Attribution</th></tr>" + recent_usage_rows + "</table>"
|
| 229 |
+
if recent_usage_rows
|
| 230 |
+
else "<p class='muted'>No tool usage recorded yet.</p>"
|
| 231 |
+
)
|
| 232 |
+
+ "</div>"
|
| 233 |
"<div class='card'><strong>Recent validations</strong>"
|
| 234 |
+ (
|
| 235 |
"<table><tr><th>Created</th><th>Check</th><th>Status</th>"
|
src/ctx/monitor/pages/ops.py
CHANGED
|
@@ -204,7 +204,7 @@ def render_status(
|
|
| 204 |
("wiki_packs", "wiki packs"),
|
| 205 |
("pack_compaction", "pack compaction"),
|
| 206 |
("wiki_graph_tar", "wiki-graph.tar.gz"),
|
| 207 |
-
("skills_sh_catalog", "
|
| 208 |
)
|
| 209 |
artifact_rows = "".join(
|
| 210 |
"<tr>"
|
|
|
|
| 204 |
("wiki_packs", "wiki packs"),
|
| 205 |
("pack_compaction", "pack compaction"),
|
| 206 |
("wiki_graph_tar", "wiki-graph.tar.gz"),
|
| 207 |
+
("skills_sh_catalog", "skills-sh-catalog.json.gz"),
|
| 208 |
)
|
| 209 |
artifact_rows = "".join(
|
| 210 |
"<tr>"
|
src/ctx/monitor/pages/recommend.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recommendation selection page renderer for ctx-monitor."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import html
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from typing import Any
|
| 8 |
+
from urllib.parse import urlencode
|
| 9 |
+
|
| 10 |
+
LayoutFn = Callable[[str, str], str]
|
| 11 |
+
RecommendFn = Callable[[str, int], list[dict[str, Any]]]
|
| 12 |
+
RelatedFn = Callable[[list[str], list[str], int], list[dict[str, Any]]]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _split_values(raw: str | None) -> list[str]:
|
| 16 |
+
values: list[str] = []
|
| 17 |
+
seen: set[str] = set()
|
| 18 |
+
for part in str(raw or "").split(","):
|
| 19 |
+
item = part.strip()
|
| 20 |
+
if item and item not in seen:
|
| 21 |
+
values.append(item)
|
| 22 |
+
seen.add(item)
|
| 23 |
+
return values
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _top_k(raw: str | None) -> int:
|
| 27 |
+
try:
|
| 28 |
+
value = int(raw or 5)
|
| 29 |
+
except ValueError:
|
| 30 |
+
value = 5
|
| 31 |
+
return max(1, min(value, 5))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _row_identity(row: dict[str, Any]) -> str:
|
| 35 |
+
row_id = row.get("id")
|
| 36 |
+
if row_id:
|
| 37 |
+
return str(row_id)
|
| 38 |
+
entity_type = str(row.get("type") or row.get("entity_type") or "skill")
|
| 39 |
+
name = str(row.get("name") or row.get("slug") or "")
|
| 40 |
+
return f"{entity_type}:{name}" if name else entity_type
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _row_cell(row: dict[str, Any], key: str, limit: int = 120) -> str:
|
| 44 |
+
return html.escape(str(row.get(key) or ""))[:limit]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _score_text(row: dict[str, Any]) -> str:
|
| 48 |
+
score = row.get("normalized_score", row.get("score", 0.0))
|
| 49 |
+
try:
|
| 50 |
+
return f"{float(score):.3f}"
|
| 51 |
+
except (TypeError, ValueError):
|
| 52 |
+
return html.escape(str(score))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _selected_link(query: str, top_k: int, selected: list[str], rejected: list[str]) -> str:
|
| 56 |
+
payload = {"q": query, "top_k": str(top_k)}
|
| 57 |
+
if selected:
|
| 58 |
+
payload["selected"] = ",".join(selected)
|
| 59 |
+
if rejected:
|
| 60 |
+
payload["rejected"] = ",".join(rejected)
|
| 61 |
+
return "/recommend?" + urlencode(payload)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _render_rows(
|
| 65 |
+
rows: list[dict[str, Any]],
|
| 66 |
+
*,
|
| 67 |
+
selected: list[str],
|
| 68 |
+
selectable: bool,
|
| 69 |
+
) -> str:
|
| 70 |
+
selected_set = set(selected)
|
| 71 |
+
body = []
|
| 72 |
+
for row in rows:
|
| 73 |
+
row_id = _row_identity(row)
|
| 74 |
+
checked = " checked" if row_id in selected_set or row.get("name") in selected_set else ""
|
| 75 |
+
checkbox = (
|
| 76 |
+
f"<input type='checkbox' name='selected' value='{html.escape(row_id)}'{checked}>"
|
| 77 |
+
if selectable
|
| 78 |
+
else ""
|
| 79 |
+
)
|
| 80 |
+
body.append(
|
| 81 |
+
"<tr>"
|
| 82 |
+
f"<td>{checkbox}</td>"
|
| 83 |
+
f"<td><code>{html.escape(row_id)}</code></td>"
|
| 84 |
+
f"<td>{_row_cell(row, 'type') or _row_cell(row, 'entity_type')}</td>"
|
| 85 |
+
f"<td>{_row_cell(row, 'name') or _row_cell(row, 'slug')}</td>"
|
| 86 |
+
f"<td>{_score_text(row)}</td>"
|
| 87 |
+
f"<td>{_row_cell(row, 'selection_state')}</td>"
|
| 88 |
+
f"<td>{_row_cell(row, 'tldr')}</td>"
|
| 89 |
+
f"<td>{_row_cell(row, 'reason', 180)}</td>"
|
| 90 |
+
"</tr>"
|
| 91 |
+
)
|
| 92 |
+
return (
|
| 93 |
+
"<table><tr><th>Select</th><th>ID</th><th>Type</th><th>Name</th>"
|
| 94 |
+
"<th>Score</th><th>State</th><th>TLDR</th><th>Reason</th></tr>" + "".join(body) + "</table>"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def render_recommendations(
|
| 99 |
+
*,
|
| 100 |
+
layout: LayoutFn,
|
| 101 |
+
query: dict[str, str],
|
| 102 |
+
recommend_bundle: RecommendFn,
|
| 103 |
+
recommend_related: RelatedFn,
|
| 104 |
+
) -> str:
|
| 105 |
+
"""Render selectable recommendation rows and related suggestions."""
|
| 106 |
+
q = str(query.get("q") or "").strip()
|
| 107 |
+
top_k = _top_k(query.get("top_k"))
|
| 108 |
+
selected = _split_values(query.get("selected"))
|
| 109 |
+
rejected = _split_values(query.get("rejected"))
|
| 110 |
+
rows: list[dict[str, Any]] = []
|
| 111 |
+
related: list[dict[str, Any]] = []
|
| 112 |
+
error = ""
|
| 113 |
+
|
| 114 |
+
if q:
|
| 115 |
+
try:
|
| 116 |
+
rows = recommend_bundle(q, top_k)
|
| 117 |
+
if selected:
|
| 118 |
+
related = recommend_related(selected, rejected, top_k)
|
| 119 |
+
except Exception as exc: # noqa: BLE001 - dashboard must show an error state.
|
| 120 |
+
error = f"{type(exc).__name__}: {exc}"
|
| 121 |
+
|
| 122 |
+
all_ids = [_row_identity(row) for row in rows]
|
| 123 |
+
search_form = (
|
| 124 |
+
"<form method='get' action='/recommend' class='card'>"
|
| 125 |
+
"<label>Query <input name='q' value='" + html.escape(q, quote=True) + "'></label> "
|
| 126 |
+
"<label>Top K <input name='top_k' type='number' min='1' max='5' value='"
|
| 127 |
+
+ str(top_k)
|
| 128 |
+
+ "'></label> "
|
| 129 |
+
"<label>Rejected <input name='rejected' value='"
|
| 130 |
+
+ html.escape(",".join(rejected), quote=True)
|
| 131 |
+
+ "'></label> "
|
| 132 |
+
"<button type='submit'>Recommend</button>"
|
| 133 |
+
"</form>"
|
| 134 |
+
)
|
| 135 |
+
links = ""
|
| 136 |
+
if q and rows:
|
| 137 |
+
links = (
|
| 138 |
+
"<p>"
|
| 139 |
+
f"<a href='{html.escape(_selected_link(q, top_k, all_ids, rejected), quote=True)}'>"
|
| 140 |
+
"Select all</a> / "
|
| 141 |
+
f"<a href='{html.escape(_selected_link(q, top_k, [], rejected), quote=True)}'>"
|
| 142 |
+
"Select none</a>"
|
| 143 |
+
"</p>"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
results = ""
|
| 147 |
+
if error:
|
| 148 |
+
results = f"<div class='card'><strong>Error</strong><p>{html.escape(error)}</p></div>"
|
| 149 |
+
elif q and rows:
|
| 150 |
+
results = (
|
| 151 |
+
"<form method='get' action='/recommend' class='card'>"
|
| 152 |
+
f"<input type='hidden' name='q' value='{html.escape(q, quote=True)}'>"
|
| 153 |
+
f"<input type='hidden' name='top_k' value='{top_k}'>"
|
| 154 |
+
f"<input type='hidden' name='rejected' value='{html.escape(','.join(rejected), quote=True)}'>"
|
| 155 |
+
"<strong>Recommendations</strong>"
|
| 156 |
+
+ links
|
| 157 |
+
+ _render_rows(rows, selected=selected, selectable=True)
|
| 158 |
+
+ "<button type='submit'>Show related</button>"
|
| 159 |
+
+ "</form>"
|
| 160 |
+
)
|
| 161 |
+
elif q:
|
| 162 |
+
results = "<div class='card'><strong>No recommendations above threshold.</strong></div>"
|
| 163 |
+
|
| 164 |
+
related_html = ""
|
| 165 |
+
if selected:
|
| 166 |
+
related_html = (
|
| 167 |
+
"<div class='card'><strong>Related recommendations</strong>"
|
| 168 |
+
+ (
|
| 169 |
+
_render_rows(related, selected=[], selectable=False)
|
| 170 |
+
if related
|
| 171 |
+
else "<p class='muted'>No related recommendations above threshold.</p>"
|
| 172 |
+
)
|
| 173 |
+
+ "</div>"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
return layout(
|
| 177 |
+
"Recommendations", "<h1>Recommendations</h1>" + search_form + results + related_html
|
| 178 |
+
)
|
src/ctx/monitor/routes.py
CHANGED
|
@@ -25,6 +25,7 @@ NAV_ROUTES: tuple[tuple[str, str, str], ...] = (
|
|
| 25 |
("skillspector", "SkillSpector", "/skillspector"),
|
| 26 |
("wiki", "Wiki", "/wiki"),
|
| 27 |
("graph", "Graph", "/graph"),
|
|
|
|
| 28 |
("manage", "Manage", "/manage"),
|
| 29 |
("harness", "Harness Setup", "/harness"),
|
| 30 |
("docs", "Docs", "/docs"),
|
|
@@ -84,6 +85,7 @@ _GET_EXACT_ROUTES: dict[str, str] = {
|
|
| 84 |
"/loaded": "loaded",
|
| 85 |
"/logs": "logs",
|
| 86 |
"/graph": "graph",
|
|
|
|
| 87 |
"/manage": "manage",
|
| 88 |
"/harness": "harness",
|
| 89 |
"/docs": "docs",
|
|
@@ -120,7 +122,7 @@ _POST_EXACT_ROUTES: dict[str, str] = {
|
|
| 120 |
|
| 121 |
def parse_request_target(request_path: str) -> ParsedRequestTarget:
|
| 122 |
raw_path, _, raw_query = request_path.partition("?")
|
| 123 |
-
query = {key: values
|
| 124 |
return ParsedRequestTarget(path=raw_path, query=query)
|
| 125 |
|
| 126 |
|
|
|
|
| 25 |
("skillspector", "SkillSpector", "/skillspector"),
|
| 26 |
("wiki", "Wiki", "/wiki"),
|
| 27 |
("graph", "Graph", "/graph"),
|
| 28 |
+
("recommend", "Recommend", "/recommend"),
|
| 29 |
("manage", "Manage", "/manage"),
|
| 30 |
("harness", "Harness Setup", "/harness"),
|
| 31 |
("docs", "Docs", "/docs"),
|
|
|
|
| 85 |
"/loaded": "loaded",
|
| 86 |
"/logs": "logs",
|
| 87 |
"/graph": "graph",
|
| 88 |
+
"/recommend": "recommend",
|
| 89 |
"/manage": "manage",
|
| 90 |
"/harness": "harness",
|
| 91 |
"/docs": "docs",
|
|
|
|
| 122 |
|
| 123 |
def parse_request_target(request_path: str) -> ParsedRequestTarget:
|
| 124 |
raw_path, _, raw_query = request_path.partition("?")
|
| 125 |
+
query = {key: ",".join(values) for key, values in parse_qs(raw_query).items() if values}
|
| 126 |
return ParsedRequestTarget(path=raw_path, query=query)
|
| 127 |
|
| 128 |
|
src/ctx/monitor/services/runtime.py
CHANGED
|
@@ -8,6 +8,9 @@ from collections.abc import Callable
|
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Any
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def read_jsonl(path: Path, limit: int | None = None) -> list[dict[str, Any]]:
|
| 13 |
if not path.exists():
|
|
@@ -38,6 +41,206 @@ def lifecycle_events(path: Path, limit: int | None = 200) -> list[dict[str, Any]
|
|
| 38 |
return [event for event in events if event.get("action") in {"validation", "escalation"}]
|
| 39 |
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def summarize_sessions(
|
| 42 |
audit: list[dict[str, Any]],
|
| 43 |
events: list[dict[str, Any]],
|
|
@@ -182,7 +385,8 @@ def escalation_key(event: dict[str, Any]) -> str:
|
|
| 182 |
|
| 183 |
|
| 184 |
def lifecycle_summary(path: Path, limit: int = 200) -> dict[str, Any]:
|
| 185 |
-
|
|
|
|
| 186 |
validations = [event for event in events if event.get("action") == "validation"]
|
| 187 |
escalations = [event for event in events if event.get("action") == "escalation"]
|
| 188 |
open_by_key: dict[str, dict[str, Any]] = {}
|
|
@@ -202,7 +406,7 @@ def lifecycle_summary(path: Path, limit: int = 200) -> dict[str, Any]:
|
|
| 202 |
sessions = sorted(
|
| 203 |
{str(event.get("session_id") or "") for event in events if event.get("session_id")}
|
| 204 |
)
|
| 205 |
-
|
| 206 |
"path": str(path),
|
| 207 |
"events_total": len(events),
|
| 208 |
"validations_total": len(validations),
|
|
@@ -214,3 +418,5 @@ def lifecycle_summary(path: Path, limit: int = 200) -> dict[str, Any]:
|
|
| 214 |
"open_escalations": open_escalations[-20:],
|
| 215 |
"sessions": sessions,
|
| 216 |
}
|
|
|
|
|
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
+
_TOKEN_ATTRIBUTIONS = ("exact", "estimated", "unavailable")
|
| 12 |
+
_SELECTION_SOURCES = ("user", "system", "host", "unknown")
|
| 13 |
+
|
| 14 |
|
| 15 |
def read_jsonl(path: Path, limit: int | None = None) -> list[dict[str, Any]]:
|
| 16 |
if not path.exists():
|
|
|
|
| 41 |
return [event for event in events if event.get("action") in {"validation", "escalation"}]
|
| 42 |
|
| 43 |
|
| 44 |
+
def _int_value(value: Any) -> int | None:
|
| 45 |
+
try:
|
| 46 |
+
result = int(value)
|
| 47 |
+
except (TypeError, ValueError):
|
| 48 |
+
return None
|
| 49 |
+
return result if result >= 0 else None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _float_value(value: Any) -> float | None:
|
| 53 |
+
try:
|
| 54 |
+
result = float(value)
|
| 55 |
+
except (TypeError, ValueError):
|
| 56 |
+
return None
|
| 57 |
+
return result if result >= 0 else None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _empty_token_usage_summary() -> dict[str, Any]:
|
| 61 |
+
return {
|
| 62 |
+
"records": 0,
|
| 63 |
+
"input_tokens": 0,
|
| 64 |
+
"output_tokens": 0,
|
| 65 |
+
"total_tokens": 0,
|
| 66 |
+
"cost_usd": 0.0,
|
| 67 |
+
"by_attribution": {key: 0 for key in _TOKEN_ATTRIBUTIONS},
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _merge_token_usage(summary: dict[str, Any], raw: Any) -> None:
|
| 72 |
+
if not isinstance(raw, dict):
|
| 73 |
+
return
|
| 74 |
+
summary["records"] = int(summary.get("records") or 0) + 1
|
| 75 |
+
attribution = str(raw.get("attribution") or "unavailable").lower()
|
| 76 |
+
if attribution not in _TOKEN_ATTRIBUTIONS:
|
| 77 |
+
attribution = "unavailable"
|
| 78 |
+
summary["by_attribution"][attribution] = (
|
| 79 |
+
int(summary["by_attribution"].get(attribution) or 0) + 1
|
| 80 |
+
)
|
| 81 |
+
for key in ("input_tokens", "output_tokens", "total_tokens"):
|
| 82 |
+
value = _int_value(raw.get(key))
|
| 83 |
+
if value is not None:
|
| 84 |
+
summary[key] = int(summary.get(key) or 0) + value
|
| 85 |
+
cost = _float_value(raw.get("cost_usd"))
|
| 86 |
+
if cost is not None:
|
| 87 |
+
summary["cost_usd"] = round(float(summary.get("cost_usd") or 0.0) + cost, 8)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _tool_key(event: dict[str, Any]) -> tuple[str, str] | None:
|
| 91 |
+
entity_type = str(event.get("entity_type") or "")
|
| 92 |
+
slug = str(event.get("slug") or "")
|
| 93 |
+
if not entity_type or not slug:
|
| 94 |
+
return None
|
| 95 |
+
return entity_type, slug
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _load_key(event: dict[str, Any]) -> tuple[str, str, str] | None:
|
| 99 |
+
key = _tool_key(event)
|
| 100 |
+
if key is None:
|
| 101 |
+
return None
|
| 102 |
+
return str(event.get("session_id") or "unknown"), key[0], key[1]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _selection_source(value: Any) -> str:
|
| 106 |
+
source = str(value or "unknown").lower()
|
| 107 |
+
return source if source in _SELECTION_SOURCES else "unknown"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _evidence_metadata(value: Any) -> dict[str, Any]:
|
| 111 |
+
if not isinstance(value, str):
|
| 112 |
+
return {"evidence_present": False, "evidence_length": 0}
|
| 113 |
+
text = value.strip()
|
| 114 |
+
return {"evidence_present": bool(text), "evidence_length": len(text)}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _usage_bucket(
|
| 118 |
+
buckets: dict[Any, dict[str, Any]],
|
| 119 |
+
key: Any,
|
| 120 |
+
**labels: Any,
|
| 121 |
+
) -> dict[str, Any]:
|
| 122 |
+
bucket = buckets.get(key)
|
| 123 |
+
if bucket is None:
|
| 124 |
+
bucket = dict(labels)
|
| 125 |
+
bucket.update(_empty_token_usage_summary())
|
| 126 |
+
buckets[key] = bucket
|
| 127 |
+
return bucket
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _usage_rows(buckets: dict[Any, dict[str, Any]]) -> list[dict[str, Any]]:
|
| 131 |
+
return sorted(
|
| 132 |
+
buckets.values(),
|
| 133 |
+
key=lambda row: (
|
| 134 |
+
-int(row.get("total_tokens") or 0),
|
| 135 |
+
str(row.get("entity_type") or ""),
|
| 136 |
+
str(row.get("slug") or ""),
|
| 137 |
+
str(row.get("session_id") or ""),
|
| 138 |
+
str(row.get("selection_source") or ""),
|
| 139 |
+
),
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _runtime_tool_summary(events: list[dict[str, Any]]) -> dict[str, Any]:
|
| 144 |
+
active: dict[tuple[str, str, str], dict[str, Any]] = {}
|
| 145 |
+
selection_sources = {key: 0 for key in _SELECTION_SOURCES}
|
| 146 |
+
token_usage = _empty_token_usage_summary()
|
| 147 |
+
usage_by_tool: dict[Any, dict[str, Any]] = {}
|
| 148 |
+
usage_by_type: dict[Any, dict[str, Any]] = {}
|
| 149 |
+
usage_by_session: dict[Any, dict[str, Any]] = {}
|
| 150 |
+
usage_by_source: dict[Any, dict[str, Any]] = {}
|
| 151 |
+
recent_tool_usage: list[dict[str, Any]] = []
|
| 152 |
+
loaded_total = 0
|
| 153 |
+
selected_total = 0
|
| 154 |
+
used_total = 0
|
| 155 |
+
|
| 156 |
+
for event in events:
|
| 157 |
+
action = event.get("action")
|
| 158 |
+
key = _tool_key(event)
|
| 159 |
+
load_key = _load_key(event)
|
| 160 |
+
if action == "load_requested" and key is not None and load_key is not None:
|
| 161 |
+
loaded_total += 1
|
| 162 |
+
selected = bool(event.get("selected", False))
|
| 163 |
+
if selected:
|
| 164 |
+
selected_total += 1
|
| 165 |
+
source = _selection_source(event.get("selection_source"))
|
| 166 |
+
selection_sources[source] += 1
|
| 167 |
+
active[load_key] = {
|
| 168 |
+
"session_id": load_key[0],
|
| 169 |
+
"entity_type": key[0],
|
| 170 |
+
"slug": key[1],
|
| 171 |
+
"selected": selected,
|
| 172 |
+
"selection_source": source,
|
| 173 |
+
}
|
| 174 |
+
elif action == "unload_requested" and load_key is not None:
|
| 175 |
+
active.pop(load_key, None)
|
| 176 |
+
elif action == "used" and key is not None:
|
| 177 |
+
used_total += 1
|
| 178 |
+
raw_usage = event.get("token_usage")
|
| 179 |
+
_merge_token_usage(token_usage, raw_usage)
|
| 180 |
+
session_id = str(event.get("session_id") or "unknown")
|
| 181 |
+
active_entry = active.get(load_key) if load_key is not None else None
|
| 182 |
+
source = _selection_source(
|
| 183 |
+
active_entry.get("selection_source") if active_entry is not None else None
|
| 184 |
+
)
|
| 185 |
+
if isinstance(raw_usage, dict):
|
| 186 |
+
_merge_token_usage(
|
| 187 |
+
_usage_bucket(
|
| 188 |
+
usage_by_tool,
|
| 189 |
+
key,
|
| 190 |
+
entity_type=key[0],
|
| 191 |
+
slug=key[1],
|
| 192 |
+
),
|
| 193 |
+
raw_usage,
|
| 194 |
+
)
|
| 195 |
+
_merge_token_usage(
|
| 196 |
+
_usage_bucket(usage_by_type, key[0], entity_type=key[0]),
|
| 197 |
+
raw_usage,
|
| 198 |
+
)
|
| 199 |
+
_merge_token_usage(
|
| 200 |
+
_usage_bucket(usage_by_session, session_id, session_id=session_id),
|
| 201 |
+
raw_usage,
|
| 202 |
+
)
|
| 203 |
+
_merge_token_usage(
|
| 204 |
+
_usage_bucket(
|
| 205 |
+
usage_by_source,
|
| 206 |
+
source,
|
| 207 |
+
selection_source=source,
|
| 208 |
+
),
|
| 209 |
+
raw_usage,
|
| 210 |
+
)
|
| 211 |
+
recent_tool_usage.append(
|
| 212 |
+
{
|
| 213 |
+
"created_at": event.get("created_at"),
|
| 214 |
+
"session_id": session_id,
|
| 215 |
+
"entity_type": key[0],
|
| 216 |
+
"slug": key[1],
|
| 217 |
+
"selection_source": source,
|
| 218 |
+
**_evidence_metadata(event.get("evidence")),
|
| 219 |
+
"token_usage": raw_usage if isinstance(raw_usage, dict) else None,
|
| 220 |
+
}
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
active_values = list(active.values())
|
| 224 |
+
return {
|
| 225 |
+
"tool_selection": {
|
| 226 |
+
"loaded_total": loaded_total,
|
| 227 |
+
"active_loaded_total": len(active_values),
|
| 228 |
+
"selected_total": selected_total,
|
| 229 |
+
"active_selected_total": sum(1 for item in active_values if item["selected"]),
|
| 230 |
+
"selection_sources": selection_sources,
|
| 231 |
+
"used_total": used_total,
|
| 232 |
+
},
|
| 233 |
+
"token_usage": token_usage,
|
| 234 |
+
"token_usage_history": {
|
| 235 |
+
"by_tool": _usage_rows(usage_by_tool),
|
| 236 |
+
"by_type": _usage_rows(usage_by_type),
|
| 237 |
+
"by_session": _usage_rows(usage_by_session),
|
| 238 |
+
"by_source": _usage_rows(usage_by_source),
|
| 239 |
+
},
|
| 240 |
+
"recent_tool_usage": recent_tool_usage[-20:],
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
|
| 244 |
def summarize_sessions(
|
| 245 |
audit: list[dict[str, Any]],
|
| 246 |
events: list[dict[str, Any]],
|
|
|
|
| 385 |
|
| 386 |
|
| 387 |
def lifecycle_summary(path: Path, limit: int = 200) -> dict[str, Any]:
|
| 388 |
+
all_events = read_jsonl(path, limit=None)
|
| 389 |
+
events = [event for event in all_events if event.get("action") in {"validation", "escalation"}]
|
| 390 |
validations = [event for event in events if event.get("action") == "validation"]
|
| 391 |
escalations = [event for event in events if event.get("action") == "escalation"]
|
| 392 |
open_by_key: dict[str, dict[str, Any]] = {}
|
|
|
|
| 406 |
sessions = sorted(
|
| 407 |
{str(event.get("session_id") or "") for event in events if event.get("session_id")}
|
| 408 |
)
|
| 409 |
+
summary = {
|
| 410 |
"path": str(path),
|
| 411 |
"events_total": len(events),
|
| 412 |
"validations_total": len(validations),
|
|
|
|
| 418 |
"open_escalations": open_escalations[-20:],
|
| 419 |
"sessions": sessions,
|
| 420 |
}
|
| 421 |
+
summary.update(_runtime_tool_summary(all_events))
|
| 422 |
+
return summary
|