Skip to content

fix(knowledge): exclude image-alt links from navigation - #195027

Merged
roboclaw-bot merged 2 commits into
openclaw:mainfrom
saariuslystoned:codex/knowledge-image-alt-195013
Nov 10, 2026
Merged

roboclaw-bot merged 2 commits into
openclaw:mainfrom
saariuslystoned:codex/knowledge-image-alt-195013

Conversation

@saariuslystoned

@saariuslystoned saariuslystoned commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #195013.

What Problem This Solves

A wikilink or Markdown link nested in image alt text appears in Knowledge navigation and backlinks even though the shared renderer displays inert text and the editable-link scanner excludes it.

User Impact

Image captions no longer create phantom navigation edges. Ordinary visible links, including those inside quotes, lists and tables, still appear. Stored Markdown and typed relationships are unchanged.

Why This Change Was Made

The extractor already lexes a fresh token tree. Clearing image children in its existing traversal aligns extraction with the shared renderer and editable-link owner without introducing another parser or changing caches. One regression covers hidden wiki/Markdown links and visible container controls; its measured20-line growth has a matching allocation.

Evidence

Exact introduced base: dd1bf005936dc143b2edaf793b7bc5fef3e3e838. Candidate: 2f3f470f17424a40e86f8beaafd06b422dec8d2c. The three remote file hashes match the frozen sole-author payload.

  • The unchanged registered-tool/native-store fixture in [Bug]: Knowledge counts inert image-alt wikilinks as navigation edges #195013 independently fails on the exact base: six intended assertions across image→visible→image, with all stages and opposite controls completed. Outgoing links incorrectly remain1→1→1 and backlinks2→2→2 while rendered anchors/editable links are0→1→0.
  • The new owning regression independently fails against the base parser for three leaked image-alt hrefs. With the candidate, the original fixture plus markdown-links.test.ts and page-budget-writes.test.ts pass17 tests in three files, exit0; wrapper67.406s. The parser suite also covers caches, generated backlinks and navigation resolution.
  • Targeted repository-runner oxfmt/type-aware oxlint pass with no warnings/errors; complete extension test types, staged test-line ratchet and diff whitespace checks pass. The isolated runtime could not stage pinned Bun for CI formatter/linter parity; these explicit supported checks are separate. Package-only types encountered an unchanged CSS ambient-declaration import; the complete extension test type lane includes those declarations and passed.

Those earlier fixtures exercise registered tools/native storage and the shared renderer. The actual shipped-Gateway observations below are separate.

Shipped Gateway behavior evidence — exact head

Immutable13-file proof, complete fixture, source bindings and terminal observations · source-bound shutdown acceptance mapping · evidence comment.

The normal exact-head runtime build passed133.135s. The complete frozen fixture then ran once under Node26.13.0/native SQLite3.54.0 through the normal repository-owned runner, with a verified loader-free owner generation in a cleared-environment/network-unshared disposable namespace.

The real built Gateway became ready, and authenticated built-CLI Knowledge operator calls performed FOUR fictional page creates and TWO edits. All54 built-CLI calls plus the empty-store fixture child returned0. Six published receipts reported local Git commits;14 complete record/raw-byte/hash/revision observations and12 exact complete connection queries held:

Diagram stage Outgoing links Target backlinks
Image caption containing wikilink 0 1
Visible wikilink 1 2
Image caption again 0 1

The visible-link control remained linked to the target and the unrelated control remained absent. Original bodies/IDs and control hashes stayed correct; the diagram advanced revisions1→2→3, and final status reported four valid records.

Precondition: a real RegistryClient owner provisioned ONLY an EMPTY physical private store, then exited before Gateway startup. All content creates/edits/reads/connections crossed the authenticated running Gateway. This does not claim first-use operator provisioning, fabricated host authority/audience/grants, model comprehension, UI/browser proof, real memories or production behavior. No raw CLI/Gateway/auth logs, auth stores or actual configuration are published.

The actual129.547s test exited1 and remains failed. All feature assertions completed, but its strict numeric-zero shutdown assertion failed on code:null/signal:SIGTERM. Source permits successful settled POSIX self-SIGTERM; canonical completion/extinction/output/listener/claim/runner-generation closure was verified. This run's actual settled-self-signal branch, absence of escalation and application-level graceful drain remain unproven. The proof accepts only the bounded feature and canonical managed-custody observations; it does not rewrite the run as whole-test green. No oracle-only journey replay was performed.

Current review and CI gates

Published native review at this exact head found no actionable code defects and requested the actual Gateway/UI navigation transition. The new evidence supplies that Gateway transition and its visible/unrelated controls. The original native hold remains authoritative until the current evidence is adjudicated; updating this body uses the target's supported native dispatch route. No native clearance or merge readiness is claimed in advance.

