machine-bridge-mcp 0.16.2 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.17.0 - 2026-07-13
4
+
5
+ ### Project governance and contribution flow
6
+
7
+ - Define a risk-based project standard covering GitHub Flow, Conventional Commits, architecture boundaries, MCP contract ownership, testing, errors, logging, supply-chain security, documentation, review, and explicit exceptions. Add pull-request and structured issue templates plus area ownership through CODEOWNERS.
8
+ - Add an executable Conventional Commit policy for pull-request and main-branch commit titles. Keep the repository on squash-based GitHub Flow rather than introducing permanent develop/release branches that do not match its single-maintainer, continuously released operating model.
9
+ - Require all repository-host operations to use local `git`, `gh`, and `gh api` through Machine Bridge. Explicitly prohibit hosted GitHub connectors or ChatGPT GitHub plugins so remote mutations, credentials, refs, checks, and recovery remain observable from one local control plane.
10
+ - Make repository automation responsible for closing the source-change lifecycle: after all required checks pass it squash-merges the pull request, verifies `main`, creates and pushes the annotated version tag, and creates or updates the matching GitHub Release. npm publication, Worker deployment, credentials, global installation, and daemon/service replacement remain separately authorized live operations.
11
+
12
+ ### Generated contracts and security automation
13
+
14
+ - Generate a complete MCP tool reference from the shared tool catalog and reject stale output in the required suite. The tool catalog remains the single source for names, availability, annotations, and JSON input schemas; REST-specific Swagger documentation is not duplicated for the MCP surface.
15
+ - Add pinned, least-privilege GitHub workflows for CodeQL analysis, pull-request dependency review, OpenSSF Scorecard publication, and governance checks. Preserve exact dependency versions, registry signature/attestation verification, SBOM generation, history privacy scanning, and cross-platform package tests.
16
+
17
+ ### Cohesion, reuse, and runtime reliability
18
+
19
+ - Extract optional project-metadata reads, strict integer normalization, plain-record validation, and uninstall/service state inventory into focused shared modules. Remove duplicate numeric clamping, record classification, and no-follow UTF-8 metadata readers while preserving the distinct strict validation semantics used by browser/application commands and Agent Context instruction files. Plain-record validation now rejects class instances instead of treating every non-array object as protocol/configuration data.
20
+ - Reduce the CLI entrypoint from 1,169 to 1,063 lines by moving profile, Worker, active-job, and process-lock inventory behind a dedicated boundary. Add direct failure-path tests and enforce 91% function/73% branch coverage for the new inventory module; raise the CLI branch floor from 5% to 10%.
21
+ - Canonicalize existing state roots before profile enumeration, fixing macOS `/var` versus `/private/var` alias mismatches that could make service removal or lock inspection report inconsistent profile paths. Retry only the final daemon-lock handoff after a verified service stop, and keep daemon fixture subprocesses out of V8 coverage so process teardown does not create platform-timing failures.
22
+ - Generate Wrangler environment declarations through a cross-platform script that creates ignored `.wrangler/` state before invoking Wrangler, instead of writing under `src/worker`; packaging tests reject generated type declarations. This removes clean-runner state dependence and reduces the dry-run package from about 410 KB/1.8 MB unpacked to about 314 KB/1.22 MB while retaining every Worker runtime module.
23
+ - Replace repeated empty WebSocket send/close catches in the Worker and browser extension with small module-local best-effort helpers whose comments preserve the primary failure semantics. Architecture checks reject unexplained empty catches on those protocol boundaries.
24
+
25
+ ### Tests and documentation
26
+
27
+ - Extend architecture checks to require generated tool documentation, governance scripts, security workflows, explicit workflow permissions, immutable Action references, and rejection of privileged pull-request triggers or write-all permissions.
28
+ - Document why aggregate 80% coverage is not a sufficient quality target, identify the current CLI orchestration branch-coverage weakness, and retain per-module risk thresholds plus behavior-level cross-platform, concurrency, fault-injection, and protocol tests.
29
+
3
30
  ## 0.16.2 - 2026-07-13
4
31
 
5
32
  ### Fixed
package/CONTRIBUTING.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  This repository treats every Git-tracked or nonignored repository file as release-relevant, including source code, tests, scripts, examples, documentation, CI configuration, ignore rules, and package metadata.
4
4
 
5
+ ## Development workflow
6
+
7
+ Read [docs/PROJECT_STANDARDS.md](docs/PROJECT_STANDARDS.md) and the relevant domain documentation before changing behavior. This repository uses GitHub Flow: branch from current `main`, keep the change coherent, open a pull request, satisfy required checks, squash-merge, and delete the branch. Permanent `develop` or generic release integration branches are not used unless an independently maintained release line creates a concrete need. Repository automation performs GitHub operations only through local `git`, `gh`, and `gh api` commands executed by Machine Bridge; hosted GitHub connectors and ChatGPT GitHub plugins are prohibited for this repository.
8
+
9
+ Branch names use a category and purpose such as `feat/browser-downloads`, `fix/relay-timeout`, or `chore/dependency-policy`.
10
+
11
+ Pull-request titles and final commit subjects use Conventional Commits:
12
+
13
+ ```text
14
+ <type>[optional scope][optional !]: <imperative description>
15
+ ```
16
+
17
+ Accepted types are `feat`, `fix`, `docs`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `security`, `release`, and `revert`. Explain the causal problem, why the solution is correct, compatibility/security/privacy risk, verification, and release impact in the pull request. Bug fixes require a regression test for the original failure mechanism.
18
+
5
19
  ## Required for every release-relevant change
