@aliip/pilah 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/BUILD_STATUS.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +108 -2
  4. package/assets/logo.svg +5 -0
  5. package/docs/AB_EVALUATION.md +62 -0
  6. package/docs/ACCEPTANCE_GATE.md +41 -0
  7. package/docs/ADAPTIVE_RCA_WORKFLOW.md +93 -0
  8. package/docs/AGENT_DECISION_REVIEW.md +17 -0
  9. package/docs/AGENT_TRACE_BENCHMARK.md +17 -0
  10. package/docs/ALWAYS_ON_5_WHYS.md +75 -0
  11. package/docs/ARCHITECTURE.md +43 -0
  12. package/docs/BEHAVIORAL_5_WHYS_V2_0_1.md +117 -0
  13. package/docs/CHECKPOINT_RECOVERY.md +86 -0
  14. package/docs/CI_EFFICIENCY.md +63 -0
  15. package/docs/COMPATIBILITY.md +84 -0
  16. package/docs/CONTRACTS.md +177 -0
  17. package/docs/CONVERSATION_USAGE.md +52 -0
  18. package/docs/ENGINEERING_METHOD.md +68 -0
  19. package/docs/HOST_VALIDATION.md +35 -0
  20. package/docs/INDEPENDENT_ACCEPTANCE_RUNBOOK.md +72 -0
  21. package/docs/INTERVENTION_LEDGER.md +25 -0
  22. package/docs/MAIN_VALIDATION_BACKLOG.md +19 -0
  23. package/docs/NATIVE_FIRST_WORKFLOW.md +27 -0
  24. package/docs/OPEN_SOURCE_ENGINEERING_STANDARDS.md +62 -0
  25. package/docs/ORCHESTRATION_ADVISOR.md +36 -0
  26. package/docs/PRE_VNEXT_INTEGRATION.md +27 -0
  27. package/docs/PRIVATE_BENCHMARK_EXPORT.md +14 -0
  28. package/docs/README.md +58 -0
  29. package/docs/RELEASE.md +33 -0
  30. package/docs/RELEASE_AUTHORIZATION.md +33 -0
  31. package/docs/RISK_GUIDANCE.md +18 -0
  32. package/docs/SECURITY.md +76 -0
  33. package/docs/SECURITY_RELIABILITY_AUDIT_V2_0_1.md +55 -0
  34. package/docs/SEMANTIC_EVIDENCE.md +27 -0
  35. package/docs/SOURCES.md +13 -0
  36. package/docs/STOCKROOM_BENCHMARK_RECHECK_2026_11_18.md +53 -0
  37. package/docs/TOKEN_EFFICIENCY.md +71 -0
  38. package/docs/TOKEN_PROVENANCE.md +15 -0
  39. package/docs/V2_0_1_TRACEABILITY.md +66 -0
  40. package/hooks.json +45 -0
  41. package/mcp_config.json +16 -0
  42. package/package.json +31 -4
  43. package/plugin.json +27 -0
  44. package/rules/AGENTS.md +2 -0
  45. package/schemas/database.sql +84 -0
  46. package/schemas/mcp-tools.json +552 -0
  47. package/scripts/a2a.mjs +343 -0
  48. package/scripts/check-release.mjs +42 -0
  49. package/scripts/check-syntax.mjs +30 -0
  50. package/scripts/checkpoint.mjs +50 -0
  51. package/scripts/compare-agent-traces.mjs +53 -0
  52. package/scripts/context-guardian.mjs +132 -0
  53. package/scripts/evaluate-acceptance.mjs +110 -0
  54. package/scripts/export-benchmark.mjs +31 -0
  55. package/scripts/generate-contracts.mjs +6 -0
  56. package/scripts/hook.mjs +406 -0
  57. package/scripts/host-check.mjs +40 -0
  58. package/scripts/intervention-ledger.mjs +94 -0
  59. package/scripts/pilah.mjs +3 -0
  60. package/scripts/release-authorization.mjs +137 -0
  61. package/scripts/review-agent-decisions.mjs +34 -0
  62. package/scripts/semantic-evidence.mjs +15 -0
  63. package/scripts/verifykit.mjs +3 -0
  64. package/skills/pilah/SKILL.md +24 -0
  65. package/src/acceptance-matrix.mjs +84 -0
  66. package/src/browser-evidence.mjs +40 -0
  67. package/src/context-health.mjs +14 -0
  68. package/src/conversations.mjs +302 -0
  69. package/src/engine.mjs +494 -0
  70. package/src/graph.mjs +169 -0
  71. package/src/mcp-diagnostics.mjs +53 -0
  72. package/src/mcp.mjs +151 -0
  73. package/src/model-recovery.mjs +108 -0
  74. package/src/native-tool-recovery.mjs +45 -0
  75. package/src/node-runtime.mjs +13 -0
  76. package/src/orchestration-advisor.mjs +24 -0
  77. package/src/rca.mjs +174 -0
  78. package/src/risk-guidance.mjs +95 -0
  79. package/src/scanner.mjs +303 -0
  80. package/src/security.mjs +793 -0
  81. package/src/semantic-evidence.mjs +144 -0
  82. package/src/skill-discovery.mjs +23 -0
  83. package/src/sqlite-compat.mjs +11 -0
  84. package/src/storage.mjs +455 -0
  85. package/src/tokens.mjs +627 -0
  86. package/src/tools.mjs +164 -0
  87. package/src/verification.mjs +567 -0
  88. package/src/workflow-router.mjs +34 -0