Historical comprehensive code review of dd1bf00→2f3f470f17424a40e86f8beaafd06b422dec8d2c, P0–P3, found no actionable findings in the supplied diff. Repository/dependency context was unavailable to that reviewer and it executed no tests. Main has advanced; this proof does not renew comprehensive coverage for the live base or borrow a broader clean verdict.

CI still has two GitHub installation API-rate-limit failures: critical shard selection and SARIF upload. The source scan preceding SARIF upload succeeded. A single same-head failed-job retry was refused with “Must have admin rights to Repository”; an upstream administrator must rerun those jobs. The successful separate security/umbrella statuses do not clear these failures. No CI/admin retry, workflow/auth change, source change, new PR or merge accompanies this evidence.

@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Exclude links inside image alt text from Knowledge navigation and backlinks.

Example: A diagram note contains Caption [[Jade Lantern]], alongside a separate visible-link control.

  • Before: The diagram incorrectly links to Jade Lantern, which has two backlinks.
  • After: The diagram has no outgoing link, and Jade Lantern retains only the visible control's backlink.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A small, complete owner-level fix with an independent regression and controlled shipped-Gateway evidence; required CI clearance remains separate.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The exact-head isolated Gateway observations exercise Knowledge saves, edits, record reads, and connections through shipped RPC surfaces on macOS arm64; image→visible→image produces outgoing 0→1→0 and backlinks 1→2→1 with opposite controls intact. The complete new comment resolves the previous shipped-entry-point request; the older run's shutdown failure remains accurately disclosed and does not negate its completed feature observations.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Image captions create phantom Knowledge navigation links and backlinks despite rendering as inert text.
Reason: The patch restores the established image contract at the existing shared owner with no new user-facing option or policy.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a current Knowledge navigation bug with a focused patch and sufficient Gateway evidence; no actionable code defects remain.

Priority: P2
Reviewed head: 2f3f470f17424a40e86f8beaafd06b422dec8d2c

Before merge

None.

Findings

None.

Agent review details

How this fits together

Knowledge parses saved Markdown through its shared link owner, resolves record targets, and derives record links, navigation connections, backlinks, and diagnostics.

flowchart LR
  A[Saved Markdown] --> B[Fresh Marked tokens]
  B --> C[Skip image children]
  C --> D[Resolve record links]
  D --> E[Navigation and backlinks]
  A --> F[Inert image renderer]
Loading

Technical review

Best possible solution:

Land the existing extractor repair once the remaining required checks clear.

Do we have a high-confidence way to reproduce the issue?

Current-main source and the pinned Marked traversal establish the failure; the contributor additionally supplies controlled Gateway observations with the base parser restored, while this read-only review executed no target code.

Is this the best way to solve the issue?

Pruning image children in the existing fresh extraction tree repairs the shared producer without another parser, cache, API, or persisted-state change.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 71bf0fcf30f9.

Provenance checked

  • Image-alt navigation extraction keeps the original intent (65ad180: Knowledge bundling retained a shared Markdown parser whose documented contract excludes images from navigation and whose image renderer emits escaped text.)
  • Private parser helpers and editable-link parity keeps the original intent (6ac4db1: The cleanup made same-module helpers private while retaining assertions through resolveLinks; this PR preserves that boundary and uses the already-public linkSpans.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Focused introduced patch: The pinned introduced diff only prunes image children in the existing extractor, adds one regression with visible container controls, and allocates its test growth. (extensions/knowledge/src/markdown-links.ts:96, 2f3f470f1742)
  • Current main still needs the repair: Current main walks nested image tokens without pruning them, while its renderer emits inert image text and linkSpans excludes image children. (extensions/knowledge/src/markdown-links.ts:95, 71bf0fcf30f9)
  • Pinned dependency confirms pruning semantics: Knowledge imports and pins marked 18.1.2; that version calls the walkTokens callback before descending into token.tokens, so clearing fresh image children prevents their extraction. (src/Instance.ts:65, 5beecae42b0b)
  • Shared consumer boundary: Both navigation directions derive their rows from resolveLinks; typed relationships are handled separately and remain unchanged. (extensions/knowledge/src/connections.ts:98, 2f3f470f1742)
  • New shipped Gateway proof resolves the prior request: The contributor's complete comment supplies the driver and live results from an isolated macOS Gateway at the exact head: outgoing links change 0→1→0 and backlinks 1→2→1, with stable visible and unrelated controls; restoring the base parser yields the incorrect 1→1→1 and 2→2→2. A local model stub provisions the store through a real agent turn; subsequent observations cross plugins.sessionAction. fix(knowledge): exclude image-alt links from navigation #195027 (comment). (2f3f470f1742)
  • Original product contract and feature history: The bundling commit already documents images as non-links and renders their text inert; subsequent history covers parse lifetime, private helper cleanup, editable spans, and encoded filenames. Local follow-history encountered an unavailable promisor object; inspected creation blobs, scoped history, blame, and GitHub PR records establish the relevant ownership without asserting earlier standalone provenance. (extensions/knowledge/src/markdown-links.ts:16, 65ad18005286)

Likely related people:

  • Josh Lehman: Raw commit 65ad180 adds extensions/knowledge/src/markdown-links.ts:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 65ad18005286; files: extensions/knowledge/src/markdown-links.ts)
  • Peter Steinberger: Raw commit 6338c20 adds extensions/knowledge/src/markdown-links.ts:42 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6338c2008e77; files: extensions/knowledge/src/markdown-links.ts)