6
20
 
7
21
  Before the reviewed code is pushed to `main`:
package/README.md CHANGED
@@ -480,7 +480,7 @@ npm pack --dry-run
480
480
 
481
481
  `npm run check` covers privacy and release-impact gates, architecture/link invariants, generated Worker types, TypeScript, recursively discovered JavaScript syntax, catalog-to-runtime handler parity, deterministic relay lifecycle and secure-file tests, concurrent lock/atomic-replacement/PID-reuse fixtures, fail-closed service lifecycle tests, descendant process-tree termination, local path/write/state/log/service invariants, Ed25519/RSA generation and key-pair validation, real-machine `full` sandbox acceptance, a clean npm package-manifest/mode/sensitive-artifact check, managed-job integrity/redaction/finally/cancellation/recovery, a live stdio MCP flow, and a live local OAuth/Worker/WebSocket/MCP flow. GitHub Actions runs the suite on Linux, macOS, and Windows with the pinned Node 26/npm 12 baseline; macOS and package-audit jobs also exercise the documented isolated global installation.
482
482
 
483
- The cross-cutting 0.12.0 review, corrected failure modes, and residual OS-level limits are recorded in [docs/AUDIT.md](docs/AUDIT.md). See also [docs/AGENT_CONTEXT.md](docs/AGENT_CONTEXT.md), [docs/LOCAL_AUTOMATION.md](docs/LOCAL_AUTOMATION.md), [docs/MANAGED_JOBS.md](docs/MANAGED_JOBS.md), [docs/TESTING.md](docs/TESTING.md), [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), [docs/ENGINEERING.md](docs/ENGINEERING.md), and [SECURITY.md](SECURITY.md).
483
+ The cross-cutting 0.12.0 review, corrected failure modes, and residual OS-level limits are recorded in [docs/AUDIT.md](docs/AUDIT.md). See also [docs/AGENT_CONTEXT.md](docs/AGENT_CONTEXT.md), [docs/LOCAL_AUTOMATION.md](docs/LOCAL_AUTOMATION.md), [docs/MANAGED_JOBS.md](docs/MANAGED_JOBS.md), [docs/TESTING.md](docs/TESTING.md), [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), [docs/ENGINEERING.md](docs/ENGINEERING.md), [docs/PROJECT_STANDARDS.md](docs/PROJECT_STANDARDS.md), the generated [MCP tool reference](docs/TOOL_REFERENCE.md), and [SECURITY.md](SECURITY.md).
484
484
 
485
485
  ## Uninstall
486
486
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Machine Bridge Browser",
4
- "version": "0.16.2",
4
+ "version": "0.17.0",
5
5
  "description": "Connects the current Chromium browser profile to the local Machine Bridge runtime for user-authorized automation.",
6
6
  "permissions": [
7
7
  "tabs",
@@ -30,5 +30,5 @@
30
30
  "action": {
31
31
  "default_title": "Machine Bridge Browser"
32
32
  },
33
- "version_name": "0.16.2"
33
+ "version_name": "0.17.0"
34
34
  }
@@ -67,12 +67,33 @@ function setConnectionState(state) {
67
67
  : state === "unconfigured"
68
68
  ? "Machine Bridge Browser: click to open pairing"
69
69
  : "Machine Bridge Browser: disconnected; click to open pairing";
70
- try { ignoreOptionalPromise(chrome.action.setBadgeText({ text: badge })); } catch {}
71
- try { ignoreOptionalPromise(chrome.action.setTitle({ title })); } catch {}
70
+ ignoreBrowserApiCall(() => chrome.action.setBadgeText({ text: badge }));
71
+ ignoreBrowserApiCall(() => chrome.action.setTitle({ title }));
72
72
  }
73
73
 
74
- function ignoreOptionalPromise(value) {
75
- if (value && typeof value.catch === "function") value.catch(() => {});
74
+ function ignoreBrowserApiCall(operation) {
75
+ try {
76
+ const value = operation();
77
+ if (value && typeof value.catch === "function") value.catch(() => {});
78
+ } catch {
79
+ // Browser UI decoration is optional and must not disrupt broker connectivity.
80
+ }
81
+ }
82
+
83
+ function closeSocketQuietly(ws, code, reason) {
84
+ try {
85
+ ws?.close(code, reason);
86
+ } catch {
87
+ // The socket may already be closed; reconnect state remains authoritative.
88
+ }
89
+ }
90
+
91
+ function sendSocketQuietly(ws, payload) {
92
+ try {
93
+ ws.send(payload);
94
+ } catch {
95
+ // A response cannot be recovered after the broker socket closes.
96
+ }
76
97
  }
77
98
 
78
99
  async function pairConfiguration(rawEndpoint, rawToken, { replace, senderUrl }) {
@@ -119,27 +140,29 @@ async function confirmRepairFromTab(tab) {
119
140
  }),
120
141
  });