@@ -0,0 +1,117 @@
1
+ > **Historical research record:** Product terminology is standardized to PILAH. Earlier test results and open/closed issue states describe historical snapshots, not current release eligibility.
2
+
3
+ # Behavioral reliability — evidence-driven Five Whys and remediation
4
+
5
+ **Scope:** PILAH v2.0.1 candidate, derived from a **private** Antigravity behavioral audit covering 110 parseable sessions and 90,407 events, 28 October–18 November 2026. This document contains **sanitized aggregate observations only**. It does not embed source transcripts, private URLs, credentials, customer IDs, or screenshots.
6
+
7
+ **Method:** An observed failure mode → five explicit causal hypotheses → a bounded PILAH mechanism → a falsifiable regression. Five Whys is **causal analysis**, not a claim that every intermediate hypothesis was independently proven. The plugin does not control Google's native browser, model or tools. See #15 for real installed Antigravity and STOCKROOM live acceptance, which automated Node tests cannot replace.
8
+
9
+ ## BA-01 and BA-05 — Completion claims exceed the observed tests (P0)
10
+
11
+ **Evidence:** Agent claims of completion were followed by user reports of broken behavior in Wedding Planner, Caseverity, UsherApp QR check-in and Mitra. The audit records transitions and timestamps, **not live reproduction of the underlying bugs**.
12
+
13
+ 1. Why was a task described as completed? Some positive signal such as build, a passing testcase, or a screenshot was available.
14
+ 2. Why did that signal fail to cover reported behavior? Specific negative, dynamic-data, viewport and repeat-flow conditions weren't shown to have been executed.
15
+ 3. Why weren't all conditions visible? Free-form acceptance descriptions do not identify exact observable transitions and required evidence types.
16
+ 4. Why was reporting too broad? Named machine reports were mixed with unsupported release/functional claims in narrative summaries.
17
+ 5. Why wasn't there a reliable boundary? Completion lacked a consistently inspectable, scenario-scoped evidence matrix.
18
+
19
+ **Root-cause candidate:** missing explicit contract separating implementation, machine assertions, visual/hardware observations and independent acceptance; *not* proof of a single prompt/model bug.
20
+
21
+ **Fix:** `pilah_verify(operation="plan")` accepts optional structured criteria with `given/when/then`, `evidence_type`, source revision and UI state/viewport/reference. Planning is `not_tested` by default. Assessment returns criterion states and a separate `completion` object with `fully_verified:false` unless authenticated acceptance uses the distinct release path. Named local reports remain **local test assertions only**. For typed browser, visual, security, hardware and independent claims, ordinary local unit/build JSON cannot grant a PASS. Evidence cannot be retroactively promoted by task narrative.
22
+
23
+ **Regression scenario:** a build-only `passed` testcase offered as proof of a functioning duplicate-check-in printer, Figma hover, dynamic data or offline restart must remain **inconclusive/not_tested** for that higher-level behavior. A genuine named local integration test may pass its own narrow assertion, but never the overall independent completion gate.
24
+
25
+ ## BA-02 — Design parity remains unproved after visual inspection (P1)
26
+
27
+ **Evidence:** 719 Figma MCP calls, 5,536 DevTools calls and repeated UI mismatch reports; these counts do not identify exactly which states or viewports were executed.
28
+
29
+ 1. Why does the user still see mismatched layout/behavior? An unobserved UI state or viewport may be wrong.
30
+ 2. Why unobserved? A screenshot or page-load smoke test covers only one moment.
31
+ 3. Why not caught? State, reference, dimensions, interactions and dynamic content aren't bound to specific checks.
32
+ 4. Why? Generic test cases do not encode UI observations as structured acceptance.
33
+ 5. Why? The workflow's default notion of verification is tool activity, not complete behavioral evidence.
34
+
35
+ **Fix:** Every typed `visual` or `browser` criterion must declare viewport, UI state and design/behavior reference. It cannot be verified by an unrelated build result. Actual screenshots/interactions remain native Antigravity work, with independent evidence gate unchanged.
36
+
37
+ **Regression scenario:** a successful Vite build offered as proof that a hover button matches a Figma node at 375×812 must return `inconclusive`, not visual parity.
38
+
39
+ ## BA-03 and BA-06 — Native tool churn and low effective PILAH adoption (P1)
40
+
41
+ **Evidence:** 412 indicative invalid argument errors, 150 missing paths, 136 edit mismatches, 64 timeouts, 14 stale browser contexts; 13 directly observed PILAH/VerifyKit calls across four sessions. Several events came from earlier plugin versions, not the current candidate.
42
+
43
+ 1. Why repeated failures? Arguments, paths or browser state sometimes become invalid.
44
+ 2. Why might the next call fail similarly? Agent may retry before refreshing the contract or state.
45
+ 3. Why isn't recovery deterministic? Timeouts, permission rejection, schema validation and edit conflicts demand different next actions.
46
+ 4. Why isn't failure easy to classify? Native tools expose varied messages while PILAH does not intercept their calls.
47
+ 5. Why is tool use inefficient? No concise, optional shared triage response for these failure classes.
48
+
49
+ **Fix:** `pilah_evidence(operation="tool_recovery")` gives bounded and privacy-safe guidance; it **never** runs, retries, modifies or proxies a native tool. Raw error hints aren't persisted or copied into responses. After repeated attempts it explicitly warns against identical retry loops. The tiny always-present rule and optional Always-On guidance remind the agent to check current state and proof scope.
50
+
51
+ **Regression scenario:** a `-32602` invalid `pageId` error yields schema/state inspection; lost browser execution context yields a fresh page/selector check; `403` yields **stop and request permission**, never bypass. Credential-bearing error text is never echoed.
52
+
53
+ ## BA-04 — Long-session rereads and ambiguous 'continue' (P1)
54
+
55
+ **Evidence:** 13,379 `read_file` calls, 9,562 repeats of the same (session,path); 111 minimal user follow-ups. Repeated paths can be **correct** after edits. These are *not* counts of objectively wasted tokens.
56
+
57
+ 1. Why repeated inspection? The same files are revisited after long tasks and edits.
58
+ 2. Why not skip unchanged work? The agent lacks a short, authenticated map of which decisions and tests remain valid.
59
+ 3. Why unavailable? Human commitments, source revisions and machine evidence are separate.
60
+ 4. Why ambiguous on continue? Without a persisted status, 'completed' might mean changed but not tested.
61
+ 5. Why costly? Recovery from entire conversations instead of concise source-fresh checkpoints increases uncertainty.
62
+
63
+ **Fix:** extend the existing, opt-in `save_checkpoint` with bounded `decisions` and `pending_tests`; on `model_recovery` return `source_freshness` and `verified:false` with the latest full-inventory source revision. Existing stored checkpoints migrate additively; no new memory backend, automatic transcript ingest or third-party component.
64
+
65
+ **Regression scenario:** record three pending QR states, edit source, call recovery: decisions remain readable but checkpoint is **stale**, and completed notes cannot be accepted as machine evidence.
66
+
67
+ ## BA-07 — Teamwork is not necessarily beneficial (P2)
68
+
69
+ **Evidence:** About 1,389 observed native teamwork/subagent calls over 82 sessions, but no such calls in the paired STOCKROOM benchmark. Two sessions do not establish the optimum number of workers.
70
+
71
+ 1. Why did some large tasks stay single-agent? Size alone doesn't guarantee delegation should happen.
72
+ 2. Why might splitting be harmful? Workers may touch overlapping files and share dependencies.
73
+ 3. Why not caught earlier? Ownership isn't always explicit.
74
+ 4. Why was a mode suggested? Previous advisor prioritized high-level horizon/workstream counts.
75
+ 5. Why a productivity risk? Parallel plans can add coordination and verification overhead.
76
+
77
+ **Fix:** advisor recommends parallel native modes only when **file ownership is explicitly independent** and dependencies low, with a user approval requirement; otherwise use one agent. Hard tightly-coupled reasoning may still receive non-parallel assistance if supported.
78
+
79
+ **Regression scenario:** overlapping owners or high dependency => `single-agent`; independent owners and confirmed native command => opt-in recommendation only. No swarm is ever launched by PILAH.
80
+
81
+ ## BA-08 — Raw transcripts contain confidential information (P0)
82
+
83
+ **Evidence:** The private audit observed at least one login credential in plaintext. No secrets are included in this document. This is not evidence of PILAH outbound data exfiltration.
84
+
85
+ 1. Why sensitive content exists? Users sometimes paste authentication details into prompts.
86
+ 2. Why could audit output expose it? Raw events or error strings may be copied to public fixtures.
87
+ 3. Why dangerous? Untrusted model-visible logs can contain credentials, paths and cookies.
88
+ 4. Why not enough to 'sanitize later'? A public GitHub push is irreversible in common operational workflows.
89
+ 5. Why protect ingestion by default? Privacy and debug convenience have different trust requirements.
90
+
91
+ **Fix:** sanitized **synthetic** test fixtures only; no original raw archive in Git; recovery messages never echo native raw errors; explicit checkpoint rejects common plaintext secret assignments. All E2E tests use disposable generated workspaces. Keep raw original private, and rotate exposed active credentials.
92
+
93
+ **Regression scenario:** `password=...` note rejected, an error containing a token never appears in PILAH guidance or GitHub test output.
94
+
95
+ ## Scope of executed verification
96
+
97
+ - `tests/behavioral_acceptance.test.mjs`: typed criteria, false-completion negative controls, source revision mismatch, checkpoint privacy/freshness, failure triage and teamwork preconditions.
98
+ - `tests/behavioral_mcp_e2e.test.mjs`: **real local Node MCP stdio process + SQLite**, with permission denial, four-tool listing, typed planning and assessment, recovery, changed-source invalidation and JSON-RPC schema rejection.
99
+ - Other existing Node unit/security/MCP tests and cross-platform CI remain mandatory.
100
+
101
+ **Important limitations:** local Node/MCP E2E is *not* a real Antigravity installation, Figma screenshot comparison, printer/QR hardware test, Laravel backend, independent STOCKROOM F01–F18 browser/DB acceptance or repeated model benchmark. The live evidence for those remains **open in #15**. PILAH cannot force the upstream native agent to follow its advice, guarantee all bugs disappear, or assert token savings from repeated-read counts.
102
+
103
+ ## Re-audit: five subsequent failure modes (19 November 2026)
104
+
105
+ The subsequent source review opened #38–#42. These are **code-confirmed gaps with isolated function reproductions**, not proof of errors in a live installed IDE:
106
+
107
+ 1. **#38 / P0 — Handoff could certify the wrong evidence kind.** Why? Positive named test plus local hook record → handoff omitted evidence-type restrictions → two verification paths diverged → regression only tested ordinary `assess` → no shared local evidence policy. **Remediation:** central `localEvidencePolicy` and positive-provenance restricted-type negative controls.
108
+ 2. **#39 / P0 — Failed native command could look successful.** Why? PostToolUse lacked a top-level error → command exit code ignored → completion conflated with success → existing report hashes could be reattached → no fail-closed exit contract. **Remediation:** explicit numeric zero exit code required; nonzero/missing/conflicting exit clears positive provenance.
109
+ 3. **#40 / P1 — Authorization denial could be hidden by a page ID.** Why? Broad `pageid` matched → first regex branch won → caller-specified deny lost → permission guidance suppressed → no severity-aware classification. **Remediation:** denial-first detection, user authorization required.
110
+ 4. **#41 / P1 — Planned acceptance cases could disappear.** Why? `plan` was transient → `assess` rebuilt scope from its own input → missing cases absent from total → no plan ID → no source-bound immutable manifest. **Remediation:** optional persisted `plan_id`, complete-scope assessment with omissions and stale/tamper detection; explicit user-triggered reissue on the new revision *without reducing the frozen criterion set*; opt-in local retention.
111
+ 5. **#42 / P2 — Full brain Markdown could be stored without explicit consent.** Why? edit-event hook called snapshot → artifact versioner stored full content → retention was optimized for history → user settings did not distinguish metadata from content → docs were unclear. **Remediation:** automatic content snapshots off by default, opt-in CLI and transparent persistent-data disclosure.
112
+
113
+ This hardening is tested with synthetic fixtures and local MCP JSON-RPC/SQLite E2E; full Antigravity/browser/QR-printer and external STOCKROOM evaluation remains in issue #15. Do not import private transcript archives into public fixtures.
114
+
115
+ ## Release and merge policy
116
+
117
+ This behavioral work **merged only into `v2.0.1`** via PR #36, commit `67ea5888caf61751952c8a7daa1eb222d738d4b6`, and all six code-level issues #30–#35 were closed as **implemented**. Post-merge GitHub CI passed 4/4 OS/runtime jobs with 213/213 tests on Ubuntu Node 22. External #15 remains open. Do not merge to `main`, create a tag, publish an npm package or declare production-readiness without independent acceptance and explicit approval.
@@ -0,0 +1,86 @@
1
+ # PILAH Checkpoints and Recovery — current v2.0.1 contract
2
+
3
+ PILAH has **two separate recovery mechanisms**. Neither automatically resumes a model, selects a quota group, launches a native tool or proves task completion.
4
+
5
+ ## 1. Explicit workspace checkpoint via MCP
6
+
7
+ Use `pilah_evidence(operation="save_checkpoint")` with an authorized workspace and a concrete conversation ID. This stores bounded explicit notes in private local SQLite.
8
+
9
+ ```json
10
+ {
11
+ "workspace": "/authorized/project",
12
+ "operation": "save_checkpoint",
13
+ "conversation_id": "conv-test-1234",
14
+ "task_summary": "Fix duplicate QR printing",
15
+ "completed": ["Changed the QR handler, not yet accepted"],
16
+ "decisions": ["Second scan must not create a second print job"],
17
+ "pending_tests": ["All features enabled", "Selfie only", "Verification only"],
18
+ "next_steps": ["Run actual repeat-scan tests on the target printer"]
19
+ }
20
+ ```
21
+
22
+ `task_summary` is <=500 characters. Each of the four arrays has up to eight nonempty statements of <=200 characters. These are **user/agent-supplied notes**, not attested results; `verified` remains `false`. Recognizable plaintext password/API key/token/cookie assignments are rejected, but the filter is a defense-in-depth heuristic, **not a guarantee** that every secret format will be detected. Never store credentials.
23
+
24
+ Call `pilah_evidence(operation="model_recovery",conversation_id="conv-test-1234")` to inspect an existing checkpoint. The response includes `source_revision`, `source_revision_matches` and `source_freshness`. If code changes, old notes remain readable but become **stale**; re-read code and rerun tests before continuing.
25
+
26
+ When Antigravity provides model invocation/stop metadata through supported hooks, PILAH records only sanitized failure category and bounded model name, **not** raw provider errors or credentials. Error classifications are heuristic, not a quota API.
27
+
28
+ ## 2. Native tool recovery guidance (no interception)
29
+
30
+ Use `pilah_evidence(operation="tool_recovery")` after a native browser, MCP, filesystem or terminal error *only when useful*:
31
+
32
+ ```json
33
+ {
34
+ "workspace": "/authorized/project",
35
+ "operation": "tool_recovery",
36
+ "tool_family": "browser",
37
+ "error_class": "context_lost",
38
+ "retry_count": 2
39
+ }
40
+ ```
41
+
42
+ Optional `error_hint` (max 400 chars) is classified heuristically but **never stored or echoed**. Prefer an `error_class` rather than including a potentially private raw message. Categories:
43
+
44
+ | Category | Safe next step |
45
+ | --- | --- |
46
+ | `invalid_arguments` | Inspect exact tool schema and required argument names |
47
+ | `context_lost` | Refresh browser page list/current execution context and selectors |
48
+ | `timeout` | Verify whether the previous action already took effect, respect backoff |
49
+ | `permission_denied` | Stop and obtain explicit authorized access; never bypass |
50
+ | `missing_file` | Inspect current project tree and confirm the authorized path exists |
51
+ | `edit_conflict` | Reopen changed file, recompute patch and rerun related tests |
52
+ | `unknown` | Inspect native diagnostics; do not retry blindly |
53
+
54
+ PILAH returns `automatic_execution:false` and `retry_same_input:false`; repeated attempts trigger escalation guidance. The agent is free to ignore advice, and PILAH is **not** a native tool proxy.
55
+
56
+ ## 3. Read-only checkpoint from an Antigravity CLI event stream
57
+
58
+ For an already captured, local headless stream:
59
+
60
+ ```bash
61
+ node scripts/checkpoint.mjs agy-stream.jsonl scenario-evidence.json
62
+ ```
63
+
64
+ Input status example:
65
+
66
+ ```json
67
+ {"scenarios":[
68
+ {"id":"online-checkout","status":"passed","evidence_ref":"ci/run-2"},
69
+ {"id":"offline-restart","status":"not-tested"},
70
+ {"id":"inventory-cross-tenant","status":"blocked","reason_code":"missing-harness"}
71
+ ]}
72
+ ```
73
+
74
+ The utility classifies incomplete steps and reported scenario statuses, but does **not** verify caller-provided source or served-build revisions. It distinguishes `reported_passed` from `verified_passed` (default **0** without an external verifier). Missing results are unknown/incomplete, not proof of quota exhaustion. A validated `agy --conversation ID` may be **suggested**, never run automatically.
75
+
76
+ Store raw headless event streams only in a private location. Do not publish cookies, prompts, authentication details, complete user logs or internal browser profiles.
77
+
78
+ ## Re-audit note: checkpoint versus acceptance plan
79
+
80
+ A task checkpoint holds **unverified** decisions and pending tests; it is not a frozen acceptance manifest. For optional complete-scope assessment use `pilah_verify(plan,persist_plan:true)` and pass its `plan_id` to `pilah_verify(assess)`. The plan is persisted only by explicit request and is bound to the source revision. `model_recovery` notes remain separate and never count as a passing test.
81
+
82
+ ## What this does not prove
83
+
84
+ An opt-in checkpoint, a locally passing named test, and a stream-derived reported pass are different evidence classes. None establishes independent HTTP/browser/DB behavior, end-user visual parity, F01–F18 STOCKROOM acceptance, or publication eligibility.
85
+
86
+ See [MCP contracts](CONTRACTS.md), [workflow](NATIVE_FIRST_WORKFLOW.md), [behavioral root causes](BEHAVIORAL_5_WHYS_V2_0_1.md), and release #15.
@@ -0,0 +1,63 @@
1
+ # PILAH: efficient CI and evidence-first tuning
2
+
3
+ ## GitHub Actions budget
4
+
5
+ This repo deliberately separates **ordinary verification** from **full compatibility certification**. Each lane runs the **same** syntax, complete Node test suite, release-contract checks, SQLite smoke, and npm-tarball hygiene checks.
6
+
7
+ | Trigger | OS / Node | Jobs | Purpose |
8
+ | --- | --- | ---: | --- |
9
+ | PR targeting main | Ubuntu / Node 24 | **1** | Fast complete regression suite for routine code review |
10
+ | Push to main | Ubuntu, macOS, Windows / Node 24 | **3** | Cross-platform main-branch smoke plus full suite |
11
+ | Manual `workflow_dispatch` | Ubuntu, macOS, Windows × Node 22, 24, 26.13.1 | **9** | Release candidate, runtime-specific changes, broad portability investigation |
12
+
13
+ Earlier workflows ran **9 jobs on each PR and each main push**. The optimized routine configuration removes **8 jobs per PR (88.9%)** and **6 per main push (66.7%)** while retaining all existing suite steps. It does **not** reduce the number of test cases within a job. These percentages count configured CI jobs, **not** runtime, runner charges, completion time or model tokens. All jobs are subject to GitHub availability; avoid claims of passed platforms until the actual run completes.
14
+
15
+ Pull requests are the only automated test entry for feature branches; there is no redundant feature-branch `push` trigger. New commits cancel older in-flight runs of the **same** PR, while main pushes use a separate concurrency group. Nothing automatically publishes packages or tags releases. `npm` / GitHub Packages publication retains its independent authorization checks.
16
+
17
+ **Manual full-matrix run:** GitHub repository → Actions → *CI Test & Quality Gate* → *Run workflow*, selecting the intended ref. Run before release or after platform/runtime compatibility changes. Passing the smaller routine matrix is not a substitute for this check.
18
+
19
+ ## Measurable indexing and model usage
20
+
21
+ Run `node benchmarks/bench.mjs` to measure local source indexing and impact time on a synthetic project. It now records cold/warm scan operations and bytes read, not an inferred savings figure. `pilah_context(action="inspect")` reports `index_scan_stats` only on inspection; routine symbol queries do not pay for that extra output.
22
+
23
+ Use `node scripts/pilah.mjs tokens --usage-file <official-usage.json> --json` for one authentic model run. Optional cache-read, cache-write, cache-creation, and cache-miss metrics are reported **only** when present in official usage. The existence of a cache counter cannot prove a discount or a task completed.
24
+
25
+ For meaningful quality comparisons, pin an evaluator-owned acceptance suite and use `node benchmarks/ab-evaluate.mjs <manifest.json>`. The evaluator intentionally leaves `comparability.ready=false` without independent acceptance evidence and does not infer model-token savings from compact context alone.
26
+
27
+ ## Evaluate efficiency without overengineering
28
+
29
+ | Suggestion | Decision | Reason |
30
+ | --- | --- | --- |
31
+ | Native-first, one scoped MCP call on uncertainty | **Keep** | PILAH already exposes four public tools, only context is eager, others lazy |
32
+ | Small, reviewable native Bash/Node/Python scripts | **Allow when useful** | Batch known, authorized operations and return concise redacted results; no blanket code-mode claim |
33
+ | Short rules, skill progressive disclosure | **Keep; ablate experimentally** | Measure prompt and instruction size and task outcomes; do not delete security guidance merely to meet token goals |
34
+ | Antigravity `/teamwork` / native Git worktrees | **Opt-in** | Use only for independent work with separate ownership; never assume model-tier entitlement or automatic free multi-model routing |
35
+ | KV-cache optimization / trajectory compaction | **Host-dependent, not PILAH-controlled** | Stable small instruction prefix helps; no guaranteed hit ratio, discounts or provider usage API |
36
+ | Sidecar daemons, polling, background workers | **Do not add** | No recurring task requires an always-on new process; may increase cost/security surface |
37
+ | Generative UI progress boards | **Native host concern** | No need for a renderer or persistent UI process within a code-analysis plugin |
38
+ | Local structured architecture map | **Reuse existing** | Use project architecture files and scoped source graph; avoid re-indexing on every turn |
39
+ | Deterministic test back-pressure | **Keep** | Never replace named tests, security, negative paths, accessibility, integration evidence with a passing build |
40
+ | Utility-scored long-term memory / automatic prompt mutation | **Deferred until independently measured** | Self-reinforcing incorrect history and private transcript leakage are more harmful than missed optimization |
41
+
42
+ Official Antigravity features: [Teamwork](https://antigravity.google/docs/teamwork/), [native worktrees](https://antigravity.google/docs/cli/projects/), [plugin skill/MCP/hook architecture](https://antigravity.google/docs/build-plugins/).
43
+
44
+ ## Host acceptance boundary
45
+
46
+ `node scripts/pilah.mjs host-check` performs a fail-closed, read-only Antigravity CLI/plugin-list preflight **only when the host is installed locally**. If the CLI is missing, it returns blocked. Even a successful local preflight leaves live agent tool choice, security denials and browser outcomes `not_tested`. Capture independent host evidence before any Native-vs-PILAH performance claim.
47
+
48
+ A six-scenario [candidate evaluation fixture](../tests/fixtures/pilah-eval-scenarios.json) is versioned in source. Freeze a copy under evaluator ownership; checked-in scenarios and PR CI cannot independently approve their own acceptance results.
49
+
50
+ ## Closed-loop evaluation, without an autonomous self-modifier
51
+
52
+ 1. Freeze a representative task suite: simple edit, cross-file issue, security denial, integration regression, debugging and complex feature.
53
+ 2. Compare Native and PILAH with identical snapshot, model, effort, permissions, available tools, and known independent outcomes. Counterbalance run order and run at least **five** distinct trials per variant.
54
+ 3. Use actual provider-reported input/output/total tokens, cache-read fields (never double count), elapsed seconds, tool calls, failed attempts, and **accepted successful outcomes**. Mark unknown fields unknown. Report `cost per accepted task`; never use token-per-turn as a substitute for completion quality.
55
+ 4. Test instruction *ablation* one line/group at a time. Keep an edit only if independent correctness and security do not regress **and** efficiency improves meaningfully.
56
+ 5. Preserve failed experiments and frozen control cases. Do not let the coding agent create or sign its own passing acceptance receipts. Existing `benchmarks/ab-evaluate.mjs` deliberately reports `comparability.ready=false` without independent evidence.
57
+ 6. No automatic production prompt updates, agent teams, persistence, or repo writes from a benchmark. Propose a reviewed PR with regression tests instead.
58
+
59
+ **Not verified for PILAH:** numerical claims such as 1M→60k tokens, 50% lower MCP overhead, >90% cache hit rate, or 2× less Bash-versus-MCP token usage. Such results are workload- and host-specific until tested. Separate source-level CI from installed Antigravity acceptance and frozen STOCKROOM F01–F18 evidence (see [main validation backlog](MAIN_VALIDATION_BACKLOG.md)).
60
+
61
+ ## Boundaries
62
+
63
+ No new third-party dependencies or long-running services; minimum complete change, not minimum line count. Never suppress tests, redact failures, fabricate independent passes, bypass approvals/workspace trust, or change settings solely to look better in a benchmark.
@@ -0,0 +1,84 @@
1
+ # Compatibility and Capability Matrix
2
+
3
+ PILAH is language-agnostic in its **file, evidence, and MCP contracts**. Static symbol extraction is heuristic. It is not a compiler or complete LSP implementation for any language.
4
+
5
+ | Stack | Manifest recognition | File-level code relationships | Existing test runner candidates | Limitations |
6
+ | --- | --- | --- | --- | --- |
7
+ | Node/JS/TS/Vue | package.json, tsconfig.json / jsconfig.json | local imports, configured literal `paths` suffix wildcards and symbols | npm scripts | dynamic imports, runtime aliases and complex inherited configurations are not modeled |
8
+ | PHP | composer.json | simple symbols, relative includes, static class `use` via Composer PSR-4 | PHPUnit / Pest candidates | Laravel container bindings, facades and dynamic routing not resolved |
9
+ | Python | pyproject.toml / requirements | simple symbols and relative Python imports | pytest candidates | import packages and decorators incomplete |
10
+ | Go | go.mod | files, `func`, `type struct/interface` symbols | go test | Go package graph not parsed fully |
11
+ | Rust | Cargo.toml | files and basic symbols | cargo test | modules/macros not fully resolved |
12
+ | Java/Kotlin | pom.xml / Gradle | classes, interfaces, `fun` symbols | Maven / Gradle test | JVM resolution/annotations incomplete |
13
+ | Dart/Flutter | pubspec.yaml | files and basic symbols | Flutter/Dart test | widget trees not statically modeled |
14
+ | Swift | Package.swift | classes, `func`, `protocol` symbols | swift test | Xcode project and runtime not inspected |
15
+ | C#/NET | csproj/sln | files and basic symbols | project-specific native runner | C# type graph incomplete |
16
+ | Godot/GDScript | project.godot | script/symbol references | Godot headless startup probe | headless start is **not** unit testing |
17
+ | C/C++ | CMakeLists.txt | quoted include references | ctest candidate | compiler flags and headers incomplete |
18
+ | Multi-language monorepo | multiple manifests | cross-file local relationships | per-ecosystem candidate list | aliases and service contracts require external evidence |
19
+
20
+ **Run test commands only with native Antigravity permissions after inspecting the project scripts.** PILAH does not install missing test infrastructure or promise identical cross-stack verification depth.
21
+
22
+ ## Antigravity surface support
23
+
24
+ - **IDE:** MCP tools & resources, `hooks.json` (`SessionStart`, targeted `PreToolUse` only for native-test report correlation, targeted `PostToolUse`; no recurring `PreInvocation`), skills, and `rules/AGENTS.md`; native browser testing remains under `/browser`.
25
+ - **App:** MCP/plugin contract; browser and orchestration remain native.
26
+ - **CLI:** MCP/plugin contract and headless operation remain native (`antigravity-cli/settings.json` `trustedWorkspaces` supported, filtered by protected roots).
27
+ - **SDK:** not used to proxy models or run third-party agents. A separately written SDK client could call this standard MCP server if supported.
28
+
29
+ Availability and model permissions depend on the actual Antigravity version and account; PILAH never assumes universal `/swarm` or `/teamwork` in IDE.
30
+
31
+ ## Runtime and evidence compatibility (PILAH 1.0.0)
32
+
33
+ Node.js **>=22.13.0** is required for built-in `node:sqlite`. CI now runs the **full test suite in one Ubuntu/Node 24 job per PR**, and **three Node 24 jobs (Ubuntu, macOS, Windows) on each main push**. The complete **9-job Node 22/24/26.13.1 × three-OS** compatibility matrix remains available via manual `workflow_dispatch`; run it before a release or when changing Node/OS-specific code. This reduces routine CI cost without deleting any test, and does **not** claim unrun combinations passed. Node 26.11+ exposes `sqlite.Database` and retains deprecated `DatabaseSync`; PILAH prefers the current class and falls back to `DatabaseSync` on Node 22. Tests include local MCP JSON-RPC/stdio, WAL/rollback, old verifykit.sqlite `VACUUM INTO` migration, permission/security and CLI doctor. Green Node CI does not prove installed Antigravity IDE compatibility on every host. The actual tool contract includes typed acceptance with UI viewport/state/reference, opt-in `model_recovery`/`tool_recovery`, and opt-in native orchestration with `file_ownership="independent"` for parallel recommendations. See [current MCP contract](CONTRACTS.md).
34
+
35
+ **Do not claim universal slash-command availability, browser access, native teamwork entitlements or running application compatibility without testing the installed environment.** PILAH never adds language runtimes or test drivers. Real PHP/Laravel STOCKROOM external acceptance remains blocked, even though its frozen sources passed syntax and Vite build preflight.
36
+
37
+ ### NVM and Antigravity desktop PATH
38
+
39
+ PILAH declares `"command": "node"` in `mcp_config.json` and invokes `node` from its hooks. It resolves **whichever Node binary is in the Antigravity process's PATH**, which may differ from the interactive shell. An NVM-only Node installation may not be present when Antigravity is started from a desktop launcher.
40
+
41
+ For Linux/NVM diagnosis, check both `command -v node` and `node scripts/pilah.mjs doctor` inside a source checkout. Doctor now reports `node`, `node_binary`, `sqlite_api` and `sqlite_version`. If Antigravity cannot start its MCP server, verify the **IDE's inherited environment** and launch the IDE from a shell that has initialized NVM, or configure its process environment via the platform's supported mechanism. Do not hardcode one user's NVM path in the public plugin manifest.
42
+
43
+ The CI test does not have access to the user's Pop!_OS GUI session; a live Antigravity plugin validation and MCP smoke remain required by release gate #15.
44
+
45
+ ### Non-login PATH advisory
46
+
47
+ `pilah doctor` reports `node_version_manager_path` and `path_advisory` when `process.execPath` is under common user-scoped NVM, fnm, Volta, asdf or nodenv layouts. This is a read-only warning: an interactive terminal's PATH does **not** prove a desktop-launched Antigravity process can spawn the same binary, and no shell probe, installation or config mutation is performed. Node 22.13+ remains required.
48
+
49
+ ### Cross-platform HOME and path boundaries
50
+
51
+ `getHomeDir()` is the shared resolver for user-scoped Antigravity brain, token history, release config, snapshots, and CLI/hook paths, supporting Windows `USERPROFILE` when `HOME` is unset. Storage protects both the OS account home and an overridden `HOME` from permission changes. Relative project snapshots resolve against the authorized workspace root rather than the MCP process CWD. `isSamePath` and `isSameOrDescendantPath` consistently handle Windows/macOS case defaults and macOS `/private/var`, `/private/tmp`, `/private/etc` aliases. The benchmark capture reader canonicalizes the manifest root. These guards do not replace real native IDE/browser tests on each OS.
52
+
53
+ ### Skill inclusion versus plugin MCP availability
54
+
55
+ An enabled plugin and four green MCP tools do not imply the PILAH skill metadata is in the **current** agent context. Antigravity may exclude skills through a global `~/.gemini/config/skills.json`, workspace `.agents/skills.json`, or subagent context filtering. Run `node scripts/pilah.mjs doctor` to inspect the **global manifest only** (`skill_discovery`), then check `/skills` in the actual IDE/CLI session and `agy plugin validate --strict`. `/skills reload` refreshes CLI discovery without invoking an PILAH MCP tool. Do not automatically remove exclusions or duplicate the skill in a second location. An `Excluded` indicator is not by itself proof of an MCP server outage or evidence that the model would choose PILAH when included.
56
+
57
+ ### Native reporter provenance (PreToolUse + PostToolUse)
58
+
59
+ PILAH captures a bounded, private pre-run fingerprint only when a direct native test command declares a known report file. PostToolUse binds the reporter to the same conversation and tool step and requires it to be created or changed during that run; unchanged reports, missing preflight context and ambiguous executions remain unverified. This never auto-approves a command, reads model thinking, or treats a local named PASS as independent acceptance. The single-use fingerprint contains only hashed command identity and reporter hashes, not raw test logs or terminal arguments.
60
+
61
+ ### Eager core context vs lazy advanced MCP tools (issue #71)
62
+
63
+ Antigravity defaults MCP tool definitions to **lazy**: a model must locate cached server schema files and call `call_mcp_tool`, even when a hook mentions the tool by name. The 21 Nov 2026 forensic archive contains 13 full transcripts, 227 planner responses and 611 native calls but **zero PILAH/MCP calls** with an injected PILAH Always-On policy in all 13; this proves no *observed invocation*, not that the tool was available to each model or that using it would have improved quality. Our original Always-On policy used direct `pilah_context(...)` syntax without explaining lazy tool discovery, a confirmed configuration/instruction mismatch.
64
+
65
+ To make **one** high-value entrypoint directly discoverable, `mcp_config.json` now marks `pilah_context` **eager**; `pilah_impact`, `pilah_verify` and `pilah_evidence` stay lazy to avoid registering four schemas every turn. Eager increases the fixed per-turn schema/context footprint even when unused. Native-first and zero **actual calls** for simple tasks remain mandatory; eager must not be used to game intervention counts. Plugin settings may still disable MCP, and subagent MCP inheritance is controlled by Antigravity. To verify: upgrade installed plugin, restart parent/subagent sessions, inspect `/mcp` and `/skills` and run an eligible read-only audit without mentioning PILAH. A full actual model-selection A/B must still be conducted independently; no performance gains are claimed from this static change.
66
+
67
+ Official reference: https://antigravity.google/docs/mcp (Tool loading: lazy vs eager).
68
+
69
+ ### Context-health (opt-in initial phase, issue #91)
70
+
71
+ The `context-health --conversation ID [--milestone-complete]` command reuses PILAH's bounded local history parser once when explicitly requested. It uses planner step counts from conversation start only (not active token occupancy or steps since the last compact), never executes a compact command, never reads other sessions when an explicit valid ID is given and never installs a PreInvocation hook. An automatically running Context Guardian requires performance and host integration evidence before it can be enabled. The `--milestone-complete` state is user-reported, not independently verified by PILAH.
72
+
73
+ ### Opt-in native Context Guardian (issue #91)
74
+
75
+ The standalone `node scripts/context-guardian.mjs status|enable|disable` CLI installs **only the PILAH-owned** `pilah-context-guardian` `PreInvocation` hook into the user's global `~/.gemini/config/hooks.json` after an explicit `enable` command. It preserves other user hooks, refuses conflicting or malformed configurations and cleanly removes its own hook on `disable`. No new global MCP server or third-party dependency is installed.
76
+
77
+ Default: disabled **with no per-turn child process**. While enabled, it reads **only Antigravity-provided** `initialNumSteps` and `invocationNum` metadata. Yellow review starts at 80 planner steps with reminders only every 35 invocations; red handoff review starts at 140 steps with 25-invocation cadence. These are UX heuristics, **not current active-context tokens or billing/quota metrics**. Uses an ephemeral message and makes **no** automatic compact/clear request. It cannot reliably detect unfinished tasks, so all advice says to finish the atomic edit/test before a handoff. No transcript text is read, state retained, or external request made.
78
+
79
+ Changing hook configuration may require restarting the Antigravity session. Antigravity's own tool and permission rules remain authoritative. If another process changes the hooks manifest concurrently or the PILAH-owned slot is occupied, the installer refuses to clobber it. This is a validated **implementation**, not proven token savings; installed-IDE latency/utility and parent/subagent behavior still require live acceptance. See [Google Antigravity hooks](https://antigravity.google/docs/hooks).
80
+
81
+
82
+ ### Opt-in Context Guardian runtime path
83
+
84
+ An explicit `node scripts/context-guardian.mjs enable` records the current absolute Node executable (`process.execPath`) in its own `PreInvocation` command, avoiding reliance on an Antigravity desktop process inheriting an NVM shell PATH. The default-disabled Guardian creates no recurring hooks. Re-enable after changing Node versions, then restart the IDE; neither this change nor CI proves actual native-host execution. Existing user hooks are preserved and a malformed/non-object hooks manifest is never overwritten.
@@ -0,0 +1,177 @@
1
+ # PILAH — MCP contracts and data dictionary
2
+
3
+ The four public tools are `pilah_context`, `pilah_impact`, `pilah_verify` and `pilah_evidence`. Earlier names remain callable compatibility aliases, hidden from default discovery. Existing configuration keys and database identities are retained internally.
4
+
5
+ **Executable source of truth:** [`src/tools.mjs`](../src/tools.mjs), [generated MCP schema](../schemas/mcp-tools.json), [SQLite DDL](../schemas/database.sql), [plugin manifest](../plugin.json), [hooks](../hooks.json). Current contracts supersede historical examples in earlier audit notes. Documentation is not an executable verifier.
6
+
7
+ ## MCP surface
8
+
9
+ Four public, JSON-RPC 2.0 **stdio** tools. Every tool requires an authorized absolute `workspace`. The legacy tool-list option remains available, but its exact identifier is defined in [tool source](../src/tools.mjs); do not invent a renamed setting.
10
+
11
+ | MCP tool | `action` / `operation` | Meaning |
12
+ | --- | --- | --- |
13
+ | `pilah_context` | `inspect`, `query`, `freshness`, `tokens`, `skeleton`, `orchestration` | Code inventory, static graph, tokens, declared native teamwork advisor |
14
+ | `pilah_impact` | `changed`, `depth` (1–4), `summary` | Bounded static change-impact analysis; uncertainty remains |
15
+ | `pilah_verify` | `plan`, `assess`, `verify_handoff`, `assess_release`, `assess_semantic`, `assess_browser` | Test planning, scoped local machine results, independent signed release assessment |
16
+ | `pilah_evidence` | `list`, `runs`, `incidents`, `record_incident`, `add_hypothesis`, `assess_hypothesis`, `hypotheses`, `delete_incident`, `side_questions`, `record_side_question`, `artifact_versions`, `artifact_diff`, `snapshot_artifact`, `save_checkpoint`, `model_recovery`, `tool_recovery` | Revision-bound evidence, incident hypotheses, explicit checkpoints, bounded recovery guidance |
17
+
18
+ The public operation enums above reflect current `src/tools.mjs`. Additional engine-internal compatibility aliases may exist but are not guaranteed as public input enums. PILAH cannot launch native commands, edit project source, run browsers, force model selection or guarantee upstream agent obedience.
19
+
20
+ ### Scope binding and privacy (19 November re-audit)
21
+
22
+ `persist_plan` (Boolean, default `false`) on `pilah_verify(operation="plan")` stores the entire user-authored acceptance matrix in private SQLite, hashed and bound to the current source revision. The result includes a `plan_id` (or `null` when disabled), `scope_bound` and `scope_persisted`. This is an explicit **local-content retention** opt-in.
23
+
24
+ Pass `plan_id` on `pilah_verify(operation="assess")`. Provide evidence bindings by `id` (`artifact`, exact `test_name` or `blocked`); the stored Given/When/Then and required evidence type cannot be replaced. Omitted required cases appear as `not_tested`; an outdated plan becomes `stale`, and unexpected IDs or mutated expectations are rejected. After changing source code, explicitly **reissue the identical frozen requirements** with `pilah_verify(operation="plan",plan_id="<old-id>",persist_plan=true,criteria=[])`. This creates a new plan ID at the current revision, resets every case to `not_tested`, and never asserts that tests ran. If a stored criterion explicitly pins a different `source_revision`, reissuing fails closed and the user must review and recreate that requirement with its new revision. Without `plan_id`, a standalone assessment remains backwards compatible but reports `scope_bound:false` and cannot know the original mandatory scenario list.
25
+
26
+ `verify_handoff` enforces the **same local evidence-kind policy** as `assess`. For browser/visual/hardware/security/independent criteria, named local reports and native hook records never produce `verified:true`. The `verified_scope` field is limited to **named local machine assertions**, with `independently_attested:false`.
27
+
28
+ PostToolUse native test provenance is **fail-closed**: only an unambiguous numeric exit code zero, without tool error, may set `succeeded:true`. A missing, malformed, conflicting or nonzero exit status does not authenticate a native test run.
29
+
30
+ Automatic full-content brain Markdown snapshots are **disabled by default**; opt in with `node scripts/pilah.mjs artifact-autosnapshot on` and disable with `off`. Opt-in stores raw local artifact content; disabling does not erase previous versions. User-invoked `snapshot_artifact` is separate.
31
+
32
+ ### Verification plan: typed acceptance
33
+
34
+ `pilah_verify(operation="plan",criteria=[...])` accepts up to 40 strings (legacy) or objects. **Typed** criteria include:
35
+
36
+ | Field | Requirement |
37
+ | --- | --- |
38
+ | `id` | Unique non-empty string, <=160 chars |
39
+ | `description` | Optional display label |
40
+ | `given`, `when`, `then` | **Required**, 1–200 chars each, when `evidence_type` is supplied |
41
+ | `evidence_type` | `build`, `unit`, `integration`, `browser`, `visual`, `hardware`, `security` or `independent` |
42
+ | `viewport`, `ui_state`, `reference` | Required for `browser` and `visual` typed scenarios |
43
+ | `negative` | Optional Boolean indicating an adversarial/negative path |
44
+ | `source_revision` | Optional bounded source revision to bind during assessment |
45
+ | `artifact`, `test_name` | For `assess`: relative machine report file + exact testcase name (no wildcard for typed criteria) |
46
+ | `blocked` | Explicitly identify inaccessible execution environment |
47
+
48
+ Example for a native browser acceptance **plan**:
49
+
50
+ ```json
51
+ {
52
+ "workspace": "/authorized/project",
53
+ "operation": "plan",
54
+ "criteria": [
55
+ {
56
+ "id": "cart-error-mobile",
57
+ "given": "User has a pending order",
58
+ "when": "The payment API fails",
59
+ "then": "A recoverable error appears and no paid order is persisted",
60
+ "evidence_type": "browser",
61
+ "viewport": "375x812",
62
+ "ui_state": "API failure",
63
+ "reference": "Checkout acceptance spec",
64
+ "negative": true
65
+ }
66
+ ]
67
+ }
68
+ ```
69
+
70
+ A plan returns `not_tested` plus `completion.fully_verified:false`. For `assess`, supply criteria with explicit `id`, relative `artifact` and `test_name`. Named JUnit/TAP/JSON machine outcomes may pass **only their exact local test assertions**; they do **not** authenticate what a browser or printer truly did. Typed `browser`, `visual`, `hardware`, `security` and `independent` cannot PASS from an ordinary local report. An explicit `source_revision` mismatch is `stale` in the criterion output, while the persisted aggregate run treats unsupported states conservatively. A passing build is never a visual parity verdict.
71
+
72
+ `completion` is a separate transparency summary: `fully_verified:false`, counts for `passed`, `failed`, `blocked`, `not_tested`, `stale` and `inconclusive`, plus bounded gaps. **Use `assess_release` with independent signed evidence for release decisions, not `assess`.**
73
+
74
+ ### Existing native tool recovery
75
+
76
+ `pilah_evidence(operation="tool_recovery")` accepts `tool_family` (mcp/browser/filesystem/terminal/other), optional `error_hint` (<=400 chars; avoid secrets), `error_class` (invalid_arguments/context_lost/timeout/permission_denied/missing_file/edit_conflict/unknown) and `retry_count` (0–20). It returns deterministic **guidance only**, `automatic_execution:false`, `retry_same_input:false`, and never copies or stores the raw hint. Native state/schema refresh is required before a changed retry; permission denial requires user consent.
77
+
78
+ ### Explicit checkpoint and resume
79
+
80
+ `pilah_evidence(operation="save_checkpoint")` uses `conversation_id`, `task_summary` (1–500 chars), up to eight bounded `completed`, `next_steps`, `decisions` and `pending_tests` notes (<=200 chars each). It rejects recognizable plaintext secret assignments and records the **source revision**, not a verified result. `model_recovery` returns source freshness, notes and a `verified:false` warning; changed source makes an older checkpoint stale. Nothing resumes or switches a model automatically. This is distinct from the read-only headless stream checkpoint CLI in [checkpoint recovery](CHECKPOINT_RECOVERY.md).
81
+
82
+ ### Native teamwork
83
+
84
+ `pilah_context(action="orchestration",task=...)` accepts user-declared tier, available native commands, workstreams, dependencies, milestones, long horizon, hard reasoning and `file_ownership` (`independent`/`shared`/`unknown`). Parallel modes require **independent ownership and low dependencies** plus confirmed command availability. PILAH never creates workers and always requires user approval.
85
+
86
+ ## MCP resources
87
+
88
+ | URI | Meaning |
89
+ | --- | --- |
90
+ | `pilah://status` | Plugin version and mode flags with redacted counts and booleans only; MCP never returns home/data directories or workspace paths |
91
+ | `pilah://tokens/session` | Local session diagnostics; internal counters are not provider-verified token billing |
92
+ | `pilah://workspace/summary` | Active workspace static index and coverage |
93
+ | `pilah://side-questions` | Opt-in recorded side-question history |
94
+
95
+ ## SQLite (`node:sqlite`, local)
96
+
97
+ | Table | Purpose |
98
+ | --- | --- |
99
+ | `meta` | SQLite schema version (v1, additive migrations) |
100
+ | `workspaces`, `revisions` | Canonical workspace identity, active source revision and historical snapshots |
101
+ | `files`, `nodes`, `edges` | Source path/hash/language/mtime and static graph |
102
+ | `evidence`, `runs` | Machine report hashes, scoped verdicts, run history |
103
+ | `incidents`, `hypotheses` | User-recorded failures, tested/unverified hypotheses and evidence links |
104
+ | `telemetry` | Estimated source/output token footprint, **not net savings** |
105
+ | `side_questions` | Explicit side-question metadata/history; opt-in transcript use |
106
+ | `artifact_versions` | Explicit versioned Markdown artifact content and diffs (local private storage) |
107
+ | `model_recovery_state` | Model failure **category**, sanitized metadata; no raw failure body |
108
+ | `recovery_checkpoints` | Explicit user-approved notes, decisions and pending tests bound to revision |
109
+
110
+ Privacy caveat: explicitly saved artifact versions and checkpoints **can contain content**. Do not store secrets in text notes or snapshot sensitive files. Historical metadata is bounded and not a provider usage API.
111
+
112
+ ## Validation and trust levels
113
+
114
+ - **JUnit XML:** exact testcase elements and suite counters reconciled; missing/incomplete reports are inconclusive.
115
+ - **TAP:** assertion lines, optional plan and skipped/failing cases respected.
116
+ - **JSON machine reports:** the parser supports existing serialized report formats with explicit completion and individual testcase states. See [verification source](../src/verification.mjs) for the exact accepted identifiers.
117
+ - **Local reports:** hashed, source-revision-bound, scoped to named assertions. A filename, test name or self-asserted run is not process authentication.
118
+ - **Semantic/browser structural reviews:** local **unattested** observations, not an independent witness.
119
+ - **External release assessment:** pinned acceptance registry, evaluator Ed25519 signatures per required case, exact source revision, and separate signed reviewer approval tied to the exact `main` commit/version. See [acceptance](ACCEPTANCE_GATE.md) and [publish gate](RELEASE_AUTHORIZATION.md).
120
+
121
+ ## Runtime and bounds
122
+
123
+ - `node >=22.13.0` and built-in `node:sqlite`, with no third-party runtime package dependencies. Node 26.11+ uses `sqlite.Database`; Node 22 uses the compatible `sqlite.DatabaseSync` fallback. Cross-platform Node 22/24/26.13.1 tests and NVM launcher notes are documented in [Compatibility](COMPATIBILITY.md).
124
+ - Local JSON-RPC messages are bounded; tool responses larger than **64 KiB** are rejected, not silently truncated into a false complete verdict. Reduce requested scope.
125
+ - Workspace authorization, protected roots, symlink checks and explicit revocation take precedence over convenience. Hooks only record limited local metadata; there is **no `PreInvocation`** hook.
126
+ - No third-party browser, runtime model API, prompt content upload or remote PILAH telemetry.
127
+
128
+ For actual error behavior and constraints, consult the executable [MCP server](../src/mcp.mjs), [verification](../src/verification.mjs), [acceptance matrix](../src/acceptance-matrix.mjs), [model recovery](../src/model-recovery.mjs), and [native recovery](../src/native-tool-recovery.mjs).
129
+
130
+ ## Compact output and prompt-budget contract (issue #44)
131
+
132
+ New installations default to `On-Demand` (**no automatic PILAH calls or SessionStart injection**) and `Compact` (**bounded result payloads**). `node scripts/pilah.mjs compact off` explicitly restores fuller responses and persists until changed. Existing explicit user settings have precedence.
133
+
134
+ In Compact, `pilah_context(action="skeleton")` limits previews to 4,800 characters total, 1,600 per file, and six previewed files out of up to 20 requested. Requested-but-omitted paths are returned with `skipped:true` and reason `compact_file_budget`; partial previews carry `truncated:true`, and summary counters disclose omissions. `action="query"` caps static relation rows at 12 and sets `relations_truncated:true` plus `relations_before_compaction` when necessary. This count refers to the query response *before compaction*, not total possible project edges. Impact `summary:true` retains its existing risk/uncertainty/coverage semantics.
135
+
136
+ Only local payload bytes/characters and heuristic estimates are measurable by these APIs; neither the skill nor the `pilah tokens` CLI can prove provider billing or net token savings. Tool outputs that are truncated must not be presented as complete analysis. See [token efficiency](TOKEN_EFFICIENCY.md).
137
+
138
+ ## Adaptive RCA / 5 Whys contract (issue #48)
139
+
140
+ The **existing** `pilah_evidence` tool now supports `assess_hypothesis`; there is **no fifth public MCP tool**. `record_incident`, `add_hypothesis` and `assess_hypothesis` require **explicit `persist_rca:true`** to store bounded private RCA text. A call to `record_incident` always yields `state:"investigating"`, even with valid evidence IDs; historical `evidence-linked` rows are displayed as *unverified*. The legacy `root_cause` field is **candidate cause text**, never a confirmed claim.
141
+
142
+ `add_hypothesis` requires `incident_id`, `hypothesis`, `experiment`, `predicted_observation`, `disconfirming_test`, and an exact `expected_criterion_id`. Optional `parent_hypothesis_id` branches a Why chain up to depth 8; optional `plan_id` must match the hypothesis criterion in a fresh, hashed acceptance plan. New hypotheses start `untested`.
143
+
144
+ `assess_hypothesis` requires `hypothesis_id`, `experiment_outcome` (`supports`, `refutes`, `inconclusive`), `observation`, optional `evidence_ids`, and `persist_rca:true`. For supported/refuted outcomes, every linked evidence record must match the current source revision/workspace and intact artifact hash, a **passing exact named unit/integration assertion**, and the hypothesis criterion. This results only in `locally_supported`, `refuted`, or `inconclusive`; **never independently proven root cause**. Source edits mark outcomes stale, even in Compact.
145
+
146
+ `hypotheses` can filter by `incident_id`, returning parent/depth, recorded outcome, current freshness and a mandatory causal-proof warning. `incidents` includes candidate cause and `root_cause_verified:false`. Optional recurrence hints contain only prior same-signature incident **IDs**, not a claim that the previous cause applies. Incident/hypothesis notes are retained locally; sanitizers reject common plaintext credential assignments as a heuristic. See [Adaptive 5 Whys](ADAPTIVE_RCA_WORKFLOW.md).
147
+
148
+ **Risk-guidance contract:** `proposeRiskTests` returns `suggested_test_ids` and `suggested_total`; its legacy `required_test_ids` is now empty because a heuristic cannot impose mandatory acceptance. Compact limits displayed suggestions to 3 while retaining all matched domain/omission counts. Only criteria explicitly added to the user's acceptance plan are mandatory.
149
+
150
+ ### RCA privacy cleanup and Compact evidence freshness
151
+
152
+ `pilah_evidence(operation="delete_incident")` requires an authorized workspace, existing `incident_id`, `persist_rca:true` and `confirm_deletion:true`. It atomically deletes only the selected incident and its linked hypotheses; existing independent machine evidence and acceptance plans are **not removed**. This is logical deletion, not secure erasure of SQLite WAL/backups. In Compact, `incidents` and `hypotheses` lists show max 8 entries and report `total` / `more_available`, retaining causal-proof warnings. The `hypotheses` read path re-checks source revisions and stored named-test evidence hashes; a previously locally-supported cause becomes **stale** if the linked report was modified or removed.
153
+
154
+ **RCA experiment audit trail:** `rca_experiments` is an append-only SQLite table for hypothesis outcomes with source revisions, criterion, observation and linked evidence IDs. A hypothesis keeps its current status and returns `recent_experiments` (max 3), `experiments_total` and `more_experiments_available`; older records are not overwritten by newer interpretations. Explicit `delete_incident` also deletes that incident's experiment history, not unrelated evidence.
155
+
156
+ ## P0 native provenance and parser constraints (issue #50–#53)
157
+
158
+ The native `PostToolUse` hook accepts current `write_file`/`edit_file` operations as well as older file-edit tool names, and normalizes supported `toolCall.args`, `toolArgs`, `toolInput` and `arguments` shapes. It recognizes only **direct, unmasked test commands** when recording success provenance. A shell command merely mentioning a test name, chained test with `|| true`, or `echo "npm test"` cannot re-attest an old passing report. Unknown or suspicious attempts clear positive local provenance; explicit numeric zero exit remains required. This is not cryptographic proof of native execution.
159
+
160
+ JUnit parsing refuses commented-out testcases, unsupported DTDs, incomplete structure and spurious failure tags inside system logs/CDATA; both single- and double-quoted attributes are accepted. TAP requires exactly one valid numeric `1..N` plan, in-order assertions, and treats `Bail out!` as failed and TODO/SKIP assertions as non-passing. Unsupported reports return inconclusive, never silently passed. This is a **conservative parser**, not a complete XML/TAP specification implementation; external signed acceptance is separate.
161
+
162
+ The CLI `tokens` absolute workspace argument and `artifacts snapshot|list|diff|show` now use explicit `fs`/`path` imports and a bounded symlink-safe `active-session.json` reader. Cross-platform artifact root falls back to `getHomeDir()`. These local test/CLI fixes have no effect on the independent release gate #15.
163
+
164
+
165
+ ## v2.0.1 reliability and privacy contract updates (19 November 2026)
166
+
167
+ - Four public MCP tools remain. `pilah_evidence` includes opt-in Adaptive 5 Whys RCA operations; local hypotheses remain non-causal suggestions unless supported by exact source-bound machine assertions.
168
+ - `pilah://status` returns redacted workspace **counts** and booleans only, not host paths or per-project names. `resources/read` errors sanitize authorization failures.
169
+ - `hooks.json` recognizes native `write_file`, `edit_file`, `write_to_file`, `replace_file_content`, `multi_replace_file_content` tool events; native test evidence rejects indirect or spoofed commands.
170
+ - `tools/list` enforces a 6,500-byte serialized contract budget with bounded IDs and criteria. Removed unused `pilah_context.conversation_id`, `pilah_context.transcript_path`, and `pilah_evidence.version_number`; deprecated `allow_stale` never permits PASS.
171
+ - Syntax validation recursively covers all source and script `.mjs` files on all CI/runtime-publish gates. `pilah doctor` advises about shell-managed Node version manager paths without executing a shell or changing user configuration.
172
+
173
+ See [security](SECURITY.md), [compatibility](COMPATIBILITY.md), and release gate #15. PILAH v2.0.1 is **not** externally certified or authorized for publishing.
174
+
175
+ ## File safety and workspace origin (v2.0.1)
176
+
177
+ Evidence list/freshness rehashes are bounded to 4 MiB per report. The release manifest is parsed and hashed from one bounded pinned read; independent acceptance registry and trusted keys reject group/world-writable files, symlinks and malformed JSON with sanitized diagnostics. Local side-question records are restricted to their owning workspace. Recursive workspace-file expansion has a visited set and depth bound; IDE SQLite trust-state reads have size/type limits. Relative snapshots are anchored to the approved project root; Antigravity brain artifacts require matching active conversation scope. See [security](SECURITY.md) and [compatibility](COMPATIBILITY.md). These are local safety gates, not proof of external software acceptance.