PR surface

Source +5, Tests +20, Other +2. Total +27 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 5 0 +5
Tests 1 21 1 +20
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 3 28 1 +27

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: same_root_cause
Canonical: #195013
Summary: This PR repairs the image-alt extraction defect tracked by the open linked issue; canonical search found no separate replacement.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Incorrect derived navigation has a bounded demonstrated impact without observed data loss, authorization failure, or availability loss.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-08T05:12:45.702Z sha 2f3f470 :: needs real behavior proof before merge. :: none

Reviewed November 8, 2026, 12:45 PM ET / 17:45 UTC (Revision 2).

@saariuslystoned

Copy link
Copy Markdown
Contributor Author

Actual shipped-Gateway evidence for reviewed head 2f3f470f17424a40e86f8beaafd06b422dec8d2c is now available: immutable complete proof, fixture, source bindings and terminal observations.

The exact-head built Gateway became ready, and authenticated built-CLI Knowledge operator calls performed four fictional page creates and two edits. All54 built-CLI calls and the separate empty-store fixture child returned0. Six published receipts reported local Git commits;14 full record/raw-byte/hash/revision observations and12 complete connection queries held.

Diagram stage Outgoing links Target backlinks
Image caption containing wikilink 0 1
Visible wikilink 1 2
Image caption again 0 1

The separate visible-link control stayed linked to the target; the unrelated control stayed absent. Exact IDs, original bodies, control hashes and diagram revisions1→2→3 were checked through the running Gateway.

Boundary: a real RegistryClient owner prepared only the empty physical store, then exited before Gateway startup. All content writes/reads used the authenticated Gateway. This does not claim first-use operator provisioning, UI/model proof or fabricated host audience/grants.

Original run:129.547s, exit1; the failed verdict is preserved. All feature assertions completed. The strict numeric-zero shutdown assertion failed on code:null, signal:SIGTERM. Exact source permits successful settled POSIX self-SIGTERM; canonical completion/extinction, output, listener/claim and runner-generation closure were verified. This run's actual settled-self-signal path, absence of escalation and application-level graceful drain remain unproven. Source-bound acceptance mapping separates those claims; this is not a whole-test-green declaration.

The 13-file artifact was read back byte-for-byte; manifest SHA256 1248b4d5e047a30239d427c3ca97aea6dcad4d90596ee32649c9c7243a627d06. CI quota failures and native review remain separate. No source change, merge or oracle-only journey rerun accompanies this evidence.

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Nov 8, 2026
@saariuslystoned

Copy link
Copy Markdown
Contributor Author

Shipped-Gateway proof for 2f3f470f1742: image-caption links no longer create Knowledge navigation, base vs head

This supplies the transition the review asked for, through a running Gateway: image caption → visible link → image caption, with the visible-link control. It runs on base and head with the same driver. It also removes the earlier run's caveats: the store is created by the agent's own first use rather than prepared outside the Gateway, and the driver exits 0.

Setup. macOS arm64, Node 24.22.1, pnpm 12.15.0.

  • Builds: each checkout is prepared with node scripts/worktree-setup.mjs gateway.
    • Head: exact 2f3f470f17424a40e86f8beaafd06b422dec8d2c.
    • Base: the same checkout with only extensions/knowledge/src/markdown-links.ts restored from the PR's parent dd1bf005936dc143b2edaf793b7bc5fef3e3e838.
  • Gateway: node scripts/run-node.mjs gateway run --port <ephemeral> --bind loopback --auth none --tailscale off --allow-unconfigured. It runs with a throwaway HOME, state, config, TMPDIR and XDG tree, an allowlisted environment, plugins.slots.memory: "knowledge" and Knowledge maintenance off.
  • Model: a loopback OpenAI-compatible stub. No real model or credential is used.
  • Store creation through the Gateway: operator calls cannot create the store ("This store is created on first authorized use"). So one real agent turn (chat.send) has the stub call dispatch_action → knowledge_save_page for the target page "Jade Lantern". That turn creates the agent's store. Status before the turn is unprovisioned; after it, ready with 1 record.
  • Everything else goes through plugins.sessionAction (pluginId: "knowledge"):
    • agent_action save_page creates three more fictional pages and makes two edits to the diagram page.
    • agent_query mutation settles each receipt.
    • agent_query record reads the diagram body back.
    • agent_query connections (limit 100) checks links and backlinks.
  • Pages:
    • target "Jade Lantern"
    • unrelated "Copper Kite"
    • visible control, body [[Jade Lantern]]
    • diagram, body Fictional diagram: ![Caption [[Jade Lantern]]](diagram.png), then edited to Fictional navigation: [[Jade Lantern]], then back to the caption.