121
142
  const paired = await pairConfiguration(result?.result?.endpoint, result?.result?.token, { replace: true, senderUrl: tab.url });
122
- await chrome.scripting.executeScript({
123
- target: { tabId: tab.id },
124
- func: (ok) => {
125
- const status = document.getElementById("status");
126
- if (status) status.textContent = ok ? "Paired. You may close this tab." : "Pairing failed.";
127
- },
128
- args: [paired.ok === true],
129
- });
143
+ await setPairingPageStatus(
144
+ tab.id,
145
+ paired.ok === true ? "Paired. You may close this tab." : "Pairing failed.",
146
+ );
130
147
  } catch {
131
- try {
132
- await chrome.scripting.executeScript({
133
- target: { tabId: tab.id },
134
- func: () => {
135
- const status = document.getElementById("status");
136
- if (status) status.textContent = "Pairing failed. Reload this page and confirm that the expected extension build is loaded.";
137
- },
138
- });
139
- } catch {}
148
+ ignoreBrowserApiCall(() => setPairingPageStatus(
149
+ tab.id,
150
+ "Pairing failed. Reload this page and confirm that the expected extension build is loaded.",
151
+ ));
140
152
  }
141
153
  }
142
154
 
155
+ function setPairingPageStatus(tabId, text) {
156
+ return chrome.scripting.executeScript({
157
+ target: { tabId },
158
+ func: (value) => {
159
+ const status = document.getElementById("status");
160
+ if (status) status.textContent = value;
161
+ },
162
+ args: [text],
163
+ });
164
+ }
165
+
143
166
  ensureReconnectAlarm();
144
167
  void connectFromStorage();
145
168
 
