← Back to Pull requests

feat: extract AppController facade and canonical tool registry (#395) #405

Merged
trueline-antigravity-agent[bot] merged 30 files (4053 lines) on Nov 30, 2026 05:43 UTC
View on GitHub
trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on Nov 30, 2026 04:39 UTC
Author

Part of #394
Closes #395

Summary


Phase 1 foundation for the Unified Agent & WebMCP Tooling Architecture:
  • Canonical Tool Registry & Policy Gate (src/tools/):

  • - src/tools/schema.js: risk tiers (read, ui, propose, write, destructive, network), write policies (read_only, propose_only, direct_with_undo), bounded { items, total, offset, limit, truncated } envelopes, structured { ok, data | error } results, and zero-dependency recursive JSON Schema validation (rejecting __proto__, constructor, prototype, and unknown properties under additionalProperties: false).
    - src/tools/registry.js: single canonical registry + PolicyGate enforcing surface visibility, toolset filtering, fail-closed isRiskPermitted & registration validation, propose_only mode clamping, and a recursive normalized security denylist blocking secret/permission capabilities and parameters (apiKey, baseUrl, passphrases, Firebase config, policy/WebMCP toggles).
    - src/tools/capabilities/collectionRead.js (collection.read): bookmarks_search (with WebMCP local-only substring enforcement so WebMCP never triggers outbound embedding requests), bookmarks_get, bookmarks_stats, folders_list, tags_list, app_get_state.
    - src/tools/capabilities/uiFilters.js & src/tools/capabilities/uiNavigation.js (ui.navigation): view_set_agent_filter, view_set_manual_filters, view_clear_filters, view_navigate, view_set_layout, selection_set, bookmark_open_editor, bookmark_open.
    - src/tools/capabilities/viewsManage.js (views.manage): saved_views_list, saved_views_apply, saved_views_save, saved_views_delete.
  • AppController Facade (src/hooks/useAppController.js):

  • - Stable ref-backed command/read facade wired into BookmarkApp.jsx, backed by backwards-compatible helpers (useUndoHistory.getState, useSidebarCollapsed.setSidebarCollapsed, useBookmarkSelection.setSelection).
  • WebMCP Migration (src/webmcp/registerWebMcpTools.js, src/hooks/useWebMcpTools.js):

  • - Migrated WebMCP from the standalone webmcpTools.js (removed) onto defaultRegistry, preserving off-by-default opt-in, default read-only collection.read toolset, and AbortSignal cleanup (including aborting on partial registration failure).
  • Docs & Changeset: Updated DESIGN.md and added .changeset/tool-registry-foundation.md.
  • Verification


  • npm run ci: passed (check:version-policy, licenses:notices:check, format:check, lint, test — 117 test files / 1,527 tests passed, build:chrome + scripts/check-chunk-laziness.mjs passed, build:storybook passed).

  • Pre-push security review (claude -p --model sonnet): LGTM on final diff.
  • <!-- agent-bot-write: ghw_58108ecedf0b2053 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    Diff: 4053 lines (+3577 / -476) across 30 files Reviewer: qwts Review duration: 64m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.72) × (1 − Review Confidence (0.77)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 4053 lines diff across 30 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.88 · 5 substantive comment(s)
    0.88
    Model 3 · Review Timing & Attention
    Session adequacy: 63% · Reviewer familiarity: 50%
    76%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    22 items
    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 30, 2026 04:39 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"f660eaf00269efdb9ff10abcc74517c3f7bae1fd","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

    <details>
    <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-30T04:43:13.171564Z">2026-11-30T04:43:13.171564Z</relative-time> | f660eaf | PR opened |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 30, 2026 04:43 UTC
    Code Review
    src/hooks/useAppController.js:1
    @@ -0,0 +1,136 @@
    +// Stable, ref-backed command/read facade over BookmarkApp's hooks & state.
    +// Tools in `src/tools/` interact exclusively with this interface (Dependency
    +// Inversion), never with React setters or store backends directly.
    +
    +import { useMemo, useRef } from "react";
    +import { mergeAgentPlan } from "../utils/bookmarkFilters.js";
    +
    +function computeOpenSurface(s) {
    +  if (s.wizardOpen) return "storageWizard";
    +  if (s.isOptionsOpen) return "options";
    +  if (s.isHelpModalOpen) return "help";
    +  if (s.isImportExportModalOpen) return "importExport";
    +  if (s.isModalOpen) return "bookmarkForm";
    +  if (s.isDeleteConfirmModalOpen) return "deleteConfirm";
    +  if (s.review) return "changeReview";
    +  if (s.duplicateReview) return "duplicateReview";
    +  if (s.digest) return "digest";
    +  if (s.linkHealthOpen) return "linkHealth";
    +  return "list";

    <sub><sub>!P2 Badge</sub></sub> Report blocking overlays in the open surface

    When the message modal, navigation drawer, bulk editor, or agent bar is open, BookmarkApp treats the UI as dialog-blocked, but none of those states is passed to this controller or checked here, so app_get_state reports openSurface: "list". A WebMCP client can consequently believe the shelf is interactive while a modal or scrim owns the UI; include these open states in the controller’s surface calculation.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 30, 2026 04:43 UTC
    Code Review
    src/tools/capabilities/uiFilters.js:1
    @@ -0,0 +1,270 @@
    +// Filter & projection tools (`ui.navigation` toolset).
    +// Keeps agent filter projection (`lastAction`) and manual filters
    +// (`manualFilters`) strictly independent per DESIGN.md.
    +
    +import { UNFILED, normalizeFolderPath } from "../../utils/folderTree.js";
    +import { EMPTY_FILTERS } from "../../utils/manualFilters.js";
    +import {
    +  ERROR_CODES,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  errorResult,
    +  okResult,
    +} from "../schema.js";
    +
    +const UI_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: false,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +const AGENT_SORT_ENUM = [
    +  "title",
    +  "url",
    +  "rating",
    +  "folder",
    +  "folderId",
    +  "createdAt",
    +  "updatedAt",
    +  "lastOpenedAt",
    +];
    +const MANUAL_SORT_ENUM = [
    +  "",
    +  "title",
    +  "url",
    +  "rating",
    +  "folderId",
    +  "createdAt",
    +  "lastOpenedAt",
    +  "updatedAt",
    +];
    +
    +function addRatingStep(steps, args) {
    +  const parameters = {};
    +  if (args.minRating !== undefined) parameters.minRating = args.minRating;
    +  if (args.maxRating !== undefined) parameters.maxRating = args.maxRating;
    +  if (args.exactRating !== undefined) parameters.exact = args.exactRating;
    +  if (Object.keys(parameters).length > 0) {
    +    steps.push({ action: "filterByRating", parameters, priority: 4 });
    +  }
    +}
    +
    +function addSortAndLimitSteps(steps, args) {
    +  if (args.sortBy) {
    +    const sortBy = args.sortBy === "folderId" ? "folder" : args.sortBy;
    +    steps.push({
    +      action: "sortBookmarks",
    +      parameters: { sortBy, order: args.order || "asc" },
    +      priority: 7,
    +    });
    +  }
    +  if (args.limit !== undefined) {
    +    steps.push({
    +      action: "limitResults",
    +      parameters: {
    +        count: args.limit,
    +        direction: args.limitDirection || "first",
    +        scope: "current",
    +      },
    +      priority: 8,
    +    });
    +  }
    +}
    +
    +function buildAgentPlanSteps(args) {
    +  const steps = [];
    +  if (typeof args.query === "string" && args.query.trim()) {
    +    steps.push({
    +      action: "searchBookmarks",
    +      parameters: { searchTerm: args.query.trim() },
    +      priority: 1,
    +    });
    +  }
    +  if (args.fieldMatch) {
    +    const action = args.fieldMatch.op === "startsWith" ? "findStartsWith" : "findIncludes";
    +    steps.push({
    +      action,
    +      parameters: { field: args.fieldMatch.field, value: args.fieldMatch.value },
    +      priority: 2,
    +    });
    +  }
    +  if (Array.isArray(args.includeTags) || Array.isArray(args.excludeTags)) {
    +    steps.push({
    +      action: "findWithTags",
    +      parameters: { includeTags: args.includeTags || [], excludeTags: args.excludeTags || [] },
    +      priority: 3,
    +    });
    +  }
    +  addRatingStep(steps, args);
    +  if (args.brokenOnly === true)
    +    steps.push({ action: "findBrokenLinks", parameters: {}, priority: 5 });
    +  if (args.neverOpened === true)
    +    steps.push({ action: "findNeverOpened", parameters: {}, priority: 6 });
    +  addSortAndLimitSteps(steps, args);
    +  return steps;
    +}
    +
    +export function executeSetAgentFilter(args, controller) {
    +  const steps = buildAgentPlanSteps(args ?? {});
    +  if (steps.length === 0) {
    +    return errorResult(
    +      ERROR_CODES.VALIDATION_ERROR,
    +      "Provide at least one filter, sort, or limit criterion."
    +    );
    +  }
    +  const merge = args?.merge === true;
    +  const plan = controller.setAgentPlan(steps, { merge });
    +  return okResult({
    +    appliedSteps: steps.length,
    +    merge,
    +    activePlanSteps: Array.isArray(plan) ? plan.length : 1,
    +  });
    +}
    +
    +const DIRECT_MANUAL_KEYS = ["text", "brokenOnly", "neverOpened", "untagged", "sortBy", "order"];
    +
    +function patchRatingFields(next, input) {
    +  if (input.unratedOnly === true) {
    +    next.unratedOnly = true;
    +    next.minRating = 0;
    +    return;
    +  }
    +  if (input.minRating !== undefined) {
    +    next.minRating = input.minRating;
    +    if (input.minRating > 0 || input.unratedOnly === false) next.unratedOnly = false;
    +    return;
    +  }
    +  if (input.unratedOnly === false) next.unratedOnly = false;
    +}
    +
    +function patchManualFilterFields(next, input) {
    +  for (const key of DIRECT_MANUAL_KEYS) {
    +    if (input[key] !== undefined) next[key] = input[key];
    +  }
    +  if (input.includeTags !== undefined) next.includeTags = [...input.includeTags];
    +  if (input.excludeTags !== undefined) next.excludeTags = [...input.excludeTags];
    +  if (input.unfiled === true) next.folder = UNFILED;
    +  else if (input.folder !== undefined) next.folder = normalizeFolderPath(input.folder);

    <sub><sub>!P2 Badge</sub></sub> Clear the unfiled filter when passed false

    In merge mode, calling view_set_manual_filters with { unfiled: false } while the current folder is UNFILED leaves the filter unchanged because only the true case is handled. Since the schema exposes unfiled as a boolean, callers reasonably use false to disable it; handle that case by clearing the folder when it currently represents unfiled, while preserving an unrelated real folder.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 30, 2026 04:43 UTC
    Code Review
    src/tools/capabilities/collectionRead.js:1
    @@ -0,0 +1,421 @@
    +// Canonical read-only collection inspection tools (`collection.read`).
    +// Pure projections over AppController + utils/* — never mutates state or leaks
    +// internal bookkeeping like `faviconUrl` or credentials.
    +
    +import {
    +  filterByRating,
    +  findIncludes,
    +  findStartsWith,
    +  findWithTags,
    +  searchBookmarks,
    +  sortBookmarks,
    +} from "../../utils/bookmarkFilters.js";
    +import {
    +  UNFILED,
    +  buildFolderTree,
    +  findInFolder,
    +  isWithinFolder,
    +  normalizeFolderPath,
    +} from "../../utils/folderTree.js";
    +import { findBrokenLinks, isBroken } from "../../utils/linkHealth.js";
    +import { deriveTagCounts, isUntagged } from "../../utils/manualFilters.js";
    +import { findNeverOpened, isNeverOpened } from "../../utils/openHistory.js";
    +import { mergeSemanticMatches } from "../../utils/semanticSearch.js";
    +import {
    +  MAX_GET_IDS,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  boundedEnvelope,
    +  clampLimit,
    +  clampOffset,
    +  errorResult,
    +  ERROR_CODES,
    +  okResult,
    +} from "../schema.js";
    +
    +const READ_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: true,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +
    +const toSearchItem = (b) => ({
    +  id: b.id,
    +  title: b.title ?? "",
    +  url: b.url ?? "",
    +  folder: b.folderId ?? "",
    +  tags: Array.isArray(b.tags) ? b.tags : [],
    +  rating: typeof b.rating === "number" ? b.rating : 0,
    +  description: b.description ?? "",
    +  createdAt: b.createdAt ?? null,
    +  updatedAt: b.updatedAt ?? null,
    +});
    +
    +const toDetailItem = (b) => ({
    +  ...toSearchItem(b),
    +  urlStatus: b.urlStatus ?? "idle",
    +  urlStatusReason: b.urlStatusReason ?? null,
    +  lastOpenedAt: b.lastOpenedAt ?? null,
    +});
    +
    +function applyStructuralFilters(input, list) {
    +  let results = list;
    +  const fm = input.fieldMatch;
    +  if (fm && typeof fm === "object" && typeof fm.value === "string") {
    +    results =
    +      fm.op === "startsWith"
    +        ? findStartsWith(fm.field || "title", fm.value, results)
    +        : findIncludes(fm.field || "title", fm.value, results);

    <sub><sub>!P2 Badge</sub></sub> Match tag fields per tag instead of joining the array

    For fieldMatch: { field: "tags", op: "includes" }, this delegates to findIncludes, which coerces the tags array to a comma-joined string rather than testing each tag. Queries spanning the synthetic separator—for example "o,b" against ["foo", "bar"]—therefore return bookmarks even though no tag contains the requested value; use per-tag matching as the startsWith path already does.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 30, 2026 04:43 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: f660eaf002

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

    </details>

    Copilot Copilot commented on code on Nov 30, 2026 04:45 UTC
    Code Review
    src/tools/registry.js:1
    @@ -0,0 +1,240 @@
    +// Canonical Tool Registry & Policy Gate.
    +// Single source of truth consumed by both the WebMCP adapter and the built-in
    +// agent runner. Enforces surface visibility, write policies, schema validation,
    +// and hard security denylists against secret/permission capabilities.
    +
    +import { COLLECTION_READ_TOOLS } from "./capabilities/collectionRead.js";
    +import { UI_NAVIGATION_TOOLS } from "./capabilities/uiNavigation.js";
    +import { VIEWS_MANAGE_TOOLS } from "./capabilities/viewsManage.js";
    +import {
    +  ERROR_CODES,
    +  RISK_TIERS,
    +  SURFACES,
    +  WRITE_POLICIES,
    +  errorResult,
    +  validateAgainstSchema,
    +} from "./schema.js";
    +
    +export const TOOLSET_METADATA = Object.freeze([
    +  {
    +    id: "collection.read",
    +    label: "Collection Read",
    +    description: "Search bookmarks, inspect details/stats, list folders and tags, read UI state.",
    +    defaultEnabled: { builtin: true, webmcp: true },
    +  },
    +  {
    +    id: "ui.navigation",
    +    label: "UI & Navigation",
    +    description:
    +      "Adjust filters, navigate views/dialogs, change layout, manage selection, open bookmarks.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +  {
    +    id: "views.manage",
    +    label: "Saved Views",
    +    description: "List, apply, save, and delete named views.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +]);
    +
    +const VALID_RISK_TIERS = new Set(Object.values(RISK_TIERS));
    +const VALID_SURFACES = new Set(Object.values(SURFACES));
    +const PROPOSE_ALLOWED_RISKS = new Set([
    +  RISK_TIERS.READ,
    +  RISK_TIERS.UI,
    +  RISK_TIERS.PROPOSE,
    +  RISK_TIERS.NETWORK,
    +]);
    +
    +const normalizeKey = (value) =>
    +  String(value ?? "")
    +    .toLowerCase()
    +    .replace(/[_-]/gu, "");
    +
    +export const HARD_DENIED_CAPABILITIES = new Set([
    +  "secrets.read",
    +  "secrets.write",
    +  "llm.apikey",
    +  "llm.baseurl",
    +  "encryption.manage",
    +  "firebase.config",
    +  "permissions.manage",
    +  "webmcp.toggle",
    +  "agent.policy",
    +]);
    +
    +export const HARD_DENIED_PARAM_KEYS = new Set([
    +  "apikey",
    +  "baseurl",
    +  "passphrase",
    +  "encryptedblob",
    +  "firebaseconfig",
    +  "authtoken",
    +  "webmcpenabled",
    +  "agentpolicy",
    +  "writepolicy",
    +]);
    +
    +function checkSchemaKeys(schema, toolName, path) {
    +  if (!schema || typeof schema !== "object") return;
    +  for (const [key, propSchema] of Object.entries(schema.properties ?? {})) {
    +    const fullPath = `${path}.${key}`;
    +    if (HARD_DENIED_PARAM_KEYS.has(normalizeKey(key))) {
    +      throw new Error(
    +        `Tool "${toolName}" parameter "${fullPath}" is blocked by the security denylist.`
    +      );
    +    }
    +    checkSchemaKeys(propSchema, toolName, fullPath);
    +  }
    +  if (schema.items) checkSchemaKeys(schema.items, toolName, `${path}[]`);
    +}

    The hard denylist is not fail-closed here: checkSchemaKeys only inspects declared properties, so an object schema with omitted/true additionalProperties can accept arbitrary keys such as apiKey or baseUrl; executeTool then passes those sanitized values straight to the executor without a recursive denylist check. This also applies to the open-ended plan.parameters schema in saved_views_save. Require recursively closed object schemas or validate the actual sanitized arguments against the denylist before execution.

    Copilot Copilot commented on code on Nov 30, 2026 04:45 UTC
    Code Review
    src/tools/registry.js:1
    @@ -0,0 +1,240 @@
    +// Canonical Tool Registry & Policy Gate.
    +// Single source of truth consumed by both the WebMCP adapter and the built-in
    +// agent runner. Enforces surface visibility, write policies, schema validation,
    +// and hard security denylists against secret/permission capabilities.
    +
    +import { COLLECTION_READ_TOOLS } from "./capabilities/collectionRead.js";
    +import { UI_NAVIGATION_TOOLS } from "./capabilities/uiNavigation.js";
    +import { VIEWS_MANAGE_TOOLS } from "./capabilities/viewsManage.js";
    +import {
    +  ERROR_CODES,
    +  RISK_TIERS,
    +  SURFACES,
    +  WRITE_POLICIES,
    +  errorResult,
    +  validateAgainstSchema,
    +} from "./schema.js";
    +
    +export const TOOLSET_METADATA = Object.freeze([
    +  {
    +    id: "collection.read",
    +    label: "Collection Read",
    +    description: "Search bookmarks, inspect details/stats, list folders and tags, read UI state.",
    +    defaultEnabled: { builtin: true, webmcp: true },
    +  },
    +  {
    +    id: "ui.navigation",
    +    label: "UI & Navigation",
    +    description:
    +      "Adjust filters, navigate views/dialogs, change layout, manage selection, open bookmarks.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +  {
    +    id: "views.manage",
    +    label: "Saved Views",
    +    description: "List, apply, save, and delete named views.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +]);
    +
    +const VALID_RISK_TIERS = new Set(Object.values(RISK_TIERS));
    +const VALID_SURFACES = new Set(Object.values(SURFACES));
    +const PROPOSE_ALLOWED_RISKS = new Set([
    +  RISK_TIERS.READ,
    +  RISK_TIERS.UI,
    +  RISK_TIERS.PROPOSE,
    +  RISK_TIERS.NETWORK,
    +]);
    +
    +const normalizeKey = (value) =>
    +  String(value ?? "")
    +    .toLowerCase()
    +    .replace(/[_-]/gu, "");
    +
    +export const HARD_DENIED_CAPABILITIES = new Set([
    +  "secrets.read",
    +  "secrets.write",
    +  "llm.apikey",
    +  "llm.baseurl",
    +  "encryption.manage",
    +  "firebase.config",
    +  "permissions.manage",
    +  "webmcp.toggle",
    +  "agent.policy",
    +]);
    +
    +export const HARD_DENIED_PARAM_KEYS = new Set([
    +  "apikey",
    +  "baseurl",
    +  "passphrase",
    +  "encryptedblob",
    +  "firebaseconfig",
    +  "authtoken",
    +  "webmcpenabled",
    +  "agentpolicy",
    +  "writepolicy",
    +]);
    +
    +function checkSchemaKeys(schema, toolName, path) {
    +  if (!schema || typeof schema !== "object") return;
    +  for (const [key, propSchema] of Object.entries(schema.properties ?? {})) {
    +    const fullPath = `${path}.${key}`;
    +    if (HARD_DENIED_PARAM_KEYS.has(normalizeKey(key))) {
    +      throw new Error(
    +        `Tool "${toolName}" parameter "${fullPath}" is blocked by the security denylist.`
    +      );
    +    }
    +    checkSchemaKeys(propSchema, toolName, fullPath);
    +  }
    +  if (schema.items) checkSchemaKeys(schema.items, toolName, `${path}[]`);
    +}
    +
    +function assertSafeDefinition(def) {
    +  if (!def || typeof def.name !== "string" || !def.name) {
    +    throw new Error("Tool definition must have a non-empty string name.");
    +  }
    +  if (!VALID_RISK_TIERS.has(def.risk)) {
    +    throw new Error(`Tool "${def.name}" has invalid risk tier "${def.risk}".`);
    +  }
    +  if (
    +    !Array.isArray(def.surfaces) ||
    +    def.surfaces.length === 0 ||
    +    def.surfaces.some((s) => !VALID_SURFACES.has(s))
    +  ) {
    +    throw new Error(`Tool "${def.name}" must specify valid surfaces.`);
    +  }
    +  const normalizedCap = String(def.capability ?? "").toLowerCase();
    +  const normalizedToolset = String(def.toolset ?? "").toLowerCase();
    +  if (
    +    HARD_DENIED_CAPABILITIES.has(normalizedCap) ||
    +    HARD_DENIED_CAPABILITIES.has(normalizedToolset)

    The capability/toolset denylist check only lower-cases the raw strings, while the parameter check uses separator-insensitive normalization. A descriptor named secrets_read, permissions-manage, or similar can therefore bypass this hard denylist and be registered, contrary to the stated fail-closed secret/permission boundary. Normalize the denylist entries and the candidate capability/toolset with the same helper before comparing them.

    Copilot Copilot commented on code on Nov 30, 2026 04:45 UTC
    Code Review
    src/tools/schema.js:1
    @@ -0,0 +1,204 @@
    +// Canonical tool contract primitives: risk tiers, policies, bounded envelopes,
    +// structured results, and lightweight zero-dependency JSON Schema validation.
    +//
    +// Pure JS only — never import `ai`, `zod`, React, `chrome.*`, or `firebase/*`
    +// here so bundle chunk laziness (#362) and WebMCP sharing hold by construction.
    +
    +export const RISK_TIERS = Object.freeze({
    +  READ: "read",
    +  UI: "ui",
    +  PROPOSE: "propose",
    +  WRITE: "write",
    +  DESTRUCTIVE: "destructive",
    +  NETWORK: "network",
    +});
    +
    +export const WRITE_POLICIES = Object.freeze({
    +  READ_ONLY: "read_only",
    +  PROPOSE_ONLY: "propose_only",
    +  DIRECT_WITH_UNDO: "direct_with_undo",
    +});
    +
    +export const SURFACES = Object.freeze({
    +  BUILTIN: "builtin",
    +  WEBMCP: "webmcp",
    +});
    +
    +export const ERROR_CODES = Object.freeze({
    +  POLICY_DENIED: "POLICY_DENIED",
    +  VALIDATION_ERROR: "VALIDATION_ERROR",
    +  NOT_FOUND: "NOT_FOUND",
    +  INVALID_URL: "INVALID_URL",
    +  KEY_LOCKED: "KEY_LOCKED",
    +  PROVIDER_NOT_READY: "PROVIDER_NOT_READY",
    +  UNSAFE_HOST: "UNSAFE_HOST",
    +  CONFLICT: "CONFLICT",
    +  EXECUTION_ERROR: "EXECUTION_ERROR",
    +});
    +
    +export const DEFAULT_RESULT_LIMIT = 20;
    +export const MAX_RESULT_LIMIT = 100;
    +export const MAX_GET_IDS = 25;
    +
    +const UNSAFE_OBJECT_KEYS = new Set(["__proto__", "constructor", "prototype"]);
    +
    +export function clampLimit(value, fallback = DEFAULT_RESULT_LIMIT, max = MAX_RESULT_LIMIT) {
    +  const n = Number(value);
    +  if (!Number.isFinite(n) || n < 1) return fallback;
    +  return Math.min(Math.floor(n), max);
    +}
    +
    +export function clampOffset(value) {
    +  const n = Number(value);
    +  if (!Number.isFinite(n) || n < 0) return 0;
    +  return Math.floor(n);
    +}
    +
    +export function boundedEnvelope(items, total, offset, limit) {
    +  return {
    +    items,
    +    total,
    +    offset,
    +    limit,
    +    truncated: offset + items.length < total,
    +  };
    +}
    +
    +export function okResult(data, meta) {
    +  return meta ? { ok: true, data, meta } : { ok: true, data };
    +}
    +
    +export function errorResult(code, message, retryable = false) {
    +  return {
    +    ok: false,
    +    error: { code, message, retryable },
    +  };
    +}
    +
    +function validateString(schema, value, path, errors) {
    +  if (typeof value !== "string") {
    +    errors.push(`${path} must be a string`);
    +    return undefined;
    +  }
    +  if (schema.minLength !== undefined && value.length < schema.minLength) {
    +    errors.push(`${path} must be at least ${schema.minLength} characters`);
    +  }
    +  if (schema.maxLength !== undefined && value.length > schema.maxLength) {
    +    errors.push(`${path} must be at most ${schema.maxLength} characters`);
    +  }
    +  if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
    +    errors.push(`${path} must be one of: ${schema.enum.join(", ")}`);
    +  }
    +  return value;
    +}
    +
    +function validateNumber(schema, value, path, errors) {
    +  if (typeof value !== "number" || !Number.isFinite(value)) {
    +    errors.push(`${path} must be a finite number`);
    +    return undefined;
    +  }
    +  if (schema.type === "integer" && !Number.isInteger(value)) {
    +    errors.push(`${path} must be an integer`);
    +    return undefined;
    +  }
    +  if (schema.minimum !== undefined && value < schema.minimum) {
    +    errors.push(`${path} must be >= ${schema.minimum}`);
    +  }
    +  if (schema.maximum !== undefined && value > schema.maximum) {
    +    errors.push(`${path} must be <= ${schema.maximum}`);
    +  }
    +  if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
    +    errors.push(`${path} must be one of: ${schema.enum.join(", ")}`);
    +  }
    +  return value;
    +}
    +
    +function validateArray(schema, value, path, errors) {
    +  if (!Array.isArray(value)) {
    +    errors.push(`${path} must be an array`);
    +    return undefined;
    +  }
    +  if (schema.minItems !== undefined && value.length < schema.minItems) {
    +    errors.push(`${path} must contain at least ${schema.minItems} item(s)`);
    +  }
    +  if (schema.maxItems !== undefined && value.length > schema.maxItems) {
    +    errors.push(`${path} must contain at most ${schema.maxItems} item(s)`);
    +  }
    +  if (!schema.items) return [...value];
    +  return value.map((item, idx) => validateValue(schema.items, item, `${path}[${idx}]`, errors));
    +}
    +
    +function validateObject(schema, value, path, errors) {
    +  if (!value || typeof value !== "object" || Array.isArray(value)) {
    +    errors.push(`${path} must be an object`);
    +    return undefined;
    +  }
    +  const props = schema.properties || {};
    +  const required = Array.isArray(schema.required) ? schema.required : [];
    +  for (const key of required) {
    +    if (value[key] === undefined || value[key] === null) {
    +      errors.push(`${path}.${key} is required`);
    +    }
    +  }
    +  const sanitized = {};
    +  for (const [key, entry] of Object.entries(value)) {
    +    if (UNSAFE_OBJECT_KEYS.has(key)) {
    +      errors.push(`Forbidden property "${path}.${key}"`);
    +      continue;
    +    }
    +    if (entry === undefined) continue;
    +    if (!Object.prototype.hasOwnProperty.call(props, key)) {
    +      if (schema.additionalProperties === false) {
    +        errors.push(`Unknown property "${path}.${key}"`);
    +      } else {
    +        sanitized[key] = entry;
    +      }

    Unknown values under an object with additionalProperties enabled are copied without being recursively visited. As a result, a forbidden key nested inside an allowed arbitrary property can pass validateAgainstSchema, contrary to the documented recursive rejection of __proto__, constructor, and prototype; for example, nested data under saved_views_save.plan[].parameters is not traversed. Recursively sanitize/check copied values (or reject arbitrary nested objects) before returning sanitized.

    Copilot Copilot commented on code on Nov 30, 2026 04:45 UTC
    Code Review
    src/tools/capabilities/collectionRead.js:1
    @@ -0,0 +1,421 @@
    +// Canonical read-only collection inspection tools (`collection.read`).
    +// Pure projections over AppController + utils/* — never mutates state or leaks
    +// internal bookkeeping like `faviconUrl` or credentials.
    +
    +import {
    +  filterByRating,
    +  findIncludes,
    +  findStartsWith,
    +  findWithTags,
    +  searchBookmarks,
    +  sortBookmarks,
    +} from "../../utils/bookmarkFilters.js";
    +import {
    +  UNFILED,
    +  buildFolderTree,
    +  findInFolder,
    +  isWithinFolder,
    +  normalizeFolderPath,
    +} from "../../utils/folderTree.js";
    +import { findBrokenLinks, isBroken } from "../../utils/linkHealth.js";
    +import { deriveTagCounts, isUntagged } from "../../utils/manualFilters.js";
    +import { findNeverOpened, isNeverOpened } from "../../utils/openHistory.js";
    +import { mergeSemanticMatches } from "../../utils/semanticSearch.js";
    +import {
    +  MAX_GET_IDS,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  boundedEnvelope,
    +  clampLimit,
    +  clampOffset,
    +  errorResult,
    +  ERROR_CODES,
    +  okResult,
    +} from "../schema.js";
    +
    +const READ_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: true,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +
    +const toSearchItem = (b) => ({
    +  id: b.id,
    +  title: b.title ?? "",
    +  url: b.url ?? "",
    +  folder: b.folderId ?? "",
    +  tags: Array.isArray(b.tags) ? b.tags : [],
    +  rating: typeof b.rating === "number" ? b.rating : 0,
    +  description: b.description ?? "",
    +  createdAt: b.createdAt ?? null,
    +  updatedAt: b.updatedAt ?? null,
    +});
    +
    +const toDetailItem = (b) => ({
    +  ...toSearchItem(b),
    +  urlStatus: b.urlStatus ?? "idle",
    +  urlStatusReason: b.urlStatusReason ?? null,
    +  lastOpenedAt: b.lastOpenedAt ?? null,
    +});
    +
    +function applyStructuralFilters(input, list) {
    +  let results = list;
    +  const fm = input.fieldMatch;
    +  if (fm && typeof fm === "object" && typeof fm.value === "string") {
    +    results =
    +      fm.op === "startsWith"
    +        ? findStartsWith(fm.field || "title", fm.value, results)
    +        : findIncludes(fm.field || "title", fm.value, results);

    When fieldMatch.field is tags and op is includes, this calls findIncludes, which coerces the whole tag array to a comma-joined string. That can match across tag boundaries (for example, ['ab', 'cd'] matching b,c) even though the same field's startsWith path checks each tag and the normal tag filters treat tags as separate values. Match tags element-by-element for this path.

    Copilot Copilot commented on code on Nov 30, 2026 04:45 UTC
    Code Review
    src/tools/capabilities/uiFilters.js:1
    @@ -0,0 +1,270 @@
    +// Filter & projection tools (`ui.navigation` toolset).
    +// Keeps agent filter projection (`lastAction`) and manual filters
    +// (`manualFilters`) strictly independent per DESIGN.md.
    +
    +import { UNFILED, normalizeFolderPath } from "../../utils/folderTree.js";
    +import { EMPTY_FILTERS } from "../../utils/manualFilters.js";
    +import {
    +  ERROR_CODES,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  errorResult,
    +  okResult,
    +} from "../schema.js";
    +
    +const UI_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: false,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +const AGENT_SORT_ENUM = [
    +  "title",
    +  "url",
    +  "rating",
    +  "folder",
    +  "folderId",
    +  "createdAt",
    +  "updatedAt",
    +  "lastOpenedAt",
    +];
    +const MANUAL_SORT_ENUM = [
    +  "",
    +  "title",
    +  "url",
    +  "rating",
    +  "folderId",
    +  "createdAt",
    +  "lastOpenedAt",
    +  "updatedAt",
    +];
    +
    +function addRatingStep(steps, args) {
    +  const parameters = {};
    +  if (args.minRating !== undefined) parameters.minRating = args.minRating;
    +  if (args.maxRating !== undefined) parameters.maxRating = args.maxRating;
    +  if (args.exactRating !== undefined) parameters.exact = args.exactRating;
    +  if (Object.keys(parameters).length > 0) {
    +    steps.push({ action: "filterByRating", parameters, priority: 4 });
    +  }
    +}
    +
    +function addSortAndLimitSteps(steps, args) {
    +  if (args.sortBy) {
    +    const sortBy = args.sortBy === "folderId" ? "folder" : args.sortBy;
    +    steps.push({
    +      action: "sortBookmarks",
    +      parameters: { sortBy, order: args.order || "asc" },
    +      priority: 7,
    +    });
    +  }
    +  if (args.limit !== undefined) {
    +    steps.push({
    +      action: "limitResults",
    +      parameters: {
    +        count: args.limit,
    +        direction: args.limitDirection || "first",
    +        scope: "current",
    +      },
    +      priority: 8,
    +    });
    +  }
    +}
    +
    +function buildAgentPlanSteps(args) {
    +  const steps = [];
    +  if (typeof args.query === "string" && args.query.trim()) {
    +    steps.push({
    +      action: "searchBookmarks",
    +      parameters: { searchTerm: args.query.trim() },
    +      priority: 1,
    +    });
    +  }
    +  if (args.fieldMatch) {
    +    const action = args.fieldMatch.op === "startsWith" ? "findStartsWith" : "findIncludes";
    +    steps.push({
    +      action,
    +      parameters: { field: args.fieldMatch.field, value: args.fieldMatch.value },
    +      priority: 2,
    +    });
    +  }
    +  if (Array.isArray(args.includeTags) || Array.isArray(args.excludeTags)) {
    +    steps.push({
    +      action: "findWithTags",
    +      parameters: { includeTags: args.includeTags || [], excludeTags: args.excludeTags || [] },
    +      priority: 3,
    +    });
    +  }
    +  addRatingStep(steps, args);
    +  if (args.brokenOnly === true)
    +    steps.push({ action: "findBrokenLinks", parameters: {}, priority: 5 });
    +  if (args.neverOpened === true)
    +    steps.push({ action: "findNeverOpened", parameters: {}, priority: 6 });
    +  addSortAndLimitSteps(steps, args);
    +  return steps;
    +}
    +
    +export function executeSetAgentFilter(args, controller) {
    +  const steps = buildAgentPlanSteps(args ?? {});
    +  if (steps.length === 0) {
    +    return errorResult(
    +      ERROR_CODES.VALIDATION_ERROR,
    +      "Provide at least one filter, sort, or limit criterion."
    +    );
    +  }
    +  const merge = args?.merge === true;
    +  const plan = controller.setAgentPlan(steps, { merge });
    +  return okResult({
    +    appliedSteps: steps.length,
    +    merge,
    +    activePlanSteps: Array.isArray(plan) ? plan.length : 1,
    +  });
    +}
    +
    +const DIRECT_MANUAL_KEYS = ["text", "brokenOnly", "neverOpened", "untagged", "sortBy", "order"];
    +
    +function patchRatingFields(next, input) {
    +  if (input.unratedOnly === true) {
    +    next.unratedOnly = true;
    +    next.minRating = 0;
    +    return;
    +  }
    +  if (input.minRating !== undefined) {
    +    next.minRating = input.minRating;
    +    if (input.minRating > 0 || input.unratedOnly === false) next.unratedOnly = false;
    +    return;
    +  }
    +  if (input.unratedOnly === false) next.unratedOnly = false;
    +}
    +
    +function patchManualFilterFields(next, input) {
    +  for (const key of DIRECT_MANUAL_KEYS) {
    +    if (input[key] !== undefined) next[key] = input[key];
    +  }
    +  if (input.includeTags !== undefined) next.includeTags = [...input.includeTags];
    +  if (input.excludeTags !== undefined) next.excludeTags = [...input.excludeTags];
    +  if (input.unfiled === true) next.folder = UNFILED;
    +  else if (input.folder !== undefined) next.folder = normalizeFolderPath(input.folder);
    +  patchRatingFields(next, input);
    +  return next;
    +}
    +
    +export function executeSetManualFilters(args, controller) {
    +  const input = args ?? {};
    +  const mode = input.mode === "replace" ? "replace" : "merge";
    +  const base =
    +    mode === "replace"
    +      ? { ...EMPTY_FILTERS }
    +      : { ...(controller.getUiState()?.manualFilters ?? EMPTY_FILTERS) };
    +  const next = patchManualFilterFields(base, input);
    +  controller.setManualFilters(next);
    +  return okResult({ mode, filters: next });
    +}
    +
    +export function executeClearFilters(args, controller) {
    +  const target = args?.target;
    +  controller.clearFilters(target);
    +  return okResult({ cleared: target });
    +}
    +
    +export const viewSetAgentFilterTool = {
    +  name: "view_set_agent_filter",
    +  toolset: "ui.navigation",
    +  capability: "view.setAgentFilter",
    +  risk: RISK_TIERS.UI,
    +  surfaces: SURFACES_ALL,
    +  annotations: UI_ANNOTATIONS,
    +  description:
    +    "Update the visible shelf via the agent filter projection (`lastAction`) without changing manual filters. " +
    +    "Set merge: true to refine the current agent filter, or false (default) to replace it.",
    +  inputSchema: {
    +    type: "object",
    +    properties: {
    +      query: { type: "string", maxLength: 500 },
    +      fieldMatch: {
    +        type: "object",
    +        properties: {
    +          field: { type: "string", enum: ["title", "url", "description", "tags"] },
    +          op: { type: "string", enum: ["includes", "startsWith"] },
    +          value: { type: "string", maxLength: 500 },
    +        },
    +        required: ["field", "op", "value"],
    +        additionalProperties: false,
    +      },
    +      includeTags: { type: "array", items: { type: "string", maxLength: 100 }, maxItems: 50 },
    +      excludeTags: { type: "array", items: { type: "string", maxLength: 100 }, maxItems: 50 },
    +      minRating: { type: "integer", minimum: 0, maximum: 5 },
    +      maxRating: { type: "integer", minimum: 0, maximum: 5 },
    +      exactRating: { type: "integer", minimum: 0, maximum: 5 },
    +      brokenOnly: { type: "boolean" },
    +      neverOpened: { type: "boolean" },
    +      sortBy: { type: "string", enum: AGENT_SORT_ENUM },
    +      order: { type: "string", enum: ["asc", "desc"] },
    +      limit: { type: "integer", minimum: 1, maximum: MAX_RESULT_LIMIT },
    +      limitDirection: { type: "string", enum: ["first", "last"] },
    +      merge: { type: "boolean" },

    view_set_agent_filter is not actually equivalent to the collection search filter vocabulary promised for this phase: folder, unfiled, unratedOnly, and untagged are absent here, and buildAgentPlanSteps has no mappings for them. Because the schema rejects unknown properties, callers cannot express these filters through the UI projection even though bookmarks_search supports them, so the two canonical surfaces can produce different results. Add the missing schema fields and corresponding display-plan steps (or explicitly narrow and document the contract).

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 30, 2026 04:45 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Approval is blocked by active critical security findings in denylist enforcement and recursive schema sanitization, along with moderate issues causing tag-matching errors and inconsistent UI filter support.

    <details open>
    <summary><strong>5 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Enforce the denylist for open-ended schema arguments · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Normalize capability names before denylist checks · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Recursively validate values under additionalProperties · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Match tags element-by-element for includes · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Add missing collection filters to the agent filter schema · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    This PR establishes the Phase 1 foundation for unified agent and WebMCP tooling by introducing a canonical tool registry, policy gate, reusable capability descriptors, and a stable AppController facade over application state.

    Changes:

  • Added tool schemas, validation, bounded result envelopes, risk policies, and security denylisting.

  • Added collection-read, UI navigation/filter, and saved-view capability toolsets.

  • Migrated WebMCP registration to the canonical registry and wired it through AppController.

  • Updated architecture documentation and release metadata.
  • | File | Description |
    | ---- | ----------- |
    | src/​webmcp/​webmcpTools.test.js | Removed tests for the superseded standalone WebMCP tool definitions. |
    | src/​webmcp/​webmcpTools.js | Removed the legacy standalone WebMCP tool implementation. |
    | src/​webmcp/​registerWebMcpTools.test.js | Tests canonical registry-based WebMCP registration and policy filtering. |
    | src/​webmcp/​registerWebMcpTools.js | Adapts resolved canonical tools to document.modelContext. |
    | src/​utils/​bookmarkFilters.js | Adds support for folder aliases when sorting bookmarks. |
    | src/​tools/​schema.test.js | Tests bounded results, structured envelopes, and schema validation. |
    | src/​tools/​schema.js | Defines tool contracts, risk tiers, policies, result helpers, and JSON Schema validation. |
    | src/​tools/​registry.test.js | Tests registry registration, policy enforcement, validation, and denylisting. |
    | src/​tools/​registry.js | Implements the canonical tool registry and policy gate. |
    | src/​tools/​capabilities/​viewsManage.test.js | Tests saved-view listing, application, saving, and deletion. |
    | src/​tools/​capabilities/​viewsManage.js | Defines saved-view management tools. |
    | src/​tools/​capabilities/​uiNavigation.test.js | Tests navigation, layout, selection, filtering, and bookmark-opening behavior. |
    | src/​tools/​capabilities/​uiNavigation.js | Defines UI navigation, layout, selection, and bookmark-opening tools. |
    | src/​tools/​capabilities/​uiFilters.js | Defines agent and manual filter capabilities. |
    | src/​tools/​capabilities/​collectionRead.test.js | Tests collection search, details, statistics, folders, tags, and state access. |
    | src/​tools/​capabilities/​collectionRead.js | Defines read-only collection inspection tools. |
    | src/​hooks/​useWebMcpTools.test.jsx | Tests WebMCP opt-in, registration lifecycle, and cleanup behavior. |
    | src/​hooks/​useWebMcpTools.js | Registers policy-filtered canonical tools through a live controller proxy. |
    | src/​hooks/​useUndoHistory.js | Exposes undo-stack state for the controller facade. |
    | src/​hooks/​useSidebarCollapsed.js | Adds explicit sidebar-collapse control for the controller. |
    | src/​hooks/​useBookmarkSelection.js | Adds controller-compatible selection updates. |
    | src/​hooks/​useAppController.test.jsx | Tests stable controller identity and current-state access. |
    | src/​hooks/​useAppController.js | Provides the stable ref-backed application command and read facade. |
    | src/​components/​BookmarkApp.jsx | Constructs the AppController and wires it into WebMCP. |
    | DESIGN.md | Documents the canonical registry, controller boundary, and WebMCP behavior. |
    | .changeset/​tool-registry-foundation.md | Adds release metadata for the tooling foundation. |
    </details>

    <sub>Review effort: Lite</sub>

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/hooks/useAppController.js:1
    @@ -0,0 +1,136 @@
    +// Stable, ref-backed command/read facade over BookmarkApp's hooks & state.
    +// Tools in `src/tools/` interact exclusively with this interface (Dependency
    +// Inversion), never with React setters or store backends directly.
    +
    +import { useMemo, useRef } from "react";
    +import { mergeAgentPlan } from "../utils/bookmarkFilters.js";
    +
    +function computeOpenSurface(s) {
    +  if (s.wizardOpen) return "storageWizard";
    +  if (s.isOptionsOpen) return "options";
    +  if (s.isHelpModalOpen) return "help";
    +  if (s.isImportExportModalOpen) return "importExport";
    +  if (s.isModalOpen) return "bookmarkForm";
    +  if (s.isDeleteConfirmModalOpen) return "deleteConfirm";
    +  if (s.review) return "changeReview";
    +  if (s.duplicateReview) return "duplicateReview";
    +  if (s.digest) return "digest";
    +  if (s.linkHealthOpen) return "linkHealth";
    +  return "list";

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Added isMessageModalOpen ("message"), isAgentBarOpen ("agentBar"), navDrawerOpen ("navDrawer"), and bulkEditorOpen ("bulkEdit") to SURFACE_CHECKS in useAppController.js ahead of workspace views (digest, linkHealth) and wired them from BookmarkApp.jsx, along with same-tick controller state sync and unit tests in useAppController.test.jsx.

    <!-- agent-bot-write: ghw_74e9106ad03cbfa3 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/capabilities/uiFilters.js:1
    @@ -0,0 +1,270 @@
    +// Filter & projection tools (`ui.navigation` toolset).
    +// Keeps agent filter projection (`lastAction`) and manual filters
    +// (`manualFilters`) strictly independent per DESIGN.md.
    +
    +import { UNFILED, normalizeFolderPath } from "../../utils/folderTree.js";
    +import { EMPTY_FILTERS } from "../../utils/manualFilters.js";
    +import {
    +  ERROR_CODES,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  errorResult,
    +  okResult,
    +} from "../schema.js";
    +
    +const UI_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: false,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +const AGENT_SORT_ENUM = [
    +  "title",
    +  "url",
    +  "rating",
    +  "folder",
    +  "folderId",
    +  "createdAt",
    +  "updatedAt",
    +  "lastOpenedAt",
    +];
    +const MANUAL_SORT_ENUM = [
    +  "",
    +  "title",
    +  "url",
    +  "rating",
    +  "folderId",
    +  "createdAt",
    +  "lastOpenedAt",
    +  "updatedAt",
    +];
    +
    +function addRatingStep(steps, args) {
    +  const parameters = {};
    +  if (args.minRating !== undefined) parameters.minRating = args.minRating;
    +  if (args.maxRating !== undefined) parameters.maxRating = args.maxRating;
    +  if (args.exactRating !== undefined) parameters.exact = args.exactRating;
    +  if (Object.keys(parameters).length > 0) {
    +    steps.push({ action: "filterByRating", parameters, priority: 4 });
    +  }
    +}
    +
    +function addSortAndLimitSteps(steps, args) {
    +  if (args.sortBy) {
    +    const sortBy = args.sortBy === "folderId" ? "folder" : args.sortBy;
    +    steps.push({
    +      action: "sortBookmarks",
    +      parameters: { sortBy, order: args.order || "asc" },
    +      priority: 7,
    +    });
    +  }
    +  if (args.limit !== undefined) {
    +    steps.push({
    +      action: "limitResults",
    +      parameters: {
    +        count: args.limit,
    +        direction: args.limitDirection || "first",
    +        scope: "current",
    +      },
    +      priority: 8,
    +    });
    +  }
    +}
    +
    +function buildAgentPlanSteps(args) {
    +  const steps = [];
    +  if (typeof args.query === "string" && args.query.trim()) {
    +    steps.push({
    +      action: "searchBookmarks",
    +      parameters: { searchTerm: args.query.trim() },
    +      priority: 1,
    +    });
    +  }
    +  if (args.fieldMatch) {
    +    const action = args.fieldMatch.op === "startsWith" ? "findStartsWith" : "findIncludes";
    +    steps.push({
    +      action,
    +      parameters: { field: args.fieldMatch.field, value: args.fieldMatch.value },
    +      priority: 2,
    +    });
    +  }
    +  if (Array.isArray(args.includeTags) || Array.isArray(args.excludeTags)) {
    +    steps.push({
    +      action: "findWithTags",
    +      parameters: { includeTags: args.includeTags || [], excludeTags: args.excludeTags || [] },
    +      priority: 3,
    +    });
    +  }
    +  addRatingStep(steps, args);
    +  if (args.brokenOnly === true)
    +    steps.push({ action: "findBrokenLinks", parameters: {}, priority: 5 });
    +  if (args.neverOpened === true)
    +    steps.push({ action: "findNeverOpened", parameters: {}, priority: 6 });
    +  addSortAndLimitSteps(steps, args);
    +  return steps;
    +}
    +
    +export function executeSetAgentFilter(args, controller) {
    +  const steps = buildAgentPlanSteps(args ?? {});
    +  if (steps.length === 0) {
    +    return errorResult(
    +      ERROR_CODES.VALIDATION_ERROR,
    +      "Provide at least one filter, sort, or limit criterion."
    +    );
    +  }
    +  const merge = args?.merge === true;
    +  const plan = controller.setAgentPlan(steps, { merge });
    +  return okResult({
    +    appliedSteps: steps.length,
    +    merge,
    +    activePlanSteps: Array.isArray(plan) ? plan.length : 1,
    +  });
    +}
    +
    +const DIRECT_MANUAL_KEYS = ["text", "brokenOnly", "neverOpened", "untagged", "sortBy", "order"];
    +
    +function patchRatingFields(next, input) {
    +  if (input.unratedOnly === true) {
    +    next.unratedOnly = true;
    +    next.minRating = 0;
    +    return;
    +  }
    +  if (input.minRating !== undefined) {
    +    next.minRating = input.minRating;
    +    if (input.minRating > 0 || input.unratedOnly === false) next.unratedOnly = false;
    +    return;
    +  }
    +  if (input.unratedOnly === false) next.unratedOnly = false;
    +}
    +
    +function patchManualFilterFields(next, input) {
    +  for (const key of DIRECT_MANUAL_KEYS) {
    +    if (input[key] !== undefined) next[key] = input[key];
    +  }
    +  if (input.includeTags !== undefined) next.includeTags = [...input.includeTags];
    +  if (input.excludeTags !== undefined) next.excludeTags = [...input.excludeTags];
    +  if (input.unfiled === true) next.folder = UNFILED;
    +  else if (input.folder !== undefined) next.folder = normalizeFolderPath(input.folder);

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Fixed patchManualFilterFields in src/tools/capabilities/uiFilters.js so unfiled: false clears UNFILED back to "" without clobbering named folders, and updated patchRatingFields so minRating (including 0) clears unratedOnly. Added tests in uiNavigation.test.js.

    <!-- agent-bot-write: ghw_74e9106ad03cbfa3 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/capabilities/collectionRead.js:1
    @@ -0,0 +1,421 @@
    +// Canonical read-only collection inspection tools (`collection.read`).
    +// Pure projections over AppController + utils/* — never mutates state or leaks
    +// internal bookkeeping like `faviconUrl` or credentials.
    +
    +import {
    +  filterByRating,
    +  findIncludes,
    +  findStartsWith,
    +  findWithTags,
    +  searchBookmarks,
    +  sortBookmarks,
    +} from "../../utils/bookmarkFilters.js";
    +import {
    +  UNFILED,
    +  buildFolderTree,
    +  findInFolder,
    +  isWithinFolder,
    +  normalizeFolderPath,
    +} from "../../utils/folderTree.js";
    +import { findBrokenLinks, isBroken } from "../../utils/linkHealth.js";
    +import { deriveTagCounts, isUntagged } from "../../utils/manualFilters.js";
    +import { findNeverOpened, isNeverOpened } from "../../utils/openHistory.js";
    +import { mergeSemanticMatches } from "../../utils/semanticSearch.js";
    +import {
    +  MAX_GET_IDS,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  boundedEnvelope,
    +  clampLimit,
    +  clampOffset,
    +  errorResult,
    +  ERROR_CODES,
    +  okResult,
    +} from "../schema.js";
    +
    +const READ_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: true,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +
    +const toSearchItem = (b) => ({
    +  id: b.id,
    +  title: b.title ?? "",
    +  url: b.url ?? "",
    +  folder: b.folderId ?? "",
    +  tags: Array.isArray(b.tags) ? b.tags : [],
    +  rating: typeof b.rating === "number" ? b.rating : 0,
    +  description: b.description ?? "",
    +  createdAt: b.createdAt ?? null,
    +  updatedAt: b.updatedAt ?? null,
    +});
    +
    +const toDetailItem = (b) => ({
    +  ...toSearchItem(b),
    +  urlStatus: b.urlStatus ?? "idle",
    +  urlStatusReason: b.urlStatusReason ?? null,
    +  lastOpenedAt: b.lastOpenedAt ?? null,
    +});
    +
    +function applyStructuralFilters(input, list) {
    +  let results = list;
    +  const fm = input.fieldMatch;
    +  if (fm && typeof fm === "object" && typeof fm.value === "string") {
    +    results =
    +      fm.op === "startsWith"
    +        ? findStartsWith(fm.field || "title", fm.value, results)
    +        : findIncludes(fm.field || "title", fm.value, results);

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Updated findIncludes in src/utils/bookmarkFilters.js to match each element of b.tags individually (matching findStartsWith), preventing comma-joined cross-tag matches in both bookmarks_search and applyAgentPlan. Added regression tests in bookmarkFilters.test.js and collectionRead.test.js.

    <!-- agent-bot-write: ghw_74e9106ad03cbfa3 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/registry.js:1
    @@ -0,0 +1,240 @@
    +// Canonical Tool Registry & Policy Gate.
    +// Single source of truth consumed by both the WebMCP adapter and the built-in
    +// agent runner. Enforces surface visibility, write policies, schema validation,
    +// and hard security denylists against secret/permission capabilities.
    +
    +import { COLLECTION_READ_TOOLS } from "./capabilities/collectionRead.js";
    +import { UI_NAVIGATION_TOOLS } from "./capabilities/uiNavigation.js";
    +import { VIEWS_MANAGE_TOOLS } from "./capabilities/viewsManage.js";
    +import {
    +  ERROR_CODES,
    +  RISK_TIERS,
    +  SURFACES,
    +  WRITE_POLICIES,
    +  errorResult,
    +  validateAgainstSchema,
    +} from "./schema.js";
    +
    +export const TOOLSET_METADATA = Object.freeze([
    +  {
    +    id: "collection.read",
    +    label: "Collection Read",
    +    description: "Search bookmarks, inspect details/stats, list folders and tags, read UI state.",
    +    defaultEnabled: { builtin: true, webmcp: true },
    +  },
    +  {
    +    id: "ui.navigation",
    +    label: "UI & Navigation",
    +    description:
    +      "Adjust filters, navigate views/dialogs, change layout, manage selection, open bookmarks.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +  {
    +    id: "views.manage",
    +    label: "Saved Views",
    +    description: "List, apply, save, and delete named views.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +]);
    +
    +const VALID_RISK_TIERS = new Set(Object.values(RISK_TIERS));
    +const VALID_SURFACES = new Set(Object.values(SURFACES));
    +const PROPOSE_ALLOWED_RISKS = new Set([
    +  RISK_TIERS.READ,
    +  RISK_TIERS.UI,
    +  RISK_TIERS.PROPOSE,
    +  RISK_TIERS.NETWORK,
    +]);
    +
    +const normalizeKey = (value) =>
    +  String(value ?? "")
    +    .toLowerCase()
    +    .replace(/[_-]/gu, "");
    +
    +export const HARD_DENIED_CAPABILITIES = new Set([
    +  "secrets.read",
    +  "secrets.write",
    +  "llm.apikey",
    +  "llm.baseurl",
    +  "encryption.manage",
    +  "firebase.config",
    +  "permissions.manage",
    +  "webmcp.toggle",
    +  "agent.policy",
    +]);
    +
    +export const HARD_DENIED_PARAM_KEYS = new Set([
    +  "apikey",
    +  "baseurl",
    +  "passphrase",
    +  "encryptedblob",
    +  "firebaseconfig",
    +  "authtoken",
    +  "webmcpenabled",
    +  "agentpolicy",
    +  "writepolicy",
    +]);
    +
    +function checkSchemaKeys(schema, toolName, path) {
    +  if (!schema || typeof schema !== "object") return;
    +  for (const [key, propSchema] of Object.entries(schema.properties ?? {})) {
    +    const fullPath = `${path}.${key}`;
    +    if (HARD_DENIED_PARAM_KEYS.has(normalizeKey(key))) {
    +      throw new Error(
    +        `Tool "${toolName}" parameter "${fullPath}" is blocked by the security denylist.`
    +      );
    +    }
    +    checkSchemaKeys(propSchema, toolName, fullPath);
    +  }
    +  if (schema.items) checkSchemaKeys(schema.items, toolName, `${path}[]`);
    +}

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Added recursive runtime argument key scanning (findDeniedArgKey, failing closed past max nesting depth) in executeTool and extended checkSchemaKeys to inspect object-valued additionalProperties schemas in src/tools/registry.js. Added regression tests in registry.test.js.

    <!-- agent-bot-write: ghw_74e9106ad03cbfa3 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/registry.js:1
    @@ -0,0 +1,240 @@
    +// Canonical Tool Registry & Policy Gate.
    +// Single source of truth consumed by both the WebMCP adapter and the built-in
    +// agent runner. Enforces surface visibility, write policies, schema validation,
    +// and hard security denylists against secret/permission capabilities.
    +
    +import { COLLECTION_READ_TOOLS } from "./capabilities/collectionRead.js";
    +import { UI_NAVIGATION_TOOLS } from "./capabilities/uiNavigation.js";
    +import { VIEWS_MANAGE_TOOLS } from "./capabilities/viewsManage.js";
    +import {
    +  ERROR_CODES,
    +  RISK_TIERS,
    +  SURFACES,
    +  WRITE_POLICIES,
    +  errorResult,
    +  validateAgainstSchema,
    +} from "./schema.js";
    +
    +export const TOOLSET_METADATA = Object.freeze([
    +  {
    +    id: "collection.read",
    +    label: "Collection Read",
    +    description: "Search bookmarks, inspect details/stats, list folders and tags, read UI state.",
    +    defaultEnabled: { builtin: true, webmcp: true },
    +  },
    +  {
    +    id: "ui.navigation",
    +    label: "UI & Navigation",
    +    description:
    +      "Adjust filters, navigate views/dialogs, change layout, manage selection, open bookmarks.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +  {
    +    id: "views.manage",
    +    label: "Saved Views",
    +    description: "List, apply, save, and delete named views.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +]);
    +
    +const VALID_RISK_TIERS = new Set(Object.values(RISK_TIERS));
    +const VALID_SURFACES = new Set(Object.values(SURFACES));
    +const PROPOSE_ALLOWED_RISKS = new Set([
    +  RISK_TIERS.READ,
    +  RISK_TIERS.UI,
    +  RISK_TIERS.PROPOSE,
    +  RISK_TIERS.NETWORK,
    +]);
    +
    +const normalizeKey = (value) =>
    +  String(value ?? "")
    +    .toLowerCase()
    +    .replace(/[_-]/gu, "");
    +
    +export const HARD_DENIED_CAPABILITIES = new Set([
    +  "secrets.read",
    +  "secrets.write",
    +  "llm.apikey",
    +  "llm.baseurl",
    +  "encryption.manage",
    +  "firebase.config",
    +  "permissions.manage",
    +  "webmcp.toggle",
    +  "agent.policy",
    +]);
    +
    +export const HARD_DENIED_PARAM_KEYS = new Set([
    +  "apikey",
    +  "baseurl",
    +  "passphrase",
    +  "encryptedblob",
    +  "firebaseconfig",
    +  "authtoken",
    +  "webmcpenabled",
    +  "agentpolicy",
    +  "writepolicy",
    +]);
    +
    +function checkSchemaKeys(schema, toolName, path) {
    +  if (!schema || typeof schema !== "object") return;
    +  for (const [key, propSchema] of Object.entries(schema.properties ?? {})) {
    +    const fullPath = `${path}.${key}`;
    +    if (HARD_DENIED_PARAM_KEYS.has(normalizeKey(key))) {
    +      throw new Error(
    +        `Tool "${toolName}" parameter "${fullPath}" is blocked by the security denylist.`
    +      );
    +    }
    +    checkSchemaKeys(propSchema, toolName, fullPath);
    +  }
    +  if (schema.items) checkSchemaKeys(schema.items, toolName, `${path}[]`);
    +}
    +
    +function assertSafeDefinition(def) {
    +  if (!def || typeof def.name !== "string" || !def.name) {
    +    throw new Error("Tool definition must have a non-empty string name.");
    +  }
    +  if (!VALID_RISK_TIERS.has(def.risk)) {
    +    throw new Error(`Tool "${def.name}" has invalid risk tier "${def.risk}".`);
    +  }
    +  if (
    +    !Array.isArray(def.surfaces) ||
    +    def.surfaces.length === 0 ||
    +    def.surfaces.some((s) => !VALID_SURFACES.has(s))
    +  ) {
    +    throw new Error(`Tool "${def.name}" must specify valid surfaces.`);
    +  }
    +  const normalizedCap = String(def.capability ?? "").toLowerCase();
    +  const normalizedToolset = String(def.toolset ?? "").toLowerCase();
    +  if (
    +    HARD_DENIED_CAPABILITIES.has(normalizedCap) ||
    +    HARD_DENIED_CAPABILITIES.has(normalizedToolset)

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Updated normalizeKey (/[^a-z0-9]/gu) and assertSafeDefinition in src/tools/registry.js to normalize capability, toolset, and name separator-insensitively against NORMALIZED_DENIED_CAPABILITIES. Added regression tests in registry.test.js.

    <!-- agent-bot-write: ghw_74e9106ad03cbfa3 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/registry.js:1
    @@ -0,0 +1,240 @@
    +// Canonical Tool Registry & Policy Gate.
    +// Single source of truth consumed by both the WebMCP adapter and the built-in
    +// agent runner. Enforces surface visibility, write policies, schema validation,
    +// and hard security denylists against secret/permission capabilities.
    +
    +import { COLLECTION_READ_TOOLS } from "./capabilities/collectionRead.js";
    +import { UI_NAVIGATION_TOOLS } from "./capabilities/uiNavigation.js";
    +import { VIEWS_MANAGE_TOOLS } from "./capabilities/viewsManage.js";
    +import {
    +  ERROR_CODES,
    +  RISK_TIERS,
    +  SURFACES,
    +  WRITE_POLICIES,
    +  errorResult,
    +  validateAgainstSchema,
    +} from "./schema.js";
    +
    +export const TOOLSET_METADATA = Object.freeze([
    +  {
    +    id: "collection.read",
    +    label: "Collection Read",
    +    description: "Search bookmarks, inspect details/stats, list folders and tags, read UI state.",
    +    defaultEnabled: { builtin: true, webmcp: true },
    +  },
    +  {
    +    id: "ui.navigation",
    +    label: "UI & Navigation",
    +    description:
    +      "Adjust filters, navigate views/dialogs, change layout, manage selection, open bookmarks.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +  {
    +    id: "views.manage",
    +    label: "Saved Views",
    +    description: "List, apply, save, and delete named views.",
    +    defaultEnabled: { builtin: true, webmcp: false },
    +  },
    +]);
    +
    +const VALID_RISK_TIERS = new Set(Object.values(RISK_TIERS));
    +const VALID_SURFACES = new Set(Object.values(SURFACES));
    +const PROPOSE_ALLOWED_RISKS = new Set([
    +  RISK_TIERS.READ,
    +  RISK_TIERS.UI,
    +  RISK_TIERS.PROPOSE,
    +  RISK_TIERS.NETWORK,
    +]);
    +
    +const normalizeKey = (value) =>
    +  String(value ?? "")
    +    .toLowerCase()
    +    .replace(/[_-]/gu, "");
    +
    +export const HARD_DENIED_CAPABILITIES = new Set([
    +  "secrets.read",
    +  "secrets.write",
    +  "llm.apikey",
    +  "llm.baseurl",
    +  "encryption.manage",
    +  "firebase.config",
    +  "permissions.manage",
    +  "webmcp.toggle",
    +  "agent.policy",
    +]);
    +
    +export const HARD_DENIED_PARAM_KEYS = new Set([
    +  "apikey",
    +  "baseurl",
    +  "passphrase",
    +  "encryptedblob",
    +  "firebaseconfig",
    +  "authtoken",
    +  "webmcpenabled",
    +  "agentpolicy",
    +  "writepolicy",
    +]);
    +
    +function checkSchemaKeys(schema, toolName, path) {
    +  if (!schema || typeof schema !== "object") return;
    +  for (const [key, propSchema] of Object.entries(schema.properties ?? {})) {
    +    const fullPath = `${path}.${key}`;
    +    if (HARD_DENIED_PARAM_KEYS.has(normalizeKey(key))) {
    +      throw new Error(
    +        `Tool "${toolName}" parameter "${fullPath}" is blocked by the security denylist.`
    +      );
    +    }
    +    checkSchemaKeys(propSchema, toolName, fullPath);
    +  }
    +  if (schema.items) checkSchemaKeys(schema.items, toolName, `${path}[]`);
    +}
    +
    +function assertSafeDefinition(def) {
    +  if (!def || typeof def.name !== "string" || !def.name) {
    +    throw new Error("Tool definition must have a non-empty string name.");
    +  }
    +  if (!VALID_RISK_TIERS.has(def.risk)) {
    +    throw new Error(`Tool "${def.name}" has invalid risk tier "${def.risk}".`);
    +  }
    +  if (
    +    !Array.isArray(def.surfaces) ||
    +    def.surfaces.length === 0 ||
    +    def.surfaces.some((s) => !VALID_SURFACES.has(s))
    +  ) {
    +    throw new Error(`Tool "${def.name}" must specify valid surfaces.`);
    +  }
    +  const normalizedCap = String(def.capability ?? "").toLowerCase();
    +  const normalizedToolset = String(def.toolset ?? "").toLowerCase();
    +  if (
    +    HARD_DENIED_CAPABILITIES.has(normalizedCap) ||
    +    HARD_DENIED_CAPABILITIES.has(normalizedToolset)

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Updated normalizeKey (/[^a-z0-9]/gu) and assertSafeDefinition in src/tools/registry.js to normalize capability, toolset, and name separator-insensitively against NORMALIZED_DENIED_CAPABILITIES. Added regression tests in registry.test.js.

    <!-- agent-bot-write: ghw_ef3fe77c10254388 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/schema.js:1
    @@ -0,0 +1,204 @@
    +// Canonical tool contract primitives: risk tiers, policies, bounded envelopes,
    +// structured results, and lightweight zero-dependency JSON Schema validation.
    +//
    +// Pure JS only — never import `ai`, `zod`, React, `chrome.*`, or `firebase/*`
    +// here so bundle chunk laziness (#362) and WebMCP sharing hold by construction.
    +
    +export const RISK_TIERS = Object.freeze({
    +  READ: "read",
    +  UI: "ui",
    +  PROPOSE: "propose",
    +  WRITE: "write",
    +  DESTRUCTIVE: "destructive",
    +  NETWORK: "network",
    +});
    +
    +export const WRITE_POLICIES = Object.freeze({
    +  READ_ONLY: "read_only",
    +  PROPOSE_ONLY: "propose_only",
    +  DIRECT_WITH_UNDO: "direct_with_undo",
    +});
    +
    +export const SURFACES = Object.freeze({
    +  BUILTIN: "builtin",
    +  WEBMCP: "webmcp",
    +});
    +
    +export const ERROR_CODES = Object.freeze({
    +  POLICY_DENIED: "POLICY_DENIED",
    +  VALIDATION_ERROR: "VALIDATION_ERROR",
    +  NOT_FOUND: "NOT_FOUND",
    +  INVALID_URL: "INVALID_URL",
    +  KEY_LOCKED: "KEY_LOCKED",
    +  PROVIDER_NOT_READY: "PROVIDER_NOT_READY",
    +  UNSAFE_HOST: "UNSAFE_HOST",
    +  CONFLICT: "CONFLICT",
    +  EXECUTION_ERROR: "EXECUTION_ERROR",
    +});
    +
    +export const DEFAULT_RESULT_LIMIT = 20;
    +export const MAX_RESULT_LIMIT = 100;
    +export const MAX_GET_IDS = 25;
    +
    +const UNSAFE_OBJECT_KEYS = new Set(["__proto__", "constructor", "prototype"]);
    +
    +export function clampLimit(value, fallback = DEFAULT_RESULT_LIMIT, max = MAX_RESULT_LIMIT) {
    +  const n = Number(value);
    +  if (!Number.isFinite(n) || n < 1) return fallback;
    +  return Math.min(Math.floor(n), max);
    +}
    +
    +export function clampOffset(value) {
    +  const n = Number(value);
    +  if (!Number.isFinite(n) || n < 0) return 0;
    +  return Math.floor(n);
    +}
    +
    +export function boundedEnvelope(items, total, offset, limit) {
    +  return {
    +    items,
    +    total,
    +    offset,
    +    limit,
    +    truncated: offset + items.length < total,
    +  };
    +}
    +
    +export function okResult(data, meta) {
    +  return meta ? { ok: true, data, meta } : { ok: true, data };
    +}
    +
    +export function errorResult(code, message, retryable = false) {
    +  return {
    +    ok: false,
    +    error: { code, message, retryable },
    +  };
    +}
    +
    +function validateString(schema, value, path, errors) {
    +  if (typeof value !== "string") {
    +    errors.push(`${path} must be a string`);
    +    return undefined;
    +  }
    +  if (schema.minLength !== undefined && value.length < schema.minLength) {
    +    errors.push(`${path} must be at least ${schema.minLength} characters`);
    +  }
    +  if (schema.maxLength !== undefined && value.length > schema.maxLength) {
    +    errors.push(`${path} must be at most ${schema.maxLength} characters`);
    +  }
    +  if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
    +    errors.push(`${path} must be one of: ${schema.enum.join(", ")}`);
    +  }
    +  return value;
    +}
    +
    +function validateNumber(schema, value, path, errors) {
    +  if (typeof value !== "number" || !Number.isFinite(value)) {
    +    errors.push(`${path} must be a finite number`);
    +    return undefined;
    +  }
    +  if (schema.type === "integer" && !Number.isInteger(value)) {
    +    errors.push(`${path} must be an integer`);
    +    return undefined;
    +  }
    +  if (schema.minimum !== undefined && value < schema.minimum) {
    +    errors.push(`${path} must be >= ${schema.minimum}`);
    +  }
    +  if (schema.maximum !== undefined && value > schema.maximum) {
    +    errors.push(`${path} must be <= ${schema.maximum}`);
    +  }
    +  if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
    +    errors.push(`${path} must be one of: ${schema.enum.join(", ")}`);
    +  }
    +  return value;
    +}
    +
    +function validateArray(schema, value, path, errors) {
    +  if (!Array.isArray(value)) {
    +    errors.push(`${path} must be an array`);
    +    return undefined;
    +  }
    +  if (schema.minItems !== undefined && value.length < schema.minItems) {
    +    errors.push(`${path} must contain at least ${schema.minItems} item(s)`);
    +  }
    +  if (schema.maxItems !== undefined && value.length > schema.maxItems) {
    +    errors.push(`${path} must contain at most ${schema.maxItems} item(s)`);
    +  }
    +  if (!schema.items) return [...value];
    +  return value.map((item, idx) => validateValue(schema.items, item, `${path}[${idx}]`, errors));
    +}
    +
    +function validateObject(schema, value, path, errors) {
    +  if (!value || typeof value !== "object" || Array.isArray(value)) {
    +    errors.push(`${path} must be an object`);
    +    return undefined;
    +  }
    +  const props = schema.properties || {};
    +  const required = Array.isArray(schema.required) ? schema.required : [];
    +  for (const key of required) {
    +    if (value[key] === undefined || value[key] === null) {
    +      errors.push(`${path}.${key} is required`);
    +    }
    +  }
    +  const sanitized = {};
    +  for (const [key, entry] of Object.entries(value)) {
    +    if (UNSAFE_OBJECT_KEYS.has(key)) {
    +      errors.push(`Forbidden property "${path}.${key}"`);
    +      continue;
    +    }
    +    if (entry === undefined) continue;
    +    if (!Object.prototype.hasOwnProperty.call(props, key)) {
    +      if (schema.additionalProperties === false) {
    +        errors.push(`Unknown property "${path}.${key}"`);
    +      } else {
    +        sanitized[key] = entry;
    +      }

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Added recursive sanitizeArbitraryValue and validateUnknownProperty in src/tools/schema.js to reject __proto__, constructor, and prototype keys, non-JSON/non-finite primitives, and excessive nesting depth inside arbitrary and open additionalProperties values. Added tests in schema.test.js.

    <!-- agent-bot-write: ghw_ef3fe77c10254388 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/capabilities/collectionRead.js:1
    @@ -0,0 +1,421 @@
    +// Canonical read-only collection inspection tools (`collection.read`).
    +// Pure projections over AppController + utils/* — never mutates state or leaks
    +// internal bookkeeping like `faviconUrl` or credentials.
    +
    +import {
    +  filterByRating,
    +  findIncludes,
    +  findStartsWith,
    +  findWithTags,
    +  searchBookmarks,
    +  sortBookmarks,
    +} from "../../utils/bookmarkFilters.js";
    +import {
    +  UNFILED,
    +  buildFolderTree,
    +  findInFolder,
    +  isWithinFolder,
    +  normalizeFolderPath,
    +} from "../../utils/folderTree.js";
    +import { findBrokenLinks, isBroken } from "../../utils/linkHealth.js";
    +import { deriveTagCounts, isUntagged } from "../../utils/manualFilters.js";
    +import { findNeverOpened, isNeverOpened } from "../../utils/openHistory.js";
    +import { mergeSemanticMatches } from "../../utils/semanticSearch.js";
    +import {
    +  MAX_GET_IDS,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  boundedEnvelope,
    +  clampLimit,
    +  clampOffset,
    +  errorResult,
    +  ERROR_CODES,
    +  okResult,
    +} from "../schema.js";
    +
    +const READ_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: true,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +
    +const toSearchItem = (b) => ({
    +  id: b.id,
    +  title: b.title ?? "",
    +  url: b.url ?? "",
    +  folder: b.folderId ?? "",
    +  tags: Array.isArray(b.tags) ? b.tags : [],
    +  rating: typeof b.rating === "number" ? b.rating : 0,
    +  description: b.description ?? "",
    +  createdAt: b.createdAt ?? null,
    +  updatedAt: b.updatedAt ?? null,
    +});
    +
    +const toDetailItem = (b) => ({
    +  ...toSearchItem(b),
    +  urlStatus: b.urlStatus ?? "idle",
    +  urlStatusReason: b.urlStatusReason ?? null,
    +  lastOpenedAt: b.lastOpenedAt ?? null,
    +});
    +
    +function applyStructuralFilters(input, list) {
    +  let results = list;
    +  const fm = input.fieldMatch;
    +  if (fm && typeof fm === "object" && typeof fm.value === "string") {
    +    results =
    +      fm.op === "startsWith"
    +        ? findStartsWith(fm.field || "title", fm.value, results)
    +        : findIncludes(fm.field || "title", fm.value, results);

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Updated findIncludes in src/utils/bookmarkFilters.js to match b.tags per element rather than coercing the array to a comma-joined string. Added regression tests in bookmarkFilters.test.js and collectionRead.test.js.

    <!-- agent-bot-write: ghw_ef3fe77c10254388 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot] commented on code on Nov 30, 2026 05:21 UTC
    Code Review
    src/tools/capabilities/uiFilters.js:1
    @@ -0,0 +1,270 @@
    +// Filter & projection tools (`ui.navigation` toolset).
    +// Keeps agent filter projection (`lastAction`) and manual filters
    +// (`manualFilters`) strictly independent per DESIGN.md.
    +
    +import { UNFILED, normalizeFolderPath } from "../../utils/folderTree.js";
    +import { EMPTY_FILTERS } from "../../utils/manualFilters.js";
    +import {
    +  ERROR_CODES,
    +  MAX_RESULT_LIMIT,
    +  RISK_TIERS,
    +  SURFACES,
    +  errorResult,
    +  okResult,
    +} from "../schema.js";
    +
    +const UI_ANNOTATIONS = Object.freeze({
    +  readOnlyHint: false,
    +  destructiveHint: false,
    +  idempotentHint: true,
    +  openWorldHint: false,
    +});
    +
    +const SURFACES_ALL = Object.freeze([SURFACES.BUILTIN, SURFACES.WEBMCP]);
    +const AGENT_SORT_ENUM = [
    +  "title",
    +  "url",
    +  "rating",
    +  "folder",
    +  "folderId",
    +  "createdAt",
    +  "updatedAt",
    +  "lastOpenedAt",
    +];
    +const MANUAL_SORT_ENUM = [
    +  "",
    +  "title",
    +  "url",
    +  "rating",
    +  "folderId",
    +  "createdAt",
    +  "lastOpenedAt",
    +  "updatedAt",
    +];
    +
    +function addRatingStep(steps, args) {
    +  const parameters = {};
    +  if (args.minRating !== undefined) parameters.minRating = args.minRating;
    +  if (args.maxRating !== undefined) parameters.maxRating = args.maxRating;
    +  if (args.exactRating !== undefined) parameters.exact = args.exactRating;
    +  if (Object.keys(parameters).length > 0) {
    +    steps.push({ action: "filterByRating", parameters, priority: 4 });
    +  }
    +}
    +
    +function addSortAndLimitSteps(steps, args) {
    +  if (args.sortBy) {
    +    const sortBy = args.sortBy === "folderId" ? "folder" : args.sortBy;
    +    steps.push({
    +      action: "sortBookmarks",
    +      parameters: { sortBy, order: args.order || "asc" },
    +      priority: 7,
    +    });
    +  }
    +  if (args.limit !== undefined) {
    +    steps.push({
    +      action: "limitResults",
    +      parameters: {
    +        count: args.limit,
    +        direction: args.limitDirection || "first",
    +        scope: "current",
    +      },
    +      priority: 8,
    +    });
    +  }
    +}
    +
    +function buildAgentPlanSteps(args) {
    +  const steps = [];
    +  if (typeof args.query === "string" && args.query.trim()) {
    +    steps.push({
    +      action: "searchBookmarks",
    +      parameters: { searchTerm: args.query.trim() },
    +      priority: 1,
    +    });
    +  }
    +  if (args.fieldMatch) {
    +    const action = args.fieldMatch.op === "startsWith" ? "findStartsWith" : "findIncludes";
    +    steps.push({
    +      action,
    +      parameters: { field: args.fieldMatch.field, value: args.fieldMatch.value },
    +      priority: 2,
    +    });
    +  }
    +  if (Array.isArray(args.includeTags) || Array.isArray(args.excludeTags)) {
    +    steps.push({
    +      action: "findWithTags",
    +      parameters: { includeTags: args.includeTags || [], excludeTags: args.excludeTags || [] },
    +      priority: 3,
    +    });
    +  }
    +  addRatingStep(steps, args);
    +  if (args.brokenOnly === true)
    +    steps.push({ action: "findBrokenLinks", parameters: {}, priority: 5 });
    +  if (args.neverOpened === true)
    +    steps.push({ action: "findNeverOpened", parameters: {}, priority: 6 });
    +  addSortAndLimitSteps(steps, args);
    +  return steps;
    +}
    +
    +export function executeSetAgentFilter(args, controller) {
    +  const steps = buildAgentPlanSteps(args ?? {});
    +  if (steps.length === 0) {
    +    return errorResult(
    +      ERROR_CODES.VALIDATION_ERROR,
    +      "Provide at least one filter, sort, or limit criterion."
    +    );
    +  }
    +  const merge = args?.merge === true;
    +  const plan = controller.setAgentPlan(steps, { merge });
    +  return okResult({
    +    appliedSteps: steps.length,
    +    merge,
    +    activePlanSteps: Array.isArray(plan) ? plan.length : 1,
    +  });
    +}
    +
    +const DIRECT_MANUAL_KEYS = ["text", "brokenOnly", "neverOpened", "untagged", "sortBy", "order"];
    +
    +function patchRatingFields(next, input) {
    +  if (input.unratedOnly === true) {
    +    next.unratedOnly = true;
    +    next.minRating = 0;
    +    return;
    +  }
    +  if (input.minRating !== undefined) {
    +    next.minRating = input.minRating;
    +    if (input.minRating > 0 || input.unratedOnly === false) next.unratedOnly = false;
    +    return;
    +  }
    +  if (input.unratedOnly === false) next.unratedOnly = false;
    +}
    +
    +function patchManualFilterFields(next, input) {
    +  for (const key of DIRECT_MANUAL_KEYS) {
    +    if (input[key] !== undefined) next[key] = input[key];
    +  }
    +  if (input.includeTags !== undefined) next.includeTags = [...input.includeTags];
    +  if (input.excludeTags !== undefined) next.excludeTags = [...input.excludeTags];
    +  if (input.unfiled === true) next.folder = UNFILED;
    +  else if (input.folder !== undefined) next.folder = normalizeFolderPath(input.folder);
    +  patchRatingFields(next, input);
    +  return next;
    +}
    +
    +export function executeSetManualFilters(args, controller) {
    +  const input = args ?? {};
    +  const mode = input.mode === "replace" ? "replace" : "merge";
    +  const base =
    +    mode === "replace"
    +      ? { ...EMPTY_FILTERS }
    +      : { ...(controller.getUiState()?.manualFilters ?? EMPTY_FILTERS) };
    +  const next = patchManualFilterFields(base, input);
    +  controller.setManualFilters(next);
    +  return okResult({ mode, filters: next });
    +}
    +
    +export function executeClearFilters(args, controller) {
    +  const target = args?.target;
    +  controller.clearFilters(target);
    +  return okResult({ cleared: target });
    +}
    +
    +export const viewSetAgentFilterTool = {
    +  name: "view_set_agent_filter",
    +  toolset: "ui.navigation",
    +  capability: "view.setAgentFilter",
    +  risk: RISK_TIERS.UI,
    +  surfaces: SURFACES_ALL,
    +  annotations: UI_ANNOTATIONS,
    +  description:
    +    "Update the visible shelf via the agent filter projection (`lastAction`) without changing manual filters. " +
    +    "Set merge: true to refine the current agent filter, or false (default) to replace it.",
    +  inputSchema: {
    +    type: "object",
    +    properties: {
    +      query: { type: "string", maxLength: 500 },
    +      fieldMatch: {
    +        type: "object",
    +        properties: {
    +          field: { type: "string", enum: ["title", "url", "description", "tags"] },
    +          op: { type: "string", enum: ["includes", "startsWith"] },
    +          value: { type: "string", maxLength: 500 },
    +        },
    +        required: ["field", "op", "value"],
    +        additionalProperties: false,
    +      },
    +      includeTags: { type: "array", items: { type: "string", maxLength: 100 }, maxItems: 50 },
    +      excludeTags: { type: "array", items: { type: "string", maxLength: 100 }, maxItems: 50 },
    +      minRating: { type: "integer", minimum: 0, maximum: 5 },
    +      maxRating: { type: "integer", minimum: 0, maximum: 5 },
    +      exactRating: { type: "integer", minimum: 0, maximum: 5 },
    +      brokenOnly: { type: "boolean" },
    +      neverOpened: { type: "boolean" },
    +      sortBy: { type: "string", enum: AGENT_SORT_ENUM },
    +      order: { type: "string", enum: ["asc", "desc"] },
    +      limit: { type: "integer", minimum: 1, maximum: MAX_RESULT_LIMIT },
    +      limitDirection: { type: "string", enum: ["first", "last"] },
    +      merge: { type: "boolean" },

    Fixed in d2f8f2b32ac6c5938a78d5cd4651f5c5761d3e8e.

    Added folder, unfiled, unratedOnly, and untagged parameters to view_set_agent_filter in src/tools/capabilities/uiFilters.js backed by canonical findInFolder and findUntagged display actions in bookmarkFilters.js and normalize.js. Added tests across uiNavigation.test.js, bookmarkFilters.test.js, and normalize.test.js.

    <!-- agent-bot-write: ghw_ef3fe77c10254388 session=210bdd5e08f0 bot=trueline-antigravity-agent[bot] conversation_id=e99b26b3-53f9-4d7f-8337-fb33257bb240 conversation_id_source=self-reported -->

    qwts qwts approved these changes on Nov 30, 2026 05:43 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    trueline-antigravity-agent[bot] trueline-antigravity-agent[bot]
    Labels
    risk: low confidence: 76.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 76.8% · Lower = rushed or shallow review
    76.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 16.6% · Safe to merge
    16.6%