Result (IDs shown by page name)

Diagram stage (revision) base dd1bf005: diagram → / target ← head 2f3f470f: diagram → / target ←
1. image caption with wikilink 1 (target) / 2 (visible, diagram) 0 (none) / 1 (visible)
2. visible wikilink 1 (target) / 2 (visible, diagram) 1 (target) / 2 (diagram, visible)
3. image caption again 1 (target) / 2 (visible, diagram) 0 (none) / 1 (visible)

On both builds, at every stage, the visible-link control links to the target and the unrelated page has no backlinks. Final status on both is ready with 4 valid records.

Per-stage connections (summary.json stages)
# base-dd1bf005
{"stage":0,"diagramBody":"Fictional diagram: ![Caption [[Jade Lantern]]](diagram.png)","diagramRevision":1,"diagramOutgoing":["target"],"targetBacklinks":["visible","diagram"],"visibleControlOutgoing":["target"],"unrelatedBacklinks":[]}
{"stage":1,"diagramBody":"Fictional navigation: [[Jade Lantern]]","diagramRevision":2,"diagramOutgoing":["target"],"targetBacklinks":["visible","diagram"],"visibleControlOutgoing":["target"],"unrelatedBacklinks":[]}
{"stage":2,"diagramBody":"Fictional diagram: ![Caption [[Jade Lantern]]](diagram.png)","diagramRevision":3,"diagramOutgoing":["target"],"targetBacklinks":["visible","diagram"],"visibleControlOutgoing":["target"],"unrelatedBacklinks":[]}
# head-2f3f470f
{"stage":0,"diagramBody":"Fictional diagram: ![Caption [[Jade Lantern]]](diagram.png)","diagramRevision":1,"diagramOutgoing":[],"targetBacklinks":["visible"],"visibleControlOutgoing":["target"],"unrelatedBacklinks":[]}
{"stage":1,"diagramBody":"Fictional navigation: [[Jade Lantern]]","diagramRevision":2,"diagramOutgoing":["target"],"targetBacklinks":["diagram","visible"],"visibleControlOutgoing":["target"],"unrelatedBacklinks":[]}
{"stage":2,"diagramBody":"Fictional diagram: ![Caption [[Jade Lantern]]](diagram.png)","diagramRevision":3,"diagramOutgoing":[],"targetBacklinks":["visible"],"visibleControlOutgoing":["target"],"unrelatedBacklinks":[]}

SHA-256 of the redacted summaries and RPC transcripts. The state root is shown as <root>; no host paths appear.

bce534be173aa8936f7494d93b64dbe648c8404c78e5bb60c708037a46dd54e8  base-dd1bf005/summary.json
fa50be904a29fed414cc347fb9d0cc86e7c0f463c7039fc8f1376a95c005ee7e  head-2f3f470f/summary.json
1e96cd15106d3a7ceec07f437ed18ec4d9fe4738d8a0e919a04bcfdef951b8da  base-dd1bf005/rpc-transcript.jsonl
14a010307cc9f69c475937447eb0e83aaf737c39cd842de863c156be8ef1565f  head-2f3f470f/rpc-transcript.jsonl

PR context, in template terms, for the triage: needs-pr-context label:

  • What Problem This Solves: a wikilink or Markdown link inside image alt text shows up in Knowledge links and backlinks, although the note renders it as plain text.
  • User Impact: image captions no longer create phantom navigation edges. Visible links, including those in quotes, lists and tables, are unchanged, and stored Markdown is untouched.
  • Why This Change Was Made: link extraction now skips image children in its own fresh token tree, matching the renderer and the editable-link scanner.
  • Evidence: this comment, plus the red/green unit regression in the body.

The context check reads only the PR body and looks for headings named "What Problem This Solves" and "Evidence". This body has the first but titles its evidence sections "Regression and static evidence" and "Shipped Gateway behavior evidence". So the label clears only when one of those headings is renamed to ## Evidence.

