Sync ctx 0f61777 (part 2)
Browse filesGitHub commit: 0f617779a5a1f11f8714c8f61087eb80c1c492b4
- qa/bug_smoke_status.csv +17 -0
- qa/feature_status.csv +0 -0
- qa/tool-selection-token-history/SPEC.md +1 -1
- src/ctx/adapters/generic/ctx_core_tools.py +82 -7
- src/ctx/adapters/generic/runtime_lifecycle.py +1 -1
- src/ctx/adapters/loopflow.py +56 -8
- src/ctx/api.py +6 -1
- src/ctx/core/wiki/wiki_packs.py +3 -1
- src/ctx/mcp_server/__init__.py +2 -0
- src/ctx/mcp_server/server.py +80 -6
- src/ctx/monitor/pages/home.py +9 -1
- src/ctx/telemetry/__init__.py +138 -49
qa/bug_smoke_status.csv
CHANGED
|
@@ -36,3 +36,20 @@ AUDIT-034,Security,Backup config,unsafe top_files entries,src/backup_config.py;
|
|
| 36 |
AUDIT-035,Security,ctx run MCP inline specs,inline secret argv persistence,src/ctx/cli/run.py; src/tests/test_harness_cli_run.py,Hegel runtime audit found --mcp specs accepted token-looking argv that could be persisted in session metadata.,High,ctx run --mcp inline commands should reject secret-looking argv and direct users to --mcp-env.,parallel runtime audit + focused pytest,Retested Pass,Inline MCP command args accepted --token and ghp_ values before fix.,MCP secrets could be embedded in command args and session metadata.,Parse an --mcp spec containing --token or ghp_ before fix and inspect parsed args.,Use existing secret scanner in _parse_mcp_spec and fail with --mcp-env guidance.,Fixed,.venv/bin/python -m pytest src/tests/test_backup_config.py src/tests/test_backup_mirror.py src/tests/test_harness_cli_run.py -q --tb=short,PASS: runtime safety focused suite reported 154 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: block inline secret-looking args only; --mcp-env remains the supported credential path.,Closed; continue repo-wide discovery.
|
| 37 |
AUDIT-036,Security,Wiki queue artifact promotion,arbitrary target_path overwrite,src/ctx/core/wiki/wiki_queue_worker.py; src/tests/test_wiki_queue_worker.py,Turing graph audit found queued artifact promotion trusted payload target_path and could replace arbitrary files.,High,Queued artifact promotion should only promote known graph and wiki artifact targets from sibling staged files.,parallel graph audit + focused pytest,Retested Pass,ARTIFACT_PROMOTION_JOB payload could promote /tmp/staged to /tmp/outside before fix.,Queue worker could overwrite files outside allowed graph artifact locations.,Enqueue artifact promotion with outside target_path and inspect overwritten outside file before fix.,Resolve paths validate exact allowed target names and require staged_path to equal target sibling .staged before promotion.,Fixed,.venv/bin/python -m pytest src/tests/test_wiki_queue_worker.py src/tests/test_wiki_queue.py src/tests/test_wiki_queue_producers.py src/tests/test_artifact_promotion.py -q --tb=short,PASS: wiki queue and artifact promotion suites reported 50 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: restrict promotion boundary only; known graph and wiki artifact promotions still work.,Closed; continue repo-wide discovery.
|
| 38 |
AUDIT-037,CI Gate,Windows pytest matrix,no-mistakes POSIX shell wrapper tests,src/tests/test_no_mistakes_env.py; .github/workflows/test.yml; scripts/ci_required.py,Post-merge Tests run 28808683083 failed only on windows-latest py3.11 and py3.12 with WSL bash and no installed distributions.,High,CI shell-wrapper tests should run only where their POSIX contract is available and CI workflow changes should run the full OS pytest matrix before merge.,GitHub Actions log audit + focused regression tests,Retested Pass,Windows pytest executed POSIX no-mistakes shell-wrapper tests through a bash command that resolved to WSL without a distro.,Post-merge main CI failed after PR checks were green because pull_request skipped the full test matrix and CI required allowed that skip unconditionally.,Inspect run 28808683083 failed logs and compare pull_request test job condition to push matrix behavior.,Skip POSIX-only no-mistakes shell-wrapper tests on Windows and require the full pytest OS matrix for PRs that change CI workflow files.,Fixed,.venv/bin/python -m pytest src/tests/test_no_mistakes_env.py src/tests/test_ci_classifier.py -q --tb=short,PASS: focused no-mistakes env and CI classifier regressions pass locally; GitHub PR matrix will verify Windows.,2026-07-06,Codex,Reviewed by local CI audit,Ponytail: preserve fast PR skips for normal changes while pulling Windows matrix forward for CI changes.,Closed; continue repo-wide discovery.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
AUDIT-035,Security,ctx run MCP inline specs,inline secret argv persistence,src/ctx/cli/run.py; src/tests/test_harness_cli_run.py,Hegel runtime audit found --mcp specs accepted token-looking argv that could be persisted in session metadata.,High,ctx run --mcp inline commands should reject secret-looking argv and direct users to --mcp-env.,parallel runtime audit + focused pytest,Retested Pass,Inline MCP command args accepted --token and ghp_ values before fix.,MCP secrets could be embedded in command args and session metadata.,Parse an --mcp spec containing --token or ghp_ before fix and inspect parsed args.,Use existing secret scanner in _parse_mcp_spec and fail with --mcp-env guidance.,Fixed,.venv/bin/python -m pytest src/tests/test_backup_config.py src/tests/test_backup_mirror.py src/tests/test_harness_cli_run.py -q --tb=short,PASS: runtime safety focused suite reported 154 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: block inline secret-looking args only; --mcp-env remains the supported credential path.,Closed; continue repo-wide discovery.
|
| 37 |
AUDIT-036,Security,Wiki queue artifact promotion,arbitrary target_path overwrite,src/ctx/core/wiki/wiki_queue_worker.py; src/tests/test_wiki_queue_worker.py,Turing graph audit found queued artifact promotion trusted payload target_path and could replace arbitrary files.,High,Queued artifact promotion should only promote known graph and wiki artifact targets from sibling staged files.,parallel graph audit + focused pytest,Retested Pass,ARTIFACT_PROMOTION_JOB payload could promote /tmp/staged to /tmp/outside before fix.,Queue worker could overwrite files outside allowed graph artifact locations.,Enqueue artifact promotion with outside target_path and inspect overwritten outside file before fix.,Resolve paths validate exact allowed target names and require staged_path to equal target sibling .staged before promotion.,Fixed,.venv/bin/python -m pytest src/tests/test_wiki_queue_worker.py src/tests/test_wiki_queue.py src/tests/test_wiki_queue_producers.py src/tests/test_artifact_promotion.py -q --tb=short,PASS: wiki queue and artifact promotion suites reported 50 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: restrict promotion boundary only; known graph and wiki artifact promotions still work.,Closed; continue repo-wide discovery.
|
| 38 |
AUDIT-037,CI Gate,Windows pytest matrix,no-mistakes POSIX shell wrapper tests,src/tests/test_no_mistakes_env.py; .github/workflows/test.yml; scripts/ci_required.py,Post-merge Tests run 28808683083 failed only on windows-latest py3.11 and py3.12 with WSL bash and no installed distributions.,High,CI shell-wrapper tests should run only where their POSIX contract is available and CI workflow changes should run the full OS pytest matrix before merge.,GitHub Actions log audit + focused regression tests,Retested Pass,Windows pytest executed POSIX no-mistakes shell-wrapper tests through a bash command that resolved to WSL without a distro.,Post-merge main CI failed after PR checks were green because pull_request skipped the full test matrix and CI required allowed that skip unconditionally.,Inspect run 28808683083 failed logs and compare pull_request test job condition to push matrix behavior.,Skip POSIX-only no-mistakes shell-wrapper tests on Windows and require the full pytest OS matrix for PRs that change CI workflow files.,Fixed,.venv/bin/python -m pytest src/tests/test_no_mistakes_env.py src/tests/test_ci_classifier.py -q --tb=short,PASS: focused no-mistakes env and CI classifier regressions pass locally; GitHub PR matrix will verify Windows.,2026-07-06,Codex,Reviewed by local CI audit,Ponytail: preserve fast PR skips for normal changes while pulling Windows matrix forward for CI changes.,Closed; continue repo-wide discovery.
|
| 39 |
+
AUDIT-038,CI Gate,No-test policy,no-tests-needed label bypass,scripts/ci_no_test_policy.py; .github/workflows/test.yml; src/tests/test_ci_classifier.py,Workbench QA pair and CTO probe showed the no-tests-needed label exemption is implemented but missing focused test coverage and workflow exemption prose.,Medium,No-test policy exemptions should be explicit in workflow prose and covered by regression tests.,agent-reviewer workbench plus local policy probe,Retested Pass,2026-07-07,No-test label bypass is not documented in the workflow exemption comment and has no focused regression.,Call evaluate_policy for scripts/ci_classifier.py with no test file and the no-tests-needed label; it passes while rg finds no no-tests-needed assertion in focused tests.,Add focused regression for the label exemption and update the workflow policy comment.,Fixed,.venv/bin/python -m pytest src/tests/test_ci_classifier.py src/tests/test_ci_preflight.py -q --tb=short,PASS: no-test policy regression/prose covered; .venv/bin/python -m pytest src/tests/test_ci_classifier.py src/tests/test_ci_preflight.py src/tests/test_public_api.py -q --tb=short -> 127 passed; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 40 |
+
AUDIT-039,API Contract,Runtime/API public exports,documented adapter helpers not exported,src/ctx/api.py; src/ctx/__init__.py; src/tests/test_public_api.py,Runtime/API pair and CTO probe showed ctx_core_tool_names and recommendation_graph exist in ctx.api but are absent from ctx.api.__all__ and top-level ctx.,Medium,Public helper names documented as adapter API should have an explicit export contract or docs should stop presenting them as public imports.,agent-reviewer workbench plus import/export probe,Retested Pass,2026-07-07,Documented adapter helpers are not exported by ctx.api.__all__ or ctx.__all__.,Run PYTHONPATH=src import probe for ctx_core_tool_names and recommendation_graph; api_attr is true while api_all ctx_attr and ctx_all are false.,Either export the helpers with tests or narrow the public API documentation.,Fixed,.venv/bin/python -m pytest src/tests/test_public_api.py src/tests/test_loopflow_adapter.py -q --tb=short,PASS: adapter-helper public contract pinned as module-level adapter support; public API tests passed in 127-test gate and combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 41 |
+
AUDIT-040,Privacy,MCP lifecycle output,absolute events_path in tool output,src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/mcp_server/server.py,Runtime/API pair and CTO probe showed ctx__load_entity returns an absolute events_path through the generic toolbox lifecycle dispatch.,Medium,MCP-facing lifecycle tool output should not expose local filesystem paths unless the caller explicitly asks for a local diagnostics field.,agent-reviewer workbench plus lifecycle dispatch probe,Retested Pass,2026-07-07,ctx__load_entity records successfully but returns an absolute events_path in model-facing JSON.,Dispatch ToolCall id 1 name ctx__load_entity through CtxCoreToolbox with temp lifecycle_dir and inspect payload events_path; it is absolute and exists.,Remove events_path from lifecycle tool responses while preserving local append-only recording.,Fixed,.venv/bin/python -m pytest src/tests/test_harness_ctx_core.py::TestRuntimeLifecycle src/tests/test_mcp_server.py -q --tb=short,PASS: 48 lifecycle and MCP server tests passed; lifecycle write responses omit events_path and temp roots while events.jsonl is still appended.,2026-07-07,Codex,Reviewed by Runtime/API actor/critic pair + local tests,Direct store output no longer serializes local path; toolbox and MCP payloads prove the path is not model-facing.,Closed; continue Phase 3 after approval.
|
| 42 |
+
AUDIT-041,Tracker Hygiene,Feature tracker duplicate route rows,blank parent linkage for duplicate dashboard API routes,qa/feature_status.csv,Feature Mapper pair and CTO CSV probe found 14 same surface plus entrypoint groups with all parent_feature_id blank including API and DASH-API route rows.,Medium,Duplicate canonical feature rows for the same route should be parent-linked or explicitly allowed so reviewers do not update stale parallel rows.,agent-reviewer workbench plus CSV duplicate probe,Retested Pass,2026-07-07,Dashboard API route coverage appears as parallel canonical rows instead of parent-linked source coverage.,Parse qa/feature_status.csv group by lowercased surface and entrypoint_or_route and filter groups with all blank parent_feature_id; observe 14 groups.,Link dashboard-specific rows to canonical API parents or add a tracker hygiene allowlist for intentional duplicates.,Fixed,.venv/bin/python -m pytest src/tests/test_feature_user_story_tracker.py -q --tb=short,PASS: canonical tracker now parent-links duplicate Dashboard API route rows; src/tests/test_feature_user_story_tracker.py covered duplicate modeling; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 43 |
+
AUDIT-042,Tracker Hygiene,Harness CLI safety coverage,missing feature tracking for opt-in execution flags,qa/feature_status.csv; src/harness_install.py; docs/entity-onboarding.md; src/tests/test_harness_install.py,Feature Mapper pair found harness install safety flags in source docs and tests but not in qa/feature_status.csv.,High,Safety-critical harness install flags should be explicitly tracked in user-story coverage.,agent-reviewer workbench plus rg coverage probe,Retested Pass,2026-07-07,ctx-harness-install approve-commands run-verify and keep-files behavior is not named in the canonical feature tracker.,Run rg for --approve-commands --run-verify --keep-files across qa docs source and tests; source docs and tests hit but qa/feature_status.csv does not.,Add B-HAR-013 child feature row under CLI-048 and pin the three safety flags in the tracker coverage test.,Fixed,.venv/bin/python -m pytest src/tests/test_feature_user_story_tracker.py src/tests/test_harness_install.py -q --tb=short,PASS: tracker and harness install tests cover --approve-commands --run-verify and --keep-files as explicit safety behavior.,2026-07-08,Codex,Reviewed by Feature Mapper actor/critic pair + local tests,Tracker-only fix; behavior already existed in code docs and tests but now has first-class canonical story coverage.,Closed; continue Phase 4 after approval.
|
| 44 |
+
AUDIT-043,Tracker Hygiene,Public docs tracker evidence,shared build evidence for per-page DOC-NAV rows,qa/feature_status.csv; src/tests/test_feature_user_story_tracker.py,Feature Mapper pair and CTO CSV probe showed all 27 DOC-NAV rows share the same mkdocs/nav evidence while promising page-specific behavior.,Medium,Per-page docs feature rows should either have page-specific evidence or be collapsed into one navigation/build feature row.,agent-reviewer workbench plus DOC-NAV CSV probe,Retested Pass,2026-07-07,DOC-NAV rows have unique stories but identical renderability evidence.,Parse qa/feature_status.csv for feature_id starting DOC-NAV; observe 27 rows with one unique evidence string and one unique test command string.,Collapse DOC-NAV rows or add page-specific content anchors and checks for each promised behavior.,Fixed,.venv/bin/python -m pytest src/tests/test_feature_user_story_tracker.py && .venv/bin/python -m mkdocs build --strict,PASS: DOC-NAV canonical rows now name page-specific evidence; src/tests/test_feature_user_story_tracker.py covered per-page evidence; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 45 |
+
AUDIT-044,Permission Model,Loopflow MCP handoff,no read-only subgroup scope for ctx MCP tools,src/ctx/adapters/loopflow.py; src/ctx/adapters/generic/ctx_core_tools.py; docs/harness/loopflow-adapter-demo.md,Loopflow pair and CTO probe showed ctx-mcp-server appears only when all capability groups are granted and then includes lifecycle write tools.,Medium,Loopflow should be able to request read-only ctx recommendation/wiki MCP tools without also granting lifecycle write tools.,agent-reviewer workbench plus loopflow permission probe,Retested Pass,2026-07-07,Loopflow MCP handoff is all-or-nothing and all grants expose lifecycle tools such as ctx__load_entity and ctx__record_validation.,Monkeypatch ctx_core_tool_names then call recommend_for_loop for mcps only skills+agents+mcps and all grants; only all grants returns ctx-mcp-server with lifecycle tools.,Split read-only recommendation/wiki tools from lifecycle/session-write tools behind explicit permission scope.,Fixed,.venv/bin/python -m pytest src/tests/test_loopflow_adapter.py src/tests/test_mcp_server.py -q --tb=short,PASS: Loopflow MCP handoff exposes read-only ctx tools for mcps grant and lifecycle tools only with all grants; loopflow/MCP tests passed; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 46 |
+
AUDIT-045,Permission Model,Loopflow harness ownership,implicit harness enablement from model metadata,src/ctx/adapters/loopflow.py; docs/harness/loopflow-adapter-demo.md,Loopflow pair and CTO probe showed own_llm false still returns harness recommendations when model_provider or model is supplied.,Medium,Harness recommendations should require explicit user model ownership consent rather than inferring ownership from ranking metadata.,agent-reviewer workbench plus loopflow harness probe,Retested Pass,2026-07-07,Passing model_provider or model unlocks dry-run harness recommendations even when own_llm is false.,Monkeypatch recommend_harnesses then call recommend_for_loop with permissions harnesses and own_llm false plus model_provider or model; harness_install is returned.,Make own_llm or explicit model_ownership authoritative and treat model fields as ranking metadata unless consent is set.,Fixed,.venv/bin/python -m pytest src/tests/test_loopflow_adapter.py -q --tb=short,PASS: harness recommendations require explicit own_llm consent; model/provider metadata alone stays blocked; loopflow tests passed; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 47 |
+
AUDIT-046,DSL Feature Gap,Loopflow .loop permissions,DSL cannot grant ctx capability groups,src/ctx/adapters/loopflow.py; docs/harness/loopflow-adapter-demo.md,Loopflow pair and CTO parse probe showed parse_loop_file ignores permissions and ctx permissions lines despite the owner ask for .loop capability grants.,Medium,Loopflow DSL files should be able to express ctx capability grants if the integration proposal promises DSL-native subgroup selection.,agent-reviewer workbench plus parse_loop_file probe,Retested Pass,2026-07-07,.loop files cannot grant capability groups today because parse_loop_file returns only source goal look_at and done_when fields.,Parse a temp .loop file containing permissions and ctx permissions lines; returned dict has no permissions field.,Add a small documented permission syntax and precedence between DSL grants and CLI/API grants.,Fixed,.venv/bin/python -m pytest src/tests/test_loopflow_adapter.py -q --tb=short,PASS: parse_loop_file supports ctx grants and CLI/API permissions override file grants; loopflow tests passed; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 48 |
+
AUDIT-047,Privacy,Telemetry redaction,raw host paths in arbitrary payload string values,src/ctx/telemetry/__init__.py; src/tests/test_enterprise_telemetry.py; docs/telemetry.md,Telemetry pair and CTO repro showed local_redacted hashes sensitive-looking keys but leaves a /Users path inside a safe_note string in spool and local export.,High,Local-redacted telemetry should not persist raw host paths inside arbitrary string payload values.,agent-reviewer workbench plus temp-spool telemetry probe,Retested Pass,2026-07-07,Payload value text can carry raw host paths into local telemetry and exported local_jsonl records.,Record event with payload safe_note containing /Users/example/private-repo/app.py then export to local_jsonl; raw and export both contain the path.,Hash local host path substrings in arbitrary payload string values and add spool/local export regression coverage.,Fixed,.venv/bin/python -m pytest src/tests/test_enterprise_telemetry.py -q,PASS: 67 enterprise telemetry tests passed; arbitrary safe_note and nested strings now contain path_hash markers and no raw host paths.,2026-07-07,Codex,Reviewed by Telemetry actor/critic pair + local tests,Exporter-boundary sanitization keeps local JSONL and OTLP payloads privacy-safe.,Closed; continue Phase 2 after approval.
|
| 49 |
+
AUDIT-048,Privacy,Telemetry OTLP export,legacy raw payload exported remotely,src/ctx/telemetry/__init__.py; src/tests/test_enterprise_telemetry.py; docs/telemetry.md,Telemetry pair and CTO repro showed OTLP export trusts an existing local_redacted record with raw payload query and path values.,High,Remote exporters should re-sanitize legacy or manually repaired local telemetry before sending payload attributes.,agent-reviewer workbench plus monkeypatched OTLP export probe,Retested Pass,2026-07-07,Legacy local event payloads with raw query and path are serialized into OTLP attributes.,Write a TelemetryEvent JSONL record with privacy_mode local_redacted and raw payload query/path then monkeypatch _post_otlp_http and export_events; captured payload contains both values.,Re-sanitize event payloads and metric attributes at exporter boundary before local_jsonl or OTLP serialization.,Fixed,.venv/bin/python -m pytest src/tests/test_enterprise_telemetry.py -q,PASS: 67 enterprise telemetry tests passed; legacy raw event payload and metric attributes are re-sanitized before OTLP export.,2026-07-07,Codex,Reviewed by Telemetry actor/critic pair + local tests,Exporter boundary now protects legacy local repairs and older raw records before remote send.,Closed; continue Phase 2 after approval.
|
| 50 |
+
AUDIT-049,Telemetry Export,Continuous checkpointing,backlog skipped after continuous export,src/ctx/telemetry/__init__.py; src/tests/test_enterprise_telemetry.py,Telemetry pair and CTO repro showed continuous event and metric export advances checkpoint to the newest record while older backlog remains unexported.,High,Enabling continuous export after a local backlog should not checkpoint past older unexported event or metric records.,agent-reviewer workbench plus event and metric checkpoint probes,Retested Pass,2026-07-07,Continuous export of the second record causes later batch export to skip the first event and first metric.,Record first event/metric with export disabled then second with export enabled and run batch export; later result is noop and first id is missing from exported JSONL.,Continuous export now drains pending event and metric spool ranges before checkpointing newest exported record.,Fixed,.venv/bin/python -m pytest src/tests/test_enterprise_telemetry.py -q,PASS: 67 enterprise telemetry tests passed; continuous event and metric export writes backlog in order checkpoints newest record and later batch export is noop.,2026-07-07,Codex,Reviewed by Telemetry actor/critic pair + local tests,Events and metrics now reuse pending-spool checkpoint semantics for continuous export.,Closed; continue Phase 2 after approval.
|
| 51 |
+
AUDIT-050,UX,Dashboard home audit links,entity type omitted from wiki href,src/ctx/monitor/pages/home.py; src/ctx/monitor/compat.py; src/tests/test_ctx_monitor.py,Dashboard UX pair and CTO render probe showed Home latest audit rows link to /wiki/<slug> without preserving subject_type.,Medium,Dashboard audit links should include entity type when available so duplicate slugs navigate to the intended wiki entity.,agent-reviewer workbench plus render_home probe,Retested Pass,2026-07-07,Home audit links drop subject_type for agent MCP and harness rows.,Render home with recent_audit subject_type agent and subject shared-slug; output contains /wiki/shared-slug and not /wiki/shared-slug?type=agent.,Build typed audit hrefs using subject_type or event prefix and add focused dashboard test.,Fixed,.venv/bin/python -m pytest src/tests/test_ctx_monitor.py src/tests/test_dashboard_user_story_tracker.py -q --tb=short,PASS: dashboard home audit links include typed wiki hrefs when subject_type is present; monitor/dashboard tests passed; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 52 |
+
AUDIT-051,Graph Artifacts,Promotion metadata,stale current hash and size for graph tarballs,graph/wiki-graph.tar.gz.promotion.json; graph/wiki-graph-runtime.tar.gz.promotion.json; src/validate_graph_artifacts.py,Graph/Wiki pair and CTO artifact probe showed hydrated graph tarballs match stats but sibling promotion current metadata has stale size and sha256 values.,Medium,Promotion metadata should match current hydrated graph artifacts or validation should flag stale current metadata.,agent-reviewer workbench plus artifact hash probe,Retested Pass,2026-07-07,Graph promotion JSON current entries do not match actual wiki graph tarball size and sha256.,Compare actual size and sha256 for graph/wiki-graph.tar.gz and graph/wiki-graph-runtime.tar.gz to sibling promotion JSON current fields; both mismatch.,Refresh promotion metadata and add validator coverage for promotion current metadata drift.,Fixed,.venv/bin/python src/validate_graph_artifacts.py --graph-dir graph,PASS: validator rejects stale promotion current metadata and local ignored promotion JSON now matches tarball size/sha256; validate_graph_artifacts passed; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 53 |
+
AUDIT-052,Security,Wiki pack manifest,non-hex checksum accepted,src/ctx/core/wiki/wiki_packs.py; src/ctx/core/graph/graph_packs.py; src/tests/test_wiki_packs.py,Graph/Wiki pair and CTO manifest probe showed wiki pack checksums accept any 64-character string while graph packs require SHA-256 hex shape.,Low,Wiki pack manifest checksum validation should reject non-hex digest strings consistently with graph pack manifests.,agent-reviewer workbench plus manifest parser probe,Retested Pass,2026-07-07,WikiPackManifest accepts pages.jsonl checksum z repeated 64 times.,Call WikiPackManifest.from_mapping with a valid base manifest and checksums pages.jsonl z*64; it accepts while GraphPackManifest rejects graph.json z*64.,Use SHA-256 hex regex in wiki pack checksum validation and add regression test.,Fixed,.venv/bin/python -m pytest src/tests/test_wiki_packs.py src/tests/test_graph_packs.py -q,PASS: WikiPackManifest rejects non-hex SHA-256 checksums; wiki/graph pack tests passed; combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 54 |
+
AUDIT-053,Docs,Dashboard route reference,missing supported routes and APIs,docs/dashboard.md; src/ctx/monitor/routes.py; src/tests/test_ctx_monitor.py,Docs/Runbook pair and CTO route diff showed dashboard docs omit /skillspector and APIs for skillspector grades and sidecars even though routes expose them.,Medium,Dashboard reference docs should list supported navigation routes and API routes that operators can use.,agent-reviewer workbench plus route-doc diff,Retested Pass,2026-07-07,Dashboard route reference omits SkillSpector and several supported JSON API routes.,Compare docs/dashboard.md text against ctx.monitor.routes; /skillspector /api/skillspector.json /api/grades.json and /api/sidecars.json are in routes but absent from docs.,Update docs/dashboard.md route and API reference and keep tracker tests passing.,Fixed,.venv/bin/python -m pytest src/tests/test_ctx_monitor.py src/tests/test_dashboard_user_story_tracker.py -q && .venv/bin/python -m mkdocs build --strict,PASS: dashboard docs now include SkillSpector and grades/sidecars/skillspector APIs; mkdocs build passed and combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
| 55 |
+
AUDIT-054,Docs,Knowledge graph pre-ship gates,docs say two gates but list three shipped gates,docs/knowledge-graph.md; pyproject.toml; src/tests/test_package_scaffold.py,Docs/Runbook pair and CTO help probes showed docs/knowledge-graph.md says two advisory pre-ship gates while pyproject exposes three related gate commands.,Low,Knowledge graph runbook wording should match the shipped pre-ship gate commands.,agent-reviewer workbench plus CLI help probes,Retested Pass,2026-07-07,Knowledge graph docs say two advisory gates while ctx-dedup-check ctx-tag-backfill and ctx-skillspector-audit are all shipped commands.,Read docs/knowledge-graph.md pre-ship gates section and run help for all three console modules; all three commands print usage.,Change wording to three advisory gates or split SkillSpector into a separate release audit section.,Fixed,.venv/bin/python -m mkdocs build --strict,PASS: knowledge graph docs now describe three advisory gates; mkdocs build passed and combined focused integration suite -> 487 passed.,2026-07-08,Codex,Reviewed by workbench agent pair + integration retest,Fixed in parallel backlog batch and retested with focused lane checks plus combined integration pytest.,Closed; keep covered by local-fast/no-mistakes gates.
|
qa/feature_status.csv
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
qa/tool-selection-token-history/SPEC.md
CHANGED
|
@@ -30,7 +30,7 @@ Supported recommendable entity types are shared through `ctx.core.entity_types.R
|
|
| 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`
|
| 34 |
|
| 35 |
## Existing Knowledge Graph Model
|
| 36 |
|
|
|
|
| 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 only when explicit user-owned model consent is supplied through `own_llm`; `model_provider` and `model` are ranking metadata.
|
| 34 |
|
| 35 |
## Existing Knowledge Graph Model
|
| 36 |
|
src/ctx/adapters/generic/ctx_core_tools.py
CHANGED
|
@@ -39,6 +39,11 @@ 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 |
"""
|
| 44 |
|
|
@@ -49,7 +54,7 @@ import json
|
|
| 49 |
import logging
|
| 50 |
import time
|
| 51 |
from pathlib import Path
|
| 52 |
-
from typing import Any, Callable, Mapping
|
| 53 |
|
| 54 |
from ctx.adapters.generic.providers import ToolCall, ToolDefinition
|
| 55 |
from ctx.adapters.generic.runtime_lifecycle import RuntimeLifecycleStore
|
|
@@ -59,6 +64,7 @@ from ctx.core.entity_types import (
|
|
| 59 |
entity_relpath,
|
| 60 |
entity_page_path,
|
| 61 |
entity_wikilink,
|
|
|
|
| 62 |
)
|
| 63 |
from ctx.telemetry import hash_identifier, record_event, record_exception, telemetry_span
|
| 64 |
|
|
@@ -298,11 +304,15 @@ class CtxCoreToolbox:
|
|
| 298 |
graph_path: Path | None = None,
|
| 299 |
lifecycle_dir: Path | None = None,
|
| 300 |
bound_session_id: str | None = None,
|
|
|
|
|
|
|
| 301 |
) -> None:
|
| 302 |
self._wiki_dir = wiki_dir
|
| 303 |
self._graph_path = graph_path
|
| 304 |
self._lifecycle = RuntimeLifecycleStore(lifecycle_dir)
|
| 305 |
self._bound_session_id = str(bound_session_id or "").strip() or None
|
|
|
|
|
|
|
| 306 |
self._graph: Any | None = None # networkx.Graph
|
| 307 |
self._pages: list[Any] | None = None # list[SkillPage]
|
| 308 |
self._graph_signature: GraphSignature | None = None
|
|
@@ -499,6 +509,8 @@ class CtxCoreToolbox:
|
|
| 499 |
),
|
| 500 |
]
|
| 501 |
definitions.extend(_lifecycle_tool_definitions(self._bound_session_id))
|
|
|
|
|
|
|
| 502 |
return definitions
|
| 503 |
|
| 504 |
def dispatch(self, call: ToolCall) -> str:
|
|
@@ -511,6 +523,8 @@ class CtxCoreToolbox:
|
|
| 511 |
"""
|
| 512 |
if not call.name.startswith(_NAMESPACE):
|
| 513 |
raise ValueError(f"CtxCoreToolbox got a non-ctx call {call.name!r}")
|
|
|
|
|
|
|
| 514 |
local_name = call.name[len(_NAMESPACE) :]
|
| 515 |
args = call.arguments or {}
|
| 516 |
started = time.perf_counter()
|
|
@@ -579,6 +593,10 @@ class CtxCoreToolbox:
|
|
| 579 |
"""True when this toolbox is the dispatcher for the given name."""
|
| 580 |
return tool_name.startswith(_NAMESPACE)
|
| 581 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 582 |
# ── Individual dispatchers ──────────────────────────────────────────
|
| 583 |
|
| 584 |
def _dispatch_recommend(self, args: dict[str, Any]) -> str:
|
|
@@ -619,12 +637,22 @@ class CtxCoreToolbox:
|
|
| 619 |
if use_semantic_query:
|
| 620 |
self._refresh_semantic_cache_signature()
|
| 621 |
semantic_cache_dir = _semantic_cache_dir(self._wiki_dir_resolved())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
raw = recommend_by_tags(
|
| 623 |
graph,
|
| 624 |
tags,
|
| 625 |
top_n=top_k,
|
| 626 |
query=query,
|
| 627 |
-
entity_types=
|
| 628 |
min_normalized_score=cfg.recommendation_min_normalized_score,
|
| 629 |
use_semantic_query=use_semantic_query,
|
| 630 |
semantic_cache_dir=semantic_cache_dir,
|
|
@@ -662,7 +690,7 @@ class CtxCoreToolbox:
|
|
| 662 |
model_provider=model_provider,
|
| 663 |
model=model,
|
| 664 |
)
|
| 665 |
-
if model_provider or model
|
| 666 |
else []
|
| 667 |
)
|
| 668 |
return _encode_response(
|
|
@@ -714,6 +742,8 @@ class CtxCoreToolbox:
|
|
| 714 |
)
|
| 715 |
results: list[dict[str, Any]] = []
|
| 716 |
for r in raw:
|
|
|
|
|
|
|
| 717 |
candidate_keys = _recommendation_selection_keys(
|
| 718 |
[_recommendation_identity(r), str(r.get("name") or "")]
|
| 719 |
)
|
|
@@ -780,6 +810,7 @@ class CtxCoreToolbox:
|
|
| 780 |
"via": r.get("via", []),
|
| 781 |
}
|
| 782 |
for r in raw
|
|
|
|
| 783 |
]
|
| 784 |
return _encode_response(
|
| 785 |
{"seeds": seeds, "results": results},
|
|
@@ -792,7 +823,11 @@ class CtxCoreToolbox:
|
|
| 792 |
return json.dumps({"error": "query must be non-empty", "results": []})
|
| 793 |
top_n = _clamp_int(args.get("top_n"), default=15, lo=1, hi=100)
|
| 794 |
|
| 795 |
-
pages =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 796 |
if not pages:
|
| 797 |
return json.dumps(
|
| 798 |
{
|
|
@@ -836,6 +871,8 @@ class CtxCoreToolbox:
|
|
| 836 |
),
|
| 837 |
}
|
| 838 |
)
|
|
|
|
|
|
|
| 839 |
|
| 840 |
# Validate — ctx-core's validator rejects traversal shapes.
|
| 841 |
from ctx.core.wiki.wiki_utils import validate_skill_name # noqa: PLC0415
|
|
@@ -849,7 +886,18 @@ class CtxCoreToolbox:
|
|
| 849 |
if wiki is None:
|
| 850 |
return json.dumps({"error": "wiki_dir not configured"})
|
| 851 |
|
| 852 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 853 |
try:
|
| 854 |
pack_pages = _wiki_pack_pages(wiki)
|
| 855 |
except Exception as exc: # noqa: BLE001 - surface corrupt pack state to callers.
|
|
@@ -886,6 +934,9 @@ class CtxCoreToolbox:
|
|
| 886 |
}
|
| 887 |
)
|
| 888 |
|
|
|
|
|
|
|
|
|
|
| 889 |
def _dispatch_lifecycle(self, args: dict[str, Any], name: str) -> str:
|
| 890 |
try:
|
| 891 |
session_id = self._lifecycle_session_id(args)
|
|
@@ -1107,15 +1158,39 @@ def _wiki_entity_link(slug: str, entity_type: str) -> str:
|
|
| 1107 |
def _wiki_get_candidates(
|
| 1108 |
wiki: Path,
|
| 1109 |
slug: str,
|
| 1110 |
-
|
| 1111 |
) -> list[tuple[str, Path, str]]:
|
| 1112 |
-
entity_types = [entity_type] if entity_type else list(RECOMMENDABLE_ENTITY_TYPES)
|
| 1113 |
return [
|
| 1114 |
(typ, _wiki_entity_path(wiki, slug, typ), _wiki_entity_link(slug, typ))
|
| 1115 |
for typ in entity_types
|
| 1116 |
]
|
| 1117 |
|
| 1118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1119 |
def _wiki_pack_pages(wiki: Path) -> dict[str, str] | None:
|
| 1120 |
packs_dir = wiki / "wiki-packs"
|
| 1121 |
if not packs_dir.is_dir():
|
|
|
|
| 39 |
token usage is recorded only when the host supplies explicit
|
| 40 |
``ctx__mark_entity_used.token_usage`` attribution.
|
| 41 |
|
| 42 |
+
Hosts that need a narrower permission surface can construct
|
| 43 |
+
``CtxCoreToolbox`` with ``allowed_tool_names`` and ``allowed_entity_types``.
|
| 44 |
+
That filters both tool discovery and read/query results before a model sees
|
| 45 |
+
them.
|
| 46 |
+
|
| 47 |
Plan 001 Phase H6.
|
| 48 |
"""
|
| 49 |
|
|
|
|
| 54 |
import logging
|
| 55 |
import time
|
| 56 |
from pathlib import Path
|
| 57 |
+
from typing import Any, Callable, Iterable, Mapping
|
| 58 |
|
| 59 |
from ctx.adapters.generic.providers import ToolCall, ToolDefinition
|
| 60 |
from ctx.adapters.generic.runtime_lifecycle import RuntimeLifecycleStore
|
|
|
|
| 64 |
entity_relpath,
|
| 65 |
entity_page_path,
|
| 66 |
entity_wikilink,
|
| 67 |
+
normalize_entity_type,
|
| 68 |
)
|
| 69 |
from ctx.telemetry import hash_identifier, record_event, record_exception, telemetry_span
|
| 70 |
|
|
|
|
| 304 |
graph_path: Path | None = None,
|
| 305 |
lifecycle_dir: Path | None = None,
|
| 306 |
bound_session_id: str | None = None,
|
| 307 |
+
allowed_tool_names: Iterable[str] | None = None,
|
| 308 |
+
allowed_entity_types: Iterable[str] | None = None,
|
| 309 |
) -> None:
|
| 310 |
self._wiki_dir = wiki_dir
|
| 311 |
self._graph_path = graph_path
|
| 312 |
self._lifecycle = RuntimeLifecycleStore(lifecycle_dir)
|
| 313 |
self._bound_session_id = str(bound_session_id or "").strip() or None
|
| 314 |
+
self._allowed_tool_names = _normalise_allowed_tool_names(allowed_tool_names)
|
| 315 |
+
self._allowed_entity_types = _normalise_allowed_entity_types(allowed_entity_types)
|
| 316 |
self._graph: Any | None = None # networkx.Graph
|
| 317 |
self._pages: list[Any] | None = None # list[SkillPage]
|
| 318 |
self._graph_signature: GraphSignature | None = None
|
|
|
|
| 509 |
),
|
| 510 |
]
|
| 511 |
definitions.extend(_lifecycle_tool_definitions(self._bound_session_id))
|
| 512 |
+
if self._allowed_tool_names is not None:
|
| 513 |
+
definitions = [td for td in definitions if td.name in self._allowed_tool_names]
|
| 514 |
return definitions
|
| 515 |
|
| 516 |
def dispatch(self, call: ToolCall) -> str:
|
|
|
|
| 523 |
"""
|
| 524 |
if not call.name.startswith(_NAMESPACE):
|
| 525 |
raise ValueError(f"CtxCoreToolbox got a non-ctx call {call.name!r}")
|
| 526 |
+
if self._allowed_tool_names is not None and call.name not in self._allowed_tool_names:
|
| 527 |
+
raise ValueError(f"ctx-core tool not allowed: {call.name!r}")
|
| 528 |
local_name = call.name[len(_NAMESPACE) :]
|
| 529 |
args = call.arguments or {}
|
| 530 |
started = time.perf_counter()
|
|
|
|
| 593 |
"""True when this toolbox is the dispatcher for the given name."""
|
| 594 |
return tool_name.startswith(_NAMESPACE)
|
| 595 |
|
| 596 |
+
def allows(self, tool_name: str) -> bool:
|
| 597 |
+
"""True when this toolbox is allowed to expose the given ctx tool."""
|
| 598 |
+
return self._allowed_tool_names is None or tool_name in self._allowed_tool_names
|
| 599 |
+
|
| 600 |
# ── Individual dispatchers ──────────────────────────────────────────
|
| 601 |
|
| 602 |
def _dispatch_recommend(self, args: dict[str, Any]) -> str:
|
|
|
|
| 637 |
if use_semantic_query:
|
| 638 |
self._refresh_semantic_cache_signature()
|
| 639 |
semantic_cache_dir = _semantic_cache_dir(self._wiki_dir_resolved())
|
| 640 |
+
entity_types = tuple(
|
| 641 |
+
entity_type
|
| 642 |
+
for entity_type in ("skill", "agent", "mcp-server")
|
| 643 |
+
if self._entity_type_allowed(entity_type)
|
| 644 |
+
)
|
| 645 |
+
if not entity_types:
|
| 646 |
+
return _encode_response(
|
| 647 |
+
{"query": query, "tags": tags, "results": [], "companion_harnesses": []},
|
| 648 |
+
_response_format_from_args(args),
|
| 649 |
+
)
|
| 650 |
raw = recommend_by_tags(
|
| 651 |
graph,
|
| 652 |
tags,
|
| 653 |
top_n=top_k,
|
| 654 |
query=query,
|
| 655 |
+
entity_types=entity_types,
|
| 656 |
min_normalized_score=cfg.recommendation_min_normalized_score,
|
| 657 |
use_semantic_query=use_semantic_query,
|
| 658 |
semantic_cache_dir=semantic_cache_dir,
|
|
|
|
| 690 |
model_provider=model_provider,
|
| 691 |
model=model,
|
| 692 |
)
|
| 693 |
+
if (model_provider or model) and self._entity_type_allowed("harness")
|
| 694 |
else []
|
| 695 |
)
|
| 696 |
return _encode_response(
|
|
|
|
| 742 |
)
|
| 743 |
results: list[dict[str, Any]] = []
|
| 744 |
for r in raw:
|
| 745 |
+
if not self._entity_type_allowed(str(r.get("type") or "")):
|
| 746 |
+
continue
|
| 747 |
candidate_keys = _recommendation_selection_keys(
|
| 748 |
[_recommendation_identity(r), str(r.get("name") or "")]
|
| 749 |
)
|
|
|
|
| 810 |
"via": r.get("via", []),
|
| 811 |
}
|
| 812 |
for r in raw
|
| 813 |
+
if self._entity_type_allowed(str(r.get("type") or ""))
|
| 814 |
]
|
| 815 |
return _encode_response(
|
| 816 |
{"seeds": seeds, "results": results},
|
|
|
|
| 823 |
return json.dumps({"error": "query must be non-empty", "results": []})
|
| 824 |
top_n = _clamp_int(args.get("top_n"), default=15, lo=1, hi=100)
|
| 825 |
|
| 826 |
+
pages = [
|
| 827 |
+
page
|
| 828 |
+
for page in self._ensure_pages()
|
| 829 |
+
if self._entity_type_allowed(str(page.entity_type))
|
| 830 |
+
]
|
| 831 |
if not pages:
|
| 832 |
return json.dumps(
|
| 833 |
{
|
|
|
|
| 871 |
),
|
| 872 |
}
|
| 873 |
)
|
| 874 |
+
if entity_type and not self._entity_type_allowed(entity_type):
|
| 875 |
+
return json.dumps({"error": f"entity_type {entity_type!r} is not allowed"})
|
| 876 |
|
| 877 |
# Validate — ctx-core's validator rejects traversal shapes.
|
| 878 |
from ctx.core.wiki.wiki_utils import validate_skill_name # noqa: PLC0415
|
|
|
|
| 886 |
if wiki is None:
|
| 887 |
return json.dumps({"error": "wiki_dir not configured"})
|
| 888 |
|
| 889 |
+
candidate_entity_types = (
|
| 890 |
+
(entity_type,)
|
| 891 |
+
if entity_type
|
| 892 |
+
else tuple(
|
| 893 |
+
allowed_type
|
| 894 |
+
for allowed_type in RECOMMENDABLE_ENTITY_TYPES
|
| 895 |
+
if self._entity_type_allowed(allowed_type)
|
| 896 |
+
)
|
| 897 |
+
)
|
| 898 |
+
if not candidate_entity_types:
|
| 899 |
+
return json.dumps({"error": "no entity types are allowed"})
|
| 900 |
+
candidates = _wiki_get_candidates(wiki, slug, candidate_entity_types)
|
| 901 |
try:
|
| 902 |
pack_pages = _wiki_pack_pages(wiki)
|
| 903 |
except Exception as exc: # noqa: BLE001 - surface corrupt pack state to callers.
|
|
|
|
| 934 |
}
|
| 935 |
)
|
| 936 |
|
| 937 |
+
def _entity_type_allowed(self, entity_type: str) -> bool:
|
| 938 |
+
return self._allowed_entity_types is None or entity_type in self._allowed_entity_types
|
| 939 |
+
|
| 940 |
def _dispatch_lifecycle(self, args: dict[str, Any], name: str) -> str:
|
| 941 |
try:
|
| 942 |
session_id = self._lifecycle_session_id(args)
|
|
|
|
| 1158 |
def _wiki_get_candidates(
|
| 1159 |
wiki: Path,
|
| 1160 |
slug: str,
|
| 1161 |
+
entity_types: Iterable[str],
|
| 1162 |
) -> list[tuple[str, Path, str]]:
|
|
|
|
| 1163 |
return [
|
| 1164 |
(typ, _wiki_entity_path(wiki, slug, typ), _wiki_entity_link(slug, typ))
|
| 1165 |
for typ in entity_types
|
| 1166 |
]
|
| 1167 |
|
| 1168 |
|
| 1169 |
+
def _normalise_allowed_tool_names(
|
| 1170 |
+
tool_names: Iterable[str] | None,
|
| 1171 |
+
) -> frozenset[str] | None:
|
| 1172 |
+
if tool_names is None:
|
| 1173 |
+
return None
|
| 1174 |
+
return frozenset(str(name).strip() for name in tool_names if str(name).strip())
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
def _normalise_allowed_entity_types(
|
| 1178 |
+
entity_types: Iterable[str] | None,
|
| 1179 |
+
) -> frozenset[str] | None:
|
| 1180 |
+
if entity_types is None:
|
| 1181 |
+
return None
|
| 1182 |
+
normalised: list[str] = []
|
| 1183 |
+
for raw in entity_types:
|
| 1184 |
+
entity_type = normalize_entity_type(raw, allowed=RECOMMENDABLE_ENTITY_TYPES)
|
| 1185 |
+
if entity_type is None:
|
| 1186 |
+
raise ValueError(
|
| 1187 |
+
"allowed_entity_types must contain only " + ", ".join(RECOMMENDABLE_ENTITY_TYPES)
|
| 1188 |
+
)
|
| 1189 |
+
if entity_type not in normalised:
|
| 1190 |
+
normalised.append(entity_type)
|
| 1191 |
+
return frozenset(normalised)
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
def _wiki_pack_pages(wiki: Path) -> dict[str, str] | None:
|
| 1195 |
packs_dir = wiki / "wiki-packs"
|
| 1196 |
if not packs_dir.is_dir():
|
src/ctx/adapters/generic/runtime_lifecycle.py
CHANGED
|
@@ -321,7 +321,7 @@ class RuntimeLifecycleStore:
|
|
| 321 |
with path.open("a", encoding="utf-8") as fh:
|
| 322 |
fh.write(json.dumps(event, sort_keys=True) + "\n")
|
| 323 |
_record_runtime_lifecycle_telemetry(event)
|
| 324 |
-
return {"ok": True, "event": event, "
|
| 325 |
|
| 326 |
def _events_for_session(self, session_id: str) -> list[dict[str, Any]]:
|
| 327 |
path = self.events_path
|
|
|
|
| 321 |
with path.open("a", encoding="utf-8") as fh:
|
| 322 |
fh.write(json.dumps(event, sort_keys=True) + "\n")
|
| 323 |
_record_runtime_lifecycle_telemetry(event)
|
| 324 |
+
return {"ok": True, "event": event, "recorded": True}
|
| 325 |
|
| 326 |
def _events_for_session(self, session_id: str) -> list[dict[str, Any]]:
|
| 327 |
path = self.events_path
|
src/ctx/adapters/loopflow.py
CHANGED
|
@@ -30,8 +30,18 @@ _PERMISSION_ALIASES = {
|
|
| 30 |
}
|
| 31 |
_ENTITY_TO_GROUP = {"agent": "agents", "mcp-server": "mcps", "skill": "skills"}
|
| 32 |
_GROUP_TO_ENTITY = {"skills": "skill", "agents": "agent", "mcps": "mcp-server"}
|
|
|
|
| 33 |
_CAPABILITY_KEYS = ("skills", "agents", "mcps", "harnesses")
|
| 34 |
_ALL_CAPABILITY_GRANTS = frozenset(_CAPABILITY_KEYS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
_HARNESS_REQUIREMENT_FLAGS = {
|
| 36 |
"runtime": "--harness-runtime",
|
| 37 |
"autonomy": "--harness-autonomy",
|
|
@@ -65,6 +75,10 @@ def _parse_permissions(values: list[str] | None) -> set[str]:
|
|
| 65 |
return permissions
|
| 66 |
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def parse_loop_file(path: Path) -> dict[str, Any]:
|
| 69 |
"""Extract the LoopFlow fields ctx needs from a .loop file.
|
| 70 |
|
|
@@ -88,6 +102,11 @@ def parse_loop_file(path: Path) -> dict[str, Any]:
|
|
| 88 |
]
|
| 89 |
if done_when:
|
| 90 |
fields["done_when"] = done_when
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return fields
|
| 92 |
|
| 93 |
|
|
@@ -272,9 +291,28 @@ def _harness_command(
|
|
| 272 |
|
| 273 |
|
| 274 |
def _ctx_mcp_tool_names(permissions: set[str]) -> list[str]:
|
| 275 |
-
if not
|
| 276 |
return []
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
|
| 280 |
def _normalize_harness_requirements(
|
|
@@ -407,11 +445,11 @@ def recommend_for_loop(
|
|
| 407 |
warnings.append(
|
| 408 |
"ignored unknown harness requirement(s): " + ", ".join(unknown_requirement_keys)
|
| 409 |
)
|
| 410 |
-
should_recommend_harness = "harnesses" in granted and
|
| 411 |
-
own_llm or bool(model_provider) or bool(model)
|
| 412 |
-
)
|
| 413 |
if "harnesses" in granted and not should_recommend_harness:
|
| 414 |
-
warnings.append(
|
|
|
|
|
|
|
| 415 |
if should_recommend_harness:
|
| 416 |
harness_query_parts = [
|
| 417 |
goal or ranking_query,
|
|
@@ -444,6 +482,7 @@ def recommend_for_loop(
|
|
| 444 |
if skill_names:
|
| 445 |
use_skills = "use skills: " + ", ".join(skill_names)
|
| 446 |
mcp_server_tools = _ctx_mcp_tool_names(granted)
|
|
|
|
| 447 |
use_tools = 'use tools from the "ctx" server' if mcp_server_tools else None
|
| 448 |
mcp_server_command = "ctx-mcp-server" if mcp_server_tools else None
|
| 449 |
|
|
@@ -463,6 +502,7 @@ def recommend_for_loop(
|
|
| 463 |
"mcp_server": {
|
| 464 |
"name": "ctx",
|
| 465 |
"command": mcp_server_command,
|
|
|
|
| 466 |
"tools": mcp_server_tools,
|
| 467 |
},
|
| 468 |
"capabilities": capability_bundle,
|
|
@@ -514,7 +554,10 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
| 514 |
parser.add_argument(
|
| 515 |
"--permissions",
|
| 516 |
action="append",
|
| 517 |
-
help=
|
|
|
|
|
|
|
|
|
|
| 518 |
)
|
| 519 |
parser.add_argument(
|
| 520 |
"--loop-kind",
|
|
@@ -540,8 +583,9 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
| 540 |
def main(argv: list[str] | None = None) -> int:
|
| 541 |
parser = _build_parser()
|
| 542 |
args = parser.parse_args(argv)
|
|
|
|
| 543 |
try:
|
| 544 |
-
permissions = _parse_permissions(args.permissions)
|
| 545 |
except ValueError as exc:
|
| 546 |
parser.error(str(exc))
|
| 547 |
|
|
@@ -551,6 +595,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 551 |
loop_fields = parse_loop_file(args.loop_file)
|
| 552 |
except OSError as exc:
|
| 553 |
parser.error(f"could not read --loop-file {args.loop_file}: {exc}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 554 |
goal = args.goal or str(loop_fields.get("goal") or "")
|
| 555 |
if not goal:
|
| 556 |
parser.error("--goal or a loop file with goal: is required")
|
|
|
|
| 30 |
}
|
| 31 |
_ENTITY_TO_GROUP = {"agent": "agents", "mcp-server": "mcps", "skill": "skills"}
|
| 32 |
_GROUP_TO_ENTITY = {"skills": "skill", "agents": "agent", "mcps": "mcp-server"}
|
| 33 |
+
_MCP_SCOPE_ENTITY_BY_GROUP = {"skills": "skill", "agents": "agent", "mcps": "mcp-server"}
|
| 34 |
_CAPABILITY_KEYS = ("skills", "agents", "mcps", "harnesses")
|
| 35 |
_ALL_CAPABILITY_GRANTS = frozenset(_CAPABILITY_KEYS)
|
| 36 |
+
_READ_ONLY_MCP_TOOL_NAMES = frozenset(
|
| 37 |
+
{
|
| 38 |
+
"ctx__recommend_bundle",
|
| 39 |
+
"ctx__graph_query",
|
| 40 |
+
"ctx__recommend_related",
|
| 41 |
+
"ctx__wiki_search",
|
| 42 |
+
"ctx__wiki_get",
|
| 43 |
+
}
|
| 44 |
+
)
|
| 45 |
_HARNESS_REQUIREMENT_FLAGS = {
|
| 46 |
"runtime": "--harness-runtime",
|
| 47 |
"autonomy": "--harness-autonomy",
|
|
|
|
| 75 |
return permissions
|
| 76 |
|
| 77 |
|
| 78 |
+
def _ordered_permissions(permissions: set[str]) -> list[str]:
|
| 79 |
+
return [key for key in _CAPABILITY_KEYS if key in permissions]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
def parse_loop_file(path: Path) -> dict[str, Any]:
|
| 83 |
"""Extract the LoopFlow fields ctx needs from a .loop file.
|
| 84 |
|
|
|
|
| 102 |
]
|
| 103 |
if done_when:
|
| 104 |
fields["done_when"] = done_when
|
| 105 |
+
permission_grants: set[str] = set()
|
| 106 |
+
for match in re.finditer(r"^\s*ctx\s+grants?\s*:\s*(.+)$", text, flags=re.MULTILINE):
|
| 107 |
+
permission_grants.update(_parse_permissions([match.group(1)]))
|
| 108 |
+
if permission_grants:
|
| 109 |
+
fields["permissions"] = _ordered_permissions(permission_grants)
|
| 110 |
return fields
|
| 111 |
|
| 112 |
|
|
|
|
| 291 |
|
| 292 |
|
| 293 |
def _ctx_mcp_tool_names(permissions: set[str]) -> list[str]:
|
| 294 |
+
if "mcps" not in permissions:
|
| 295 |
return []
|
| 296 |
+
tool_names = ctx_api.ctx_core_tool_names()
|
| 297 |
+
if _ALL_CAPABILITY_GRANTS <= permissions:
|
| 298 |
+
return tool_names
|
| 299 |
+
return [name for name in tool_names if name in _READ_ONLY_MCP_TOOL_NAMES]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _ctx_mcp_server_args(permissions: set[str], tool_names: list[str]) -> list[str]:
|
| 303 |
+
if not tool_names or _ALL_CAPABILITY_GRANTS <= permissions:
|
| 304 |
+
return []
|
| 305 |
+
entity_types = [
|
| 306 |
+
entity_type
|
| 307 |
+
for group, entity_type in _MCP_SCOPE_ENTITY_BY_GROUP.items()
|
| 308 |
+
if group in permissions
|
| 309 |
+
]
|
| 310 |
+
return [
|
| 311 |
+
"--allow-tools",
|
| 312 |
+
",".join(tool_names),
|
| 313 |
+
"--entity-types",
|
| 314 |
+
",".join(entity_types),
|
| 315 |
+
]
|
| 316 |
|
| 317 |
|
| 318 |
def _normalize_harness_requirements(
|
|
|
|
| 445 |
warnings.append(
|
| 446 |
"ignored unknown harness requirement(s): " + ", ".join(unknown_requirement_keys)
|
| 447 |
)
|
| 448 |
+
should_recommend_harness = "harnesses" in granted and own_llm
|
|
|
|
|
|
|
| 449 |
if "harnesses" in granted and not should_recommend_harness:
|
| 450 |
+
warnings.append(
|
| 451 |
+
"harnesses permission granted but --own-llm/user-owned model consent was not declared"
|
| 452 |
+
)
|
| 453 |
if should_recommend_harness:
|
| 454 |
harness_query_parts = [
|
| 455 |
goal or ranking_query,
|
|
|
|
| 482 |
if skill_names:
|
| 483 |
use_skills = "use skills: " + ", ".join(skill_names)
|
| 484 |
mcp_server_tools = _ctx_mcp_tool_names(granted)
|
| 485 |
+
mcp_server_args = _ctx_mcp_server_args(granted, mcp_server_tools)
|
| 486 |
use_tools = 'use tools from the "ctx" server' if mcp_server_tools else None
|
| 487 |
mcp_server_command = "ctx-mcp-server" if mcp_server_tools else None
|
| 488 |
|
|
|
|
| 502 |
"mcp_server": {
|
| 503 |
"name": "ctx",
|
| 504 |
"command": mcp_server_command,
|
| 505 |
+
"args": mcp_server_args,
|
| 506 |
"tools": mcp_server_tools,
|
| 507 |
},
|
| 508 |
"capabilities": capability_bundle,
|
|
|
|
| 554 |
parser.add_argument(
|
| 555 |
"--permissions",
|
| 556 |
action="append",
|
| 557 |
+
help=(
|
| 558 |
+
"Comma-separated capability grants: skills, agents, mcps, harnesses. "
|
| 559 |
+
"Overrides ctx grants in a .loop file."
|
| 560 |
+
),
|
| 561 |
)
|
| 562 |
parser.add_argument(
|
| 563 |
"--loop-kind",
|
|
|
|
| 583 |
def main(argv: list[str] | None = None) -> int:
|
| 584 |
parser = _build_parser()
|
| 585 |
args = parser.parse_args(argv)
|
| 586 |
+
cli_permissions_provided = args.permissions is not None
|
| 587 |
try:
|
| 588 |
+
permissions = _parse_permissions(args.permissions) if cli_permissions_provided else set()
|
| 589 |
except ValueError as exc:
|
| 590 |
parser.error(str(exc))
|
| 591 |
|
|
|
|
| 595 |
loop_fields = parse_loop_file(args.loop_file)
|
| 596 |
except OSError as exc:
|
| 597 |
parser.error(f"could not read --loop-file {args.loop_file}: {exc}")
|
| 598 |
+
except ValueError as exc:
|
| 599 |
+
parser.error(f"could not parse --loop-file {args.loop_file}: {exc}")
|
| 600 |
+
if not cli_permissions_provided:
|
| 601 |
+
permissions = set(loop_fields.get("permissions", []))
|
| 602 |
goal = args.goal or str(loop_fields.get("goal") or "")
|
| 603 |
if not goal:
|
| 604 |
parser.error("--goal or a loop file with goal: is required")
|
src/ctx/api.py
CHANGED
|
@@ -53,7 +53,7 @@ Public functions:
|
|
| 53 |
by default) — lets callers pre-build a custom CtxCoreToolbox
|
| 54 |
pointed at a non-default location.
|
| 55 |
|
| 56 |
-
Adapter support helpers:
|
| 57 |
|
| 58 |
ctx_core_tool_names()
|
| 59 |
Return ctx-core tool names exposed by the shared toolbox.
|
|
@@ -61,6 +61,11 @@ Adapter support helpers:
|
|
| 61 |
recommendation_graph()
|
| 62 |
Return the shared recommendation graph for adapter-side ranking.
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
Plan 001 Phase H9.
|
| 65 |
"""
|
| 66 |
|
|
|
|
| 53 |
by default) — lets callers pre-build a custom CtxCoreToolbox
|
| 54 |
pointed at a non-default location.
|
| 55 |
|
| 56 |
+
Adapter support helpers, not part of the stable public import contract:
|
| 57 |
|
| 58 |
ctx_core_tool_names()
|
| 59 |
Return ctx-core tool names exposed by the shared toolbox.
|
|
|
|
| 61 |
recommendation_graph()
|
| 62 |
Return the shared recommendation graph for adapter-side ranking.
|
| 63 |
|
| 64 |
+
These remain module-level support for first-party adapters. They are
|
| 65 |
+
intentionally omitted from ``__all__`` and from top-level ``ctx``
|
| 66 |
+
re-exports; third-party callers that need adapter plumbing should use
|
| 67 |
+
``CtxCoreToolbox`` directly.
|
| 68 |
+
|
| 69 |
Plan 001 Phase H9.
|
| 70 |
"""
|
| 71 |
|
src/ctx/core/wiki/wiki_packs.py
CHANGED
|
@@ -11,6 +11,7 @@ from __future__ import annotations
|
|
| 11 |
import argparse
|
| 12 |
import hashlib
|
| 13 |
import json
|
|
|
|
| 14 |
import sys
|
| 15 |
from dataclasses import dataclass
|
| 16 |
from datetime import UTC, datetime
|
|
@@ -22,6 +23,7 @@ from ctx.utils._fs_utils import atomic_write_text
|
|
| 22 |
WIKI_PACK_MANIFEST = "wiki-pack-manifest.json"
|
| 23 |
WIKI_PACK_SCHEMA_VERSION = 1
|
| 24 |
WIKI_PACK_TYPES = frozenset({"base", "overlay"})
|
|
|
|
| 25 |
|
| 26 |
WikiPackType = Literal["base", "overlay"]
|
| 27 |
|
|
@@ -663,7 +665,7 @@ def _checksums(value: object) -> dict[str, str]:
|
|
| 663 |
raise WikiPackManifestError("wiki pack manifest checksum names must be strings")
|
| 664 |
name = raw_name.replace("\\", "/").strip()
|
| 665 |
_validate_relative_name(name, "checksum name")
|
| 666 |
-
if not isinstance(raw_digest, str) or
|
| 667 |
raise WikiPackManifestError(
|
| 668 |
f"wiki pack manifest checksum for {name} must be a SHA-256 hex digest"
|
| 669 |
)
|
|
|
|
| 11 |
import argparse
|
| 12 |
import hashlib
|
| 13 |
import json
|
| 14 |
+
import re
|
| 15 |
import sys
|
| 16 |
from dataclasses import dataclass
|
| 17 |
from datetime import UTC, datetime
|
|
|
|
| 23 |
WIKI_PACK_MANIFEST = "wiki-pack-manifest.json"
|
| 24 |
WIKI_PACK_SCHEMA_VERSION = 1
|
| 25 |
WIKI_PACK_TYPES = frozenset({"base", "overlay"})
|
| 26 |
+
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
| 27 |
|
| 28 |
WikiPackType = Literal["base", "overlay"]
|
| 29 |
|
|
|
|
| 665 |
raise WikiPackManifestError("wiki pack manifest checksum names must be strings")
|
| 666 |
name = raw_name.replace("\\", "/").strip()
|
| 667 |
_validate_relative_name(name, "checksum name")
|
| 668 |
+
if not isinstance(raw_digest, str) or not _SHA256_RE.match(raw_digest):
|
| 669 |
raise WikiPackManifestError(
|
| 670 |
f"wiki pack manifest checksum for {name} must be a SHA-256 hex digest"
|
| 671 |
)
|
src/ctx/mcp_server/__init__.py
CHANGED
|
@@ -18,6 +18,8 @@ Tools exposed:
|
|
| 18 |
runtime lifecycle records and session state
|
| 19 |
|
| 20 |
Console script: ``ctx-mcp-server``.
|
|
|
|
|
|
|
| 21 |
|
| 22 |
Host examples that can attach this server:
|
| 23 |
Claude Code: claude mcp add ctx-wiki -- ctx-mcp-server
|
|
|
|
| 18 |
runtime lifecycle records and session state
|
| 19 |
|
| 20 |
Console script: ``ctx-mcp-server``.
|
| 21 |
+
Use ``--allow-tools`` and ``--entity-types`` to expose a scoped subset for
|
| 22 |
+
permissioned adapters.
|
| 23 |
|
| 24 |
Host examples that can attach this server:
|
| 25 |
Claude Code: claude mcp add ctx-wiki -- ctx-mcp-server
|
src/ctx/mcp_server/server.py
CHANGED
|
@@ -22,6 +22,9 @@ 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 — that
|
| 26 |
module is the source of truth for the tool catalogue):
|
| 27 |
|
|
@@ -60,15 +63,17 @@ Plan 001 Phase H8.
|
|
| 60 |
|
| 61 |
from __future__ import annotations
|
| 62 |
|
|
|
|
| 63 |
import json
|
| 64 |
import logging
|
| 65 |
import sys
|
| 66 |
import time
|
| 67 |
from dataclasses import dataclass
|
| 68 |
-
from typing import Any, BinaryIO
|
| 69 |
|
| 70 |
from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
|
| 71 |
from ctx.adapters.generic.providers import ToolCall
|
|
|
|
| 72 |
from ctx.telemetry import (
|
| 73 |
hash_identifier,
|
| 74 |
parse_traceparent,
|
|
@@ -100,10 +105,15 @@ class _ServerState:
|
|
| 100 |
|
| 101 |
initialized: bool = False
|
| 102 |
toolbox: CtxCoreToolbox | None = None
|
|
|
|
|
|
|
| 103 |
|
| 104 |
def ensure_toolbox(self) -> CtxCoreToolbox:
|
| 105 |
if self.toolbox is None:
|
| 106 |
-
self.toolbox = CtxCoreToolbox(
|
|
|
|
|
|
|
|
|
|
| 107 |
return self.toolbox
|
| 108 |
|
| 109 |
|
|
@@ -166,7 +176,7 @@ def _handle_tools_call(state: _ServerState, params: dict[str, Any]) -> dict[str,
|
|
| 166 |
if not isinstance(arguments, dict):
|
| 167 |
raise _JsonRpcError(_ErrorCode.INVALID_PARAMS, "params.arguments must be an object")
|
| 168 |
|
| 169 |
-
if not toolbox.owns(name):
|
| 170 |
raise _JsonRpcError(
|
| 171 |
_ErrorCode.METHOD_NOT_FOUND,
|
| 172 |
f"tool not found: {name!r}. Known prefix: ctx__",
|
|
@@ -390,6 +400,40 @@ def _record_mcp_request(
|
|
| 390 |
pass
|
| 391 |
|
| 392 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
class _JsonRpcError(Exception):
|
| 394 |
"""Raised inside a handler to emit an RPC-level error response."""
|
| 395 |
|
|
@@ -406,6 +450,9 @@ class _JsonRpcError(Exception):
|
|
| 406 |
def run_server(
|
| 407 |
stdin: BinaryIO | None = None,
|
| 408 |
stdout: BinaryIO | None = None,
|
|
|
|
|
|
|
|
|
|
| 409 |
) -> int:
|
| 410 |
"""Read JSON-RPC frames from ``stdin`` until EOF, write to ``stdout``.
|
| 411 |
|
|
@@ -418,7 +465,10 @@ def run_server(
|
|
| 418 |
"""
|
| 419 |
in_stream: BinaryIO = stdin if stdin is not None else sys.stdin.buffer
|
| 420 |
out_stream: BinaryIO = stdout if stdout is not None else sys.stdout.buffer
|
| 421 |
-
state = _ServerState(
|
|
|
|
|
|
|
|
|
|
| 422 |
|
| 423 |
try:
|
| 424 |
while True:
|
|
@@ -635,8 +685,29 @@ def _write_error(
|
|
| 635 |
# ── CLI entry ─────────────────────────────────────────────────────────────
|
| 636 |
|
| 637 |
|
| 638 |
-
def main() -> int:
|
| 639 |
"""Entry point for the ``ctx-mcp-server`` console script."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 640 |
# Keep logging on stderr so it doesn't corrupt the stdout JSON-RPC
|
| 641 |
# stream. Level defaults to WARNING — hosts typically don't want
|
| 642 |
# debug noise unless the user opts in.
|
|
@@ -645,7 +716,10 @@ def main() -> int:
|
|
| 645 |
level=logging.WARNING,
|
| 646 |
format="%(asctime)s ctx-mcp-server %(levelname)s %(message)s",
|
| 647 |
)
|
| 648 |
-
return run_server(
|
|
|
|
|
|
|
|
|
|
| 649 |
|
| 650 |
|
| 651 |
if __name__ == "__main__":
|
|
|
|
| 22 |
|
| 23 |
<host-specific config pointing at the ``ctx-mcp-server`` binary>
|
| 24 |
|
| 25 |
+
Permissioned adapters can pass ``--allow-tools`` and ``--entity-types`` to
|
| 26 |
+
expose only selected ctx tools and entity types.
|
| 27 |
+
|
| 28 |
Tools exposed (same as ctx.adapters.generic.ctx_core_tools — that
|
| 29 |
module is the source of truth for the tool catalogue):
|
| 30 |
|
|
|
|
| 63 |
|
| 64 |
from __future__ import annotations
|
| 65 |
|
| 66 |
+
import argparse
|
| 67 |
import json
|
| 68 |
import logging
|
| 69 |
import sys
|
| 70 |
import time
|
| 71 |
from dataclasses import dataclass
|
| 72 |
+
from typing import Any, BinaryIO, Iterable
|
| 73 |
|
| 74 |
from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
|
| 75 |
from ctx.adapters.generic.providers import ToolCall
|
| 76 |
+
from ctx.core.entity_types import RECOMMENDABLE_ENTITY_TYPES, normalize_entity_type
|
| 77 |
from ctx.telemetry import (
|
| 78 |
hash_identifier,
|
| 79 |
parse_traceparent,
|
|
|
|
| 105 |
|
| 106 |
initialized: bool = False
|
| 107 |
toolbox: CtxCoreToolbox | None = None
|
| 108 |
+
allowed_tool_names: frozenset[str] | None = None
|
| 109 |
+
allowed_entity_types: frozenset[str] | None = None
|
| 110 |
|
| 111 |
def ensure_toolbox(self) -> CtxCoreToolbox:
|
| 112 |
if self.toolbox is None:
|
| 113 |
+
self.toolbox = CtxCoreToolbox(
|
| 114 |
+
allowed_tool_names=self.allowed_tool_names,
|
| 115 |
+
allowed_entity_types=self.allowed_entity_types,
|
| 116 |
+
)
|
| 117 |
return self.toolbox
|
| 118 |
|
| 119 |
|
|
|
|
| 176 |
if not isinstance(arguments, dict):
|
| 177 |
raise _JsonRpcError(_ErrorCode.INVALID_PARAMS, "params.arguments must be an object")
|
| 178 |
|
| 179 |
+
if not toolbox.owns(name) or not toolbox.allows(name):
|
| 180 |
raise _JsonRpcError(
|
| 181 |
_ErrorCode.METHOD_NOT_FOUND,
|
| 182 |
f"tool not found: {name!r}. Known prefix: ctx__",
|
|
|
|
| 400 |
pass
|
| 401 |
|
| 402 |
|
| 403 |
+
def _csv_items(values: Iterable[str] | None) -> list[str]:
|
| 404 |
+
if values is None:
|
| 405 |
+
return []
|
| 406 |
+
items: list[str] = []
|
| 407 |
+
for value in values:
|
| 408 |
+
items.extend(piece.strip() for piece in value.split(",") if piece.strip())
|
| 409 |
+
return items
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _normalise_allowed_tool_names(
|
| 413 |
+
tool_names: Iterable[str] | None,
|
| 414 |
+
) -> frozenset[str] | None:
|
| 415 |
+
if tool_names is None:
|
| 416 |
+
return None
|
| 417 |
+
return frozenset(str(name).strip() for name in tool_names if str(name).strip())
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _normalise_allowed_entity_types(
|
| 421 |
+
entity_types: Iterable[str] | None,
|
| 422 |
+
) -> frozenset[str] | None:
|
| 423 |
+
if entity_types is None:
|
| 424 |
+
return None
|
| 425 |
+
normalised: list[str] = []
|
| 426 |
+
for raw in entity_types:
|
| 427 |
+
entity_type = normalize_entity_type(raw, allowed=RECOMMENDABLE_ENTITY_TYPES)
|
| 428 |
+
if entity_type is None:
|
| 429 |
+
raise ValueError(
|
| 430 |
+
"allowed entity types must be one of " + ", ".join(RECOMMENDABLE_ENTITY_TYPES)
|
| 431 |
+
)
|
| 432 |
+
if entity_type not in normalised:
|
| 433 |
+
normalised.append(entity_type)
|
| 434 |
+
return frozenset(normalised)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
class _JsonRpcError(Exception):
|
| 438 |
"""Raised inside a handler to emit an RPC-level error response."""
|
| 439 |
|
|
|
|
| 450 |
def run_server(
|
| 451 |
stdin: BinaryIO | None = None,
|
| 452 |
stdout: BinaryIO | None = None,
|
| 453 |
+
*,
|
| 454 |
+
allowed_tool_names: Iterable[str] | None = None,
|
| 455 |
+
allowed_entity_types: Iterable[str] | None = None,
|
| 456 |
) -> int:
|
| 457 |
"""Read JSON-RPC frames from ``stdin`` until EOF, write to ``stdout``.
|
| 458 |
|
|
|
|
| 465 |
"""
|
| 466 |
in_stream: BinaryIO = stdin if stdin is not None else sys.stdin.buffer
|
| 467 |
out_stream: BinaryIO = stdout if stdout is not None else sys.stdout.buffer
|
| 468 |
+
state = _ServerState(
|
| 469 |
+
allowed_tool_names=_normalise_allowed_tool_names(allowed_tool_names),
|
| 470 |
+
allowed_entity_types=_normalise_allowed_entity_types(allowed_entity_types),
|
| 471 |
+
)
|
| 472 |
|
| 473 |
try:
|
| 474 |
while True:
|
|
|
|
| 685 |
# ── CLI entry ─────────────────────────────────────────────────────────────
|
| 686 |
|
| 687 |
|
| 688 |
+
def main(argv: list[str] | None = None) -> int:
|
| 689 |
"""Entry point for the ``ctx-mcp-server`` console script."""
|
| 690 |
+
parser = argparse.ArgumentParser(description="Run the ctx MCP stdio server.")
|
| 691 |
+
parser.add_argument(
|
| 692 |
+
"--allow-tools",
|
| 693 |
+
action="append",
|
| 694 |
+
help="Comma-separated ctx tool names to expose. Omit to expose all ctx tools.",
|
| 695 |
+
)
|
| 696 |
+
parser.add_argument(
|
| 697 |
+
"--entity-types",
|
| 698 |
+
action="append",
|
| 699 |
+
help=(
|
| 700 |
+
"Comma-separated entity types allowed in read/query results. "
|
| 701 |
+
"Omit to expose every recommendable entity type."
|
| 702 |
+
),
|
| 703 |
+
)
|
| 704 |
+
args = parser.parse_args(argv)
|
| 705 |
+
allowed_entity_types = _csv_items(args.entity_types) if args.entity_types is not None else None
|
| 706 |
+
try:
|
| 707 |
+
_normalise_allowed_entity_types(allowed_entity_types)
|
| 708 |
+
except ValueError as exc:
|
| 709 |
+
parser.error(str(exc))
|
| 710 |
+
|
| 711 |
# Keep logging on stderr so it doesn't corrupt the stdout JSON-RPC
|
| 712 |
# stream. Level defaults to WARNING — hosts typically don't want
|
| 713 |
# debug noise unless the user opts in.
|
|
|
|
| 716 |
level=logging.WARNING,
|
| 717 |
format="%(asctime)s ctx-mcp-server %(levelname)s %(message)s",
|
| 718 |
)
|
| 719 |
+
return run_server(
|
| 720 |
+
allowed_tool_names=_csv_items(args.allow_tools) if args.allow_tools is not None else None,
|
| 721 |
+
allowed_entity_types=allowed_entity_types,
|
| 722 |
+
)
|
| 723 |
|
| 724 |
|
| 725 |
if __name__ == "__main__":
|
src/ctx/monitor/pages/home.py
CHANGED
|
@@ -5,11 +5,19 @@ from __future__ import annotations
|
|
| 5 |
import html
|
| 6 |
from collections.abc import Callable
|
| 7 |
from typing import Any
|
|
|
|
| 8 |
|
| 9 |
LayoutFn = Callable[[str, str], str]
|
| 10 |
FormatCountFn = Callable[[int], str]
|
| 11 |
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
def render_home(
|
| 14 |
*,
|
| 15 |
manifest: dict[str, Any],
|
|
@@ -49,7 +57,7 @@ def render_home(
|
|
| 49 |
audit_rows = "".join(
|
| 50 |
f"<tr><td class='muted'>{html.escape((row.get('ts') or '')[-8:])}</td>"
|
| 51 |
f"<td><span class='pill'>{html.escape(row.get('event', ''))}</span></td>"
|
| 52 |
-
f"<td><a href='
|
| 53 |
"</tr>"
|
| 54 |
for row in reversed(recent_audit)
|
| 55 |
)
|
|
|
|
| 5 |
import html
|
| 6 |
from collections.abc import Callable
|
| 7 |
from typing import Any
|
| 8 |
+
from urllib.parse import quote
|
| 9 |
|
| 10 |
LayoutFn = Callable[[str, str], str]
|
| 11 |
FormatCountFn = Callable[[int], str]
|
| 12 |
|
| 13 |
|
| 14 |
+
def _audit_subject_href(row: dict[str, Any]) -> str:
|
| 15 |
+
subject = str(row.get("subject") or "")
|
| 16 |
+
subject_type = str(row.get("subject_type") or "")
|
| 17 |
+
suffix = f"?type={quote(subject_type)}" if subject_type else ""
|
| 18 |
+
return f"/wiki/{quote(subject)}{suffix}"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
def render_home(
|
| 22 |
*,
|
| 23 |
manifest: dict[str, Any],
|
|
|
|
| 57 |
audit_rows = "".join(
|
| 58 |
f"<tr><td class='muted'>{html.escape((row.get('ts') or '')[-8:])}</td>"
|
| 59 |
f"<td><span class='pill'>{html.escape(row.get('event', ''))}</span></td>"
|
| 60 |
+
f"<td><a href='{html.escape(_audit_subject_href(row))}'><code>{html.escape(row.get('subject', ''))}</code></a></td>"
|
| 61 |
"</tr>"
|
| 62 |
for row in reversed(recent_audit)
|
| 63 |
)
|
src/ctx/telemetry/__init__.py
CHANGED
|
@@ -13,13 +13,14 @@ import ipaddress
|
|
| 13 |
import json
|
| 14 |
import math
|
| 15 |
import os
|
|
|
|
| 16 |
import secrets
|
| 17 |
import sys
|
| 18 |
import traceback
|
| 19 |
import uuid
|
| 20 |
from contextlib import contextmanager
|
| 21 |
from contextvars import ContextVar
|
| 22 |
-
from dataclasses import asdict, dataclass, field
|
| 23 |
from datetime import datetime, timedelta, timezone
|
| 24 |
from importlib.metadata import PackageNotFoundError, version as package_version
|
| 25 |
from pathlib import Path
|
|
@@ -131,6 +132,20 @@ _RAW_VALUE_KEY_SUFFIXES = (
|
|
| 131 |
"_project_url",
|
| 132 |
)
|
| 133 |
_SCALAR_TYPES = (str, int, float, bool, type(None))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
def _raw_value_key_like(normalized_key: str) -> bool:
|
|
@@ -594,38 +609,38 @@ def record_event(
|
|
| 594 |
return None
|
| 595 |
if settings["export_enabled"]:
|
| 596 |
started_at = _now_iso()
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
settings,
|
| 600 |
-
source_path=target,
|
| 601 |
-
trusted_root=trusted_root,
|
| 602 |
-
)
|
| 603 |
-
checkpoint_before_event_id = _read_export_checkpoint(
|
| 604 |
-
checkpoint_path,
|
| 605 |
settings=settings,
|
| 606 |
-
|
|
|
|
| 607 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
checkpoint_after_event_id = checkpoint_before_event_id
|
| 609 |
checkpoint_advanced = False
|
| 610 |
last_success_at = None
|
| 611 |
last_success_event_id = None
|
| 612 |
-
if result.failed == 0 and result.exported:
|
| 613 |
-
_write_export_checkpoint(
|
| 614 |
-
settings,
|
| 615 |
-
source_path=target,
|
| 616 |
-
event=event,
|
| 617 |
-
trusted_root=trusted_root,
|
| 618 |
-
)
|
| 619 |
-
checkpoint_after_event_id = event.event_id
|
| 620 |
-
checkpoint_advanced = checkpoint_after_event_id != checkpoint_before_event_id
|
| 621 |
last_success_at = _now_iso()
|
| 622 |
-
last_success_event_id =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 623 |
status_path = _export_status_path(
|
| 624 |
settings,
|
| 625 |
source_path=target,
|
| 626 |
trusted_root=trusted_root,
|
| 627 |
)
|
| 628 |
-
status =
|
| 629 |
final_result = ExportResult(
|
| 630 |
attempted=result.attempted,
|
| 631 |
exported=result.exported,
|
|
@@ -635,11 +650,15 @@ def record_event(
|
|
| 635 |
error_kind=result.error_kind,
|
| 636 |
checkpoint_path=str(checkpoint_path),
|
| 637 |
last_event_id=checkpoint_after_event_id,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 638 |
status_path=str(status_path),
|
| 639 |
checkpoint_before_event_id=checkpoint_before_event_id,
|
| 640 |
checkpoint_after_event_id=checkpoint_after_event_id,
|
| 641 |
checkpoint_advanced=checkpoint_advanced,
|
| 642 |
-
checkpoint_found=
|
| 643 |
destination_hash=_export_destination_hash(settings),
|
| 644 |
last_success_at=last_success_at,
|
| 645 |
last_success_event_id=last_success_event_id,
|
|
@@ -1904,6 +1923,38 @@ def _is_forbidden_otlp_ip(host: str) -> bool:
|
|
| 1904 |
)
|
| 1905 |
|
| 1906 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1907 |
def _export_events(
|
| 1908 |
events: list[TelemetryEvent],
|
| 1909 |
*,
|
|
@@ -1914,10 +1965,15 @@ def _export_events(
|
|
| 1914 |
if not events:
|
| 1915 |
return ExportResult(attempted=0, exported=0, failed=0, sink=sink)
|
| 1916 |
try:
|
|
|
|
| 1917 |
if sink == "local_jsonl":
|
| 1918 |
-
_export_local_jsonl(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1919 |
elif sink == "otlp_http":
|
| 1920 |
-
_post_otlp_http(_otlp_logs_payload(
|
| 1921 |
else:
|
| 1922 |
return ExportResult(
|
| 1923 |
attempted=len(events),
|
|
@@ -1946,38 +2002,38 @@ def _export_recorded_metric(
|
|
| 1946 |
trusted_root: Path | None,
|
| 1947 |
) -> None:
|
| 1948 |
started_at = _now_iso()
|
| 1949 |
-
|
| 1950 |
-
|
| 1951 |
-
settings,
|
| 1952 |
-
source_path=source_path,
|
| 1953 |
-
trusted_root=trusted_root,
|
| 1954 |
-
)
|
| 1955 |
-
checkpoint_before_metric_id = _read_metric_export_checkpoint(
|
| 1956 |
-
checkpoint_path,
|
| 1957 |
settings=settings,
|
| 1958 |
-
|
|
|
|
| 1959 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1960 |
checkpoint_after_metric_id = checkpoint_before_metric_id
|
| 1961 |
checkpoint_advanced = False
|
| 1962 |
last_success_at = None
|
| 1963 |
last_success_metric_id = None
|
| 1964 |
-
if result.failed == 0 and result.exported:
|
| 1965 |
-
_write_metric_export_checkpoint(
|
| 1966 |
-
settings,
|
| 1967 |
-
source_path=source_path,
|
| 1968 |
-
metric=metric,
|
| 1969 |
-
trusted_root=trusted_root,
|
| 1970 |
-
)
|
| 1971 |
-
checkpoint_after_metric_id = metric.metric_id
|
| 1972 |
-
checkpoint_advanced = checkpoint_after_metric_id != checkpoint_before_metric_id
|
| 1973 |
last_success_at = _now_iso()
|
| 1974 |
-
last_success_metric_id =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1975 |
status_path = _metric_export_status_path(
|
| 1976 |
settings,
|
| 1977 |
source_path=source_path,
|
| 1978 |
trusted_root=trusted_root,
|
| 1979 |
)
|
| 1980 |
-
status =
|
| 1981 |
final_result = MetricExportResult(
|
| 1982 |
attempted=result.attempted,
|
| 1983 |
exported=result.exported,
|
|
@@ -1987,11 +2043,15 @@ def _export_recorded_metric(
|
|
| 1987 |
error_kind=result.error_kind,
|
| 1988 |
checkpoint_path=str(checkpoint_path),
|
| 1989 |
last_metric_id=checkpoint_after_metric_id,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1990 |
status_path=str(status_path),
|
| 1991 |
checkpoint_before_metric_id=checkpoint_before_metric_id,
|
| 1992 |
checkpoint_after_metric_id=checkpoint_after_metric_id,
|
| 1993 |
checkpoint_advanced=checkpoint_advanced,
|
| 1994 |
-
checkpoint_found=
|
| 1995 |
destination_hash=_metric_export_destination_hash(settings),
|
| 1996 |
last_success_at=last_success_at,
|
| 1997 |
last_success_metric_id=last_success_metric_id,
|
|
@@ -2016,14 +2076,15 @@ def _export_metrics(
|
|
| 2016 |
if not metrics:
|
| 2017 |
return MetricExportResult(attempted=0, exported=0, failed=0, sink=sink)
|
| 2018 |
try:
|
|
|
|
| 2019 |
if sink == "local_jsonl":
|
| 2020 |
_export_local_metrics_jsonl(
|
| 2021 |
-
|
| 2022 |
Path(str(settings["metric_export_path"])),
|
| 2023 |
trusted_root,
|
| 2024 |
)
|
| 2025 |
elif sink == "otlp_http":
|
| 2026 |
-
_post_otlp_http(_otlp_metrics_payload(
|
| 2027 |
else:
|
| 2028 |
return MetricExportResult(
|
| 2029 |
attempted=len(metrics),
|
|
@@ -2562,7 +2623,11 @@ def _otlp_metrics_payload(
|
|
| 2562 |
{
|
| 2563 |
"scope": {"name": "ctx.telemetry", "version": METRIC_SCHEMA_VERSION},
|
| 2564 |
"metrics": [
|
| 2565 |
-
_otlp_metric_record(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2566 |
],
|
| 2567 |
}
|
| 2568 |
],
|
|
@@ -2661,6 +2726,13 @@ def _otlp_log_record(event: TelemetryEvent, *, settings: Mapping[str, Any]) -> d
|
|
| 2661 |
session_hash = event.session_hash
|
| 2662 |
if session_hash is None and event.session_id:
|
| 2663 |
session_hash = hash_identifier(event.session_id, salt=settings["hash_salt"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2664 |
attributes = {
|
| 2665 |
"event.name": event.event_name,
|
| 2666 |
"ctx.schema_version": event.schema_version,
|
|
@@ -2668,7 +2740,7 @@ def _otlp_log_record(event: TelemetryEvent, *, settings: Mapping[str, Any]) -> d
|
|
| 2668 |
"ctx.source": event.source,
|
| 2669 |
"ctx.outcome": event.outcome,
|
| 2670 |
"ctx.privacy_mode": event.privacy_mode,
|
| 2671 |
-
**{f"ctx.payload.{key}": value for key, value in
|
| 2672 |
}
|
| 2673 |
optional = {
|
| 2674 |
"ctx.session.hash": session_hash,
|
|
@@ -2723,6 +2795,21 @@ def _otlp_value(value: Any) -> dict[str, Any]:
|
|
| 2723 |
return {"stringValue": json.dumps(value, sort_keys=True, default=str)}
|
| 2724 |
|
| 2725 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2726 |
def _sanitize_payload(
|
| 2727 |
payload: Mapping[str, Any],
|
| 2728 |
*,
|
|
@@ -2769,6 +2856,8 @@ def _sanitize_value(
|
|
| 2769 |
if isinstance(value, _SCALAR_TYPES):
|
| 2770 |
if isinstance(value, str):
|
| 2771 |
text = redact_secret_text(value)
|
|
|
|
|
|
|
| 2772 |
if len(text) > max_value_len:
|
| 2773 |
return text[:max_value_len] + "...[truncated]"
|
| 2774 |
return text
|
|
|
|
| 13 |
import json
|
| 14 |
import math
|
| 15 |
import os
|
| 16 |
+
import re
|
| 17 |
import secrets
|
| 18 |
import sys
|
| 19 |
import traceback
|
| 20 |
import uuid
|
| 21 |
from contextlib import contextmanager
|
| 22 |
from contextvars import ContextVar
|
| 23 |
+
from dataclasses import asdict, dataclass, field, replace
|
| 24 |
from datetime import datetime, timedelta, timezone
|
| 25 |
from importlib.metadata import PackageNotFoundError, version as package_version
|
| 26 |
from pathlib import Path
|
|
|
|
| 132 |
"_project_url",
|
| 133 |
)
|
| 134 |
_SCALAR_TYPES = (str, int, float, bool, type(None))
|
| 135 |
+
_PATH_TEXT_SEGMENT_RE = r"[^/\\\s'\"`<>|:;,\)\]]+"
|
| 136 |
+
_POSIX_LOCAL_HOST_PATH_RE = re.compile(
|
| 137 |
+
rf"(?<![\w./-])/(?:Users|home|private|tmp|var)(?:/{_PATH_TEXT_SEGMENT_RE})+"
|
| 138 |
+
)
|
| 139 |
+
_TILDE_LOCAL_HOST_PATH_RE = re.compile(rf"(?<![\w./-])~(?:/{_PATH_TEXT_SEGMENT_RE})+")
|
| 140 |
+
_WINDOWS_LOCAL_HOST_PATH_RE = re.compile(
|
| 141 |
+
r"(?<![\w./-])[A-Za-z]:[\\/](?:[^/\\\s'\"`<>|:;,\)\]]+[\\/])*"
|
| 142 |
+
r"[^/\\\s'\"`<>|:;,\)\]]+"
|
| 143 |
+
)
|
| 144 |
+
_LOCAL_HOST_PATH_PATTERNS = (
|
| 145 |
+
_POSIX_LOCAL_HOST_PATH_RE,
|
| 146 |
+
_TILDE_LOCAL_HOST_PATH_RE,
|
| 147 |
+
_WINDOWS_LOCAL_HOST_PATH_RE,
|
| 148 |
+
)
|
| 149 |
|
| 150 |
|
| 151 |
def _raw_value_key_like(normalized_key: str) -> bool:
|
|
|
|
| 609 |
return None
|
| 610 |
if settings["export_enabled"]:
|
| 611 |
started_at = _now_iso()
|
| 612 |
+
pending = _events_pending_export(
|
| 613 |
+
target,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 614 |
settings=settings,
|
| 615 |
+
trusted_root=trusted_root,
|
| 616 |
+
include_exported=False,
|
| 617 |
)
|
| 618 |
+
last_event = pending.events[-1] if pending.events else None
|
| 619 |
+
result = _export_events(pending.events, settings=settings, trusted_root=trusted_root)
|
| 620 |
+
checkpoint_path = pending.checkpoint_path
|
| 621 |
+
checkpoint_before_event_id = pending.checkpoint_before_event_id
|
| 622 |
checkpoint_after_event_id = checkpoint_before_event_id
|
| 623 |
checkpoint_advanced = False
|
| 624 |
last_success_at = None
|
| 625 |
last_success_event_id = None
|
| 626 |
+
if result.failed == 0 and result.exported and last_event is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 627 |
last_success_at = _now_iso()
|
| 628 |
+
last_success_event_id = last_event.event_id
|
| 629 |
+
if pending.malformed_pending_records == 0:
|
| 630 |
+
_write_export_checkpoint(
|
| 631 |
+
settings,
|
| 632 |
+
source_path=target,
|
| 633 |
+
event=last_event,
|
| 634 |
+
trusted_root=trusted_root,
|
| 635 |
+
)
|
| 636 |
+
checkpoint_after_event_id = last_event.event_id
|
| 637 |
+
checkpoint_advanced = checkpoint_after_event_id != checkpoint_before_event_id
|
| 638 |
status_path = _export_status_path(
|
| 639 |
settings,
|
| 640 |
source_path=target,
|
| 641 |
trusted_root=trusted_root,
|
| 642 |
)
|
| 643 |
+
status = _export_status(result, pending=pending)
|
| 644 |
final_result = ExportResult(
|
| 645 |
attempted=result.attempted,
|
| 646 |
exported=result.exported,
|
|
|
|
| 650 |
error_kind=result.error_kind,
|
| 651 |
checkpoint_path=str(checkpoint_path),
|
| 652 |
last_event_id=checkpoint_after_event_id,
|
| 653 |
+
malformed_records=pending.malformed_total_records,
|
| 654 |
+
malformed_pending_records=pending.malformed_pending_records,
|
| 655 |
+
malformed_first_line=pending.malformed_first_line,
|
| 656 |
+
malformed_last_line=pending.malformed_last_line,
|
| 657 |
status_path=str(status_path),
|
| 658 |
checkpoint_before_event_id=checkpoint_before_event_id,
|
| 659 |
checkpoint_after_event_id=checkpoint_after_event_id,
|
| 660 |
checkpoint_advanced=checkpoint_advanced,
|
| 661 |
+
checkpoint_found=pending.checkpoint_found,
|
| 662 |
destination_hash=_export_destination_hash(settings),
|
| 663 |
last_success_at=last_success_at,
|
| 664 |
last_success_event_id=last_success_event_id,
|
|
|
|
| 1923 |
)
|
| 1924 |
|
| 1925 |
|
| 1926 |
+
def _sanitize_event_for_export(
|
| 1927 |
+
event: TelemetryEvent,
|
| 1928 |
+
settings: Mapping[str, Any],
|
| 1929 |
+
) -> TelemetryEvent:
|
| 1930 |
+
payload = _sanitize_payload(
|
| 1931 |
+
dict(event.payload),
|
| 1932 |
+
privacy_mode=event.privacy_mode,
|
| 1933 |
+
hash_salt=settings["hash_salt"],
|
| 1934 |
+
max_keys=int(settings["max_payload_keys"]),
|
| 1935 |
+
max_value_len=int(settings["max_payload_value_chars"]),
|
| 1936 |
+
)
|
| 1937 |
+
if payload == dict(event.payload):
|
| 1938 |
+
return event
|
| 1939 |
+
return replace(event, payload=payload)
|
| 1940 |
+
|
| 1941 |
+
|
| 1942 |
+
def _sanitize_metric_for_export(
|
| 1943 |
+
metric: TelemetryMetric,
|
| 1944 |
+
settings: Mapping[str, Any],
|
| 1945 |
+
) -> TelemetryMetric:
|
| 1946 |
+
attributes = _sanitize_payload(
|
| 1947 |
+
dict(metric.attributes),
|
| 1948 |
+
privacy_mode=metric.privacy_mode,
|
| 1949 |
+
hash_salt=settings["hash_salt"],
|
| 1950 |
+
max_keys=int(settings["max_payload_keys"]),
|
| 1951 |
+
max_value_len=int(settings["max_payload_value_chars"]),
|
| 1952 |
+
)
|
| 1953 |
+
if attributes == dict(metric.attributes):
|
| 1954 |
+
return metric
|
| 1955 |
+
return replace(metric, attributes=attributes)
|
| 1956 |
+
|
| 1957 |
+
|
| 1958 |
def _export_events(
|
| 1959 |
events: list[TelemetryEvent],
|
| 1960 |
*,
|
|
|
|
| 1965 |
if not events:
|
| 1966 |
return ExportResult(attempted=0, exported=0, failed=0, sink=sink)
|
| 1967 |
try:
|
| 1968 |
+
sanitized_events = [_sanitize_event_for_export(event, settings) for event in events]
|
| 1969 |
if sink == "local_jsonl":
|
| 1970 |
+
_export_local_jsonl(
|
| 1971 |
+
sanitized_events,
|
| 1972 |
+
Path(str(settings["export_path"])),
|
| 1973 |
+
trusted_root,
|
| 1974 |
+
)
|
| 1975 |
elif sink == "otlp_http":
|
| 1976 |
+
_post_otlp_http(_otlp_logs_payload(sanitized_events, settings), settings)
|
| 1977 |
else:
|
| 1978 |
return ExportResult(
|
| 1979 |
attempted=len(events),
|
|
|
|
| 2002 |
trusted_root: Path | None,
|
| 2003 |
) -> None:
|
| 2004 |
started_at = _now_iso()
|
| 2005 |
+
pending = _metrics_pending_export(
|
| 2006 |
+
source_path,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2007 |
settings=settings,
|
| 2008 |
+
trusted_root=trusted_root,
|
| 2009 |
+
include_exported=False,
|
| 2010 |
)
|
| 2011 |
+
last_metric = pending.metrics[-1] if pending.metrics else None
|
| 2012 |
+
result = _export_metrics(pending.metrics, settings=settings, trusted_root=trusted_root)
|
| 2013 |
+
checkpoint_path = pending.checkpoint_path
|
| 2014 |
+
checkpoint_before_metric_id = pending.checkpoint_before_metric_id
|
| 2015 |
checkpoint_after_metric_id = checkpoint_before_metric_id
|
| 2016 |
checkpoint_advanced = False
|
| 2017 |
last_success_at = None
|
| 2018 |
last_success_metric_id = None
|
| 2019 |
+
if result.failed == 0 and result.exported and last_metric is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2020 |
last_success_at = _now_iso()
|
| 2021 |
+
last_success_metric_id = last_metric.metric_id
|
| 2022 |
+
if pending.malformed_pending_records == 0:
|
| 2023 |
+
_write_metric_export_checkpoint(
|
| 2024 |
+
settings,
|
| 2025 |
+
source_path=source_path,
|
| 2026 |
+
metric=last_metric,
|
| 2027 |
+
trusted_root=trusted_root,
|
| 2028 |
+
)
|
| 2029 |
+
checkpoint_after_metric_id = last_metric.metric_id
|
| 2030 |
+
checkpoint_advanced = checkpoint_after_metric_id != checkpoint_before_metric_id
|
| 2031 |
status_path = _metric_export_status_path(
|
| 2032 |
settings,
|
| 2033 |
source_path=source_path,
|
| 2034 |
trusted_root=trusted_root,
|
| 2035 |
)
|
| 2036 |
+
status = _metric_export_status(result, pending=pending)
|
| 2037 |
final_result = MetricExportResult(
|
| 2038 |
attempted=result.attempted,
|
| 2039 |
exported=result.exported,
|
|
|
|
| 2043 |
error_kind=result.error_kind,
|
| 2044 |
checkpoint_path=str(checkpoint_path),
|
| 2045 |
last_metric_id=checkpoint_after_metric_id,
|
| 2046 |
+
malformed_records=pending.malformed_total_records,
|
| 2047 |
+
malformed_pending_records=pending.malformed_pending_records,
|
| 2048 |
+
malformed_first_line=pending.malformed_first_line,
|
| 2049 |
+
malformed_last_line=pending.malformed_last_line,
|
| 2050 |
status_path=str(status_path),
|
| 2051 |
checkpoint_before_metric_id=checkpoint_before_metric_id,
|
| 2052 |
checkpoint_after_metric_id=checkpoint_after_metric_id,
|
| 2053 |
checkpoint_advanced=checkpoint_advanced,
|
| 2054 |
+
checkpoint_found=pending.checkpoint_found,
|
| 2055 |
destination_hash=_metric_export_destination_hash(settings),
|
| 2056 |
last_success_at=last_success_at,
|
| 2057 |
last_success_metric_id=last_success_metric_id,
|
|
|
|
| 2076 |
if not metrics:
|
| 2077 |
return MetricExportResult(attempted=0, exported=0, failed=0, sink=sink)
|
| 2078 |
try:
|
| 2079 |
+
sanitized_metrics = [_sanitize_metric_for_export(metric, settings) for metric in metrics]
|
| 2080 |
if sink == "local_jsonl":
|
| 2081 |
_export_local_metrics_jsonl(
|
| 2082 |
+
sanitized_metrics,
|
| 2083 |
Path(str(settings["metric_export_path"])),
|
| 2084 |
trusted_root,
|
| 2085 |
)
|
| 2086 |
elif sink == "otlp_http":
|
| 2087 |
+
_post_otlp_http(_otlp_metrics_payload(sanitized_metrics, settings), settings)
|
| 2088 |
else:
|
| 2089 |
return MetricExportResult(
|
| 2090 |
attempted=len(metrics),
|
|
|
|
| 2623 |
{
|
| 2624 |
"scope": {"name": "ctx.telemetry", "version": METRIC_SCHEMA_VERSION},
|
| 2625 |
"metrics": [
|
| 2626 |
+
_otlp_metric_record(
|
| 2627 |
+
_sanitize_metric_for_export(metric, settings),
|
| 2628 |
+
settings=settings,
|
| 2629 |
+
)
|
| 2630 |
+
for metric in metrics
|
| 2631 |
],
|
| 2632 |
}
|
| 2633 |
],
|
|
|
|
| 2726 |
session_hash = event.session_hash
|
| 2727 |
if session_hash is None and event.session_id:
|
| 2728 |
session_hash = hash_identifier(event.session_id, salt=settings["hash_salt"])
|
| 2729 |
+
payload = _sanitize_payload(
|
| 2730 |
+
dict(event.payload),
|
| 2731 |
+
privacy_mode=event.privacy_mode,
|
| 2732 |
+
hash_salt=settings["hash_salt"],
|
| 2733 |
+
max_keys=int(settings["max_payload_keys"]),
|
| 2734 |
+
max_value_len=int(settings["max_payload_value_chars"]),
|
| 2735 |
+
)
|
| 2736 |
attributes = {
|
| 2737 |
"event.name": event.event_name,
|
| 2738 |
"ctx.schema_version": event.schema_version,
|
|
|
|
| 2740 |
"ctx.source": event.source,
|
| 2741 |
"ctx.outcome": event.outcome,
|
| 2742 |
"ctx.privacy_mode": event.privacy_mode,
|
| 2743 |
+
**{f"ctx.payload.{key}": value for key, value in payload.items()},
|
| 2744 |
}
|
| 2745 |
optional = {
|
| 2746 |
"ctx.session.hash": session_hash,
|
|
|
|
| 2795 |
return {"stringValue": json.dumps(value, sort_keys=True, default=str)}
|
| 2796 |
|
| 2797 |
|
| 2798 |
+
def _redact_local_host_paths(
|
| 2799 |
+
text: str,
|
| 2800 |
+
*,
|
| 2801 |
+
hash_salt: str | bytes | None,
|
| 2802 |
+
) -> str:
|
| 2803 |
+
redacted = text
|
| 2804 |
+
|
| 2805 |
+
def replacement(match: re.Match[str]) -> str:
|
| 2806 |
+
return f"[path_hash:{hash_identifier(match.group(0), salt=hash_salt)}]"
|
| 2807 |
+
|
| 2808 |
+
for pattern in _LOCAL_HOST_PATH_PATTERNS:
|
| 2809 |
+
redacted = pattern.sub(replacement, redacted)
|
| 2810 |
+
return redacted
|
| 2811 |
+
|
| 2812 |
+
|
| 2813 |
def _sanitize_payload(
|
| 2814 |
payload: Mapping[str, Any],
|
| 2815 |
*,
|
|
|
|
| 2856 |
if isinstance(value, _SCALAR_TYPES):
|
| 2857 |
if isinstance(value, str):
|
| 2858 |
text = redact_secret_text(value)
|
| 2859 |
+
if privacy_mode == DEFAULT_PRIVACY_MODE:
|
| 2860 |
+
text = _redact_local_host_paths(text, hash_salt=hash_salt)
|
| 2861 |
if len(text) > max_value_len:
|
| 2862 |
return text[:max_value_len] + "...[truncated]"
|
| 2863 |
return text
|