@@ -162,7 +185,7 @@ function connect(endpoint, token, { reconnect = true } = {}) {
162
185
  clearTimeout(reconnectTimer);
163
186
  reconnectTimer = null;
164
187
  if (socket) {
165
- try { socket.close(); } catch {}
188
+ closeSocketQuietly(socket);
166
189
  }
167
190
  const ws = new WebSocket(endpoint, [`mbm.${token}`]);
168
191
  socket = ws;
@@ -181,12 +204,12 @@ function connect(endpoint, token, { reconnect = true } = {}) {
181
204
  };
182
205
  ws.onopen = () => {
183
206
  if (socket !== ws) {
184
- try { ws.close(); } catch {}
207
+ closeSocketQuietly(ws);
185
208
  settle(new Error("browser connection was superseded"));
186
209
  return;
187
210
  }
188
211
  ws.handshakeTimer = setTimeout(() => {
189
- try { ws.close(1002, "browser broker handshake timed out"); } catch {}
212
+ closeSocketQuietly(ws, 1002, "browser broker handshake timed out");
190
213
  }, HANDSHAKE_TIMEOUT_MS);
191
214
  };
192
215
  ws.onmessage = (event) => void handleMessage(ws, event.data, () => settle());
@@ -214,12 +237,12 @@ function scheduleReconnect(endpoint, token) {
214
237
  async function handleMessage(ws, raw, onReady = () => {}) {
215
238
  let message;
216
239
  try { message = JSON.parse(String(raw)); } catch {
217
- try { ws.close(1007, "invalid broker JSON"); } catch {}
240
+ closeSocketQuietly(ws, 1007, "invalid broker JSON");
218
241
  return;
219
242
  }
220
243
  if (message?.type === "hello") {
221
244
  if (ws.serverHelloSeen || message.role !== "extension" || message.protocol !== BROWSER_EXTENSION_PROTOCOL) {
222
- try { ws.close(1002, "browser broker protocol mismatch"); } catch {}
245
+ closeSocketQuietly(ws, 1002, "browser broker protocol mismatch");
223
246
  return;
224
247
  }
225
248
  ws.serverHelloSeen = true;
@@ -237,7 +260,7 @@ async function handleMessage(ws, raw, onReady = () => {}) {
237
260
  }
238
261
  if (message?.type === "hello_ack") {
239
262
  if (ws.bridgeReady || !ws.serverHelloSeen || message.role !== "extension" || message.protocol !== BROWSER_EXTENSION_PROTOCOL) {
240
- try { ws.close(1002, "invalid browser broker acknowledgement"); } catch {}
263
+ closeSocketQuietly(ws, 1002, "invalid browser broker acknowledgement");
241
264
  return;
242
265
  }
243
266
  clearTimeout(ws.handshakeTimer);
@@ -252,7 +275,7 @@ async function handleMessage(ws, raw, onReady = () => {}) {
252
275
  return;
253
276
  }
254
277
  if (!ws.bridgeReady) {
255
- try { ws.close(1002, "browser broker acknowledgement required"); } catch {}
278
+ closeSocketQuietly(ws, 1002, "browser broker acknowledgement required");
256
279
  return;
257
280
  }
258
281
  if (message?.type === "cancel" && typeof message.id === "string") {
@@ -291,7 +314,7 @@ function sendResponse(ws, id, ok, result, error = "") {
291
314
  if (new TextEncoder().encode(payload).byteLength > MAX_RESULT_BYTES) {
292
315
  payload = JSON.stringify({ type: "response", id, ok: false, error: "browser result exceeds maximum size" });
293
316
  }
294
- try { ws.send(payload); } catch {}
317
+ sendSocketQuietly(ws, payload);
295
318
  }
296
319
 
297
320
 
@@ -1,6 +1,6 @@
1
1
  # Engineering principles and maintenance rules
2
2
 
3
- This document records project-wide decisions that must survive individual fixes, releases, and maintainers. It is normative for repository changes. Machine-specific observations belong in the ignored `.project-local/` directory instead.
3
+ This document records project-wide decisions that must survive individual fixes, releases, and maintainers. It is normative for repository changes together with [PROJECT_STANDARDS.md](PROJECT_STANDARDS.md). Machine-specific observations belong in the ignored `.project-local/` directory instead.
4
4
 
5
5
  ## Product and security invariants
6
6
 
@@ -146,6 +146,8 @@ Cross-platform tests must not depend on shell syntax, case-sensitive Windows pat
146
146
  - OPERATIONS contains diagnosis and recovery procedures.
147
147
  - TESTING records executable coverage and regression expectations.
148
148
  - CHANGELOG records externally relevant changes, including documentation and workflow changes.
149
+ - PROJECT_STANDARDS defines collaboration, contract, testing, supply-chain, review, and exception policy.
150
+ - TOOL_REFERENCE is generated from the shared MCP tool catalog and must never be maintained by hand.
149
151
 
150
152
  Documentation that claims a guarantee must identify the code or test enforcing it. Do not document an aspirational behavior as implemented.
151
153
 
@@ -0,0 +1,143 @@
1
+ # Project standards
2
+
3
+ This document defines the repository-wide engineering and collaboration standard. It complements the product and security invariants in [ENGINEERING.md](ENGINEERING.md). A rule is preferred only when it reduces material risk, makes review easier, or can be enforced consistently; ceremony without a credible failure mode is not a quality control.
4
+
5
+ ## 1. Change flow
6
+
7
+ The repository uses **GitHub Flow**:
8
+
9
+ 1. create a short-lived branch from current `main`;
10
+ 2. make one coherent change, including tests and documentation;
11
+ 3. open a pull request and let required checks complete;
12
+ 4. resolve review conversations and rebase or update the branch when required;
13
+ 5. squash-merge into `main` and delete the branch.
14
+
15
+ Permanent `develop`, `feature`, and `release` integration branches are not used. A supported maintenance line may use a temporary `release/x.y` branch only when an older published version must receive fixes independently of `main`.
16
+
17
+ Branch names use a short category and purpose, for example `feat/browser-downloads`, `fix/relay-timeout`, `docs/release-guide`, or `chore/dependency-policy`.
18
+
19
+ Direct pushes to `main`, force pushes, and branch deletion are blocked by repository protection. An exception requires an incident record and an explicit owner decision.
20
+
21
+ ### Completion ownership
22
+
23
+ Repository automation owns the complete source-change lifecycle. After required checks pass, it updates the pull-request branch when necessary, squash-merges through local `gh`, verifies the resulting `main` commit, and removes the merged branch. A completed change must not remain indefinitely as an open pull request.
24
+
25
+ Every release-relevant change advances the package version and is completed by an annotated `v<version>` tag plus a final GitHub Release for the exact successful `main` commit. The coding agent performs that tag and GitHub Release work by default through local `git`, `gh`, and `gh api`; repeated per-task authorization is not required. npm publication, Worker deployment, credential mutation, global installation, and daemon/service replacement remain separate live operations requiring explicit authorization.
26
+
27
+ ### Local GitHub control plane
28
+
29
+ Repository automation must use local `git`, `gh`, and `gh api` commands executed through Machine Bridge for every GitHub read or mutation. A hosted GitHub connector or ChatGPT GitHub plugin must not be used. Mixing control planes can produce stale refs, unreviewed remote-only commits, ambiguous credentials, and recovery paths that cannot be reproduced from the maintainer's machine. Fetch before mutation and verify the remote result afterward.
30
+
31
+ ## 2. Commits and pull requests
32
+
33
+ Commit and squash-merge subjects follow Conventional Commits:
34
+
35
+ ```text
36
+ <type>[optional scope][optional !]: <imperative description>
37
+ ```
38
+
39
+ Allowed types are `feat`, `fix`, `docs`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `security`, `release`, and `revert`. `feat` and `fix` carry their normal semantic-version meaning. A breaking change uses `!` and explains migration impact in the body or a `BREAKING CHANGE:` footer.
40
+
41
+ A good change explains both **what changed and why**. Commits should be logically coherent, but intermediate branch history may be amended because the final pull request is squash-merged. Pull-request titles must satisfy the same format because they become the `main` commit subject.
42
+
43
+ Pull requests must state:
44
+
45
+ - the problem and causal mechanism;
46
+ - the chosen solution and important rejected alternatives;
47
+ - user-visible, compatibility, security, privacy, and operational risk;
48
+ - tests and manual verification performed;
49
+ - documentation, release, and rollback consequences.
50
+
51
+ Keep a pull request small enough to review as one argument. Generated files, mechanical renames, or dependency lockfile changes should be isolated when they obscure substantive behavior. Large changes should be split by a stable contract, not into dependent fragments that cannot be evaluated independently.
52
+
53
+ ## 3. Architecture and dependency direction
54
+
55
+ The architectural dependency direction in [ENGINEERING.md](ENGINEERING.md) is normative. In addition:
56
+
57
+ - A module owns one coherent reason to change. Related state-machine transitions may stay together when ordering is part of the safety argument.
58
+ - Domain modules do not import CLI, transport, service, presentation, or deployment adapters.
59
+ - Cross-layer calls go through an explicit interface or orchestration boundary; no adapter reaches through another layer to mutate its internals.
60
+ - Policy, schemas, error codes, protocol metadata, and capability inventories have one authoritative source. Adapters translate them but do not maintain parallel copies.
61
+ - Side effects are isolated behind small interfaces so policy and lifecycle behavior can be tested deterministically.
62
+ - Dependency cycles are prohibited. Hidden global state and import-time operational side effects are avoided.
63
+ - Line-count and complexity thresholds are diagnostic guardrails, not design goals. A threshold may not be satisfied by moving incoherent code into a generic utility module.
64
+ - **High cohesion and low coupling:** one source file or function owns one coherent responsibility and reason to change; collaboration occurs through narrow explicit contracts rather than cross-layer reach-through.
65
+ - **KISS:** prefer the simplest explicit implementation that satisfies current requirements. Do not introduce factories, registries, inheritance, generic frameworks, or configuration layers without an observed variation that needs them.
66
+ - **DRY:** extract repeated business rules, validation, security boundaries, or lifecycle logic into one authoritative implementation. Do not merge merely similar code when its semantics or failure policy differ.
67
+ - Design patterns are used only when they remove an observed variation or coupling. A direct function or small module is preferred over speculative abstractions.
68
+
69
+ Any deliberate boundary exception must document the dependency, reason, owner, test coverage, and removal condition.
70
+
71
+ ## 4. Public contracts and generated documentation
72
+
73
+ The MCP tool catalog in `src/shared/tool-catalog.json` is the authoritative public API description. Tool names, availability, annotations, and JSON input schemas are rendered into [TOOL_REFERENCE.md](TOOL_REFERENCE.md); CI rejects stale generated documentation.
74
+
75
+ Swagger/OpenAPI is required only if the project later exposes a user-facing HTTP REST API. It is not a substitute for MCP tool schemas or end-to-end MCP protocol tests. Hand-maintained copies of generated contracts are prohibited.
76
+
77
+ A public contract change must address:
78
+
79
+ - backward and forward compatibility;
80
+ - bounded input and output behavior;
81
+ - authorization and destructive-operation annotations;
82
+ - stable error classification;
83
+ - protocol negotiation or versioning when peers may differ;
84
+ - documentation, tests, changelog, and semantic-version impact.
85
+
86
+ ## 5. Testing and quality gates
87
+
88
+ Tests follow risk rather than a repository-wide aggregate percentage:
89
+
90
+ - Every defect fix includes a regression test that fails for the original causal reason.
91
+ - Pure policy and normalization logic is tested directly; adapters receive integration coverage proving that they use the policy correctly.
92
+ - Permission expansion includes denial tests. Bounded resources include over-limit tests. Multi-stage mutations include partial-failure and rollback tests.
93
+ - Concurrency, locking, process trees, persistence, cancellation, retry, and recovery require behavior-level or fault-injection coverage.
94
+ - Protocol changes include producer-consumer contract tests and malformed-input tests.
95
+ - Supported operating systems run the required suite in CI.
96
+ - Critical modules have explicit function and branch baselines. Thresholds may rise after better tests or extraction; lowering one requires an audit note explaining why the old measurement was misleading.
97
+
98
+ An 80% aggregate coverage target is not a repository requirement: it can hide untested critical branches behind trivial files. New or materially changed pure business modules should normally achieve at least 80% function coverage and meaningful branch coverage, but risk-specific tests remain the acceptance criterion.
99
+
100
+ Flaky tests are defects. A retry may diagnose environmental instability but may not be used to make a nondeterministic test appear healthy.
101
+
102
+ ## 6. Errors, retries, and logs
103
+
104
+ - Expected operational failures use typed stable error codes and concise operator messages.
105
+ - Unexpected programming errors remain distinguishable from ordinary unavailability.
106
+ - Request boundaries normalize errors once. Lower layers preserve causes and do not repeatedly translate them.
107
+ - Cleanup catches may be best effort only when the primary failure is retained and cleanup failure is observable where useful.
108
+ - Empty catches and catch-and-continue behavior are prohibited unless a comment explains why the event is intentionally irrelevant.
109
+ - Retries require positive transient classification, bounded attempts, backoff, and idempotency or authoritative state reconciliation.
110
+ - Unhandled process-level exceptions are logged with redaction and cause controlled termination; continuing in an unknown state is not a recovery strategy.
111
+ - Operational logs follow [LOGGING.md](LOGGING.md), remain structured, bounded, actionable, and free of secrets or user content.
112
+
113
+ ## 7. Security and software supply chain
114
+
115
+ - GitHub workflow permissions default to read-only and are expanded per job only when required.
116
+ - Third-party Actions are pinned to immutable commit SHAs and reviewed when Dependabot updates them.
117
+ - npm dependencies use exact versions and a committed lockfile. Registry signatures and attestations are verified in CI.
118
+ - Dependency review blocks newly introduced vulnerable dependencies. CodeQL performs JavaScript/TypeScript and workflow analysis. OpenSSF Scorecard periodically audits repository supply-chain posture.
119
+ - CI generates and validates a CycloneDX SBOM. Release artifacts must be reproducible from a reviewed commit and tied to successful exact-commit CI evidence.
120
+ - Secret scanning and push protection are enabled. Repository examples use synthetic identities and reserved domains; reachable history is scanned before release.
121
+ - Long-lived publication tokens should be replaced by npm trusted publishing with GitHub OIDC. Until that external registry configuration is completed, release credentials remain an explicit operator responsibility and must never be stored in the repository.
122
+ - Security reports follow [SECURITY.md](../SECURITY.md), not public issue templates.
123
+
124
+ ## 8. Documentation and comments
125
+
126
+ - README covers supported setup, operation, major capabilities, limitations, and risk.
127
+ - Architecture, security, testing, operations, logging, policy, and release documents each own their designated concern; avoid repeating whole procedures across files.
128
+ - Documentation claims a guarantee only when code, configuration, or a test enforces it.
129
+ - Public behavior changes update the changelog and relevant user documentation in the same pull request.
130
+ - Comments explain non-obvious **why**, invariants, external constraints, and safety ordering. They do not narrate self-explanatory syntax.
131
+ - Temporary workarounds state the triggering condition and removal criterion; use an issue reference when one exists.
132
+
133
+ ## 9. Review and ownership
134
+
135
+ `CODEOWNERS` identifies responsible areas and requests informed review. It does not prove independent review when author and owner are the same person.
136
+
137
+ Review examines correctness, causal completeness, security/privacy boundaries, compatibility, failure paths, observability, test evidence, and maintainability. Style preferences do not override a simpler correct design without a documented project rule.
138
+
139
+ This repository currently has one human maintainer. Requiring one independent approval would deadlock maintenance and therefore is not enabled. The first governance priority when another active maintainer is added is to require one non-author approval for security-sensitive, release, policy, Worker, browser, and execution changes.
140
+
141
+ ## 10. Exceptions and evolution
142
+
143
+ A standard may be changed when evidence shows that it creates more risk or cost than it removes. The change must update this document, relevant automation, and the changelog together. Silent exceptions and permanently waived failing checks are prohibited.
package/docs/RELEASING.md CHANGED
@@ -12,6 +12,12 @@ The release invariant is:
12
12
 
13
13
  `npm publish` runs `release:check` through `prepublishOnly`, so npm publication is blocked until all GitHub state is synchronized.
14
14
 
15
+ ## Default automation responsibility
16
+
17
+ For every reviewed release-relevant change, repository automation completes the source release without requiring the owner to repeat the instruction: it merges the pull request, waits for successful push-triggered CI on the exact `main` commit, creates and pushes the annotated version tag, creates or updates the final GitHub Release, uploads the generated npm tarball, and verifies that all references identify the same commit. These GitHub operations use only local `git`, `gh`, and `gh api` through Machine Bridge.
18
+
19
+ This standing responsibility does not authorize npm publication, Cloudflare Worker deployment, credential changes, global package installation, or local daemon/service replacement. Those operations change a registry or live machine and require explicit authorization.
20
+
15
21
  ## Prepare a version
16
22
 
17
23
  1. Set the new version without creating an automatic npm tag. The npm version hook synchronizes the Worker and packaged browser-extension versions:
@@ -65,3 +71,9 @@ The npm lifecycle repeats the full project checks and the GitHub synchronization
65
71
  - An npm account that owns the package or has maintainer permission.
66
72
 
67
73
  GitHub Actions is a required publication boundary. The authenticated GitHub CLI must be able to read Actions runs, and a missing, pending, cancelled, skipped, or failed exact-commit push run blocks both `release:publish` and `release:check`. This prevents a machine-specific local pass from publishing a version that fails another supported platform.
74
+
75
+ ## Registry publication hardening
76
+
77
+ The preferred target is npm trusted publishing from a narrowly scoped GitHub Actions release workflow using OIDC and a protected GitHub environment. This removes the need for a long-lived npm publication token and allows npm to generate provenance automatically. Enabling it requires an explicit package-owner configuration in npm and a reviewed change to the release workflow; repository code alone cannot complete that trust relationship.
78
+
79
+ Until trusted publishing is configured, publication remains a deliberate local operator step after `release:check`. Do not add an npm token to repository or environment files, workflow YAML, logs, or local project notes. Restrict any fallback token to the shortest practical lifetime and minimum package scope.
package/docs/TESTING.md CHANGED
@@ -14,12 +14,14 @@ The suite includes:
14
14
 
15
15
  - release-impact enforcement requiring a new package version and CHANGELOG section for release-relevant changes;
16
16
  - release-state diagnostics distinguishing missing local/remote version tags from tags that point to the wrong commit, plus a release-CI gate that rejects missing, pending, failed, pull-request-only, stale, or wrong-commit runs;
17
- - generated Cloudflare Worker types and strict TypeScript checking, including unused-local and unused-parameter rejection;
17
+ - generated Cloudflare Worker types under ignored `.wrangler/` state and strict TypeScript checking, including unused-local and unused-parameter rejection; packaging rejects generated declarations;
18
+ - Conventional Commit title validation, shared Markdown escaping regression coverage, and generated MCP tool-reference drift detection;
19
+ - direct tests for shared project-metadata reads, strict integer normalization, plain-record classification, and canonical profile/Worker/job/lock inventory;
18
20
  - recursive syntax validation for every JavaScript file under the shipped/runtime/test roots plus the shell wrapper;
19
21
  - shared tool-catalog schema, annotation, and profile-inventory checks;
20
22
  - default working-agreement injection without user files, bounded automatic project metadata, script-body non-disclosure, user-global opt-out, repository opt-out rejection, global `model_instructions_file` injection in stdio/remote initialization, hierarchical precedence, `.agents/skills` and `.codex/skills` compatibility discovery, live project/skill rescanning and fingerprints, automatic task ranking/loading with English inflection normalization, bounded Chinese/English intent aliases, capability-name weighting, and selected-skill instruction loading; automatic `package.*` commands with English/Chinese workflow-intent matching and Windows command-shim execution, explicit command override/removal, direct argv handling, timeout ceilings, runtime-keyed routing-telemetry privacy, and execution-profile denial;
21
23
  - concurrent complete-before-visible lock claims, atomic replacement under active readers, malformed-lock grace, snapshot/token-safe reclamation, absolute-age expiry, PID-reuse detection, and bounded startup-lock waiting;
22
- - foreground takeover of active and orphaned background daemons, legacy lock identification from canonicalized process arguments, foreground-process protection, actual-PID exit waiting, POSIX non-escalating timeout behavior, Windows verified-daemon stop semantics, daemon lock mode/version/process-start metadata, launchd service-target semantics, and silent idempotent duplicate service starts;
24
+ - foreground takeover of active and orphaned background daemons, legacy lock identification from canonicalized process arguments, foreground-process protection, bounded final lock-handoff retry, actual-PID exit waiting, POSIX non-escalating timeout behavior, Windows verified-daemon stop semantics, daemon lock mode/version/process-start metadata, launchd service-target semantics, and silent idempotent duplicate service starts; daemon fixture subprocesses intentionally do not inherit V8 coverage because their purpose is ownership timing rather than code measurement;
23
25
  - fail-closed service lifecycle ordering for provider-stop, all-workspace daemon-stop, and definition removal, including platform/daemon/removal failure injection and normalized macOS/systemd/Windows results;
24
26
  - machine-level browser-broker ownership/client proxying, authenticated extension origin/subprotocol, non-cacheable local pairing, pairing-token non-disclosure, resource-backed upload routing, broker result redaction, pre-registered runtime-handshake listeners, bounded socket/HTTP waits, installed-application discovery caching, and name-based task matching;
25
27
  - relay environment-proxy direct/bypass/agent selection, unsupported proxy rejection, fail-fast invalid configuration, and route observability without endpoint or credential disclosure;
@@ -67,7 +69,7 @@ For deterministic release validation, perform an isolated-profile smoke test wit
67
69
 
68
70
  `npm run coverage:test` runs selected in-process and lightweight entrypoint fixtures under V8 coverage and enforces per-module baselines for policy, typed errors, call registration, execution middleware, lifecycle/observability, logging, Runtime/CLI orchestration, and Worker pending/policy/error modules. The full stdio and Worker OAuth/MCP integrations run separately in the main suite and are not duplicated inside coverage collection. The gate deliberately reports each module rather than one aggregate percentage. JavaScript modules enforce function and branch minima; Node's direct TypeScript stripping does not expose trustworthy branch ranges, so TypeScript modules enforce function coverage plus explicit state-machine tests and the real workerd integration suite.
69
71
 
70
- The current CLI entrypoint remains the weakest covered orchestration surface; its baseline is therefore reported and locked independently, while extracted `cli-options` and `cli-policy` pure modules carry substantially higher thresholds. A refactor may raise a threshold, but must not lower one merely to make CI green without an explicit audit explanation.
72
+ The current CLI entrypoint remains the weakest covered orchestration surface; its baseline is therefore reported and locked independently, while extracted `cli-options`, `cli-policy`, `records`, and `state-inventory` modules carry substantially higher thresholds. The state-inventory extraction raised the CLI branch floor from 5% to 10%; a refactor may raise a threshold, but must not lower one merely to make CI green without an explicit audit explanation.
71
73
 
72
74
  ## Additional release checks
73
75
 
@@ -83,7 +85,7 @@ npm run version:check
83
85
  npm run release-impact:check
84
86
  ```
85
87
 
86
- GitHub Actions executes the main suite on Linux, macOS, and Windows using the pinned Node 26/npm 12 baseline. Because Node 26 currently bundles npm 11, CI explicitly disables setup-node's automatic package-manager cache and upgrades npm from the runner temporary directory before any project-local npm command can trigger strict `devEngines`. Checkout fetches version tags so the release-impact gate can compare the branch with the latest release. A separate package-audit job scans reachable Git history, audits both the complete dependency graph and the production-only graph, verifies registry signatures and attestations, validates a CycloneDX SBOM written under the runner temporary directory, exercises the documented isolated global installation, then performs a dry-run package build. The macOS matrix job also runs the installation smoke test because Wrangler's optional `fsevents` resolution is platform-specific. Third-party Actions are pinned to immutable 40-character commit SHAs; architecture tests reject movable tags, and Dependabot monitors both action and dependency updates.
88
+ GitHub Actions executes the main suite on Linux, macOS, and Windows using the pinned Node 26/npm 12 baseline. Because Node 26 currently bundles npm 11, CI explicitly disables setup-node's automatic package-manager cache and upgrades npm from the runner temporary directory before any project-local npm command can trigger strict `devEngines`. Checkout fetches version tags so the release-impact gate can compare the branch with the latest release. A separate package-audit job scans reachable Git history, audits both the complete dependency graph and the production-only graph, verifies registry signatures and attestations, validates a CycloneDX SBOM written under the runner temporary directory, exercises the documented isolated global installation, then performs a dry-run package build. Separate pinned workflows validate governance titles, review dependency changes, run CodeQL over JavaScript/TypeScript and GitHub Actions, and publish OpenSSF Scorecard results. The macOS matrix job also runs the installation smoke test because Wrangler's optional `fsevents` resolution is platform-specific. Third-party Actions are pinned to immutable 40-character commit SHAs; architecture tests reject movable tags, and Dependabot monitors both action and dependency updates.
87
89
 
88
90
  ## Test design rules
89
91
 
@@ -104,7 +106,7 @@ Run `npm run privacy:check` before committing and before packaging. Run and revi
104
106
 
105
107
  ## Package manifest
106
108
 
107
- `npm run package:test` executes a real silent `npm pack --dry-run --json`, requires clean parseable JSON, rejects sensitive local artifacts and credential-like file classes, validates every packaged mode as `0644` or `0755`, and verifies that privacy/engineering guidance, runtime/relay/secure-file/lock/service/browser/app modules, all package-script helpers, the packaged browser extension, contribution discipline, and privacy/release-impact checkers are present. `npm run install:test` requires npm 12, installs the real tarball from a package-free directory into an isolated global prefix with the documented options, verifies the packaged npm engine requirement, rejects blocked-script warnings, confirms optional `fsevents` is absent, and runs the installed CLI. The test runs on Linux, macOS, and Windows CI.
109
+ `npm run package:test` executes a real silent `npm pack --dry-run --json`, requires clean parseable JSON, rejects sensitive local artifacts, credential-like file classes, and generated Worker type declarations, validates every packaged mode as `0644` or `0755`, and verifies that privacy/engineering guidance, runtime/relay/secure-file/lock/service/browser/app modules, all package-script helpers, the packaged browser extension, contribution discipline, and privacy/release-impact checkers are present. `npm run install:test` requires npm 12, installs the real tarball from a package-free directory into an isolated global prefix with the documented options, verifies the packaged npm engine requirement, rejects blocked-script warnings, confirms optional `fsevents` is absent, and runs the installed CLI. The test runs on Linux, macOS, and Windows CI.
108
110
 
109
111
  The stdio integration test also sends an oversized line, verifies bounded rejection, and confirms that the next valid request is still processed.
110
112