Reproduce with the two files below: node --import <checkout>/scripts/tsx.mjs scenario-195027.mts <checkout> <outDir> <label>.

gw-lib.mts (isolated Gateway harness)
// Shared isolated-Gateway harness for PR proof runs.
// Starts `node scripts/run-node.mjs gateway run` from a checkout with a throwaway
// HOME/state/config/TMPDIR/XDG tree, an ephemeral loopback port, auth none, and an
// allowlisted environment (no inherited OPENCLAW_* or provider keys).
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { connect, createServer } from "node:net";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

export type GatewayHandle = {
  root: string;
  port: number;
  call: (method: string, params: unknown, timeoutMs?: number) => Promise<any>;
  stop: () => Promise<{ code: number | null; signal: string | null }>;
};

// run-node keeps the checkout's dist lock for the Gateway's lifetime and leaves it on SIGTERM.
// Remove it only when its recorded owner process is gone (scratch checkout only).
export function clearDeadDistLock(checkout: string) {
  const dir = path.join(checkout, ".artifacts", "dist-artifacts.lock");
  const owner = path.join(dir, "owner.json");
  if (!existsSync(owner)) return;
  const pid = Number(JSON.parse(readFileSync(owner, "utf8")).pid);
  try {
    process.kill(pid, 0);
    return; // still alive
  } catch {}
  rmSync(dir, { recursive: true, force: true });
}

export async function freePort(): Promise<number> {
  return await new Promise((resolve) => {
    const s = createServer();
    s.listen(0, "127.0.0.1", () => {
      const p = (s.address() as { port: number }).port;
      s.close(() => resolve(p));
    });
  });
}

export function makeRoot(outDir: string) {
  const root = path.join(outDir, "root");
  for (const d of ["home", "state", "workspace", "tmp", "logs", "xdg-config", "xdg-data", "xdg-cache", "xdg-state"]) {
    mkdirSync(path.join(root, d), { recursive: true });
  }
  return root;
}

export function isolatedEnv(root: string, configPath: string, extra: Record<string, string | undefined> = {}) {
  const env: NodeJS.ProcessEnv = {
    PATH: process.env.PATH,
    LANG: "en_US.UTF-8",
    HOME: path.join(root, "home"),
    OPENCLAW_HOME: path.join(root, "home"),
    OPENCLAW_STATE_DIR: path.join(root, "state"),
    OPENCLAW_CONFIG_PATH: configPath,
    TMPDIR: path.join(root, "tmp"),
    XDG_CONFIG_HOME: path.join(root, "xdg-config"),
    XDG_DATA_HOME: path.join(root, "xdg-data"),
    XDG_CACHE_HOME: path.join(root, "xdg-cache"),
    XDG_STATE_HOME: path.join(root, "xdg-state"),
    OPENCLAW_SKIP_CHANNELS: "1",
    OPENCLAW_SKIP_CRON: "1",
    OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
    OPENCLAW_SKIP_CANVAS_HOST: "1",
    OPENCLAW_SKIP_GMAIL_WATCHER: "1",
    // Own service-coordination key: the default label is shared by every checkout on this Mac.
    OPENCLAW_LAUNCHD_LABEL: "ai.openclaw.proofcloser",
  };
  for (const [k, v] of Object.entries(extra)) {
    if (v === undefined) delete env[k];
    else env[k] = v;
  }
  return env;
}

const portOpen = (port: number) =>
  new Promise<boolean>((resolve) => {
    const sock = connect(port, "127.0.0.1");
    sock.once("connect", () => {
      sock.destroy();
      resolve(true);
    });
    sock.once("error", () => resolve(false));
  });

