Plugin API: compaction/reset hooks, bootstrap file globs, memory plugin status (#13287)

* feat: add before_compaction and before_reset plugin hooks with session context

- Pass session messages to before_compaction hook
- Add before_reset plugin hook for /new and /reset commands
- Add sessionId to plugin hook agent context

* feat: extraBootstrapFiles config with glob pattern support

Add extraBootstrapFiles to agent defaults config, allowing glob patterns
(e.g. "projects/*/TOOLS.md") to auto-load project-level bootstrap files
into agent context every turn. Missing files silently skipped.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(status): show custom memory plugins as enabled, not unavailable

The status command probes memory availability using the built-in
memory-core manager. Custom memory plugins (e.g. via plugin slot)
can't be probed this way, so they incorrectly showed "unavailable".
Now they show "enabled (plugin X)" without the misleading label.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use async fs.glob and capture pre-compaction messages

- Replace globSync (node:fs) with fs.glob (node:fs/promises) to match
  codebase conventions for async file operations
- Capture session.messages BEFORE replaceMessages(limited) so
  before_compaction hook receives the full conversation history,
  not the already-truncated list

* fix: resolve lint errors from CI (oxlint strict mode)

- Add void to fire-and-forget IIFE (no-floating-promises)
- Use String() for unknown catch params in template literals
- Add curly braces to single-statement if (curly rule)

* fix: resolve remaining CI lint errors in workspace.ts

- Remove `| string` from WorkspaceBootstrapFileName union (made all
  typeof members redundant per no-redundant-type-constituents)
- Use type assertion for extra bootstrap file names
- Drop redundant await on fs.glob() AsyncIterable (await-thenable)

* fix: address Greptile review — path traversal guard + fs/promises import

- workspace.ts: use path.resolve() + traversal check in loadExtraBootstrapFiles()
- commands-core.ts: import fs from node:fs/promises, drop fs.promises prefix

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve symlinks before workspace boundary check

Greptile correctly identified that symlinks inside the workspace could
point to files outside it, bypassing the path prefix check. Now uses
fs.realpath() to resolve symlinks before verifying the real path stays
within the workspace boundary.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address Greptile review — hook reliability and type safety

1. before_compaction: add compactingCount field so plugins know both
   the full pre-compaction message count and the truncated count being
   fed to the compaction LLM. Clarify semantics in comment.

2. loadExtraBootstrapFiles: use path.basename() for the name field
   so "projects/quaid/TOOLS.md" maps to the known "TOOLS.md" type
   instead of an invalid WorkspaceBootstrapFileName cast.

3. before_reset: fire the hook even when no session file exists.
   Previously, short sessions without a persisted file would silently
   skip the hook. Now fires with empty messages array so plugins
   always know a reset occurred.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: validate bootstrap filenames and add compaction hook timeout

- Only load extra bootstrap files whose basename matches a recognized
  workspace filename (AGENTS.md, TOOLS.md, etc.), preventing arbitrary
  files from being injected into agent context.
- Wrap before_compaction hook in a 30-second Promise.race timeout so
  misbehaving plugins cannot stall the compaction pipeline.
- Clarify hook comments: before_compaction is intentionally awaited
  (plugins need messages before they're discarded) but bounded.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: make before_compaction non-blocking, add sessionFile to after_compaction

- before_compaction is now true fire-and-forget — no await, no timeout.
  Plugins that need full conversation data should persist it themselves
  and return quickly, or use after_compaction for async processing.
- after_compaction now includes sessionFile path so plugins can read
  the full JSONL transcript asynchronously. All pre-compaction messages
  are preserved on disk, eliminating the need to block compaction.
- Removes Promise.race timeout pattern that didn't actually cancel
  slow hooks (just raced past them while they continued running).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add sessionFile to before_compaction for parallel processing

The session JSONL already has all messages on disk before compaction
starts. By providing sessionFile in before_compaction, plugins can
read and extract data in parallel with the compaction LLM call rather
than waiting for after_compaction. This is the optimal path for memory
plugins that need the full conversation history.

sessionFile is also kept on after_compaction for plugins that only
need to act after compaction completes (analytics, cleanup, etc.).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: move bootstrap extras into bundled hook

---------

Co-authored-by: Solomon Steadman <solstead@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Clawdbot <clawdbot@alfie.local>
Co-authored-by: Peter Steinberger <steipete@gmail.com>
This commit is contained in:
solstead
2026-02-14 06:45:45 +07:00
committed by GitHub
parent 3bda3df729
commit ab71fdf821
15 changed files with 565 additions and 2 deletions

View File

@@ -18,6 +18,20 @@ Automatically saves session context to memory when you issue `/new`.
openclaw hooks enable session-memory
```
### 📎 bootstrap-extra-files
Injects extra bootstrap files (for example monorepo `AGENTS.md`/`TOOLS.md`) during prompt assembly.
**Events**: `agent:bootstrap`
**What it does**: Expands configured workspace glob/path patterns and appends matching bootstrap files to injected context.
**Output**: No files written; context is modified in-memory only.
**Enable**:
```bash
openclaw hooks enable bootstrap-extra-files
```
### 📝 command-logger
Logs all command events to a centralized audit file.

View File

@@ -0,0 +1,53 @@
---
name: bootstrap-extra-files
description: "Inject additional workspace bootstrap files via glob/path patterns"
homepage: https://docs.openclaw.ai/automation/hooks#bootstrap-extra-files
metadata:
{
"openclaw":
{
"emoji": "📎",
"events": ["agent:bootstrap"],
"requires": { "config": ["workspace.dir"] },
"install": [{ "id": "bundled", "kind": "bundled", "label": "Bundled with OpenClaw" }],
},
}
---
# Bootstrap Extra Files Hook
Loads additional bootstrap files into `Project Context` during `agent:bootstrap`.
## Why
Use this when your workspace has multiple context roots (for example monorepos) and
you want to include extra `AGENTS.md`/`TOOLS.md`-class files without changing the
workspace root.
## Configuration
```json
{
"hooks": {
"internal": {
"enabled": true,
"entries": {
"bootstrap-extra-files": {
"enabled": true,
"paths": ["packages/*/AGENTS.md", "packages/*/TOOLS.md"]
}
}
}
}
}
```
## Options
- `paths` (string[]): preferred list of glob/path patterns.
- `patterns` (string[]): alias of `paths`.
- `files` (string[]): alias of `paths`.
All paths are resolved from the workspace and must stay inside it (including realpath checks).
Only recognized bootstrap basenames are loaded (`AGENTS.md`, `SOUL.md`, `TOOLS.md`,
`IDENTITY.md`, `USER.md`, `HEARTBEAT.md`, `BOOTSTRAP.md`, `MEMORY.md`, `memory.md`).

View File

@@ -0,0 +1,106 @@
import fs from "node:fs/promises";
import path from "node:path";
import { describe, expect, it } from "vitest";
import type { OpenClawConfig } from "../../../config/config.js";
import type { AgentBootstrapHookContext } from "../../hooks.js";
import { makeTempWorkspace, writeWorkspaceFile } from "../../../test-helpers/workspace.js";
import { createHookEvent } from "../../hooks.js";
import handler from "./handler.js";
describe("bootstrap-extra-files hook", () => {
it("appends extra bootstrap files from configured patterns", async () => {
const tempDir = await makeTempWorkspace("openclaw-bootstrap-extra-");
const extraDir = path.join(tempDir, "packages", "core");
await fs.mkdir(extraDir, { recursive: true });
await fs.writeFile(path.join(extraDir, "AGENTS.md"), "extra agents", "utf-8");
const cfg: OpenClawConfig = {
hooks: {
internal: {
entries: {
"bootstrap-extra-files": {
enabled: true,
paths: ["packages/*/AGENTS.md"],
},
},
},
},
};
const context: AgentBootstrapHookContext = {
workspaceDir: tempDir,
bootstrapFiles: [
{
name: "AGENTS.md",
path: await writeWorkspaceFile({
dir: tempDir,
name: "AGENTS.md",
content: "root agents",
}),
content: "root agents",
missing: false,
},
],
cfg,
sessionKey: "agent:main:main",
};
const event = createHookEvent("agent", "bootstrap", "agent:main:main", context);
await handler(event);
const injected = context.bootstrapFiles.filter((f) => f.name === "AGENTS.md");
expect(injected).toHaveLength(2);
expect(injected.some((f) => f.path.endsWith(path.join("packages", "core", "AGENTS.md")))).toBe(
true,
);
});
it("re-applies subagent bootstrap allowlist after extras are added", async () => {
const tempDir = await makeTempWorkspace("openclaw-bootstrap-extra-subagent-");
const extraDir = path.join(tempDir, "packages", "persona");
await fs.mkdir(extraDir, { recursive: true });
await fs.writeFile(path.join(extraDir, "SOUL.md"), "evil", "utf-8");
const cfg: OpenClawConfig = {
hooks: {
internal: {
entries: {
"bootstrap-extra-files": {
enabled: true,
paths: ["packages/*/SOUL.md"],
},
},
},
},
};
const context: AgentBootstrapHookContext = {
workspaceDir: tempDir,
bootstrapFiles: [
{
name: "AGENTS.md",
path: await writeWorkspaceFile({
dir: tempDir,
name: "AGENTS.md",
content: "root agents",
}),
content: "root agents",
missing: false,
},
{
name: "TOOLS.md",
path: await writeWorkspaceFile({ dir: tempDir, name: "TOOLS.md", content: "root tools" }),
content: "root tools",
missing: false,
},
],
cfg,
sessionKey: "agent:main:subagent:abc",
};
const event = createHookEvent("agent", "bootstrap", "agent:main:subagent:abc", context);
await handler(event);
expect(context.bootstrapFiles.map((f) => f.name).toSorted()).toEqual(["AGENTS.md", "TOOLS.md"]);
});
});

View File

@@ -0,0 +1,59 @@
import {
filterBootstrapFilesForSession,
loadExtraBootstrapFiles,
} from "../../../agents/workspace.js";
import { resolveHookConfig } from "../../config.js";
import { isAgentBootstrapEvent, type HookHandler } from "../../hooks.js";
const HOOK_KEY = "bootstrap-extra-files";
function normalizeStringArray(value: unknown): string[] {
if (!Array.isArray(value)) {
return [];
}
return value.map((v) => (typeof v === "string" ? v.trim() : "")).filter(Boolean);
}
function resolveExtraBootstrapPatterns(hookConfig: Record<string, unknown>): string[] {
const fromPaths = normalizeStringArray(hookConfig.paths);
if (fromPaths.length > 0) {
return fromPaths;
}
const fromPatterns = normalizeStringArray(hookConfig.patterns);
if (fromPatterns.length > 0) {
return fromPatterns;
}
return normalizeStringArray(hookConfig.files);
}
const bootstrapExtraFilesHook: HookHandler = async (event) => {
if (!isAgentBootstrapEvent(event)) {
return;
}
const context = event.context;
const hookConfig = resolveHookConfig(context.cfg, HOOK_KEY);
if (!hookConfig || hookConfig.enabled === false) {
return;
}
const patterns = resolveExtraBootstrapPatterns(hookConfig as Record<string, unknown>);
if (patterns.length === 0) {
return;
}
try {
const extras = await loadExtraBootstrapFiles(context.workspaceDir, patterns);
if (extras.length === 0) {
return;
}
context.bootstrapFiles = filterBootstrapFilesForSession(
[...context.bootstrapFiles, ...extras],
context.sessionKey,
);
} catch (err) {
console.warn(`[bootstrap-extra-files] failed: ${String(err)}`);
}
};
export default bootstrapExtraFilesHook;