export async function startGateway(params: {
  checkout: string;
  outDir: string;
  root: string;
  port: number;
  config: Record<string, unknown>;
  env?: Record<string, string | undefined>;
}): Promise<GatewayHandle> {
  const { checkout, outDir, root, port } = params;
  const configPath = path.join(root, "openclaw.json");
  writeFileSync(configPath, `${JSON.stringify(params.config, null, 2)}\n`);
  const env = isolatedEnv(root, configPath, params.env);
  const args = ["scripts/run-node.mjs", "gateway", "run", "--port", String(port), "--bind", "loopback", "--auth", "none", "--tailscale", "off", "--allow-unconfigured"];
  writeFileSync(
    path.join(outDir, "gateway-command.txt"),
    `cwd=<checkout>\nnode ${args.join(" ")}\nenv keys: ${Object.keys(env).toSorted().join(",")}\n`,
  );
  const gw: ChildProcess = spawn(process.execPath, args, {
    cwd: checkout,
    env,
    detached: true,
    stdio: ["ignore", openSync(path.join(outDir, "gateway.stdout.log"), "w"), openSync(path.join(outDir, "gateway.stderr.log"), "w")],
  });
  const exited = new Promise<{ code: number | null; signal: string | null }>((resolve) =>
    gw.once("exit", (code, signal) => resolve({ code, signal })),
  );
  const deadline = Date.now() + 1_800_000;
  while (!(await portOpen(port))) {
    if (gw.exitCode !== null) throw new Error(`gateway exited early (${gw.exitCode}); see gateway.stderr.log`);
    if (Date.now() > deadline) throw new Error("gateway not listening within 1800s");
    await sleep(500);
  }
  const { GatewayClient, startGatewayClientWhenEventLoopReady } = await import(
    path.join(checkout, "src/plugin-sdk/gateway-runtime.ts")
  );
  let helloResolve!: () => void;
  const hello = new Promise<void>((r) => (helloResolve = r));
  const client = new GatewayClient({
    url: `ws://127.0.0.1:${port}`,
    requestTimeoutMs: 180_000,
    clientName: "gateway-client",
    deviceIdentity: null,
    mode: "backend",
    scopes: ["operator.admin"],
    onHelloOk: () => helloResolve(),
  });
  const readiness = await startGatewayClientWhenEventLoopReady(client, { timeoutMs: 180_000 });
  if (!readiness.ready) throw new Error("gateway client readiness timeout");
  await Promise.race([hello, sleep(180_000).then(() => { throw new Error("hello timeout"); })]);
  return {
    root,
    port,
    call: (method, p, timeoutMs = 180_000) => client.request(method, p, { timeoutMs }),
    stop: async () => {
      await client.stopAndWait?.().catch?.(() => {});
      // Signal the run-node wrapper only: it forwards to the Gateway and releases its dist lock.
      if (gw.exitCode === null && gw.pid) {
        try { process.kill(gw.pid, "SIGTERM"); } catch {}
      }
      const timer = setTimeout(() => { try { if (gw.pid) process.kill(-gw.pid, "SIGKILL"); } catch {} }, 60_000);
      const result = await exited;
      clearTimeout(timer);
      clearDeadDistLock(checkout);
      return result;
    },
  };
}
scenario-195027.mts
// PR 195027: Knowledge navigation for a wikilink inside image alt text, through a running Gateway.
// Stages: diagram body = image caption with [[Jade Lantern]] -> visible [[Jade Lantern]] -> caption again.
// Controls: a separate page with a visible [[Jade Lantern]] link; an unrelated page with no backlinks.
// Usage: node --import <checkout>/scripts/tsx.mjs scenario-195027.mts <checkout> <outDir> <label>
import { randomUUID } from "node:crypto";
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
import { createServer } from "node:http";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { freePort, makeRoot, startGateway } from "./gw-lib.mts";

const [checkout, outDir, label] = process.argv.slice(2);
if (!checkout || !outDir || !label) throw new Error("usage: scenario-195027.mts <checkout> <outDir> <label>");
mkdirSync(outDir, { recursive: true });
const root = makeRoot(outDir);
// Loopback model stub: the first turn saves the target page with knowledge_save_page through
// dispatch_action, so the agent's own first authorized use creates its store (operator calls
// cannot); then it answers text.
const firstRequestId = randomUUID();
const modelLog = path.join(outDir, "model-requests.jsonl");
writeFileSync(modelLog, "");
const model = createServer((req, res) => {
  let raw = "";
  req.setEncoding("utf8");
  req.on("data", (c) => (raw += c));
  req.on("end", () => {
    let body: any = {};
    try { body = JSON.parse(raw); } catch {}
    const messages: any[] = Array.isArray(body.messages) ? body.messages : [];
    const callTool = messages.at(-1)?.role !== "tool";
    const tools = (body.tools ?? []).map((t: any) => t.function?.name).filter(Boolean);
    appendFileSync(modelLog, `${JSON.stringify({ lastRole: messages.at(-1)?.role, offeredTools: tools, reply: callTool ? "dispatch_action knowledge_save_page" : "text" })}\n`);
    const delta = callTool
      ? { role: "assistant", content: null, tool_calls: [{ index: 0, id: "call_status", type: "function", function: { name: "dispatch_action", arguments: JSON.stringify({ id: "knowledge_save_page", args: { requestId: firstRequestId, title: "Jade Lantern", body: "A wholly fictional target page.", type: "note" } }) } }] }
      : { role: "assistant", content: "Saved." };
    res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
    const chunk = (o: unknown) => res.write(`data: ${JSON.stringify(o)}\n\n`);
    chunk({ id: "c", object: "chat.completion.chunk", choices: [{ index: 0, delta }] });
    chunk({ id: "c", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: callTool ? "tool_calls" : "stop" }] });
    chunk({ id: "c", object: "chat.completion.chunk", choices: [], usage: { prompt_tokens: 100, completion_tokens: 10, total_tokens: 110 } });
    res.write("data: [DONE]\n\n");
    res.end();
  });
});
const modelPort = await new Promise<number>((resolve) => model.listen(0, "127.0.0.1", () => resolve((model.address() as { port: number }).port)));
const zeroCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
const port = await freePort();
const config = {
  meta: { migrations: { skillWorkshopPlugin: true } },
  models: {
    mode: "replace",
    providers: {
      stub: {
        baseUrl: `http://127.0.0.1:${modelPort}/v1`, apiKey: "test", api: "openai-completions", request: { allowPrivateNetwork: true },
        models: [{ id: "m", name: "m", api: "openai-completions", reasoning: false, input: ["text"], cost: zeroCost, contextWindow: 64000, maxTokens: 1024 }],
      },
    },
  },
  tools: { profile: "full" },
  logging: { file: path.join(root, "logs", "openclaw-YYYY-MM-DD.log") },
  cron: { enabled: false },
  hooks: { enabled: false },
  gateway: { mode: "local", bind: "loopback", port, auth: { mode: "none" }, controlUi: { enabled: false } },
  agents: { defaults: { workspace: path.join(root, "workspace"), model: { primary: "stub/m" }, models: { "stub/m": {} } } },
  plugins: {
    slots: { memory: "knowledge" },
    entries: { knowledge: { enabled: true, config: { maintenance: { enabled: false } } } },
  },
};
const gw = await startGateway({ checkout, outDir, root, port, config });
const transcript = path.join(outDir, "rpc-transcript.jsonl");
writeFileSync(transcript, "");
const redact = (v: unknown) => JSON.parse(JSON.stringify(v ?? null).split(root).join("<root>"));
const AGENT = "main";
async function knowledge(actionId: "agent_action" | "agent_query", operation: string, input: unknown) {
  const params = { pluginId: "knowledge", actionId, payload: { agent: AGENT, operation, input } };
  const answer = await gw.call("plugins.sessionAction", params, 60_000);
  appendFileSync(transcript, `${JSON.stringify(redact({ method: "plugins.sessionAction", params, answer }))}\n`);
  if (!answer || answer.ok !== true) throw new Error(`${operation} refused: ${JSON.stringify(redact(answer))}`);
  return answer.result;
}
async function save(input: Record<string, unknown>) {
  const requestId = randomUUID();
  let receipt = await knowledge("agent_action", "save_page", { requestId, type: "note", ...input });
  const until = Date.now() + 60_000;
  while (receipt?.state === "accepted" && Date.now() < until) {
    await sleep(250);
    receipt = (await knowledge("agent_query", "mutation", { requestId, includeFiles: false })).receipt;
  }
  if (receipt?.state !== "published") throw new Error(`save not published: ${JSON.stringify(redact(receipt))}`);
  return receipt as { id: string; revision: number; hash: string };
}
async function connected(id: string, direction: "links" | "backlinks") {
  const out = await knowledge("agent_query", "connections", { id, direction, limit: 100 });
  return { ids: (out.connections ?? []).map((c: any) => c.record.id).toSorted(), total: out.total, nextOffset: out.nextOffset };
}

const stages: unknown[] = [];
const result: Record<string, unknown> = { label, port };
try {
  result.statusBefore = redact(await knowledge("agent_query", "status", {}));
  // The agent's own first use: one chat turn whose only tool call is knowledge_status.
  const turn = await gw.call("chat.send", { sessionKey: "agent:main:main", message: "Save a note titled Jade Lantern.", deliver: false, idempotencyKey: randomUUID() });
  result.firstUseTurn = redact(await gw.call("agent.wait", { runId: turn?.runId, timeoutMs: 120_000 }, 130_000));
  const history = await gw.call("chat.history", { sessionKey: "agent:main:main", limit: 20 }).catch((e: unknown) => ({ error: String(e) }));
  writeFileSync(path.join(outDir, "first-use-history.json"), `${JSON.stringify(redact(history), null, 2)}\n`);
  result.statusAfterFirstUse = redact(await knowledge("agent_query", "status", {}));
  const pages = {
    target: { title: "Jade Lantern", body: "A wholly fictional target page." },
    unrelated: { title: "Copper Kite", body: "A wholly fictional unrelated page." },
    visible: { title: "Visible navigation control", body: "[[Jade Lantern]]" },
    diagram: { title: "Diagram note", body: "Fictional diagram: ![Caption [[Jade Lantern]]](diagram.png)" },
  };
  const saved: Record<string, { id: string; revision: number; hash: string }> = {};
  // Target page: saved by the agent's own turn above; read its receipt by request ID.
  let first = (await knowledge("agent_query", "mutation", { requestId: firstRequestId, includeFiles: false })).receipt;
  const firstUntil = Date.now() + 60_000;
  while (first?.state === "accepted" && Date.now() < firstUntil) {
    await sleep(250);
    first = (await knowledge("agent_query", "mutation", { requestId: firstRequestId, includeFiles: false })).receipt;
  }
  if (first?.state !== "published") throw new Error(`agent save not published: ${JSON.stringify(redact(first))}`);
  saved.target = first;
  for (const [name, page] of Object.entries(pages)) if (name !== "target") saved[name] = await save(page);
  const names = Object.fromEntries(Object.entries(saved).map(([n, r]) => [r.id, n]));
  const named = (c: { ids: string[] }) => c.ids.map((id) => names[id] ?? id);
  const bodies = [pages.diagram.body, "Fictional navigation: [[Jade Lantern]]", pages.diagram.body];
  for (let i = 0; i < bodies.length; i += 1) {
    if (i > 0) {
      const before = saved.diagram;
      saved.diagram = await save({ id: before.id, expectedRevision: before.revision, expectedHash: before.hash, title: pages.diagram.title, body: bodies[i] });
    }
    const record = await knowledge("agent_query", "record", { id: saved.diagram.id, metadataView: "none" });
    const diagramLinks = await connected(saved.diagram.id, "links");
    const targetBacklinks = await connected(saved.target.id, "backlinks");
    const visibleLinks = await connected(saved.visible.id, "links");
    const unrelatedBacklinks = await connected(saved.unrelated.id, "backlinks");
    stages.push({
      stage: i,
      diagramBody: record?.record?.body,
      diagramRevision: saved.diagram.revision,
      diagramOutgoing: named(diagramLinks),
      targetBacklinks: named(targetBacklinks),
      visibleControlOutgoing: named(visibleLinks),
      unrelatedBacklinks: named(unrelatedBacklinks),
    });
  }
  result.stages = stages;
  result.statusAfter = redact(await knowledge("agent_query", "status", {}));
} catch (error) {
  result.error = String(error);
  result.stages = stages;
} finally {
  result.gatewayExit = await gw.stop();
  model.close();
}
writeFileSync(path.join(outDir, "summary.json"), `${JSON.stringify(result, null, 2)}\n`);
console.log(JSON.stringify(result, null, 2));

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Nov 8, 2026

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 2f3f470f17, applied on current main (54b059c478f, clean).

The fix claims that extraction now agrees with the other two link consumers (the inert renderer and linkSpans), so I ran the same bodies through resolveLinks, linkSpans and markdown.parse, on base and on this PR:

Body base resolveLinks PR resolveLinks linkSpans (both) rendered anchor (both)
[![badge](b.png)](target.md) target.md target.md target.md target.md
[![a [x](hidden.md)](b.png)](target.md) target.md, hidden.md target.md target.md target.md
[![a [[Hidden]]](b.png)](target.md) #wiki=Hidden none none none
![a [[Ref]]][img] with [img]: i.png #wiki=Ref none none none
![alt [[One]]](x.png)![alt2 [[Two]]](y.png) [[Visible]] One, Two, Visible Visible Visible Visible

So the outer link of a linked image badge survives the pruning (its link token is visited before the image child is cleared), reference-style images are covered too, and in every row the PR's extraction matches both linkSpans and the rendered HTML. On base the new test fails (13/14 in the file); with the PR, 14/14.

Side note, not something this PR changes: in the third row the outer [...](target.md) renders as literal text on both base and PR, and all three consumers agree on that, so there is no new inconsistency.

No changes requested from me.

@roboclaw-bot
roboclaw-bot merged commit 75059aa into openclaw:main Nov 10, 2026
98 checks passed
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
maplel pushed a commit to maplel/openclaw that referenced this pull request Nov 24, 2026
Release adaptation: extract only fragment-before-decode repair and focused scan/backlink regression from openclaw#191791; retain baseline parser and unrelated test cleanup. Later openclaw#195027, openclaw#196767 and openclaw#198441 changes are unrelated and already represented by baseline parser structure; no later PR-number follow-up.

(cherry picked from commit 2563438)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 7fdc9ad3b334ac08cb9a76604cfbb78ec56ef479)
(cherry picked from commit af609748bca14f61086ecfa82a961787701bdfcd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor P2 Normal backlog priority with limited blast radius. plugin: knowledge proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Knowledge counts inert image-alt wikilinks as navigation edges

3 participants