mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 23:43:16 +01:00
fix: fail closed on unusable Codex auth during sandbox auth merge
When reusing a Codex sandbox, the workspace-restore step now performs an auth-merge check before adopting the sandbox's auth.json. The merge fails closed when: - host or sandbox Codex auth is unusable (missing token or account) - the subscription payload shapes differ between host and sandbox - subscription account identities do not match Additional hardening: node absence on PATH during the embedded decision script now exits non-zero instead of silently falling through. Co-change comments link parseAuth (the embedded script) to hasUsableAuthPayload (codex-home.ts) so a future auth-format change cannot silently diverge between the two implementations. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
98df214917
3422 files changed
+1614966
No files matched your search
@@ -0,0 +1,52 @@
|
||||
# @paperclipai/create-paperclip-plugin
|
||||
|
||||
Scaffolding tool for creating new Paperclip plugins.
|
||||
|
||||
```bash
|
||||
npx @paperclipai/create-paperclip-plugin my-plugin
|
||||
```
|
||||
|
||||
Or with options:
|
||||
|
||||
```bash
|
||||
npx @paperclipai/create-paperclip-plugin @acme/my-plugin \
|
||||
--template connector \
|
||||
--category connector \
|
||||
--display-name "Acme Connector" \
|
||||
--description "Syncs Acme data into Paperclip" \
|
||||
--author "Acme Inc"
|
||||
```
|
||||
|
||||
Supported templates: `default`, `connector`, `workspace`
|
||||
Supported categories: `connector`, `workspace`, `automation`, `ui`
|
||||
|
||||
Generates:
|
||||
- typed manifest + worker entrypoint
|
||||
- example UI widget using the supported `@paperclipai/plugin-sdk/ui` hooks
|
||||
- test file using `@paperclipai/plugin-sdk/testing`
|
||||
- `esbuild` and `rollup` config files using SDK bundler presets
|
||||
- dev server script for hot-reload (`paperclip-plugin-dev-server`)
|
||||
|
||||
The scaffold starts with plain React elements so the generated plugin stays minimal. For Paperclip-native controls, import shared host components such as `MarkdownEditor`, `FileTree`, `AssigneePicker`, and `ProjectPicker` from `@paperclipai/plugin-sdk/ui`.
|
||||
|
||||
Inside this repo, the generated package uses `@paperclipai/plugin-sdk` via `workspace:*`.
|
||||
|
||||
Outside this repo, the scaffold snapshots `@paperclipai/plugin-sdk` from your local Paperclip checkout into a `.paperclip-sdk/` tarball and points the generated package at that local file by default. You can override the SDK source explicitly:
|
||||
|
||||
```bash
|
||||
node packages/plugins/create-paperclip-plugin/dist/bin.js @acme/my-plugin \
|
||||
--output /absolute/path/to/plugins \
|
||||
--sdk-path /absolute/path/to/paperclip/packages/plugins/sdk
|
||||
```
|
||||
|
||||
That gives you an outside-repo local development path before the SDK is published to npm.
|
||||
|
||||
## Workflow after scaffolding
|
||||
|
||||
```bash
|
||||
cd my-plugin
|
||||
pnpm install
|
||||
pnpm dev # watch worker + manifest + ui bundles
|
||||
pnpm dev:ui # local UI preview server with hot-reload events
|
||||
pnpm test
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "@paperclipai/create-paperclip-plugin",
|
||||
"version": "0.1.0",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/paperclipai/paperclip",
|
||||
"bugs": {
|
||||
"url": "https://github.com/paperclipai/paperclip/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/paperclipai/paperclip",
|
||||
"directory": "packages/plugins/create-paperclip-plugin"
|
||||
},
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"create-paperclip-plugin": "./dist/bin.js"
|
||||
},
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"bin": {
|
||||
"create-paperclip-plugin": "./dist/bin.js"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf dist",
|
||||
"test": "pnpm -w exec vitest run --root packages/plugins/create-paperclip-plugin --config vitest.config.ts",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@paperclipai/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.19.21",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env node
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { scaffoldPluginProject, type ScaffoldPluginOptions } from "./index.js";
|
||||
|
||||
interface RunCliDeps {
|
||||
cwd?: string;
|
||||
stdout?: (message: string) => void;
|
||||
stderr?: (message: string) => void;
|
||||
exit?: (code: number) => never;
|
||||
}
|
||||
|
||||
function parseArg(argv: string[], name: string): string | undefined {
|
||||
const index = argv.indexOf(name);
|
||||
if (index === -1) return undefined;
|
||||
return argv[index + 1];
|
||||
}
|
||||
|
||||
/** Convert `@scope/name` to an output directory basename (`name`). */
|
||||
function packageToDirName(pluginName: string): string {
|
||||
return pluginName.replace(/^@[^/]+\//, "");
|
||||
}
|
||||
|
||||
/** CLI wrapper for `scaffoldPluginProject`. */
|
||||
export function runCli(argv = process.argv, deps: RunCliDeps = {}): string | undefined {
|
||||
const pluginName = argv[2];
|
||||
const stderr = deps.stderr ?? console.error;
|
||||
const stdout = deps.stdout ?? console.log;
|
||||
const exit = deps.exit ?? process.exit;
|
||||
|
||||
if (!pluginName) {
|
||||
stderr("Usage: create-paperclip-plugin <name> [--template default|connector|workspace] [--output <dir>] [--sdk-path <paperclip-sdk-path>]");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
const template = (parseArg(argv, "--template") ?? "default") as ScaffoldPluginOptions["template"];
|
||||
const outputRoot = parseArg(argv, "--output") ?? deps.cwd ?? process.cwd();
|
||||
const targetDir = path.resolve(outputRoot, packageToDirName(pluginName));
|
||||
|
||||
const out = scaffoldPluginProject({
|
||||
pluginName,
|
||||
outputDir: targetDir,
|
||||
template,
|
||||
displayName: parseArg(argv, "--display-name"),
|
||||
description: parseArg(argv, "--description"),
|
||||
author: parseArg(argv, "--author"),
|
||||
category: parseArg(argv, "--category") as ScaffoldPluginOptions["category"] | undefined,
|
||||
sdkPath: parseArg(argv, "--sdk-path"),
|
||||
});
|
||||
|
||||
stdout(`Created plugin scaffold at ${out}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
function isMainModule(): boolean {
|
||||
const entrypoint = process.argv[1];
|
||||
return entrypoint ? import.meta.url === pathToFileURL(entrypoint).href : false;
|
||||
}
|
||||
|
||||
if (isMainModule()) {
|
||||
runCli();
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(process.cwd(), ".tmp-create-paperclip-plugin-"));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop();
|
||||
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("create-paperclip-plugin entrypoints", () => {
|
||||
it("keeps src/index.ts import-safe when process.argv points at another bundled CLI", async () => {
|
||||
const originalArgv = process.argv;
|
||||
const outputRoot = makeTempDir();
|
||||
|
||||
try {
|
||||
process.argv = [process.execPath, path.resolve("cli/dist/index.js"), "demo-plugin", "--output", outputRoot];
|
||||
const library = await import("./index.js");
|
||||
|
||||
expect(library.scaffoldPluginProject).toBeTypeOf("function");
|
||||
expect(fs.existsSync(path.join(outputRoot, "demo-plugin"))).toBe(false);
|
||||
} finally {
|
||||
process.argv = originalArgv;
|
||||
}
|
||||
});
|
||||
|
||||
it("runs scaffolding from src/bin.ts", async () => {
|
||||
const { runCli } = await import("./bin.js");
|
||||
const outputRoot = makeTempDir();
|
||||
const stdout: string[] = [];
|
||||
const outputDir = path.join(outputRoot, "demo-plugin");
|
||||
|
||||
const result = runCli(
|
||||
[
|
||||
process.execPath,
|
||||
"create-paperclip-plugin",
|
||||
"demo-plugin",
|
||||
"--output",
|
||||
outputRoot,
|
||||
"--sdk-path",
|
||||
path.resolve("packages/plugins/sdk"),
|
||||
],
|
||||
{
|
||||
stdout: (message) => stdout.push(message),
|
||||
stderr: (message) => {
|
||||
throw new Error(message);
|
||||
},
|
||||
exit: (code) => {
|
||||
throw new Error(`unexpected exit ${code}`);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toBe(outputDir);
|
||||
expect(stdout).toEqual([`Created plugin scaffold at ${outputDir}`]);
|
||||
expect(JSON.parse(fs.readFileSync(path.join(outputDir, "package.json"), "utf8"))).toMatchObject({
|
||||
name: "demo-plugin",
|
||||
paperclipPlugin: {
|
||||
manifest: "./dist/manifest.js",
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui/",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,700 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const VALID_TEMPLATES = ["default", "connector", "workspace", "environment"] as const;
|
||||
type PluginTemplate = (typeof VALID_TEMPLATES)[number];
|
||||
const VALID_CATEGORIES = new Set(["connector", "workspace", "automation", "ui", "environment"] as const);
|
||||
|
||||
export interface ScaffoldPluginOptions {
|
||||
pluginName: string;
|
||||
outputDir: string;
|
||||
template?: PluginTemplate;
|
||||
displayName?: string;
|
||||
description?: string;
|
||||
author?: string;
|
||||
category?: "connector" | "workspace" | "automation" | "ui" | "environment";
|
||||
sdkPath?: string;
|
||||
}
|
||||
|
||||
/** Validate npm-style plugin package names (scoped or unscoped). */
|
||||
export function isValidPluginName(name: string): boolean {
|
||||
const scopedPattern = /^@[a-z0-9_-]+\/[a-z0-9._-]+$/;
|
||||
const unscopedPattern = /^[a-z0-9._-]+$/;
|
||||
return scopedPattern.test(name) || unscopedPattern.test(name);
|
||||
}
|
||||
|
||||
/** Convert `@scope/name` to an output directory basename (`name`). */
|
||||
function packageToDirName(pluginName: string): string {
|
||||
return pluginName.replace(/^@[^/]+\//, "");
|
||||
}
|
||||
|
||||
/** Convert an npm package name into a manifest-safe plugin id. */
|
||||
function packageToManifestId(pluginName: string): string {
|
||||
if (!pluginName.startsWith("@")) {
|
||||
return pluginName;
|
||||
}
|
||||
|
||||
return pluginName.slice(1).replace("/", ".");
|
||||
}
|
||||
|
||||
/** Build a human-readable display name from package name tokens. */
|
||||
function makeDisplayName(pluginName: string): string {
|
||||
const raw = packageToDirName(pluginName).replace(/[._-]+/g, " ").trim();
|
||||
return raw
|
||||
.split(/\s+/)
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function writeFile(target: string, content: string) {
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, content);
|
||||
}
|
||||
|
||||
function quote(value: string): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function toPosixPath(value: string): string {
|
||||
return value.split(path.sep).join("/");
|
||||
}
|
||||
|
||||
export function shellQuote(value: string): string {
|
||||
if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) return value;
|
||||
return `'${value.replace(/'/g, "'\"'\"'")}'`;
|
||||
}
|
||||
|
||||
function formatFileDependency(absPath: string): string {
|
||||
return `file:${toPosixPath(path.resolve(absPath))}`;
|
||||
}
|
||||
|
||||
function getLocalSdkPackagePath(): string {
|
||||
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "sdk");
|
||||
}
|
||||
|
||||
function getRepoRootFromSdkPath(sdkPath: string): string {
|
||||
return path.resolve(sdkPath, "..", "..", "..");
|
||||
}
|
||||
|
||||
function getLocalSharedPackagePath(sdkPath: string): string {
|
||||
return path.resolve(getRepoRootFromSdkPath(sdkPath), "packages", "shared");
|
||||
}
|
||||
|
||||
function isInsideDir(targetPath: string, parentPath: string): boolean {
|
||||
const relative = path.relative(parentPath, targetPath);
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
function packLocalPackage(packagePath: string, outputDir: string): string {
|
||||
const packageJsonPath = path.join(packagePath, "package.json");
|
||||
if (!fs.existsSync(packageJsonPath)) {
|
||||
throw new Error(`Package package.json not found at ${packageJsonPath}`);
|
||||
}
|
||||
|
||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")) as {
|
||||
name?: string;
|
||||
version?: string;
|
||||
};
|
||||
const packageName = packageJson.name ?? path.basename(packagePath);
|
||||
const packageVersion = packageJson.version ?? "0.0.0";
|
||||
const tarballFileName = `${packageName.replace(/^@/, "").replace("/", "-")}-${packageVersion}.tgz`;
|
||||
const sdkBundleDir = path.join(outputDir, ".paperclip-sdk");
|
||||
|
||||
fs.mkdirSync(sdkBundleDir, { recursive: true });
|
||||
execFileSync("pnpm", ["build"], { cwd: packagePath, stdio: "pipe" });
|
||||
execFileSync("pnpm", ["pack", "--pack-destination", sdkBundleDir], { cwd: packagePath, stdio: "pipe" });
|
||||
|
||||
const tarballPath = path.join(sdkBundleDir, tarballFileName);
|
||||
if (!fs.existsSync(tarballPath)) {
|
||||
throw new Error(`Packed tarball was not created at ${tarballPath}`);
|
||||
}
|
||||
|
||||
return tarballPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a complete Paperclip plugin starter project.
|
||||
*
|
||||
* Output includes manifest/worker/UI entries, SDK harness tests, bundler presets,
|
||||
* and a local dev server script for hot-reload workflow.
|
||||
*/
|
||||
export function scaffoldPluginProject(options: ScaffoldPluginOptions): string {
|
||||
const template = options.template ?? "default";
|
||||
if (!VALID_TEMPLATES.includes(template)) {
|
||||
throw new Error(`Invalid template '${template}'. Expected one of: ${VALID_TEMPLATES.join(", ")}`);
|
||||
}
|
||||
|
||||
if (!isValidPluginName(options.pluginName)) {
|
||||
throw new Error("Invalid plugin name. Must be lowercase and may include scope, dots, underscores, or hyphens.");
|
||||
}
|
||||
|
||||
if (options.category && !VALID_CATEGORIES.has(options.category)) {
|
||||
throw new Error(`Invalid category '${options.category}'. Expected one of: ${[...VALID_CATEGORIES].join(", ")}`);
|
||||
}
|
||||
|
||||
const outputDir = path.resolve(options.outputDir);
|
||||
if (fs.existsSync(outputDir)) {
|
||||
throw new Error(`Directory already exists: ${outputDir}`);
|
||||
}
|
||||
|
||||
const displayName = options.displayName ?? makeDisplayName(options.pluginName);
|
||||
const description = options.description ?? "A Paperclip plugin";
|
||||
const author = options.author ?? "Plugin Author";
|
||||
const category = options.category ?? (template === "workspace" ? "workspace" : template === "environment" ? "environment" : "connector");
|
||||
const manifestId = packageToManifestId(options.pluginName);
|
||||
const localSdkPath = path.resolve(options.sdkPath ?? getLocalSdkPackagePath());
|
||||
const localSharedPath = getLocalSharedPackagePath(localSdkPath);
|
||||
const repoRoot = getRepoRootFromSdkPath(localSdkPath);
|
||||
const useWorkspaceSdk = isInsideDir(outputDir, repoRoot);
|
||||
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
|
||||
const packedSharedTarball = useWorkspaceSdk ? null : packLocalPackage(localSharedPath, outputDir);
|
||||
const sdkDependency = useWorkspaceSdk
|
||||
? "workspace:*"
|
||||
: `file:${toPosixPath(path.relative(outputDir, packLocalPackage(localSdkPath, outputDir)))}`;
|
||||
|
||||
const packageJson = {
|
||||
name: options.pluginName,
|
||||
version: "0.1.0",
|
||||
type: "module",
|
||||
private: true,
|
||||
description,
|
||||
scripts: {
|
||||
build: "node ./esbuild.config.mjs",
|
||||
"build:rollup": "rollup -c",
|
||||
dev: "node ./esbuild.config.mjs --watch",
|
||||
"dev:ui": "paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177",
|
||||
test: "vitest run --config ./vitest.config.ts",
|
||||
typecheck: "tsc --noEmit"
|
||||
},
|
||||
paperclipPlugin: {
|
||||
manifest: "./dist/manifest.js",
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui/"
|
||||
},
|
||||
keywords: ["paperclip", "plugin", category],
|
||||
author,
|
||||
license: "MIT",
|
||||
...(packedSharedTarball
|
||||
? {
|
||||
pnpm: {
|
||||
overrides: {
|
||||
"@paperclipai/shared": `file:${toPosixPath(path.relative(outputDir, packedSharedTarball))}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
devDependencies: {
|
||||
...(packedSharedTarball
|
||||
? {
|
||||
"@paperclipai/shared": `file:${toPosixPath(path.relative(outputDir, packedSharedTarball))}`,
|
||||
}
|
||||
: {}),
|
||||
"@paperclipai/plugin-sdk": sdkDependency,
|
||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"@types/node": "^24.6.0",
|
||||
"@types/react": "^19.0.8",
|
||||
esbuild: "^0.27.3",
|
||||
rollup: "^4.38.0",
|
||||
tslib: "^2.8.1",
|
||||
typescript: "^5.7.3",
|
||||
vitest: "^3.0.5"
|
||||
},
|
||||
peerDependencies: {
|
||||
react: ">=18"
|
||||
}
|
||||
};
|
||||
|
||||
writeFile(path.join(outputDir, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
|
||||
const tsconfig = {
|
||||
compilerOptions: {
|
||||
target: "ES2022",
|
||||
module: "NodeNext",
|
||||
moduleResolution: "NodeNext",
|
||||
lib: ["ES2022", "DOM"],
|
||||
jsx: "react-jsx",
|
||||
strict: true,
|
||||
skipLibCheck: true,
|
||||
declaration: true,
|
||||
declarationMap: true,
|
||||
sourceMap: true,
|
||||
outDir: "dist",
|
||||
rootDir: "."
|
||||
},
|
||||
include: ["src", "tests"],
|
||||
exclude: ["dist", "node_modules"]
|
||||
};
|
||||
|
||||
writeFile(path.join(outputDir, "tsconfig.json"), `${JSON.stringify(tsconfig, null, 2)}\n`);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "esbuild.config.mjs"),
|
||||
`import esbuild from "esbuild";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
const watch = process.argv.includes("--watch");
|
||||
|
||||
const workerCtx = await esbuild.context(presets.esbuild.worker);
|
||||
const manifestCtx = await esbuild.context(presets.esbuild.manifest);
|
||||
const uiCtx = await esbuild.context(presets.esbuild.ui);
|
||||
|
||||
if (watch) {
|
||||
await Promise.all([workerCtx.watch(), manifestCtx.watch(), uiCtx.watch()]);
|
||||
console.log("esbuild watch mode enabled for worker, manifest, and ui");
|
||||
} else {
|
||||
await Promise.all([workerCtx.rebuild(), manifestCtx.rebuild(), uiCtx.rebuild()]);
|
||||
await Promise.all([workerCtx.dispose(), manifestCtx.dispose(), uiCtx.dispose()]);
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "rollup.config.mjs"),
|
||||
`import { nodeResolve } from "@rollup/plugin-node-resolve";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
|
||||
function withPlugins(config) {
|
||||
if (!config) return null;
|
||||
return {
|
||||
...config,
|
||||
plugins: [
|
||||
nodeResolve({
|
||||
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"],
|
||||
}),
|
||||
typescript({
|
||||
tsconfig: "./tsconfig.json",
|
||||
declaration: false,
|
||||
declarationMap: false,
|
||||
}),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export default [
|
||||
withPlugins(presets.rollup.manifest),
|
||||
withPlugins(presets.rollup.worker),
|
||||
withPlugins(presets.rollup.ui),
|
||||
].filter(Boolean);
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "vitest.config.ts"),
|
||||
`import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["tests/**/*.spec.ts"],
|
||||
environment: "node",
|
||||
},
|
||||
});
|
||||
`,
|
||||
);
|
||||
|
||||
if (template === "environment") {
|
||||
writeFile(
|
||||
path.join(outputDir, "src", "manifest.ts"),
|
||||
`import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: ${quote(manifestId)},
|
||||
apiVersion: 1,
|
||||
version: "0.1.0",
|
||||
displayName: ${quote(displayName)},
|
||||
description: ${quote(description)},
|
||||
author: ${quote(author)},
|
||||
categories: [${quote(category)}],
|
||||
capabilities: [
|
||||
"environment.drivers.register",
|
||||
"plugin.state.read",
|
||||
"plugin.state.write",
|
||||
"ui.dashboardWidget.register"
|
||||
],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui"
|
||||
},
|
||||
environmentDrivers: [
|
||||
{
|
||||
driverKey: ${quote(manifestId + "-driver")},
|
||||
displayName: ${quote(displayName + " Driver")}
|
||||
}
|
||||
],
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "dashboardWidget",
|
||||
id: "health-widget",
|
||||
displayName: ${quote(`${displayName} Health`)},
|
||||
exportName: "DashboardWidget"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "src", "worker.ts"),
|
||||
`import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
|
||||
import type {
|
||||
PluginEnvironmentValidateConfigParams,
|
||||
PluginEnvironmentProbeParams,
|
||||
PluginEnvironmentAcquireLeaseParams,
|
||||
PluginEnvironmentResumeLeaseParams,
|
||||
PluginEnvironmentReleaseLeaseParams,
|
||||
PluginEnvironmentDestroyLeaseParams,
|
||||
PluginEnvironmentRealizeWorkspaceParams,
|
||||
PluginEnvironmentExecuteParams,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
|
||||
const plugin = definePlugin({
|
||||
async setup(ctx) {
|
||||
ctx.data.register("health", async () => {
|
||||
return { status: "ok", checkedAt: new Date().toISOString() };
|
||||
});
|
||||
},
|
||||
|
||||
async onHealth() {
|
||||
return { status: "ok", message: "Environment plugin worker is running" };
|
||||
},
|
||||
|
||||
async onEnvironmentValidateConfig(params: PluginEnvironmentValidateConfigParams) {
|
||||
if (!params.config || typeof params.config !== "object") {
|
||||
return { ok: false, errors: ["Config must be a non-null object"] };
|
||||
}
|
||||
return { ok: true, normalizedConfig: params.config };
|
||||
},
|
||||
|
||||
async onEnvironmentProbe(_params: PluginEnvironmentProbeParams) {
|
||||
return { ok: true, summary: "Environment is reachable" };
|
||||
},
|
||||
|
||||
async onEnvironmentAcquireLease(params: PluginEnvironmentAcquireLeaseParams) {
|
||||
const providerLeaseId = \`lease-\${params.runId}-\${Date.now()}\`;
|
||||
return {
|
||||
providerLeaseId,
|
||||
metadata: { acquiredAt: new Date().toISOString() },
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentResumeLease(params: PluginEnvironmentResumeLeaseParams) {
|
||||
return {
|
||||
providerLeaseId: params.providerLeaseId,
|
||||
metadata: { ...params.leaseMetadata, resumed: true },
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentReleaseLease(_params: PluginEnvironmentReleaseLeaseParams) {
|
||||
// Release provider-side resources here
|
||||
},
|
||||
|
||||
async onEnvironmentDestroyLease(_params: PluginEnvironmentDestroyLeaseParams) {
|
||||
// Destroy provider-side resources here
|
||||
},
|
||||
|
||||
async onEnvironmentRealizeWorkspace(params: PluginEnvironmentRealizeWorkspaceParams) {
|
||||
const cwd = params.workspace.remotePath ?? params.workspace.localPath ?? "/tmp/workspace";
|
||||
return { cwd, metadata: { realized: true } };
|
||||
},
|
||||
|
||||
async onEnvironmentExecute(params: PluginEnvironmentExecuteParams) {
|
||||
// Replace this with real command execution against your provider
|
||||
return {
|
||||
exitCode: 0,
|
||||
timedOut: false,
|
||||
stdout: \`Executed: \${params.command}\`,
|
||||
stderr: "",
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
runWorker(plugin, import.meta.url);
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "src", "ui", "index.tsx"),
|
||||
`import { usePluginData, type PluginWidgetProps } from "@paperclipai/plugin-sdk/ui";
|
||||
|
||||
type HealthData = {
|
||||
status: "ok" | "degraded" | "error";
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
export function DashboardWidget(_props: PluginWidgetProps) {
|
||||
const { data, loading, error } = usePluginData<HealthData>("health");
|
||||
|
||||
if (loading) return <div>Loading environment health...</div>;
|
||||
if (error) return <div>Plugin error: {error.message}</div>;
|
||||
|
||||
return (
|
||||
<div style={{ display: "grid", gap: "0.5rem" }}>
|
||||
<strong>${displayName}</strong>
|
||||
<div>Health: {data?.status ?? "unknown"}</div>
|
||||
<div>Checked: {data?.checkedAt ?? "never"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "tests", "plugin.spec.ts"),
|
||||
`import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createEnvironmentTestHarness,
|
||||
createFakeEnvironmentDriver,
|
||||
assertEnvironmentEventOrder,
|
||||
assertLeaseLifecycle,
|
||||
} from "@paperclipai/plugin-sdk/testing";
|
||||
import manifest from "../src/manifest.js";
|
||||
import plugin from "../src/worker.js";
|
||||
|
||||
const ENV_ID = "env-test-1";
|
||||
const BASE_PARAMS = {
|
||||
driverKey: manifest.environmentDrivers![0].driverKey,
|
||||
companyId: "co-1",
|
||||
environmentId: ENV_ID,
|
||||
config: {},
|
||||
};
|
||||
|
||||
describe("environment plugin scaffold", () => {
|
||||
it("declares capabilities for its manifest features", () => {
|
||||
expect(manifest.capabilities).toContain("environment.drivers.register");
|
||||
expect(manifest.capabilities).toContain("ui.dashboardWidget.register");
|
||||
});
|
||||
|
||||
it("validates config", async () => {
|
||||
const driver = createFakeEnvironmentDriver({ driverKey: BASE_PARAMS.driverKey });
|
||||
const harness = createEnvironmentTestHarness({ manifest, environmentDriver: driver });
|
||||
await plugin.definition.setup(harness.ctx);
|
||||
|
||||
const result = await plugin.definition.onEnvironmentValidateConfig!({
|
||||
driverKey: BASE_PARAMS.driverKey,
|
||||
config: { host: "test" },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("probes the environment", async () => {
|
||||
const driver = createFakeEnvironmentDriver({ driverKey: BASE_PARAMS.driverKey });
|
||||
const harness = createEnvironmentTestHarness({ manifest, environmentDriver: driver });
|
||||
await plugin.definition.setup(harness.ctx);
|
||||
|
||||
const result = await plugin.definition.onEnvironmentProbe!(BASE_PARAMS);
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("runs a full lease lifecycle through the harness", async () => {
|
||||
const driver = createFakeEnvironmentDriver({ driverKey: BASE_PARAMS.driverKey });
|
||||
const harness = createEnvironmentTestHarness({ manifest, environmentDriver: driver });
|
||||
await plugin.definition.setup(harness.ctx);
|
||||
|
||||
const lease = await harness.acquireLease({ ...BASE_PARAMS, runId: "run-1" });
|
||||
expect(lease.providerLeaseId).toBeTruthy();
|
||||
|
||||
await harness.realizeWorkspace({
|
||||
...BASE_PARAMS,
|
||||
lease,
|
||||
workspace: { localPath: "/tmp/test" },
|
||||
});
|
||||
|
||||
await harness.releaseLease({
|
||||
...BASE_PARAMS,
|
||||
providerLeaseId: lease.providerLeaseId,
|
||||
});
|
||||
|
||||
assertEnvironmentEventOrder(harness.environmentEvents, [
|
||||
"acquireLease",
|
||||
"realizeWorkspace",
|
||||
"releaseLease",
|
||||
]);
|
||||
assertLeaseLifecycle(harness.environmentEvents, ENV_ID);
|
||||
});
|
||||
});
|
||||
`,
|
||||
);
|
||||
} else {
|
||||
writeFile(
|
||||
path.join(outputDir, "src", "manifest.ts"),
|
||||
`import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: ${quote(manifestId)},
|
||||
apiVersion: 1,
|
||||
version: "0.1.0",
|
||||
displayName: ${quote(displayName)},
|
||||
description: ${quote(description)},
|
||||
author: ${quote(author)},
|
||||
categories: [${quote(category)}],
|
||||
capabilities: [
|
||||
"events.subscribe",
|
||||
"plugin.state.read",
|
||||
"plugin.state.write",
|
||||
"ui.dashboardWidget.register"
|
||||
],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui"
|
||||
},
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "dashboardWidget",
|
||||
id: "health-widget",
|
||||
displayName: ${quote(`${displayName} Health`)},
|
||||
exportName: "DashboardWidget"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "src", "worker.ts"),
|
||||
`import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const plugin = definePlugin({
|
||||
async setup(ctx) {
|
||||
ctx.events.on("issue.created", async (event) => {
|
||||
const issueId = event.entityId ?? "unknown";
|
||||
await ctx.state.set({ scopeKind: "issue", scopeId: issueId, stateKey: "seen" }, true);
|
||||
ctx.logger.info("Observed issue.created", { issueId });
|
||||
});
|
||||
|
||||
ctx.data.register("health", async () => {
|
||||
return { status: "ok", checkedAt: new Date().toISOString() };
|
||||
});
|
||||
|
||||
ctx.actions.register("ping", async () => {
|
||||
ctx.logger.info("Ping action invoked");
|
||||
return { pong: true, at: new Date().toISOString() };
|
||||
});
|
||||
},
|
||||
|
||||
async onHealth() {
|
||||
return { status: "ok", message: "Plugin worker is running" };
|
||||
}
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
runWorker(plugin, import.meta.url);
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "src", "ui", "index.tsx"),
|
||||
`import { usePluginAction, usePluginData, type PluginWidgetProps } from "@paperclipai/plugin-sdk/ui";
|
||||
|
||||
type HealthData = {
|
||||
status: "ok" | "degraded" | "error";
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
export function DashboardWidget(_props: PluginWidgetProps) {
|
||||
const { data, loading, error } = usePluginData<HealthData>("health");
|
||||
const ping = usePluginAction("ping");
|
||||
|
||||
if (loading) return <div>Loading plugin health...</div>;
|
||||
if (error) return <div>Plugin error: {error.message}</div>;
|
||||
|
||||
return (
|
||||
<div style={{ display: "grid", gap: "0.5rem" }}>
|
||||
<strong>${displayName}</strong>
|
||||
<div>Health: {data?.status ?? "unknown"}</div>
|
||||
<div>Checked: {data?.checkedAt ?? "never"}</div>
|
||||
<button onClick={() => void ping()}>Ping Worker</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "tests", "plugin.spec.ts"),
|
||||
`import { describe, expect, it } from "vitest";
|
||||
import { createTestHarness } from "@paperclipai/plugin-sdk/testing";
|
||||
import manifest from "../src/manifest.js";
|
||||
import plugin from "../src/worker.js";
|
||||
|
||||
describe("plugin scaffold", () => {
|
||||
it("declares capabilities for its manifest features", () => {
|
||||
expect(manifest.capabilities).toContain("events.subscribe");
|
||||
expect(manifest.capabilities).toContain("ui.dashboardWidget.register");
|
||||
});
|
||||
|
||||
it("registers data + actions and handles events", async () => {
|
||||
const harness = createTestHarness({ manifest, capabilities: [...manifest.capabilities, "events.emit"] });
|
||||
await plugin.definition.setup(harness.ctx);
|
||||
|
||||
await harness.emit("issue.created", { issueId: "iss_1" }, { entityId: "iss_1", entityType: "issue" });
|
||||
expect(harness.getState({ scopeKind: "issue", scopeId: "iss_1", stateKey: "seen" })).toBe(true);
|
||||
|
||||
const data = await harness.getData<{ status: string }>("health");
|
||||
expect(data.status).toBe("ok");
|
||||
|
||||
const action = await harness.performAction<{ pong: boolean }>("ping");
|
||||
expect(action.pong).toBe(true);
|
||||
});
|
||||
});
|
||||
`,
|
||||
);
|
||||
}
|
||||
|
||||
writeFile(
|
||||
path.join(outputDir, "README.md"),
|
||||
`# ${displayName}
|
||||
|
||||
${description}
|
||||
|
||||
## Development
|
||||
|
||||
\`\`\`bash
|
||||
pnpm install
|
||||
pnpm dev # watch builds
|
||||
pnpm dev:ui # local dev server with hot-reload events
|
||||
pnpm test
|
||||
\`\`\`
|
||||
|
||||
\`pnpm dev\` rebuilds the worker, manifest, and UI bundles into \`dist/\`.
|
||||
When this package is installed from a local path, Paperclip watches that rebuilt
|
||||
output and reloads the plugin worker. Local installs run trusted code from this
|
||||
folder on your machine.
|
||||
|
||||
${sdkDependency.startsWith("file:")
|
||||
? `This scaffold snapshots \`@paperclipai/plugin-sdk\` and \`@paperclipai/shared\` from a local Paperclip checkout at:\n\n\`${toPosixPath(localSdkPath)}\`\n\nThe packed tarballs live in \`.paperclip-sdk/\` for local development. Before publishing this plugin, switch those dependencies to published package versions once they are available on npm.\n\n`
|
||||
: ""}
|
||||
|
||||
## Install Into Paperclip
|
||||
|
||||
\`\`\`bash
|
||||
paperclipai plugin install ${shellQuote(toPosixPath(outputDir))}
|
||||
\`\`\`
|
||||
|
||||
## Build Options
|
||||
|
||||
- \`pnpm build\` uses esbuild presets from \`@paperclipai/plugin-sdk/bundlers\`.
|
||||
- \`pnpm build:rollup\` uses rollup presets from the same SDK.
|
||||
`,
|
||||
);
|
||||
|
||||
writeFile(path.join(outputDir, ".gitignore"), "dist\nnode_modules\n.paperclip-sdk\n");
|
||||
|
||||
return outputDir;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: "node",
|
||||
include: ["src/**/*.test.ts"],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
dist
|
||||
node_modules
|
||||
@@ -0,0 +1,23 @@
|
||||
# Plugin Authoring Smoke Example
|
||||
|
||||
A Paperclip plugin
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev # watch builds
|
||||
pnpm dev:ui # local dev server with hot-reload events
|
||||
pnpm test
|
||||
```
|
||||
|
||||
## Install Into Paperclip
|
||||
|
||||
```bash
|
||||
pnpm paperclipai plugin install ./
|
||||
```
|
||||
|
||||
## Build Options
|
||||
|
||||
- `pnpm build` uses esbuild presets from `@paperclipai/plugin-sdk/bundlers`.
|
||||
- `pnpm build:rollup` uses rollup presets from the same SDK.
|
||||
@@ -0,0 +1,17 @@
|
||||
import esbuild from "esbuild";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
const watch = process.argv.includes("--watch");
|
||||
|
||||
const workerCtx = await esbuild.context(presets.esbuild.worker);
|
||||
const manifestCtx = await esbuild.context(presets.esbuild.manifest);
|
||||
const uiCtx = await esbuild.context(presets.esbuild.ui);
|
||||
|
||||
if (watch) {
|
||||
await Promise.all([workerCtx.watch(), manifestCtx.watch(), uiCtx.watch()]);
|
||||
console.log("esbuild watch mode enabled for worker, manifest, and ui");
|
||||
} else {
|
||||
await Promise.all([workerCtx.rebuild(), manifestCtx.rebuild(), uiCtx.rebuild()]);
|
||||
await Promise.all([workerCtx.dispose(), manifestCtx.dispose(), uiCtx.dispose()]);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-authoring-smoke-example",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"description": "A Paperclip plugin",
|
||||
"scripts": {
|
||||
"prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
|
||||
"build": "node ./esbuild.config.mjs",
|
||||
"build:rollup": "rollup -c",
|
||||
"dev": "node ./esbuild.config.mjs --watch",
|
||||
"dev:ui": "paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177",
|
||||
"test": "vitest run --config ./vitest.config.ts",
|
||||
"typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit"
|
||||
},
|
||||
"paperclipPlugin": {
|
||||
"manifest": "./dist/manifest.js",
|
||||
"worker": "./dist/worker.js",
|
||||
"ui": "./dist/ui/"
|
||||
},
|
||||
"keywords": [
|
||||
"paperclip",
|
||||
"plugin",
|
||||
"connector"
|
||||
],
|
||||
"author": "Plugin Author",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@paperclipai/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"@types/node": "^22.19.21",
|
||||
"@types/react": "^19.2.17",
|
||||
"esbuild": "^0.28.1",
|
||||
"rollup": "^4.62.2",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.1.8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
|
||||
function withPlugins(config) {
|
||||
if (!config) return null;
|
||||
return {
|
||||
...config,
|
||||
plugins: [
|
||||
nodeResolve({
|
||||
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"],
|
||||
}),
|
||||
typescript({
|
||||
tsconfig: "./tsconfig.json",
|
||||
declaration: false,
|
||||
declarationMap: false,
|
||||
}),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export default [
|
||||
withPlugins(presets.rollup.manifest),
|
||||
withPlugins(presets.rollup.worker),
|
||||
withPlugins(presets.rollup.ui),
|
||||
].filter(Boolean);
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: "paperclipai.plugin-authoring-smoke-example",
|
||||
apiVersion: 1,
|
||||
version: "0.1.0",
|
||||
displayName: "Plugin Authoring Smoke Example",
|
||||
description: "A Paperclip plugin",
|
||||
author: "Plugin Author",
|
||||
categories: ["connector"],
|
||||
capabilities: [
|
||||
"events.subscribe",
|
||||
"plugin.state.read",
|
||||
"plugin.state.write",
|
||||
"ui.dashboardWidget.register"
|
||||
],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui"
|
||||
},
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "dashboardWidget",
|
||||
id: "health-widget",
|
||||
displayName: "Plugin Authoring Smoke Example Health",
|
||||
exportName: "DashboardWidget"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { usePluginAction, usePluginData, type PluginWidgetProps } from "@paperclipai/plugin-sdk/ui";
|
||||
|
||||
type HealthData = {
|
||||
status: "ok" | "degraded" | "error";
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
export function DashboardWidget(_props: PluginWidgetProps) {
|
||||
const { data, loading, error } = usePluginData<HealthData>("health");
|
||||
const ping = usePluginAction("ping");
|
||||
|
||||
if (loading) return <div>Loading plugin health...</div>;
|
||||
if (error) return <div>Plugin error: {error.message}</div>;
|
||||
|
||||
return (
|
||||
<div style={{ display: "grid", gap: "0.5rem" }}>
|
||||
<strong>Plugin Authoring Smoke Example</strong>
|
||||
<div>Health: {data?.status ?? "unknown"}</div>
|
||||
<div>Checked: {data?.checkedAt ?? "never"}</div>
|
||||
<button onClick={() => void ping()}>Ping Worker</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const plugin = definePlugin({
|
||||
async setup(ctx) {
|
||||
ctx.events.on("issue.created", async (event) => {
|
||||
const issueId = event.entityId ?? "unknown";
|
||||
await ctx.state.set({ scopeKind: "issue", scopeId: issueId, stateKey: "seen" }, true);
|
||||
ctx.logger.info("Observed issue.created", { issueId });
|
||||
});
|
||||
|
||||
ctx.data.register("health", async () => {
|
||||
return { status: "ok", checkedAt: new Date().toISOString() };
|
||||
});
|
||||
|
||||
ctx.actions.register("ping", async () => {
|
||||
ctx.logger.info("Ping action invoked");
|
||||
return { pong: true, at: new Date().toISOString() };
|
||||
});
|
||||
},
|
||||
|
||||
async onHealth() {
|
||||
return { status: "ok", message: "Plugin worker is running" };
|
||||
}
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
runWorker(plugin, import.meta.url);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createTestHarness } from "@paperclipai/plugin-sdk/testing";
|
||||
import manifest from "../src/manifest.js";
|
||||
import plugin from "../src/worker.js";
|
||||
|
||||
describe("plugin scaffold", () => {
|
||||
it("declares capabilities for its manifest features", () => {
|
||||
expect(manifest.capabilities).toContain("events.subscribe");
|
||||
expect(manifest.capabilities).toContain("ui.dashboardWidget.register");
|
||||
});
|
||||
|
||||
it("registers data + actions and handles events", async () => {
|
||||
const harness = createTestHarness({ manifest, capabilities: [...manifest.capabilities, "events.emit"] });
|
||||
await plugin.definition.setup(harness.ctx);
|
||||
|
||||
await harness.emit("issue.created", { issueId: "iss_1" }, { entityId: "iss_1", entityType: "issue" });
|
||||
expect(harness.getState({ scopeKind: "issue", scopeId: "iss_1", stateKey: "seen" })).toBe(true);
|
||||
|
||||
const data = await harness.getData<{ status: string }>("health");
|
||||
expect(data.status).toBe("ok");
|
||||
|
||||
const action = await harness.performAction<{ pong: boolean }>("ping");
|
||||
expect(action.pong).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": [
|
||||
"ES2022",
|
||||
"DOM"
|
||||
],
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "."
|
||||
},
|
||||
"include": [
|
||||
"src",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"dist",
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["tests/**/*.spec.ts"],
|
||||
environment: "node",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
# File Browser Example Plugin
|
||||
|
||||
Example Paperclip plugin that demonstrates:
|
||||
|
||||
- **projectSidebarItem** — An optional "Files" link under each project in the sidebar that opens the project detail with this plugin’s tab selected. This is controlled by plugin settings and defaults to off.
|
||||
- **detailTab** (entityType project) — A project detail tab with a workspace-path selector, a desktop two-column layout (file tree left, editor right), and a mobile one-panel flow with a back button from editor to file tree, including save support.
|
||||
|
||||
This is a repo-local example plugin for development. It should not be assumed to ship in a generic production build unless it is explicitly included.
|
||||
|
||||
## Slots
|
||||
|
||||
| Slot | Type | Description |
|
||||
|---------------------|---------------------|--------------------------------------------------|
|
||||
| Files (sidebar) | `projectSidebarItem`| Optional link under each project → project detail + tab. |
|
||||
| Files (tab) | `detailTab` | Responsive tree/editor layout with save support.|
|
||||
|
||||
## Settings
|
||||
|
||||
- `Show Files in Sidebar` — toggles the project sidebar link on or off. Defaults to off.
|
||||
- `Comment File Links` — controls whether comment annotations and the comment context-menu action are shown.
|
||||
|
||||
## Capabilities
|
||||
|
||||
- `ui.sidebar.register` — project sidebar item
|
||||
- `ui.detailTab.register` — project detail tab
|
||||
- `projects.read` — resolve project
|
||||
- `project.workspaces.read` — list workspaces and read paths for file access
|
||||
|
||||
## Worker
|
||||
|
||||
- **getData `workspaces`** — `ctx.projects.listWorkspaces(projectId, companyId)` (ordered, primary first).
|
||||
- **getData `fileList`** — `{ projectId, workspaceId, directoryPath? }` → list directory entries for the workspace root or a subdirectory (Node `fs`).
|
||||
- **getData `fileContent`** — `{ projectId, workspaceId, filePath }` → read file content using workspace-relative paths (Node `fs`).
|
||||
- **performAction `writeFile`** — `{ projectId, workspaceId, filePath, content }` → write the current editor buffer back to disk.
|
||||
|
||||
## Local Install (Dev)
|
||||
|
||||
From the repo root, build the plugin and install it by local path:
|
||||
|
||||
```bash
|
||||
pnpm --filter @paperclipai/plugin-file-browser-example build
|
||||
pnpm paperclipai plugin install ./packages/plugins/examples/plugin-file-browser-example
|
||||
```
|
||||
|
||||
To uninstall:
|
||||
|
||||
```bash
|
||||
pnpm paperclipai plugin uninstall paperclip-file-browser-example --force
|
||||
```
|
||||
|
||||
**Local development notes:**
|
||||
|
||||
- **Build first.** The host resolves the worker from the manifest `entrypoints.worker` (e.g. `./dist/worker.js`). Run `pnpm build` in the plugin directory before installing so the worker file exists.
|
||||
- **Dev-only install path.** This local-path install flow assumes this monorepo checkout is present on disk. For deployed installs, publish an npm package instead of depending on `packages/plugins/examples/...` existing on the host.
|
||||
- **Reinstall after pulling.** If you installed a plugin by local path before the server stored `package_path`, the plugin may show status **error** (worker not found). Uninstall and install again so the server persists the path and can activate the plugin.
|
||||
- Optional: use `paperclip-plugin-dev-server` for UI hot-reload with `devUiUrl` in plugin config.
|
||||
|
||||
## Structure
|
||||
|
||||
- `src/manifest.ts` — manifest with `projectSidebarItem` and `detailTab` (entityTypes `["project"]`).
|
||||
- `src/worker.ts` — data handlers for workspaces, file list, file content.
|
||||
- `src/ui/index.tsx` — `FilesLink` (sidebar) and `FilesTab` (workspace path selector + two-panel file tree/editor).
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-file-browser-example",
|
||||
"version": "0.1.0",
|
||||
"description": "Example plugin: project sidebar Files link + project detail tab with workspace selector and file browser",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"paperclipPlugin": {
|
||||
"manifest": "./dist/manifest.js",
|
||||
"worker": "./dist/worker.js",
|
||||
"ui": "./dist/ui/"
|
||||
},
|
||||
"scripts": {
|
||||
"prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
|
||||
"build": "tsc && node ./scripts/build-ui.mjs",
|
||||
"clean": "rm -rf dist",
|
||||
"typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/language": "^6.12.3",
|
||||
"@codemirror/state": "^6.7.0",
|
||||
"@codemirror/view": "^6.43.1",
|
||||
"@lezer/highlight": "^1.2.1",
|
||||
"@paperclipai/plugin-sdk": "workspace:*",
|
||||
"codemirror": "^6.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.19.21",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"esbuild": "^0.28.1",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"typescript": "^5.7.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import esbuild from "esbuild";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const packageRoot = path.resolve(__dirname, "..");
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [path.join(packageRoot, "src/ui/index.tsx")],
|
||||
outfile: path.join(packageRoot, "dist/ui/index.js"),
|
||||
bundle: true,
|
||||
format: "esm",
|
||||
platform: "browser",
|
||||
target: ["es2022"],
|
||||
sourcemap: true,
|
||||
external: [
|
||||
"react",
|
||||
"react-dom",
|
||||
"react/jsx-runtime",
|
||||
"@paperclipai/plugin-sdk/ui",
|
||||
],
|
||||
logLevel: "info",
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as manifest } from "./manifest.js";
|
||||
export { default as worker } from "./worker.js";
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const PLUGIN_ID = "paperclip-file-browser-example";
|
||||
const FILES_SIDEBAR_SLOT_ID = "files-link";
|
||||
const FILES_TAB_SLOT_ID = "files-tab";
|
||||
const COMMENT_FILE_LINKS_SLOT_ID = "comment-file-links";
|
||||
const COMMENT_OPEN_FILES_SLOT_ID = "comment-open-files";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: PLUGIN_ID,
|
||||
apiVersion: 1,
|
||||
version: "0.2.0",
|
||||
displayName: "File Browser (Example)",
|
||||
description: "Example plugin that adds a Files link under each project in the sidebar, a file browser + editor tab on the project detail page, and per-comment file link annotations with a context menu action to open referenced files.",
|
||||
author: "Paperclip",
|
||||
categories: ["workspace", "ui"],
|
||||
capabilities: [
|
||||
"ui.sidebar.register",
|
||||
"ui.detailTab.register",
|
||||
"ui.commentAnnotation.register",
|
||||
"ui.action.register",
|
||||
"projects.read",
|
||||
"project.workspaces.read",
|
||||
"issue.comments.read",
|
||||
"plugin.state.read",
|
||||
],
|
||||
instanceConfigSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
showFilesInSidebar: {
|
||||
type: "boolean",
|
||||
title: "Show Files in Sidebar",
|
||||
default: false,
|
||||
description: "Adds the Files link under each project in the sidebar.",
|
||||
},
|
||||
commentAnnotationMode: {
|
||||
type: "string",
|
||||
title: "Comment File Links",
|
||||
enum: ["annotation", "contextMenu", "both", "none"],
|
||||
default: "both",
|
||||
description: "Controls which comment extensions are active: 'annotation' shows file links below each comment, 'contextMenu' adds an \"Open in Files\" action to the comment menu, 'both' enables both, 'none' disables comment features.",
|
||||
},
|
||||
},
|
||||
},
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui",
|
||||
},
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "projectSidebarItem",
|
||||
id: FILES_SIDEBAR_SLOT_ID,
|
||||
displayName: "Files",
|
||||
exportName: "FilesLink",
|
||||
entityTypes: ["project"],
|
||||
order: 10,
|
||||
},
|
||||
{
|
||||
type: "detailTab",
|
||||
id: FILES_TAB_SLOT_ID,
|
||||
displayName: "Files",
|
||||
exportName: "FilesTab",
|
||||
entityTypes: ["project"],
|
||||
order: 10,
|
||||
},
|
||||
{
|
||||
type: "commentAnnotation",
|
||||
id: COMMENT_FILE_LINKS_SLOT_ID,
|
||||
displayName: "File Links",
|
||||
exportName: "CommentFileLinks",
|
||||
entityTypes: ["comment"],
|
||||
},
|
||||
{
|
||||
type: "commentContextMenuItem",
|
||||
id: COMMENT_OPEN_FILES_SLOT_ID,
|
||||
displayName: "Open in Files",
|
||||
exportName: "CommentOpenFiles",
|
||||
entityTypes: ["comment"],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
@@ -0,0 +1,773 @@
|
||||
import type {
|
||||
FileTreeNode,
|
||||
PluginProjectSidebarItemProps,
|
||||
PluginDetailTabProps,
|
||||
PluginCommentAnnotationProps,
|
||||
PluginCommentContextMenuItemProps,
|
||||
} from "@paperclipai/plugin-sdk/ui";
|
||||
import { FileTree, usePluginAction, usePluginData } from "@paperclipai/plugin-sdk/ui";
|
||||
import { useCallback, useMemo, useState, useEffect, useRef, type MouseEvent, type RefObject } from "react";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
|
||||
import { tags } from "@lezer/highlight";
|
||||
|
||||
const PLUGIN_KEY = "paperclip-file-browser-example";
|
||||
const FILES_TAB_SLOT_ID = "files-tab";
|
||||
|
||||
const editorBaseTheme = {
|
||||
"&": {
|
||||
height: "100%",
|
||||
},
|
||||
".cm-scroller": {
|
||||
overflow: "auto",
|
||||
fontFamily:
|
||||
"ui-monospace, SFMono-Regular, SF Mono, Menlo, Monaco, Consolas, Liberation Mono, monospace",
|
||||
fontSize: "13px",
|
||||
lineHeight: "1.6",
|
||||
},
|
||||
".cm-content": {
|
||||
padding: "12px 14px 18px",
|
||||
},
|
||||
};
|
||||
|
||||
const editorDarkTheme = EditorView.theme({
|
||||
...editorBaseTheme,
|
||||
"&": {
|
||||
...editorBaseTheme["&"],
|
||||
backgroundColor: "oklch(0.23 0.02 255)",
|
||||
color: "oklch(0.93 0.01 255)",
|
||||
},
|
||||
".cm-gutters": {
|
||||
backgroundColor: "oklch(0.25 0.015 255)",
|
||||
color: "oklch(0.74 0.015 255)",
|
||||
borderRight: "1px solid oklch(0.34 0.01 255)",
|
||||
},
|
||||
".cm-activeLine, .cm-activeLineGutter": {
|
||||
backgroundColor: "oklch(0.30 0.012 255 / 0.55)",
|
||||
},
|
||||
".cm-selectionBackground, .cm-content ::selection": {
|
||||
backgroundColor: "oklch(0.42 0.02 255 / 0.45)",
|
||||
},
|
||||
"&.cm-focused .cm-selectionBackground": {
|
||||
backgroundColor: "oklch(0.47 0.025 255 / 0.5)",
|
||||
},
|
||||
".cm-cursor, .cm-dropCursor": {
|
||||
borderLeftColor: "oklch(0.93 0.01 255)",
|
||||
},
|
||||
".cm-matchingBracket": {
|
||||
backgroundColor: "oklch(0.37 0.015 255 / 0.5)",
|
||||
color: "oklch(0.95 0.01 255)",
|
||||
outline: "none",
|
||||
},
|
||||
".cm-nonmatchingBracket": {
|
||||
color: "oklch(0.70 0.08 24)",
|
||||
},
|
||||
}, { dark: true });
|
||||
|
||||
const editorLightTheme = EditorView.theme({
|
||||
...editorBaseTheme,
|
||||
"&": {
|
||||
...editorBaseTheme["&"],
|
||||
backgroundColor: "color-mix(in oklab, var(--card) 92%, var(--background))",
|
||||
color: "var(--foreground)",
|
||||
},
|
||||
".cm-content": {
|
||||
...editorBaseTheme[".cm-content"],
|
||||
caretColor: "var(--foreground)",
|
||||
},
|
||||
".cm-gutters": {
|
||||
backgroundColor: "color-mix(in oklab, var(--card) 96%, var(--background))",
|
||||
color: "var(--muted-foreground)",
|
||||
borderRight: "1px solid var(--border)",
|
||||
},
|
||||
".cm-activeLine, .cm-activeLineGutter": {
|
||||
backgroundColor: "color-mix(in oklab, var(--accent) 52%, transparent)",
|
||||
},
|
||||
".cm-selectionBackground, .cm-content ::selection": {
|
||||
backgroundColor: "color-mix(in oklab, var(--accent) 72%, transparent)",
|
||||
},
|
||||
"&.cm-focused .cm-selectionBackground": {
|
||||
backgroundColor: "color-mix(in oklab, var(--accent) 84%, transparent)",
|
||||
},
|
||||
".cm-cursor, .cm-dropCursor": {
|
||||
borderLeftColor: "color-mix(in oklab, var(--foreground) 88%, transparent)",
|
||||
},
|
||||
".cm-matchingBracket": {
|
||||
backgroundColor: "color-mix(in oklab, var(--accent) 45%, transparent)",
|
||||
color: "var(--foreground)",
|
||||
outline: "none",
|
||||
},
|
||||
".cm-nonmatchingBracket": {
|
||||
color: "var(--destructive)",
|
||||
},
|
||||
});
|
||||
|
||||
const editorDarkHighlightStyle = HighlightStyle.define([
|
||||
{ tag: tags.keyword, color: "oklch(0.78 0.025 265)" },
|
||||
{ tag: [tags.name, tags.variableName], color: "oklch(0.88 0.01 255)" },
|
||||
{ tag: [tags.string, tags.special(tags.string)], color: "oklch(0.80 0.02 170)" },
|
||||
{ tag: [tags.number, tags.bool, tags.null], color: "oklch(0.79 0.02 95)" },
|
||||
{ tag: [tags.comment, tags.lineComment, tags.blockComment], color: "oklch(0.64 0.01 255)" },
|
||||
{ tag: [tags.function(tags.variableName), tags.labelName], color: "oklch(0.84 0.018 220)" },
|
||||
{ tag: [tags.typeName, tags.className], color: "oklch(0.82 0.02 245)" },
|
||||
{ tag: [tags.operator, tags.punctuation], color: "oklch(0.77 0.01 255)" },
|
||||
{ tag: [tags.invalid, tags.deleted], color: "oklch(0.70 0.08 24)" },
|
||||
]);
|
||||
|
||||
const editorLightHighlightStyle = HighlightStyle.define([
|
||||
{ tag: tags.keyword, color: "oklch(0.45 0.07 270)" },
|
||||
{ tag: [tags.name, tags.variableName], color: "oklch(0.28 0.01 255)" },
|
||||
{ tag: [tags.string, tags.special(tags.string)], color: "oklch(0.45 0.06 165)" },
|
||||
{ tag: [tags.number, tags.bool, tags.null], color: "oklch(0.48 0.08 90)" },
|
||||
{ tag: [tags.comment, tags.lineComment, tags.blockComment], color: "oklch(0.53 0.01 255)" },
|
||||
{ tag: [tags.function(tags.variableName), tags.labelName], color: "oklch(0.42 0.07 220)" },
|
||||
{ tag: [tags.typeName, tags.className], color: "oklch(0.40 0.06 245)" },
|
||||
{ tag: [tags.operator, tags.punctuation], color: "oklch(0.36 0.01 255)" },
|
||||
{ tag: [tags.invalid, tags.deleted], color: "oklch(0.55 0.16 24)" },
|
||||
]);
|
||||
|
||||
type Workspace = { id: string; projectId: string; name: string; path: string; isPrimary: boolean };
|
||||
type FileEntry = { name: string; path: string; isDirectory: boolean };
|
||||
|
||||
function entryToFileTreeNode(entry: FileEntry): FileTreeNode {
|
||||
return {
|
||||
name: entry.name,
|
||||
path: entry.path,
|
||||
kind: entry.isDirectory ? "dir" : "file",
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
|
||||
function entriesToFileTreeNodes(entries: FileEntry[]): FileTreeNode[] {
|
||||
return entries.map(entryToFileTreeNode);
|
||||
}
|
||||
|
||||
function setChildrenAtPath(nodes: FileTreeNode[], path: string, children: FileTreeNode[]): FileTreeNode[] {
|
||||
return nodes.map((node) => {
|
||||
if (node.path === path) {
|
||||
return { ...node, children };
|
||||
}
|
||||
if (node.kind === "dir" && node.children.length > 0 && (path === node.path || path.startsWith(`${node.path}/`))) {
|
||||
return { ...node, children: setChildrenAtPath(node.children, path, children) };
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
|
||||
const PathLikePattern = /[\\/]/;
|
||||
const WindowsDrivePathPattern = /^[A-Za-z]:[\\/]/;
|
||||
const UuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
function isLikelyPath(pathValue: string): boolean {
|
||||
const trimmed = pathValue.trim();
|
||||
return PathLikePattern.test(trimmed) || WindowsDrivePathPattern.test(trimmed);
|
||||
}
|
||||
|
||||
function workspaceLabel(workspace: Workspace): string {
|
||||
const pathLabel = workspace.path.trim();
|
||||
const nameLabel = workspace.name.trim();
|
||||
const hasPathLabel = isLikelyPath(pathLabel) && !UuidPattern.test(pathLabel);
|
||||
const hasNameLabel = nameLabel.length > 0 && !UuidPattern.test(nameLabel);
|
||||
const baseLabel = hasPathLabel ? pathLabel : hasNameLabel ? nameLabel : "";
|
||||
if (!baseLabel) {
|
||||
return workspace.isPrimary ? "(no workspace path) (primary)" : "(no workspace path)";
|
||||
}
|
||||
|
||||
return workspace.isPrimary ? `${baseLabel} (primary)` : baseLabel;
|
||||
}
|
||||
|
||||
function useIsMobile(breakpointPx = 768): boolean {
|
||||
const [isMobile, setIsMobile] = useState(() =>
|
||||
typeof window !== "undefined" ? window.innerWidth < breakpointPx : false,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
const mediaQuery = window.matchMedia(`(max-width: ${breakpointPx - 1}px)`);
|
||||
const update = () => setIsMobile(mediaQuery.matches);
|
||||
update();
|
||||
mediaQuery.addEventListener("change", update);
|
||||
return () => mediaQuery.removeEventListener("change", update);
|
||||
}, [breakpointPx]);
|
||||
|
||||
return isMobile;
|
||||
}
|
||||
|
||||
function useIsDarkMode(): boolean {
|
||||
const [isDarkMode, setIsDarkMode] = useState(() =>
|
||||
typeof document !== "undefined" && document.documentElement.classList.contains("dark"),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof document === "undefined") return;
|
||||
const root = document.documentElement;
|
||||
const update = () => setIsDarkMode(root.classList.contains("dark"));
|
||||
update();
|
||||
|
||||
const observer = new MutationObserver(update);
|
||||
observer.observe(root, { attributes: true, attributeFilter: ["class"] });
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return isDarkMode;
|
||||
}
|
||||
|
||||
function useAvailableHeight(
|
||||
ref: RefObject<HTMLElement | null>,
|
||||
options?: { bottomPadding?: number; minHeight?: number },
|
||||
): number | null {
|
||||
const bottomPadding = options?.bottomPadding ?? 24;
|
||||
const minHeight = options?.minHeight ?? 384;
|
||||
const [height, setHeight] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const update = () => {
|
||||
const element = ref.current;
|
||||
if (!element) return;
|
||||
const rect = element.getBoundingClientRect();
|
||||
const nextHeight = Math.max(minHeight, Math.floor(window.innerHeight - rect.top - bottomPadding));
|
||||
setHeight(nextHeight);
|
||||
};
|
||||
|
||||
update();
|
||||
window.addEventListener("resize", update);
|
||||
window.addEventListener("orientationchange", update);
|
||||
|
||||
const observer = typeof ResizeObserver !== "undefined"
|
||||
? new ResizeObserver(() => update())
|
||||
: null;
|
||||
if (observer && ref.current) observer.observe(ref.current);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", update);
|
||||
window.removeEventListener("orientationchange", update);
|
||||
observer?.disconnect();
|
||||
};
|
||||
}, [bottomPadding, minHeight, ref]);
|
||||
|
||||
return height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project sidebar item: link "Files" that opens the project detail with the Files plugin tab.
|
||||
*/
|
||||
export function FilesLink({ context }: PluginProjectSidebarItemProps) {
|
||||
const { data: config, loading: configLoading } = usePluginData<PluginConfig>("plugin-config", {});
|
||||
const showFilesInSidebar = config?.showFilesInSidebar ?? false;
|
||||
|
||||
if (configLoading || !showFilesInSidebar) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const projectId = context.entityId;
|
||||
const projectRef = (context as PluginProjectSidebarItemProps["context"] & { projectRef?: string | null })
|
||||
.projectRef
|
||||
?? projectId;
|
||||
const prefix = context.companyPrefix ? `/${context.companyPrefix}` : "";
|
||||
const tabValue = `plugin:${PLUGIN_KEY}:${FILES_TAB_SLOT_ID}`;
|
||||
const href = `${prefix}/projects/${projectRef}?tab=${encodeURIComponent(tabValue)}`;
|
||||
const isActive = typeof window !== "undefined" && (() => {
|
||||
const pathname = window.location.pathname.replace(/\/+$/, "");
|
||||
const segments = pathname.split("/").filter(Boolean);
|
||||
const projectsIndex = segments.indexOf("projects");
|
||||
const activeProjectRef = projectsIndex >= 0 ? segments[projectsIndex + 1] ?? null : null;
|
||||
const activeTab = new URLSearchParams(window.location.search).get("tab");
|
||||
if (activeTab !== tabValue) return false;
|
||||
if (!activeProjectRef) return false;
|
||||
return activeProjectRef === projectId || activeProjectRef === projectRef;
|
||||
})();
|
||||
|
||||
const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
|
||||
if (
|
||||
event.defaultPrevented
|
||||
|| event.button !== 0
|
||||
|| event.metaKey
|
||||
|| event.ctrlKey
|
||||
|| event.altKey
|
||||
|| event.shiftKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
window.history.pushState({}, "", href);
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
};
|
||||
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
onClick={handleClick}
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
className={`block px-3 py-1 text-[12px] truncate transition-colors ${
|
||||
isActive
|
||||
? "bg-accent text-foreground font-medium"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-accent/50"
|
||||
}`}
|
||||
>
|
||||
Files
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Project detail tab: workspace selector, file tree, and CodeMirror editor.
|
||||
*/
|
||||
export function FilesTab({ context }: PluginDetailTabProps) {
|
||||
const companyId = context.companyId;
|
||||
const projectId = context.entityId;
|
||||
const isMobile = useIsMobile();
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const panesRef = useRef<HTMLDivElement | null>(null);
|
||||
const availableHeight = useAvailableHeight(panesRef, {
|
||||
bottomPadding: isMobile ? 16 : 24,
|
||||
minHeight: isMobile ? 320 : 420,
|
||||
});
|
||||
const { data: workspacesData } = usePluginData<Workspace[]>("workspaces", {
|
||||
projectId,
|
||||
companyId,
|
||||
});
|
||||
const workspaces = workspacesData ?? [];
|
||||
const workspaceSelectKey = workspaces.map((w) => `${w.id}:${workspaceLabel(w)}`).join("|");
|
||||
const [workspaceId, setWorkspaceId] = useState<string | null>(null);
|
||||
const resolvedWorkspaceId = workspaceId ?? workspaces[0]?.id ?? null;
|
||||
const selectedWorkspace = useMemo(
|
||||
() => workspaces.find((w) => w.id === resolvedWorkspaceId) ?? null,
|
||||
[workspaces, resolvedWorkspaceId],
|
||||
);
|
||||
|
||||
const fileListParams = useMemo(
|
||||
() => (selectedWorkspace ? { projectId, companyId, workspaceId: selectedWorkspace.id } : {}),
|
||||
[companyId, projectId, selectedWorkspace],
|
||||
);
|
||||
const { data: fileListData, loading: fileListLoading, error: fileListError } = usePluginData<{ entries: FileEntry[] }>(
|
||||
"fileList",
|
||||
fileListParams,
|
||||
);
|
||||
|
||||
// Lazy-load directory children through an imperative action so the shared
|
||||
// FileTree can reuse `expandedPaths` for state without spawning a hook per
|
||||
// expanded directory.
|
||||
const loadFileList = usePluginAction("loadFileList");
|
||||
const [nodes, setNodes] = useState<FileTreeNode[]>([]);
|
||||
const [expandedPaths, setExpandedPaths] = useState<Set<string>>(() => new Set());
|
||||
const [loadedDirs, setLoadedDirs] = useState<Set<string>>(() => new Set());
|
||||
const [loadingDirs, setLoadingDirs] = useState<Set<string>>(() => new Set());
|
||||
|
||||
useEffect(() => {
|
||||
setNodes(fileListData?.entries ? entriesToFileTreeNodes(fileListData.entries) : []);
|
||||
setExpandedPaths(new Set());
|
||||
setLoadedDirs(new Set());
|
||||
setLoadingDirs(new Set());
|
||||
}, [fileListData, selectedWorkspace?.id]);
|
||||
|
||||
const handleToggleDir = useCallback(
|
||||
(dirPath: string) => {
|
||||
setExpandedPaths((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(dirPath)) next.delete(dirPath);
|
||||
else next.add(dirPath);
|
||||
return next;
|
||||
});
|
||||
if (!selectedWorkspace) return;
|
||||
if (loadedDirs.has(dirPath) || loadingDirs.has(dirPath)) return;
|
||||
setLoadingDirs((current) => new Set(current).add(dirPath));
|
||||
void loadFileList({
|
||||
projectId,
|
||||
companyId,
|
||||
workspaceId: selectedWorkspace.id,
|
||||
directoryPath: dirPath,
|
||||
})
|
||||
.then((response) => {
|
||||
const entries = (response as { entries?: FileEntry[] })?.entries ?? [];
|
||||
const children = entriesToFileTreeNodes(entries);
|
||||
setNodes((current) => setChildrenAtPath(current, dirPath, children));
|
||||
setLoadedDirs((current) => new Set(current).add(dirPath));
|
||||
})
|
||||
.finally(() => {
|
||||
setLoadingDirs((current) => {
|
||||
const next = new Set(current);
|
||||
next.delete(dirPath);
|
||||
return next;
|
||||
});
|
||||
});
|
||||
},
|
||||
[companyId, loadFileList, loadedDirs, loadingDirs, projectId, selectedWorkspace],
|
||||
);
|
||||
|
||||
// Track the `?file=` query parameter across navigations (popstate).
|
||||
const [urlFilePath, setUrlFilePath] = useState<string | null>(() => {
|
||||
if (typeof window === "undefined") return null;
|
||||
return new URLSearchParams(window.location.search).get("file") || null;
|
||||
});
|
||||
const lastConsumedFileRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
const onNav = () => {
|
||||
const next = new URLSearchParams(window.location.search).get("file") || null;
|
||||
setUrlFilePath(next);
|
||||
};
|
||||
window.addEventListener("popstate", onNav);
|
||||
return () => window.removeEventListener("popstate", onNav);
|
||||
}, []);
|
||||
|
||||
const [selectedPath, setSelectedPath] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
setSelectedPath(null);
|
||||
setMobileView("browser");
|
||||
lastConsumedFileRef.current = null;
|
||||
}, [selectedWorkspace?.id]);
|
||||
|
||||
// When a file path appears (or changes) in the URL and workspace is ready, select it.
|
||||
useEffect(() => {
|
||||
if (!urlFilePath || !selectedWorkspace) return;
|
||||
if (lastConsumedFileRef.current === urlFilePath) return;
|
||||
lastConsumedFileRef.current = urlFilePath;
|
||||
setSelectedPath(urlFilePath);
|
||||
setMobileView("editor");
|
||||
}, [urlFilePath, selectedWorkspace]);
|
||||
|
||||
const fileContentParams = useMemo(
|
||||
() =>
|
||||
selectedPath && selectedWorkspace
|
||||
? { projectId, companyId, workspaceId: selectedWorkspace.id, filePath: selectedPath }
|
||||
: null,
|
||||
[companyId, projectId, selectedWorkspace, selectedPath],
|
||||
);
|
||||
const fileContentResult = usePluginData<{ content: string | null; error?: string }>(
|
||||
"fileContent",
|
||||
fileContentParams ?? {},
|
||||
);
|
||||
const { data: fileContentData, refresh: refreshFileContent } = fileContentResult;
|
||||
const writeFile = usePluginAction("writeFile");
|
||||
const editorRef = useRef<HTMLDivElement | null>(null);
|
||||
const viewRef = useRef<EditorView | null>(null);
|
||||
const loadedContentRef = useRef("");
|
||||
const [isDirty, setIsDirty] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [saveMessage, setSaveMessage] = useState<string | null>(null);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [mobileView, setMobileView] = useState<"browser" | "editor">("browser");
|
||||
|
||||
useEffect(() => {
|
||||
if (!editorRef.current) return;
|
||||
const content = fileContentData?.content ?? "";
|
||||
loadedContentRef.current = content;
|
||||
setIsDirty(false);
|
||||
setSaveMessage(null);
|
||||
setSaveError(null);
|
||||
if (viewRef.current) {
|
||||
viewRef.current.destroy();
|
||||
viewRef.current = null;
|
||||
}
|
||||
const view = new EditorView({
|
||||
doc: content,
|
||||
extensions: [
|
||||
basicSetup,
|
||||
javascript(),
|
||||
isDarkMode ? editorDarkTheme : editorLightTheme,
|
||||
syntaxHighlighting(isDarkMode ? editorDarkHighlightStyle : editorLightHighlightStyle),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (!update.docChanged) return;
|
||||
const nextValue = update.state.doc.toString();
|
||||
setIsDirty(nextValue !== loadedContentRef.current);
|
||||
setSaveMessage(null);
|
||||
setSaveError(null);
|
||||
}),
|
||||
],
|
||||
parent: editorRef.current,
|
||||
});
|
||||
viewRef.current = view;
|
||||
return () => {
|
||||
view.destroy();
|
||||
viewRef.current = null;
|
||||
};
|
||||
}, [fileContentData?.content, selectedPath, isDarkMode]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "s") {
|
||||
return;
|
||||
}
|
||||
if (!selectedWorkspace || !selectedPath || !isDirty || isSaving) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
void handleSave();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeydown);
|
||||
return () => window.removeEventListener("keydown", handleKeydown);
|
||||
}, [selectedWorkspace, selectedPath, isDirty, isSaving]);
|
||||
|
||||
async function handleSave() {
|
||||
if (!selectedWorkspace || !selectedPath || !viewRef.current) {
|
||||
return;
|
||||
}
|
||||
const content = viewRef.current.state.doc.toString();
|
||||
setIsSaving(true);
|
||||
setSaveError(null);
|
||||
setSaveMessage(null);
|
||||
try {
|
||||
await writeFile({
|
||||
projectId,
|
||||
companyId,
|
||||
workspaceId: selectedWorkspace.id,
|
||||
filePath: selectedPath,
|
||||
content,
|
||||
});
|
||||
loadedContentRef.current = content;
|
||||
setIsDirty(false);
|
||||
setSaveMessage("Saved");
|
||||
refreshFileContent();
|
||||
} catch (error) {
|
||||
setSaveError(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<label className="text-sm font-medium text-muted-foreground">Workspace</label>
|
||||
<select
|
||||
key={workspaceSelectKey}
|
||||
className="mt-2 block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
value={resolvedWorkspaceId ?? ""}
|
||||
onChange={(e) => setWorkspaceId(e.target.value || null)}
|
||||
>
|
||||
{workspaces.map((w) => {
|
||||
const label = workspaceLabel(w);
|
||||
return (
|
||||
<option key={`${w.id}:${label}`} value={w.id} label={label} title={label}>
|
||||
{label}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={panesRef}
|
||||
className="min-h-0"
|
||||
style={{
|
||||
display: isMobile ? "block" : "grid",
|
||||
gap: "1rem",
|
||||
gridTemplateColumns: isMobile ? undefined : "320px minmax(0, 1fr)",
|
||||
height: availableHeight ? `${availableHeight}px` : undefined,
|
||||
minHeight: isMobile ? "20rem" : "26rem",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex min-h-0 flex-col overflow-hidden rounded-lg border border-border bg-card"
|
||||
style={{ display: isMobile && mobileView === "editor" ? "none" : "flex" }}
|
||||
>
|
||||
<div className="border-b border-border px-3 py-2 text-xs font-medium uppercase tracking-[0.12em] text-muted-foreground">
|
||||
File Tree
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-auto p-2">
|
||||
{selectedWorkspace ? (
|
||||
<FileTree
|
||||
nodes={nodes}
|
||||
selectedFile={selectedPath}
|
||||
expandedPaths={expandedPaths}
|
||||
onToggleDir={handleToggleDir}
|
||||
onSelectFile={(path: string) => {
|
||||
setSelectedPath(path);
|
||||
setMobileView("editor");
|
||||
}}
|
||||
loading={fileListLoading}
|
||||
error={fileListError ? { message: fileListError.message } : null}
|
||||
empty={{
|
||||
title: "No files",
|
||||
description: "No files found in this workspace.",
|
||||
}}
|
||||
ariaLabel="Workspace files"
|
||||
/>
|
||||
) : (
|
||||
<p className="px-2 py-3 text-sm text-muted-foreground">Select a workspace to browse files.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="flex min-h-0 flex-col overflow-hidden rounded-lg border border-border bg-card"
|
||||
style={{ display: isMobile && mobileView === "browser" ? "none" : "flex" }}
|
||||
>
|
||||
<div className="sticky top-0 z-10 flex items-center justify-between gap-3 border-b border-border bg-card px-4 py-2">
|
||||
<div className="min-w-0">
|
||||
<button
|
||||
type="button"
|
||||
className="mb-2 inline-flex rounded-md border border-input bg-background px-2 py-1 text-xs font-medium text-muted-foreground"
|
||||
style={{ display: isMobile ? "inline-flex" : "none" }}
|
||||
onClick={() => setMobileView("browser")}
|
||||
>
|
||||
Back to files
|
||||
</button>
|
||||
<div className="text-xs font-medium uppercase tracking-[0.12em] text-muted-foreground">Editor</div>
|
||||
<div className="truncate text-sm text-foreground">{selectedPath ?? "No file selected"}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm font-medium text-foreground transition-colors hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={!selectedWorkspace || !selectedPath || !isDirty || isSaving}
|
||||
onClick={() => void handleSave()}
|
||||
>
|
||||
{isSaving ? "Saving..." : "Save"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{isDirty || saveMessage || saveError ? (
|
||||
<div className="border-b border-border px-4 py-2 text-xs">
|
||||
{saveError ? (
|
||||
<span className="text-destructive">{saveError}</span>
|
||||
) : saveMessage ? (
|
||||
<span className="text-emerald-600">{saveMessage}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Unsaved changes</span>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
{selectedPath && fileContentData?.error && fileContentData.error !== "Missing file context" ? (
|
||||
<div className="border-b border-border px-4 py-2 text-xs text-destructive">{fileContentData.error}</div>
|
||||
) : null}
|
||||
<div ref={editorRef} className="min-h-0 flex-1 overflow-auto overscroll-contain" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Comment Annotation: renders detected file links below each comment
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type PluginConfig = {
|
||||
showFilesInSidebar?: boolean;
|
||||
commentAnnotationMode: "annotation" | "contextMenu" | "both" | "none";
|
||||
};
|
||||
|
||||
/**
|
||||
* Per-comment annotation showing file-path-like links extracted from the
|
||||
* comment body. Each link navigates to the project Files tab with the
|
||||
* matching path pre-selected.
|
||||
*
|
||||
* Respects the `commentAnnotationMode` instance config — hidden when mode
|
||||
* is `"contextMenu"` or `"none"`.
|
||||
*/
|
||||
function buildFileBrowserHref(prefix: string, projectId: string | null, filePath: string): string {
|
||||
if (!projectId) return "#";
|
||||
const tabValue = `plugin:${PLUGIN_KEY}:${FILES_TAB_SLOT_ID}`;
|
||||
return `${prefix}/projects/${projectId}?tab=${encodeURIComponent(tabValue)}&file=${encodeURIComponent(filePath)}`;
|
||||
}
|
||||
|
||||
function navigateToFileBrowser(href: string, event: MouseEvent<HTMLAnchorElement>) {
|
||||
if (
|
||||
event.defaultPrevented
|
||||
|| event.button !== 0
|
||||
|| event.metaKey
|
||||
|| event.ctrlKey
|
||||
|| event.altKey
|
||||
|| event.shiftKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
window.history.pushState({}, "", href);
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
}
|
||||
|
||||
export function CommentFileLinks({ context }: PluginCommentAnnotationProps) {
|
||||
const { data: config } = usePluginData<PluginConfig>("plugin-config", {});
|
||||
const mode = config?.commentAnnotationMode ?? "both";
|
||||
|
||||
const { data } = usePluginData<{ links: string[] }>("comment-file-links", {
|
||||
commentId: context.entityId,
|
||||
issueId: context.parentEntityId,
|
||||
companyId: context.companyId,
|
||||
});
|
||||
|
||||
if (mode === "contextMenu" || mode === "none") return null;
|
||||
if (!data?.links?.length) return null;
|
||||
|
||||
const prefix = context.companyPrefix ? `/${context.companyPrefix}` : "";
|
||||
const projectId = context.projectId;
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">Files:</span>
|
||||
{data.links.map((link) => {
|
||||
const href = buildFileBrowserHref(prefix, projectId, link);
|
||||
return (
|
||||
<a
|
||||
key={link}
|
||||
href={href}
|
||||
onClick={(e) => navigateToFileBrowser(href, e)}
|
||||
className="inline-flex items-center rounded-md border border-border bg-accent/30 px-1.5 py-0.5 text-xs font-mono text-primary hover:bg-accent/60 hover:underline transition-colors"
|
||||
title={`Open ${link} in file browser`}
|
||||
>
|
||||
{link}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Comment Context Menu Item: "Open in Files" action per comment
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Per-comment context menu item that appears in the comment "more" (⋮) menu.
|
||||
* Extracts file paths from the comment body and, if any are found, renders
|
||||
* a button to open the first file in the project Files tab.
|
||||
*
|
||||
* Respects the `commentAnnotationMode` instance config — hidden when mode
|
||||
* is `"annotation"` or `"none"`.
|
||||
*/
|
||||
export function CommentOpenFiles({ context }: PluginCommentContextMenuItemProps) {
|
||||
const { data: config } = usePluginData<PluginConfig>("plugin-config", {});
|
||||
const mode = config?.commentAnnotationMode ?? "both";
|
||||
|
||||
const { data } = usePluginData<{ links: string[] }>("comment-file-links", {
|
||||
commentId: context.entityId,
|
||||
issueId: context.parentEntityId,
|
||||
companyId: context.companyId,
|
||||
});
|
||||
|
||||
if (mode === "annotation" || mode === "none") return null;
|
||||
if (!data?.links?.length) return null;
|
||||
|
||||
const prefix = context.companyPrefix ? `/${context.companyPrefix}` : "";
|
||||
const projectId = context.projectId;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="px-2 py-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Files
|
||||
</div>
|
||||
{data.links.map((link) => {
|
||||
const href = buildFileBrowserHref(prefix, projectId, link);
|
||||
const fileName = link.split("/").pop() ?? link;
|
||||
return (
|
||||
<a
|
||||
key={link}
|
||||
href={href}
|
||||
onClick={(e) => navigateToFileBrowser(href, e)}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1 text-xs text-foreground hover:bg-accent transition-colors"
|
||||
title={`Open ${link} in file browser`}
|
||||
>
|
||||
<span className="truncate font-mono">{fileName}</span>
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
const PLUGIN_NAME = "file-browser-example";
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
const PATH_LIKE_PATTERN = /[\\/]/;
|
||||
const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
|
||||
function looksLikePath(value: string): boolean {
|
||||
const normalized = value.trim();
|
||||
return (PATH_LIKE_PATTERN.test(normalized) || WINDOWS_DRIVE_PATH_PATTERN.test(normalized))
|
||||
&& !UUID_PATTERN.test(normalized);
|
||||
}
|
||||
|
||||
function sanitizeWorkspacePath(pathValue: string): string {
|
||||
return looksLikePath(pathValue) ? pathValue.trim() : "";
|
||||
}
|
||||
|
||||
function resolveWorkspace(workspacePath: string, requestedPath?: string): string | null {
|
||||
const root = path.resolve(workspacePath);
|
||||
const resolved = requestedPath ? path.resolve(root, requestedPath) : root;
|
||||
const relative = path.relative(root, resolved);
|
||||
if (relative.startsWith("..") || path.isAbsolute(relative)) {
|
||||
return null;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Regex that matches file-path-like tokens in comment text.
|
||||
* Captures tokens that either start with `.` `/` `~` or contain a `/`
|
||||
* (directory separator), plus bare words that could be filenames with
|
||||
* extensions (e.g. `README.md`). The file-extension check in
|
||||
* `extractFilePaths` filters out non-file matches.
|
||||
*/
|
||||
const FILE_PATH_REGEX = /(?:^|[\s(`"'])([^\s,;)}`"'>\]]*\/[^\s,;)}`"'>\]]+|[.\/~][^\s,;)}`"'>\]]+|[a-zA-Z0-9_-]+\.[a-zA-Z0-9]{1,10}(?:\/[^\s,;)}`"'>\]]+)?)/g;
|
||||
|
||||
/** Common file extensions to recognise path-like tokens as actual file references. */
|
||||
const FILE_EXTENSION_REGEX = /\.[a-zA-Z0-9]{1,10}$/;
|
||||
|
||||
/**
|
||||
* Tokens that look like paths but are almost certainly URL route segments
|
||||
* (e.g. `/projects/abc`, `/settings`, `/dashboard`).
|
||||
*/
|
||||
const URL_ROUTE_PATTERN = /^\/(?:projects|issues|agents|settings|dashboard|plugins|api|auth|admin)\b/i;
|
||||
|
||||
function extractFilePaths(body: string): string[] {
|
||||
const paths = new Set<string>();
|
||||
for (const match of body.matchAll(FILE_PATH_REGEX)) {
|
||||
const raw = match[1];
|
||||
// Strip trailing punctuation that isn't part of a path
|
||||
const cleaned = raw.replace(/[.:,;!?)]+$/, "");
|
||||
if (cleaned.length <= 1) continue;
|
||||
// Must have a file extension (e.g. .ts, .json, .md)
|
||||
if (!FILE_EXTENSION_REGEX.test(cleaned)) continue;
|
||||
// Skip things that look like URL routes
|
||||
if (URL_ROUTE_PATTERN.test(cleaned)) continue;
|
||||
paths.add(cleaned);
|
||||
}
|
||||
return [...paths];
|
||||
}
|
||||
|
||||
const plugin = definePlugin({
|
||||
async setup(ctx) {
|
||||
ctx.logger.info(`${PLUGIN_NAME} plugin setup`);
|
||||
|
||||
// Expose the current plugin config so UI components can read operator
|
||||
// settings from the canonical instance config store.
|
||||
ctx.data.register("plugin-config", async () => {
|
||||
const config = await ctx.config.get();
|
||||
return {
|
||||
showFilesInSidebar: config?.showFilesInSidebar === true,
|
||||
commentAnnotationMode: config?.commentAnnotationMode ?? "both",
|
||||
};
|
||||
});
|
||||
|
||||
// Fetch a comment by ID and extract file-path-like tokens from its body.
|
||||
ctx.data.register("comment-file-links", async (params: Record<string, unknown>) => {
|
||||
const commentId = typeof params.commentId === "string" ? params.commentId : "";
|
||||
const issueId = typeof params.issueId === "string" ? params.issueId : "";
|
||||
const companyId = typeof params.companyId === "string" ? params.companyId : "";
|
||||
if (!commentId || !issueId || !companyId) return { links: [] };
|
||||
try {
|
||||
const comments = await ctx.issues.listComments(issueId, companyId);
|
||||
const comment = comments.find((c) => c.id === commentId);
|
||||
if (!comment?.body) return { links: [] };
|
||||
return { links: extractFilePaths(comment.body) };
|
||||
} catch (err) {
|
||||
ctx.logger.warn("Failed to fetch comment for file link extraction", { commentId, error: String(err) });
|
||||
return { links: [] };
|
||||
}
|
||||
});
|
||||
|
||||
ctx.data.register("workspaces", async (params: Record<string, unknown>) => {
|
||||
const projectId = params.projectId as string;
|
||||
const companyId = typeof params.companyId === "string" ? params.companyId : "";
|
||||
if (!projectId || !companyId) return [];
|
||||
const workspaces = await ctx.projects.listWorkspaces(projectId, companyId);
|
||||
return workspaces.map((w) => ({
|
||||
id: w.id,
|
||||
projectId: w.projectId,
|
||||
name: w.name,
|
||||
path: sanitizeWorkspacePath(w.path),
|
||||
isPrimary: w.isPrimary,
|
||||
}));
|
||||
});
|
||||
|
||||
async function readFileList(params: Record<string, unknown>) {
|
||||
const projectId = params.projectId as string;
|
||||
const companyId = typeof params.companyId === "string" ? params.companyId : "";
|
||||
const workspaceId = params.workspaceId as string;
|
||||
const directoryPath = typeof params.directoryPath === "string" ? params.directoryPath : "";
|
||||
if (!projectId || !companyId || !workspaceId) return { entries: [] };
|
||||
const workspaces = await ctx.projects.listWorkspaces(projectId, companyId);
|
||||
const workspace = workspaces.find((w) => w.id === workspaceId);
|
||||
if (!workspace) return { entries: [] };
|
||||
const workspacePath = sanitizeWorkspacePath(workspace.path);
|
||||
if (!workspacePath) return { entries: [] };
|
||||
const dirPath = resolveWorkspace(workspacePath, directoryPath);
|
||||
if (!dirPath) {
|
||||
return { entries: [] };
|
||||
}
|
||||
if (!fs.existsSync(dirPath) || !fs.statSync(dirPath).isDirectory()) {
|
||||
return { entries: [] };
|
||||
}
|
||||
const names = fs.readdirSync(dirPath).sort((a, b) => a.localeCompare(b));
|
||||
const entries = names.map((name) => {
|
||||
const full = path.join(dirPath, name);
|
||||
const stat = fs.lstatSync(full);
|
||||
const relativePath = path.relative(workspacePath, full);
|
||||
return {
|
||||
name,
|
||||
path: relativePath,
|
||||
isDirectory: stat.isDirectory(),
|
||||
};
|
||||
}).sort((a, b) => {
|
||||
if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
return { entries };
|
||||
}
|
||||
|
||||
ctx.data.register("fileList", readFileList);
|
||||
|
||||
// Mirror `fileList` as an action so the UI can lazily fetch directory
|
||||
// children on tree expand without spawning a usePluginData hook per dir.
|
||||
ctx.actions.register("loadFileList", readFileList);
|
||||
|
||||
ctx.data.register(
|
||||
"fileContent",
|
||||
async (params: Record<string, unknown>) => {
|
||||
const projectId = params.projectId as string;
|
||||
const companyId = typeof params.companyId === "string" ? params.companyId : "";
|
||||
const workspaceId = params.workspaceId as string;
|
||||
const filePath = params.filePath as string;
|
||||
if (!projectId || !companyId || !workspaceId || !filePath) {
|
||||
return { content: null, error: "Missing file context" };
|
||||
}
|
||||
const workspaces = await ctx.projects.listWorkspaces(projectId, companyId);
|
||||
const workspace = workspaces.find((w) => w.id === workspaceId);
|
||||
if (!workspace) return { content: null, error: "Workspace not found" };
|
||||
const workspacePath = sanitizeWorkspacePath(workspace.path);
|
||||
if (!workspacePath) return { content: null, error: "Workspace has no path" };
|
||||
const fullPath = resolveWorkspace(workspacePath, filePath);
|
||||
if (!fullPath) {
|
||||
return { content: null, error: "Path outside workspace" };
|
||||
}
|
||||
try {
|
||||
const content = fs.readFileSync(fullPath, "utf-8");
|
||||
return { content };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return { content: null, error: message };
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
ctx.actions.register(
|
||||
"writeFile",
|
||||
async (params: Record<string, unknown>) => {
|
||||
const projectId = params.projectId as string;
|
||||
const companyId = typeof params.companyId === "string" ? params.companyId : "";
|
||||
const workspaceId = params.workspaceId as string;
|
||||
const filePath = typeof params.filePath === "string" ? params.filePath.trim() : "";
|
||||
if (!filePath) {
|
||||
throw new Error("filePath must be a non-empty string");
|
||||
}
|
||||
const content = typeof params.content === "string" ? params.content : null;
|
||||
if (!projectId || !companyId || !workspaceId) {
|
||||
throw new Error("Missing workspace context");
|
||||
}
|
||||
const workspaces = await ctx.projects.listWorkspaces(projectId, companyId);
|
||||
const workspace = workspaces.find((w) => w.id === workspaceId);
|
||||
if (!workspace) {
|
||||
throw new Error("Workspace not found");
|
||||
}
|
||||
const workspacePath = sanitizeWorkspacePath(workspace.path);
|
||||
if (!workspacePath) {
|
||||
throw new Error("Workspace has no path");
|
||||
}
|
||||
if (content === null) {
|
||||
throw new Error("Missing file content");
|
||||
}
|
||||
const fullPath = resolveWorkspace(workspacePath, filePath);
|
||||
if (!fullPath) {
|
||||
throw new Error("Path outside workspace");
|
||||
}
|
||||
const stat = fs.statSync(fullPath);
|
||||
if (!stat.isFile()) {
|
||||
throw new Error("Selected path is not a file");
|
||||
}
|
||||
fs.writeFileSync(fullPath, content, "utf-8");
|
||||
return {
|
||||
ok: true,
|
||||
path: filePath,
|
||||
bytes: Buffer.byteLength(content, "utf-8"),
|
||||
};
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async onHealth() {
|
||||
return { status: "ok", message: `${PLUGIN_NAME} ready` };
|
||||
},
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
runWorker(plugin, import.meta.url);
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
# @paperclipai/plugin-hello-world-example
|
||||
|
||||
First-party reference plugin showing the smallest possible UI extension.
|
||||
|
||||
## What It Demonstrates
|
||||
|
||||
- a manifest with a `dashboardWidget` UI slot
|
||||
- `entrypoints.ui` wiring for plugin UI bundles
|
||||
- a minimal React widget rendered in the Paperclip dashboard
|
||||
- reading host context (`companyId`) from `PluginWidgetProps`
|
||||
- worker lifecycle hooks (`setup`, `onHealth`) for basic runtime observability
|
||||
|
||||
## API Surface
|
||||
|
||||
- This example does not add custom HTTP endpoints.
|
||||
- The widget is discovered/rendered through host-managed plugin APIs (for example `GET /api/plugins/ui-contributions`).
|
||||
|
||||
## Notes
|
||||
|
||||
This is intentionally simple and is designed as the quickest "hello world" starting point for UI plugin authors.
|
||||
It is a repo-local example plugin for development, not a plugin that should be assumed to ship in generic production builds.
|
||||
|
||||
## Local Install (Dev)
|
||||
|
||||
From the repo root, build the plugin and install it by local path:
|
||||
|
||||
```bash
|
||||
pnpm --filter @paperclipai/plugin-hello-world-example build
|
||||
pnpm paperclipai plugin install ./packages/plugins/examples/plugin-hello-world-example
|
||||
```
|
||||
|
||||
**Local development notes:**
|
||||
|
||||
- **Build first.** The host resolves the worker from the manifest `entrypoints.worker` (e.g. `./dist/worker.js`). Run `pnpm build` in the plugin directory before installing so the worker file exists.
|
||||
- **Dev-only install path.** This local-path install flow assumes a source checkout with this example package present on disk. For deployed installs, publish an npm package instead of relying on the monorepo example path.
|
||||
- **Reinstall after pulling.** If you installed a plugin by local path before the server stored `package_path`, the plugin may show status **error** (worker not found). Uninstall and install again so the server persists the path and can activate the plugin:
|
||||
`pnpm paperclipai plugin uninstall paperclip.hello-world-example --force` then
|
||||
`pnpm paperclipai plugin install ./packages/plugins/examples/plugin-hello-world-example`.
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-hello-world-example",
|
||||
"version": "0.1.0",
|
||||
"description": "First-party reference plugin that adds a Hello World dashboard widget",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"paperclipPlugin": {
|
||||
"manifest": "./dist/manifest.js",
|
||||
"worker": "./dist/worker.js",
|
||||
"ui": "./dist/ui/"
|
||||
},
|
||||
"scripts": {
|
||||
"prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf dist",
|
||||
"typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@paperclipai/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.19.21",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"typescript": "^5.7.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as manifest } from "./manifest.js";
|
||||
export { default as worker } from "./worker.js";
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
/**
|
||||
* Stable plugin ID used by host registration and namespacing.
|
||||
*/
|
||||
const PLUGIN_ID = "paperclip.hello-world-example";
|
||||
const PLUGIN_VERSION = "0.1.0";
|
||||
const DASHBOARD_WIDGET_SLOT_ID = "hello-world-dashboard-widget";
|
||||
const DASHBOARD_WIDGET_EXPORT_NAME = "HelloWorldDashboardWidget";
|
||||
|
||||
/**
|
||||
* Minimal manifest demonstrating a UI-only plugin with one dashboard widget slot.
|
||||
*/
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: PLUGIN_ID,
|
||||
apiVersion: 1,
|
||||
version: PLUGIN_VERSION,
|
||||
displayName: "Hello World Widget (Example)",
|
||||
description: "Reference UI plugin that adds a simple Hello World widget to the Paperclip dashboard.",
|
||||
author: "Paperclip",
|
||||
categories: ["ui"],
|
||||
capabilities: ["ui.dashboardWidget.register"],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui",
|
||||
},
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "dashboardWidget",
|
||||
id: DASHBOARD_WIDGET_SLOT_ID,
|
||||
displayName: "Hello World",
|
||||
exportName: DASHBOARD_WIDGET_EXPORT_NAME,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { PluginWidgetProps } from "@paperclipai/plugin-sdk/ui";
|
||||
|
||||
const WIDGET_LABEL = "Hello world plugin widget";
|
||||
|
||||
/**
|
||||
* Example dashboard widget showing the smallest possible UI contribution.
|
||||
*/
|
||||
export function HelloWorldDashboardWidget({ context }: PluginWidgetProps) {
|
||||
return (
|
||||
<section aria-label={WIDGET_LABEL}>
|
||||
<strong>Hello world</strong>
|
||||
<div>This widget was added by @paperclipai/plugin-hello-world-example.</div>
|
||||
{/* Include host context so authors can see where scoped IDs come from. */}
|
||||
<div>Company context: {context.companyId}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const PLUGIN_NAME = "hello-world-example";
|
||||
const HEALTH_MESSAGE = "Hello World example plugin ready";
|
||||
|
||||
/**
|
||||
* Worker lifecycle hooks for the Hello World reference plugin.
|
||||
* This stays intentionally small so new authors can copy the shape quickly.
|
||||
*/
|
||||
const plugin = definePlugin({
|
||||
/**
|
||||
* Called when the host starts the plugin worker.
|
||||
*/
|
||||
async setup(ctx) {
|
||||
ctx.logger.info(`${PLUGIN_NAME} plugin setup complete`);
|
||||
},
|
||||
|
||||
/**
|
||||
* Called by the host health probe endpoint.
|
||||
*/
|
||||
async onHealth() {
|
||||
return { status: "ok", message: HEALTH_MESSAGE };
|
||||
},
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
runWorker(plugin, import.meta.url);
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# @paperclipai/plugin-kitchen-sink-example
|
||||
|
||||
Kitchen Sink is the first-party reference plugin that demonstrates nearly the full currently implemented Paperclip plugin surface in one package.
|
||||
|
||||
It is intentionally broad:
|
||||
|
||||
- full plugin page
|
||||
- dashboard widget
|
||||
- project and issue surfaces
|
||||
- comment surfaces
|
||||
- sidebar surfaces
|
||||
- settings page
|
||||
- worker bridge data/actions
|
||||
- events, jobs, webhooks, tools, streams
|
||||
- state, entities, assets, metrics, activity
|
||||
- local workspace and process demos
|
||||
|
||||
This plugin is for local development, contributor onboarding, and runtime regression testing. It is not meant as a production plugin template to ship unchanged.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
pnpm --filter @paperclipai/plugin-kitchen-sink-example build
|
||||
pnpm paperclipai plugin install ./packages/plugins/examples/plugin-kitchen-sink-example
|
||||
```
|
||||
|
||||
Or install it from the Paperclip plugin manager as a bundled example once this repo is built.
|
||||
|
||||
## Notes
|
||||
|
||||
- Local workspace and process demos are trusted-only and default to safe, curated commands.
|
||||
- The plugin settings page lets you toggle optional demo surfaces and local runtime behavior.
|
||||
- Some SDK-defined host surfaces still depend on the Paperclip host wiring them visibly; this package aims to exercise the currently mounted ones and make the rest obvious.
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-kitchen-sink-example",
|
||||
"version": "0.1.0",
|
||||
"description": "Reference plugin that demonstrates the full Paperclip plugin surface area in one package",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"paperclipPlugin": {
|
||||
"manifest": "./dist/manifest.js",
|
||||
"worker": "./dist/worker.js",
|
||||
"ui": "./dist/ui/"
|
||||
},
|
||||
"scripts": {
|
||||
"prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
|
||||
"build": "tsc && node ./scripts/build-ui.mjs",
|
||||
"clean": "rm -rf dist",
|
||||
"typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@paperclipai/plugin-sdk": "workspace:*",
|
||||
"@paperclipai/shared": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "^0.28.1",
|
||||
"@types/node": "^22.19.21",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"typescript": "^5.7.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import esbuild from "esbuild";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const packageRoot = path.resolve(__dirname, "..");
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [path.join(packageRoot, "src/ui/index.tsx")],
|
||||
outfile: path.join(packageRoot, "dist/ui/index.js"),
|
||||
bundle: true,
|
||||
format: "esm",
|
||||
platform: "browser",
|
||||
target: ["es2022"],
|
||||
sourcemap: true,
|
||||
external: [
|
||||
"react",
|
||||
"react-dom",
|
||||
"react/jsx-runtime",
|
||||
"@paperclipai/plugin-sdk/ui",
|
||||
],
|
||||
logLevel: "info",
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { PluginLauncherRegistration } from "@paperclipai/plugin-sdk";
|
||||
|
||||
export const PLUGIN_ID = "paperclip-kitchen-sink-example";
|
||||
export const PLUGIN_VERSION = "0.1.0";
|
||||
export const PAGE_ROUTE = "kitchensink";
|
||||
|
||||
export const SLOT_IDS = {
|
||||
page: "kitchen-sink-page",
|
||||
settingsPage: "kitchen-sink-settings-page",
|
||||
companySettingsPage: "kitchen-sink-company-settings-page",
|
||||
dashboardWidget: "kitchen-sink-dashboard-widget",
|
||||
sidebar: "kitchen-sink-sidebar-link",
|
||||
sidebarPanel: "kitchen-sink-sidebar-panel",
|
||||
projectSidebarItem: "kitchen-sink-project-link",
|
||||
projectTab: "kitchen-sink-project-tab",
|
||||
issueTab: "kitchen-sink-issue-tab",
|
||||
taskDetailView: "kitchen-sink-task-detail",
|
||||
toolbarButton: "kitchen-sink-toolbar-action",
|
||||
contextMenuItem: "kitchen-sink-context-action",
|
||||
commentAnnotation: "kitchen-sink-comment-annotation",
|
||||
commentContextMenuItem: "kitchen-sink-comment-action",
|
||||
} as const;
|
||||
|
||||
export const EXPORT_NAMES = {
|
||||
page: "KitchenSinkPage",
|
||||
settingsPage: "KitchenSinkSettingsPage",
|
||||
companySettingsPage: "KitchenSinkCompanySettingsPage",
|
||||
dashboardWidget: "KitchenSinkDashboardWidget",
|
||||
sidebar: "KitchenSinkSidebarLink",
|
||||
sidebarPanel: "KitchenSinkSidebarPanel",
|
||||
projectSidebarItem: "KitchenSinkProjectSidebarItem",
|
||||
projectTab: "KitchenSinkProjectTab",
|
||||
issueTab: "KitchenSinkIssueTab",
|
||||
taskDetailView: "KitchenSinkTaskDetailView",
|
||||
toolbarButton: "KitchenSinkToolbarButton",
|
||||
contextMenuItem: "KitchenSinkContextMenuItem",
|
||||
commentAnnotation: "KitchenSinkCommentAnnotation",
|
||||
commentContextMenuItem: "KitchenSinkCommentContextMenuItem",
|
||||
launcherModal: "KitchenSinkLauncherModal",
|
||||
} as const;
|
||||
|
||||
export const JOB_KEYS = {
|
||||
heartbeat: "demo-heartbeat",
|
||||
} as const;
|
||||
|
||||
export const WEBHOOK_KEYS = {
|
||||
demo: "demo-ingest",
|
||||
} as const;
|
||||
|
||||
export const TOOL_NAMES = {
|
||||
echo: "echo",
|
||||
companySummary: "company-summary",
|
||||
createIssue: "create-issue",
|
||||
} as const;
|
||||
|
||||
export const STREAM_CHANNELS = {
|
||||
progress: "progress",
|
||||
agentChat: "agent-chat",
|
||||
} as const;
|
||||
|
||||
export const SAFE_COMMANDS = [
|
||||
{
|
||||
key: "pwd",
|
||||
label: "Print workspace path",
|
||||
command: "pwd",
|
||||
args: [] as string[],
|
||||
description: "Prints the current workspace directory.",
|
||||
},
|
||||
{
|
||||
key: "ls",
|
||||
label: "List workspace files",
|
||||
command: "ls",
|
||||
args: ["-la"] as string[],
|
||||
description: "Lists files in the selected workspace.",
|
||||
},
|
||||
{
|
||||
key: "git-status",
|
||||
label: "Git status",
|
||||
command: "git",
|
||||
args: ["status", "--short", "--branch"] as string[],
|
||||
description: "Shows git status for the selected workspace.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type SafeCommandKey = (typeof SAFE_COMMANDS)[number]["key"];
|
||||
|
||||
export const DEFAULT_CONFIG = {
|
||||
showSidebarEntry: true,
|
||||
showSidebarPanel: true,
|
||||
showProjectSidebarItem: true,
|
||||
showCommentAnnotation: true,
|
||||
showCommentContextMenuItem: true,
|
||||
enableWorkspaceDemos: true,
|
||||
enableProcessDemos: false,
|
||||
secretRefExample: "",
|
||||
httpDemoUrl: "https://httpbin.org/anything",
|
||||
allowedCommands: SAFE_COMMANDS.map((command) => command.key),
|
||||
workspaceScratchFile: ".paperclip-kitchen-sink-demo.txt",
|
||||
} as const;
|
||||
|
||||
export const RUNTIME_LAUNCHER: PluginLauncherRegistration = {
|
||||
id: "kitchen-sink-runtime-launcher",
|
||||
displayName: "Kitchen Sink Modal",
|
||||
description: "Demonstrates runtime launcher registration from the worker.",
|
||||
placementZone: "toolbarButton",
|
||||
entityTypes: ["project", "issue"],
|
||||
action: {
|
||||
type: "openModal",
|
||||
target: EXPORT_NAMES.launcherModal,
|
||||
},
|
||||
render: {
|
||||
environment: "hostOverlay",
|
||||
bounds: "wide",
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as manifest } from "./manifest.js";
|
||||
export { default as worker } from "./worker.js";
|
||||
@@ -0,0 +1,298 @@
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
import {
|
||||
DEFAULT_CONFIG,
|
||||
EXPORT_NAMES,
|
||||
JOB_KEYS,
|
||||
PAGE_ROUTE,
|
||||
PLUGIN_ID,
|
||||
PLUGIN_VERSION,
|
||||
SLOT_IDS,
|
||||
TOOL_NAMES,
|
||||
WEBHOOK_KEYS,
|
||||
} from "./constants.js";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: PLUGIN_ID,
|
||||
apiVersion: 1,
|
||||
version: PLUGIN_VERSION,
|
||||
displayName: "Kitchen Sink (Example)",
|
||||
description: "Reference plugin that demonstrates the current Paperclip plugin API surface, UI surfaces, bridge actions, events, jobs, webhooks, tools, local workspace access, and runtime diagnostics in one place.",
|
||||
author: "Paperclip",
|
||||
categories: ["ui", "automation", "workspace", "connector"],
|
||||
capabilities: [
|
||||
"companies.read",
|
||||
"projects.read",
|
||||
"project.workspaces.read",
|
||||
"issues.read",
|
||||
"issues.create",
|
||||
"issues.update",
|
||||
"issue.comments.read",
|
||||
"issue.comments.create",
|
||||
"agents.read",
|
||||
"agents.pause",
|
||||
"agents.resume",
|
||||
"agents.invoke",
|
||||
"agent.sessions.create",
|
||||
"agent.sessions.list",
|
||||
"agent.sessions.send",
|
||||
"agent.sessions.close",
|
||||
"goals.read",
|
||||
"goals.create",
|
||||
"goals.update",
|
||||
"activity.log.write",
|
||||
"metrics.write",
|
||||
"telemetry.track",
|
||||
"plugin.state.read",
|
||||
"plugin.state.write",
|
||||
"events.subscribe",
|
||||
"events.emit",
|
||||
"jobs.schedule",
|
||||
"webhooks.receive",
|
||||
"http.outbound",
|
||||
"secrets.read-ref",
|
||||
"agent.tools.register",
|
||||
"instance.settings.register",
|
||||
"ui.sidebar.register",
|
||||
"ui.page.register",
|
||||
"ui.detailTab.register",
|
||||
"ui.dashboardWidget.register",
|
||||
"ui.commentAnnotation.register",
|
||||
"ui.action.register",
|
||||
],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui",
|
||||
},
|
||||
instanceConfigSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
showSidebarEntry: {
|
||||
type: "boolean",
|
||||
title: "Show Sidebar Entry",
|
||||
default: DEFAULT_CONFIG.showSidebarEntry,
|
||||
},
|
||||
showSidebarPanel: {
|
||||
type: "boolean",
|
||||
title: "Show Sidebar Panel",
|
||||
default: DEFAULT_CONFIG.showSidebarPanel,
|
||||
},
|
||||
showProjectSidebarItem: {
|
||||
type: "boolean",
|
||||
title: "Show Project Sidebar Item",
|
||||
default: DEFAULT_CONFIG.showProjectSidebarItem,
|
||||
},
|
||||
showCommentAnnotation: {
|
||||
type: "boolean",
|
||||
title: "Show Comment Annotation",
|
||||
default: DEFAULT_CONFIG.showCommentAnnotation,
|
||||
},
|
||||
showCommentContextMenuItem: {
|
||||
type: "boolean",
|
||||
title: "Show Comment Action",
|
||||
default: DEFAULT_CONFIG.showCommentContextMenuItem,
|
||||
},
|
||||
enableWorkspaceDemos: {
|
||||
type: "boolean",
|
||||
title: "Enable Workspace Demos",
|
||||
default: DEFAULT_CONFIG.enableWorkspaceDemos,
|
||||
},
|
||||
enableProcessDemos: {
|
||||
type: "boolean",
|
||||
title: "Enable Process Demos",
|
||||
default: DEFAULT_CONFIG.enableProcessDemos,
|
||||
description: "Allows curated local child-process demos in project workspaces.",
|
||||
},
|
||||
secretRefExample: {
|
||||
type: "string",
|
||||
title: "Secret Reference Example",
|
||||
default: DEFAULT_CONFIG.secretRefExample,
|
||||
},
|
||||
httpDemoUrl: {
|
||||
type: "string",
|
||||
title: "HTTP Demo URL",
|
||||
default: DEFAULT_CONFIG.httpDemoUrl,
|
||||
},
|
||||
allowedCommands: {
|
||||
type: "array",
|
||||
title: "Allowed Process Commands",
|
||||
items: {
|
||||
type: "string",
|
||||
enum: DEFAULT_CONFIG.allowedCommands,
|
||||
},
|
||||
default: DEFAULT_CONFIG.allowedCommands,
|
||||
},
|
||||
workspaceScratchFile: {
|
||||
type: "string",
|
||||
title: "Workspace Scratch File",
|
||||
default: DEFAULT_CONFIG.workspaceScratchFile,
|
||||
},
|
||||
},
|
||||
},
|
||||
jobs: [
|
||||
{
|
||||
jobKey: JOB_KEYS.heartbeat,
|
||||
displayName: "Demo Heartbeat",
|
||||
description: "Periodic demo job that records plugin runtime activity.",
|
||||
schedule: "*/15 * * * *",
|
||||
},
|
||||
],
|
||||
webhooks: [
|
||||
{
|
||||
endpointKey: WEBHOOK_KEYS.demo,
|
||||
displayName: "Demo Ingest",
|
||||
description: "Accepts arbitrary webhook payloads and records the latest delivery in plugin state.",
|
||||
},
|
||||
],
|
||||
tools: [
|
||||
{
|
||||
name: TOOL_NAMES.echo,
|
||||
displayName: "Kitchen Sink Echo",
|
||||
description: "Returns the provided message and the current run context.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message: { type: "string" },
|
||||
},
|
||||
required: ["message"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: TOOL_NAMES.companySummary,
|
||||
displayName: "Kitchen Sink Company Summary",
|
||||
description: "Summarizes the current company using the Paperclip domain APIs.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: TOOL_NAMES.createIssue,
|
||||
displayName: "Kitchen Sink Create Issue",
|
||||
description: "Creates an issue in the current project from an agent tool call.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string" },
|
||||
description: { type: "string" },
|
||||
},
|
||||
required: ["title"],
|
||||
},
|
||||
},
|
||||
],
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "page",
|
||||
id: SLOT_IDS.page,
|
||||
displayName: "Kitchen Sink",
|
||||
exportName: EXPORT_NAMES.page,
|
||||
routePath: PAGE_ROUTE,
|
||||
},
|
||||
{
|
||||
type: "settingsPage",
|
||||
id: SLOT_IDS.settingsPage,
|
||||
displayName: "Kitchen Sink Settings",
|
||||
exportName: EXPORT_NAMES.settingsPage,
|
||||
},
|
||||
{
|
||||
type: "companySettingsPage",
|
||||
id: SLOT_IDS.companySettingsPage,
|
||||
displayName: "Kitchen Sink",
|
||||
exportName: EXPORT_NAMES.companySettingsPage,
|
||||
routePath: "kitchen-sink",
|
||||
},
|
||||
{
|
||||
type: "dashboardWidget",
|
||||
id: SLOT_IDS.dashboardWidget,
|
||||
displayName: "Kitchen Sink",
|
||||
exportName: EXPORT_NAMES.dashboardWidget,
|
||||
},
|
||||
{
|
||||
type: "sidebar",
|
||||
id: SLOT_IDS.sidebar,
|
||||
displayName: "Kitchen Sink",
|
||||
exportName: EXPORT_NAMES.sidebar,
|
||||
},
|
||||
{
|
||||
type: "sidebarPanel",
|
||||
id: SLOT_IDS.sidebarPanel,
|
||||
displayName: "Kitchen Sink Panel",
|
||||
exportName: EXPORT_NAMES.sidebarPanel,
|
||||
},
|
||||
{
|
||||
type: "projectSidebarItem",
|
||||
id: SLOT_IDS.projectSidebarItem,
|
||||
displayName: "Kitchen Sink",
|
||||
exportName: EXPORT_NAMES.projectSidebarItem,
|
||||
entityTypes: ["project"],
|
||||
},
|
||||
{
|
||||
type: "detailTab",
|
||||
id: SLOT_IDS.projectTab,
|
||||
displayName: "Kitchen Sink",
|
||||
exportName: EXPORT_NAMES.projectTab,
|
||||
entityTypes: ["project"],
|
||||
},
|
||||
{
|
||||
type: "detailTab",
|
||||
id: SLOT_IDS.issueTab,
|
||||
displayName: "Kitchen Sink",
|
||||
exportName: EXPORT_NAMES.issueTab,
|
||||
entityTypes: ["issue"],
|
||||
},
|
||||
{
|
||||
type: "taskDetailView",
|
||||
id: SLOT_IDS.taskDetailView,
|
||||
displayName: "Kitchen Sink Task View",
|
||||
exportName: EXPORT_NAMES.taskDetailView,
|
||||
entityTypes: ["issue"],
|
||||
},
|
||||
{
|
||||
type: "toolbarButton",
|
||||
id: SLOT_IDS.toolbarButton,
|
||||
displayName: "Kitchen Sink Action",
|
||||
exportName: EXPORT_NAMES.toolbarButton,
|
||||
entityTypes: ["project", "issue"],
|
||||
},
|
||||
{
|
||||
type: "contextMenuItem",
|
||||
id: SLOT_IDS.contextMenuItem,
|
||||
displayName: "Kitchen Sink Context",
|
||||
exportName: EXPORT_NAMES.contextMenuItem,
|
||||
entityTypes: ["project", "issue"],
|
||||
},
|
||||
{
|
||||
type: "commentAnnotation",
|
||||
id: SLOT_IDS.commentAnnotation,
|
||||
displayName: "Kitchen Sink Comment Annotation",
|
||||
exportName: EXPORT_NAMES.commentAnnotation,
|
||||
entityTypes: ["comment"],
|
||||
},
|
||||
{
|
||||
type: "commentContextMenuItem",
|
||||
id: SLOT_IDS.commentContextMenuItem,
|
||||
displayName: "Kitchen Sink Comment Action",
|
||||
exportName: EXPORT_NAMES.commentContextMenuItem,
|
||||
entityTypes: ["comment"],
|
||||
},
|
||||
],
|
||||
launchers: [
|
||||
{
|
||||
id: "kitchen-sink-launcher",
|
||||
displayName: "Kitchen Sink Modal",
|
||||
placementZone: "toolbarButton",
|
||||
entityTypes: ["project", "issue"],
|
||||
action: {
|
||||
type: "openModal",
|
||||
target: EXPORT_NAMES.launcherModal,
|
||||
},
|
||||
render: {
|
||||
environment: "hostOverlay",
|
||||
bounds: "wide",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
@@ -0,0 +1,363 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
const CHARS = [" ", ".", "·", "▪", "▫", "○"] as const;
|
||||
const TARGET_FPS = 24;
|
||||
const FRAME_INTERVAL_MS = 1000 / TARGET_FPS;
|
||||
|
||||
const PAPERCLIP_SPRITES = [
|
||||
[
|
||||
" ╭────╮ ",
|
||||
" ╭╯╭──╮│ ",
|
||||
" │ │ ││ ",
|
||||
" │ │ ││ ",
|
||||
" │ │ ││ ",
|
||||
" │ │ ││ ",
|
||||
" │ ╰──╯│ ",
|
||||
" ╰─────╯ ",
|
||||
],
|
||||
[
|
||||
" ╭─────╮ ",
|
||||
" │╭──╮╰╮ ",
|
||||
" ││ │ │ ",
|
||||
" ││ │ │ ",
|
||||
" ││ │ │ ",
|
||||
" ││ │ │ ",
|
||||
" │╰──╯ │ ",
|
||||
" ╰────╯ ",
|
||||
],
|
||||
] as const;
|
||||
|
||||
type PaperclipSprite = (typeof PAPERCLIP_SPRITES)[number];
|
||||
|
||||
interface Clip {
|
||||
x: number;
|
||||
y: number;
|
||||
vx: number;
|
||||
vy: number;
|
||||
life: number;
|
||||
maxLife: number;
|
||||
drift: number;
|
||||
sprite: PaperclipSprite;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
function measureChar(container: HTMLElement): { w: number; h: number } {
|
||||
const span = document.createElement("span");
|
||||
span.textContent = "M";
|
||||
span.style.cssText =
|
||||
"position:absolute;visibility:hidden;white-space:pre;font-size:11px;font-family:monospace;line-height:1;";
|
||||
container.appendChild(span);
|
||||
const rect = span.getBoundingClientRect();
|
||||
container.removeChild(span);
|
||||
return { w: rect.width, h: rect.height };
|
||||
}
|
||||
|
||||
function spriteSize(sprite: PaperclipSprite): { width: number; height: number } {
|
||||
let width = 0;
|
||||
for (const row of sprite) width = Math.max(width, row.length);
|
||||
return { width, height: sprite.length };
|
||||
}
|
||||
|
||||
export function AsciiArtAnimation() {
|
||||
const preRef = useRef<HTMLPreElement>(null);
|
||||
const frameRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!preRef.current) return;
|
||||
const preEl: HTMLPreElement = preRef.current;
|
||||
const motionMedia = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
let isVisible = document.visibilityState !== "hidden";
|
||||
let loopActive = false;
|
||||
let lastRenderAt = 0;
|
||||
let tick = 0;
|
||||
let cols = 0;
|
||||
let rows = 0;
|
||||
let charW = 7;
|
||||
let charH = 11;
|
||||
let trail = new Float32Array(0);
|
||||
let colWave = new Float32Array(0);
|
||||
let rowWave = new Float32Array(0);
|
||||
let clipMask = new Uint16Array(0);
|
||||
let clips: Clip[] = [];
|
||||
let lastOutput = "";
|
||||
|
||||
function toGlyph(value: number): string {
|
||||
const clamped = Math.max(0, Math.min(0.999, value));
|
||||
const idx = Math.floor(clamped * CHARS.length);
|
||||
return CHARS[idx] ?? " ";
|
||||
}
|
||||
|
||||
function rebuildGrid() {
|
||||
const nextCols = Math.max(0, Math.ceil(preEl.clientWidth / Math.max(1, charW)));
|
||||
const nextRows = Math.max(0, Math.ceil(preEl.clientHeight / Math.max(1, charH)));
|
||||
if (nextCols === cols && nextRows === rows) return;
|
||||
|
||||
cols = nextCols;
|
||||
rows = nextRows;
|
||||
const cellCount = cols * rows;
|
||||
trail = new Float32Array(cellCount);
|
||||
colWave = new Float32Array(cols);
|
||||
rowWave = new Float32Array(rows);
|
||||
clipMask = new Uint16Array(cellCount);
|
||||
clips = clips.filter((clip) => {
|
||||
return (
|
||||
clip.x > -clip.width - 2 &&
|
||||
clip.x < cols + 2 &&
|
||||
clip.y > -clip.height - 2 &&
|
||||
clip.y < rows + 2
|
||||
);
|
||||
});
|
||||
lastOutput = "";
|
||||
}
|
||||
|
||||
function drawStaticFrame() {
|
||||
if (cols <= 0 || rows <= 0) {
|
||||
preEl.textContent = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const grid = Array.from({ length: rows }, () => Array.from({ length: cols }, () => " "));
|
||||
for (let r = 0; r < rows; r++) {
|
||||
for (let c = 0; c < cols; c++) {
|
||||
const ambient = (Math.sin(c * 0.11 + r * 0.04) + Math.cos(r * 0.08 - c * 0.02)) * 0.18 + 0.22;
|
||||
grid[r]![c] = toGlyph(ambient);
|
||||
}
|
||||
}
|
||||
|
||||
const gapX = 18;
|
||||
const gapY = 13;
|
||||
for (let baseRow = 1; baseRow < rows - 9; baseRow += gapY) {
|
||||
const startX = Math.floor(baseRow / gapY) % 2 === 0 ? 2 : 10;
|
||||
for (let baseCol = startX; baseCol < cols - 10; baseCol += gapX) {
|
||||
const sprite = PAPERCLIP_SPRITES[(baseCol + baseRow) % PAPERCLIP_SPRITES.length]!;
|
||||
for (let sr = 0; sr < sprite.length; sr++) {
|
||||
const line = sprite[sr]!;
|
||||
for (let sc = 0; sc < line.length; sc++) {
|
||||
const ch = line[sc] ?? " ";
|
||||
if (ch === " ") continue;
|
||||
const row = baseRow + sr;
|
||||
const col = baseCol + sc;
|
||||
if (row < 0 || row >= rows || col < 0 || col >= cols) continue;
|
||||
grid[row]![col] = ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const output = grid.map((line) => line.join("")).join("\n");
|
||||
preEl.textContent = output;
|
||||
lastOutput = output;
|
||||
}
|
||||
|
||||
function spawnClip() {
|
||||
const sprite = PAPERCLIP_SPRITES[Math.floor(Math.random() * PAPERCLIP_SPRITES.length)]!;
|
||||
const size = spriteSize(sprite);
|
||||
const edge = Math.random();
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
let vx = 0;
|
||||
let vy = 0;
|
||||
|
||||
if (edge < 0.68) {
|
||||
x = Math.random() < 0.5 ? -size.width - 1 : cols + 1;
|
||||
y = Math.random() * Math.max(1, rows - size.height);
|
||||
vx = x < 0 ? 0.04 + Math.random() * 0.05 : -(0.04 + Math.random() * 0.05);
|
||||
vy = (Math.random() - 0.5) * 0.014;
|
||||
} else {
|
||||
x = Math.random() * Math.max(1, cols - size.width);
|
||||
y = Math.random() < 0.5 ? -size.height - 1 : rows + 1;
|
||||
vx = (Math.random() - 0.5) * 0.014;
|
||||
vy = y < 0 ? 0.028 + Math.random() * 0.034 : -(0.028 + Math.random() * 0.034);
|
||||
}
|
||||
|
||||
clips.push({
|
||||
x,
|
||||
y,
|
||||
vx,
|
||||
vy,
|
||||
life: 0,
|
||||
maxLife: 260 + Math.random() * 220,
|
||||
drift: (Math.random() - 0.5) * 1.2,
|
||||
sprite,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
});
|
||||
}
|
||||
|
||||
function stampClip(clip: Clip, alpha: number) {
|
||||
const baseCol = Math.round(clip.x);
|
||||
const baseRow = Math.round(clip.y);
|
||||
for (let sr = 0; sr < clip.sprite.length; sr++) {
|
||||
const line = clip.sprite[sr]!;
|
||||
const row = baseRow + sr;
|
||||
if (row < 0 || row >= rows) continue;
|
||||
for (let sc = 0; sc < line.length; sc++) {
|
||||
const ch = line[sc] ?? " ";
|
||||
if (ch === " ") continue;
|
||||
const col = baseCol + sc;
|
||||
if (col < 0 || col >= cols) continue;
|
||||
const idx = row * cols + col;
|
||||
const stroke = ch === "│" || ch === "─" ? 0.8 : 0.92;
|
||||
trail[idx] = Math.max(trail[idx] ?? 0, alpha * stroke);
|
||||
clipMask[idx] = ch.charCodeAt(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function step(time: number) {
|
||||
if (!loopActive) return;
|
||||
frameRef.current = requestAnimationFrame(step);
|
||||
if (time - lastRenderAt < FRAME_INTERVAL_MS || cols <= 0 || rows <= 0) return;
|
||||
|
||||
const delta = Math.min(2, lastRenderAt === 0 ? 1 : (time - lastRenderAt) / 16.6667);
|
||||
lastRenderAt = time;
|
||||
tick += delta;
|
||||
|
||||
const cellCount = cols * rows;
|
||||
const targetCount = Math.max(3, Math.floor(cellCount / 2200));
|
||||
while (clips.length < targetCount) spawnClip();
|
||||
|
||||
for (let i = 0; i < trail.length; i++) trail[i] *= 0.92;
|
||||
clipMask.fill(0);
|
||||
|
||||
for (let i = clips.length - 1; i >= 0; i--) {
|
||||
const clip = clips[i]!;
|
||||
clip.life += delta;
|
||||
|
||||
const wobbleX = Math.sin((clip.y + clip.drift + tick * 0.12) * 0.09) * 0.0018;
|
||||
const wobbleY = Math.cos((clip.x - clip.drift - tick * 0.09) * 0.08) * 0.0014;
|
||||
clip.vx = (clip.vx + wobbleX) * 0.998;
|
||||
clip.vy = (clip.vy + wobbleY) * 0.998;
|
||||
|
||||
clip.x += clip.vx * delta;
|
||||
clip.y += clip.vy * delta;
|
||||
|
||||
if (
|
||||
clip.life >= clip.maxLife ||
|
||||
clip.x < -clip.width - 2 ||
|
||||
clip.x > cols + 2 ||
|
||||
clip.y < -clip.height - 2 ||
|
||||
clip.y > rows + 2
|
||||
) {
|
||||
clips.splice(i, 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
const life = clip.life / clip.maxLife;
|
||||
const alpha = life < 0.12 ? life / 0.12 : life > 0.88 ? (1 - life) / 0.12 : 1;
|
||||
stampClip(clip, alpha);
|
||||
}
|
||||
|
||||
for (let c = 0; c < cols; c++) colWave[c] = Math.sin(c * 0.08 + tick * 0.06);
|
||||
for (let r = 0; r < rows; r++) rowWave[r] = Math.cos(r * 0.1 - tick * 0.05);
|
||||
|
||||
let output = "";
|
||||
for (let r = 0; r < rows; r++) {
|
||||
for (let c = 0; c < cols; c++) {
|
||||
const idx = r * cols + c;
|
||||
const clipChar = clipMask[idx];
|
||||
if (clipChar > 0) {
|
||||
output += String.fromCharCode(clipChar);
|
||||
continue;
|
||||
}
|
||||
|
||||
const ambient = 0.2 + colWave[c]! * 0.08 + rowWave[r]! * 0.06 + Math.sin((c + r) * 0.1 + tick * 0.035) * 0.05;
|
||||
output += toGlyph((trail[idx] ?? 0) + ambient);
|
||||
}
|
||||
if (r < rows - 1) output += "\n";
|
||||
}
|
||||
|
||||
if (output !== lastOutput) {
|
||||
preEl.textContent = output;
|
||||
lastOutput = output;
|
||||
}
|
||||
}
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
const measured = measureChar(preEl);
|
||||
charW = measured.w || 7;
|
||||
charH = measured.h || 11;
|
||||
rebuildGrid();
|
||||
if (motionMedia.matches || !isVisible) {
|
||||
drawStaticFrame();
|
||||
}
|
||||
});
|
||||
|
||||
function startLoop() {
|
||||
if (loopActive) return;
|
||||
loopActive = true;
|
||||
lastRenderAt = 0;
|
||||
frameRef.current = requestAnimationFrame(step);
|
||||
}
|
||||
|
||||
function stopLoop() {
|
||||
loopActive = false;
|
||||
if (frameRef.current !== null) {
|
||||
cancelAnimationFrame(frameRef.current);
|
||||
frameRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
function syncMode() {
|
||||
if (motionMedia.matches || !isVisible) {
|
||||
stopLoop();
|
||||
drawStaticFrame();
|
||||
} else {
|
||||
startLoop();
|
||||
}
|
||||
}
|
||||
|
||||
function handleVisibility() {
|
||||
isVisible = document.visibilityState !== "hidden";
|
||||
syncMode();
|
||||
}
|
||||
|
||||
const measured = measureChar(preEl);
|
||||
charW = measured.w || 7;
|
||||
charH = measured.h || 11;
|
||||
rebuildGrid();
|
||||
resizeObserver.observe(preEl);
|
||||
motionMedia.addEventListener("change", syncMode);
|
||||
document.addEventListener("visibilitychange", handleVisibility);
|
||||
syncMode();
|
||||
|
||||
return () => {
|
||||
stopLoop();
|
||||
resizeObserver.disconnect();
|
||||
motionMedia.removeEventListener("change", syncMode);
|
||||
document.removeEventListener("visibilitychange", handleVisibility);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
height: "320px",
|
||||
minHeight: "320px",
|
||||
maxHeight: "350px",
|
||||
background: "#1d1d1d",
|
||||
color: "#f2efe6",
|
||||
overflow: "hidden",
|
||||
borderRadius: "12px",
|
||||
border: "1px solid color-mix(in srgb, var(--border) 75%, transparent)",
|
||||
}}
|
||||
>
|
||||
<pre
|
||||
ref={preRef}
|
||||
aria-hidden="true"
|
||||
style={{
|
||||
margin: 0,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
padding: "14px",
|
||||
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, monospace",
|
||||
fontSize: "11px",
|
||||
lineHeight: 1,
|
||||
whiteSpace: "pre",
|
||||
userSelect: "none",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
dist
|
||||
node_modules
|
||||
.paperclip-sdk
|
||||
@@ -0,0 +1,48 @@
|
||||
# Plugin Orchestration Smoke Example
|
||||
|
||||
This first-party example validates the orchestration-grade plugin host surface.
|
||||
It is intentionally small and exists as an acceptance fixture rather than a
|
||||
product plugin.
|
||||
|
||||
## What it exercises
|
||||
|
||||
- `apiRoutes` under `/api/plugins/:pluginId/api/*`
|
||||
- restricted database migrations and runtime `ctx.db`
|
||||
- plugin-owned rows joined to `public.issues`
|
||||
- plugin-created child issues with namespaced origin metadata
|
||||
- billing codes, workspace inheritance, blocker relations, documents, wakeups,
|
||||
and orchestration summaries
|
||||
- issue detail and settings UI slots that surface route, capability, namespace,
|
||||
and smoke status
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm typecheck
|
||||
pnpm test
|
||||
pnpm build
|
||||
```
|
||||
|
||||
## Install Into Paperclip
|
||||
|
||||
Use an absolute local path during development:
|
||||
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:3100/api/plugins/install \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"packageName":"/absolute/path/to/paperclip/packages/plugins/examples/plugin-orchestration-smoke-example","isLocalPath":true}'
|
||||
```
|
||||
|
||||
## Scoped Route Smoke
|
||||
|
||||
After the plugin is ready, run the scoped route against an existing issue:
|
||||
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:3100/api/plugins/paperclipai.plugin-orchestration-smoke-example/api/issues/<issue-id>/smoke \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"assigneeAgentId":"<agent-id>"}'
|
||||
```
|
||||
|
||||
The route returns the generated child issue, resolved blocker, billing code,
|
||||
subtree ids, and wakeup result.
|
||||
@@ -0,0 +1,17 @@
|
||||
import esbuild from "esbuild";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
const watch = process.argv.includes("--watch");
|
||||
|
||||
const workerCtx = await esbuild.context(presets.esbuild.worker);
|
||||
const manifestCtx = await esbuild.context(presets.esbuild.manifest);
|
||||
const uiCtx = await esbuild.context(presets.esbuild.ui);
|
||||
|
||||
if (watch) {
|
||||
await Promise.all([workerCtx.watch(), manifestCtx.watch(), uiCtx.watch()]);
|
||||
console.log("esbuild watch mode enabled for worker, manifest, and ui");
|
||||
} else {
|
||||
await Promise.all([workerCtx.rebuild(), manifestCtx.rebuild(), uiCtx.rebuild()]);
|
||||
await Promise.all([workerCtx.dispose(), manifestCtx.dispose(), uiCtx.dispose()]);
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE plugin_orchestration_smoke_1e8c264c64.smoke_runs (
|
||||
id uuid PRIMARY KEY,
|
||||
root_issue_id uuid NOT NULL REFERENCES public.issues(id) ON DELETE CASCADE,
|
||||
child_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
blocker_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
billing_code text NOT NULL,
|
||||
last_summary jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-orchestration-smoke-example",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"description": "First-party smoke plugin for orchestration-grade Paperclip plugin APIs",
|
||||
"scripts": {
|
||||
"prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
|
||||
"build": "node ./esbuild.config.mjs",
|
||||
"build:rollup": "rollup -c",
|
||||
"dev": "node ./esbuild.config.mjs --watch",
|
||||
"dev:ui": "paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177",
|
||||
"test": "vitest run --config ./vitest.config.ts",
|
||||
"typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit"
|
||||
},
|
||||
"paperclipPlugin": {
|
||||
"manifest": "./dist/manifest.js",
|
||||
"worker": "./dist/worker.js",
|
||||
"ui": "./dist/ui/"
|
||||
},
|
||||
"keywords": [
|
||||
"paperclip",
|
||||
"plugin",
|
||||
"connector"
|
||||
],
|
||||
"author": "Paperclip",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@paperclipai/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@paperclipai/shared": "workspace:*",
|
||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"@types/node": "^22.19.21",
|
||||
"@types/react": "^19.2.17",
|
||||
"esbuild": "^0.28.1",
|
||||
"rollup": "^4.62.2",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.1.8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
|
||||
function withPlugins(config) {
|
||||
if (!config) return null;
|
||||
return {
|
||||
...config,
|
||||
plugins: [
|
||||
nodeResolve({
|
||||
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"],
|
||||
}),
|
||||
typescript({
|
||||
tsconfig: "./tsconfig.json",
|
||||
declaration: false,
|
||||
declarationMap: false,
|
||||
}),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export default [
|
||||
withPlugins(presets.rollup.manifest),
|
||||
withPlugins(presets.rollup.worker),
|
||||
withPlugins(presets.rollup.ui),
|
||||
].filter(Boolean);
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: "paperclipai.plugin-orchestration-smoke-example",
|
||||
apiVersion: 1,
|
||||
version: "0.1.0",
|
||||
displayName: "Plugin Orchestration Smoke Example",
|
||||
description: "First-party smoke plugin that exercises Paperclip orchestration-grade plugin APIs.",
|
||||
author: "Paperclip",
|
||||
categories: ["automation", "ui"],
|
||||
capabilities: [
|
||||
"api.routes.register",
|
||||
"database.namespace.migrate",
|
||||
"database.namespace.read",
|
||||
"database.namespace.write",
|
||||
"issues.read",
|
||||
"issues.create",
|
||||
"issues.wakeup",
|
||||
"issue.relations.read",
|
||||
"issue.relations.write",
|
||||
"issue.documents.read",
|
||||
"issue.documents.write",
|
||||
"issue.subtree.read",
|
||||
"issues.orchestration.read",
|
||||
"ui.dashboardWidget.register",
|
||||
"ui.detailTab.register",
|
||||
"instance.settings.register"
|
||||
],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui"
|
||||
},
|
||||
database: {
|
||||
namespaceSlug: "orchestration_smoke",
|
||||
migrationsDir: "migrations",
|
||||
coreReadTables: ["issues"]
|
||||
},
|
||||
apiRoutes: [
|
||||
{
|
||||
routeKey: "initialize",
|
||||
method: "POST",
|
||||
path: "/issues/:issueId/smoke",
|
||||
auth: "board-or-agent",
|
||||
capability: "api.routes.register",
|
||||
checkoutPolicy: "required-for-agent-in-progress",
|
||||
companyResolution: { from: "issue", param: "issueId" }
|
||||
},
|
||||
{
|
||||
routeKey: "summary",
|
||||
method: "GET",
|
||||
path: "/issues/:issueId/smoke",
|
||||
auth: "board-or-agent",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "issue", param: "issueId" }
|
||||
}
|
||||
],
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "dashboardWidget",
|
||||
id: "health-widget",
|
||||
displayName: "Orchestration Smoke Health",
|
||||
exportName: "DashboardWidget"
|
||||
},
|
||||
{
|
||||
type: "taskDetailView",
|
||||
id: "issue-panel",
|
||||
displayName: "Orchestration Smoke",
|
||||
exportName: "IssuePanel",
|
||||
entityTypes: ["issue"]
|
||||
},
|
||||
{
|
||||
type: "settingsPage",
|
||||
id: "settings",
|
||||
displayName: "Orchestration Smoke",
|
||||
exportName: "SettingsPage"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
usePluginAction,
|
||||
usePluginData,
|
||||
type PluginDetailTabProps,
|
||||
type PluginSettingsPageProps,
|
||||
type PluginWidgetProps,
|
||||
} from "@paperclipai/plugin-sdk/ui";
|
||||
import type React from "react";
|
||||
|
||||
type SurfaceStatus = {
|
||||
status: "ok" | "degraded" | "error";
|
||||
checkedAt: string;
|
||||
databaseNamespace: string;
|
||||
routeKeys: string[];
|
||||
capabilities: string[];
|
||||
summary: null | {
|
||||
rootIssueId: string;
|
||||
childIssueId: string | null;
|
||||
blockerIssueId: string | null;
|
||||
billingCode: string;
|
||||
subtreeIssueIds: string[];
|
||||
wakeupQueued: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
const panelStyle = {
|
||||
display: "grid",
|
||||
gap: 10,
|
||||
fontSize: 13,
|
||||
lineHeight: 1.45,
|
||||
} satisfies React.CSSProperties;
|
||||
|
||||
const rowStyle = {
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
gap: 12,
|
||||
} satisfies React.CSSProperties;
|
||||
|
||||
const buttonStyle = {
|
||||
border: "1px solid #1f2937",
|
||||
background: "#111827",
|
||||
color: "#fff",
|
||||
borderRadius: 6,
|
||||
padding: "6px 10px",
|
||||
font: "inherit",
|
||||
cursor: "pointer",
|
||||
} satisfies React.CSSProperties;
|
||||
|
||||
function SurfaceRows({ data }: { data: SurfaceStatus }) {
|
||||
return (
|
||||
<div style={{ display: "grid", gap: 6 }}>
|
||||
<div style={rowStyle}><span>Status</span><strong>{data.status}</strong></div>
|
||||
<div style={rowStyle}><span>Namespace</span><code>{data.databaseNamespace}</code></div>
|
||||
<div style={rowStyle}><span>Routes</span><code>{data.routeKeys.join(", ")}</code></div>
|
||||
<div style={rowStyle}><span>Capabilities</span><strong>{data.capabilities.length}</strong></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DashboardWidget({ context }: PluginWidgetProps) {
|
||||
const { data, loading, error } = usePluginData<SurfaceStatus>("surface-status", {
|
||||
companyId: context.companyId,
|
||||
});
|
||||
|
||||
if (loading) return <div>Loading orchestration smoke status...</div>;
|
||||
if (error) return <div>Orchestration smoke error: {error.message}</div>;
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<div style={panelStyle}>
|
||||
<strong>Orchestration Smoke</strong>
|
||||
<SurfaceRows data={data} />
|
||||
<div>Checked {data.checkedAt}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function IssuePanel({ context }: PluginDetailTabProps) {
|
||||
const { data, loading, error, refresh } = usePluginData<SurfaceStatus>("surface-status", {
|
||||
companyId: context.companyId,
|
||||
issueId: context.entityId,
|
||||
});
|
||||
const initialize = usePluginAction("initialize-smoke");
|
||||
|
||||
if (loading) return <div>Loading orchestration smoke...</div>;
|
||||
if (error) return <div>Orchestration smoke error: {error.message}</div>;
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<div style={panelStyle}>
|
||||
<div style={rowStyle}>
|
||||
<strong>Orchestration Smoke</strong>
|
||||
<button
|
||||
style={buttonStyle}
|
||||
onClick={async () => {
|
||||
await initialize({ companyId: context.companyId, issueId: context.entityId });
|
||||
refresh();
|
||||
}}
|
||||
>
|
||||
Run Smoke
|
||||
</button>
|
||||
</div>
|
||||
<SurfaceRows data={data} />
|
||||
{data.summary ? (
|
||||
<div style={{ display: "grid", gap: 4 }}>
|
||||
<div style={rowStyle}><span>Child</span><code>{data.summary.childIssueId ?? "none"}</code></div>
|
||||
<div style={rowStyle}><span>Blocker</span><code>{data.summary.blockerIssueId ?? "none"}</code></div>
|
||||
<div style={rowStyle}><span>Billing</span><code>{data.summary.billingCode}</code></div>
|
||||
<div style={rowStyle}><span>Subtree</span><strong>{data.summary.subtreeIssueIds.length}</strong></div>
|
||||
<div style={rowStyle}><span>Wakeup</span><strong>{data.summary.wakeupQueued ? "queued" : "not queued"}</strong></div>
|
||||
</div>
|
||||
) : (
|
||||
<div>No smoke run recorded for this issue.</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsPage({ context }: PluginSettingsPageProps) {
|
||||
const { data, loading, error } = usePluginData<SurfaceStatus>("surface-status", {
|
||||
companyId: context.companyId,
|
||||
});
|
||||
|
||||
if (loading) return <div>Loading orchestration smoke settings...</div>;
|
||||
if (error) return <div>Orchestration smoke settings error: {error.message}</div>;
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<div style={panelStyle}>
|
||||
<strong>Orchestration Smoke Surface</strong>
|
||||
<SurfaceRows data={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { definePlugin, runWorker, type PluginApiRequestInput } from "@paperclipai/plugin-sdk";
|
||||
|
||||
type SmokeInput = {
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
assigneeAgentId?: string | null;
|
||||
actorAgentId?: string | null;
|
||||
actorUserId?: string | null;
|
||||
actorRunId?: string | null;
|
||||
};
|
||||
|
||||
type SmokeSummary = {
|
||||
rootIssueId: string;
|
||||
childIssueId: string | null;
|
||||
blockerIssueId: string | null;
|
||||
billingCode: string;
|
||||
joinedRows: unknown[];
|
||||
subtreeIssueIds: string[];
|
||||
wakeupQueued: boolean;
|
||||
};
|
||||
|
||||
let readSmokeSummary: ((companyId: string, issueId: string) => Promise<SmokeSummary | null>) | null = null;
|
||||
let initializeSmoke: ((input: SmokeInput) => Promise<SmokeSummary>) | null = null;
|
||||
|
||||
function tableName(namespace: string) {
|
||||
return `${namespace}.smoke_runs`;
|
||||
}
|
||||
|
||||
function stringField(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
const plugin = definePlugin({
|
||||
async setup(ctx) {
|
||||
readSmokeSummary = async function readSummary(companyId: string, issueId: string): Promise<SmokeSummary | null> {
|
||||
const rows = await ctx.db.query<{
|
||||
root_issue_id: string;
|
||||
child_issue_id: string | null;
|
||||
blocker_issue_id: string | null;
|
||||
billing_code: string;
|
||||
issue_title: string;
|
||||
last_summary: unknown;
|
||||
}>(
|
||||
`SELECT s.root_issue_id, s.child_issue_id, s.blocker_issue_id, s.billing_code, i.title AS issue_title, s.last_summary
|
||||
FROM ${tableName(ctx.db.namespace)} s
|
||||
JOIN public.issues i ON i.id = s.root_issue_id
|
||||
WHERE s.root_issue_id = $1`,
|
||||
[issueId],
|
||||
);
|
||||
const row = rows[0];
|
||||
if (!row) return null;
|
||||
const orchestration = await ctx.issues.summaries.getOrchestration({
|
||||
issueId,
|
||||
companyId,
|
||||
includeSubtree: true,
|
||||
billingCode: row.billing_code,
|
||||
});
|
||||
return {
|
||||
rootIssueId: row.root_issue_id,
|
||||
childIssueId: row.child_issue_id,
|
||||
blockerIssueId: row.blocker_issue_id,
|
||||
billingCode: row.billing_code,
|
||||
joinedRows: rows,
|
||||
subtreeIssueIds: orchestration.subtreeIssueIds,
|
||||
wakeupQueued: Boolean((row.last_summary as { wakeupQueued?: unknown } | null)?.wakeupQueued),
|
||||
};
|
||||
};
|
||||
|
||||
initializeSmoke = async function runSmoke(input: SmokeInput): Promise<SmokeSummary> {
|
||||
const root = await ctx.issues.get(input.issueId, input.companyId);
|
||||
if (!root) throw new Error(`Issue not found: ${input.issueId}`);
|
||||
|
||||
const billingCode = `plugin-smoke:${input.issueId}`;
|
||||
const actor = {
|
||||
actorAgentId: input.actorAgentId ?? null,
|
||||
actorUserId: input.actorUserId ?? null,
|
||||
actorRunId: input.actorRunId ?? null,
|
||||
};
|
||||
const blocker = await ctx.issues.create({
|
||||
companyId: input.companyId,
|
||||
parentId: input.issueId,
|
||||
inheritExecutionWorkspaceFromIssueId: input.issueId,
|
||||
title: "Orchestration smoke blocker",
|
||||
description: "Resolved blocker used to verify plugin relation writes without preventing the smoke wakeup.",
|
||||
status: "done",
|
||||
priority: "low",
|
||||
billingCode,
|
||||
originKind: `plugin:${ctx.manifest.id}:blocker`,
|
||||
originId: `${input.issueId}:blocker`,
|
||||
actor,
|
||||
});
|
||||
|
||||
const child = await ctx.issues.create({
|
||||
companyId: input.companyId,
|
||||
parentId: input.issueId,
|
||||
inheritExecutionWorkspaceFromIssueId: input.issueId,
|
||||
title: "Orchestration smoke child",
|
||||
description: "Generated by the orchestration smoke plugin to verify issue, document, relation, wakeup, and summary APIs.",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: input.assigneeAgentId ?? root.assigneeAgentId ?? undefined,
|
||||
billingCode,
|
||||
originKind: `plugin:${ctx.manifest.id}:child`,
|
||||
originId: `${input.issueId}:child`,
|
||||
blockedByIssueIds: [blocker.id],
|
||||
actor,
|
||||
});
|
||||
|
||||
await ctx.issues.relations.setBlockedBy(child.id, [blocker.id], input.companyId, actor);
|
||||
await ctx.issues.documents.upsert({
|
||||
issueId: child.id,
|
||||
companyId: input.companyId,
|
||||
key: "orchestration-smoke",
|
||||
title: "Orchestration Smoke",
|
||||
format: "markdown",
|
||||
body: [
|
||||
"# Orchestration Smoke",
|
||||
"",
|
||||
`- Root issue: ${input.issueId}`,
|
||||
`- Child issue: ${child.id}`,
|
||||
`- Billing code: ${billingCode}`,
|
||||
].join("\n"),
|
||||
changeSummary: "Recorded orchestration smoke output",
|
||||
});
|
||||
|
||||
const wakeup = await ctx.issues.requestWakeup(child.id, input.companyId, {
|
||||
reason: "plugin:orchestration_smoke",
|
||||
contextSource: "plugin-orchestration-smoke",
|
||||
idempotencyKey: `${input.issueId}:child`,
|
||||
...actor,
|
||||
});
|
||||
const orchestration = await ctx.issues.summaries.getOrchestration({
|
||||
issueId: input.issueId,
|
||||
companyId: input.companyId,
|
||||
includeSubtree: true,
|
||||
billingCode,
|
||||
});
|
||||
const summarySnapshot = {
|
||||
childIssueId: child.id,
|
||||
blockerIssueId: blocker.id,
|
||||
wakeupQueued: wakeup.queued,
|
||||
subtreeIssueIds: orchestration.subtreeIssueIds,
|
||||
};
|
||||
|
||||
await ctx.db.execute(
|
||||
`INSERT INTO ${tableName(ctx.db.namespace)} (id, root_issue_id, child_issue_id, blocker_issue_id, billing_code, last_summary)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
child_issue_id = EXCLUDED.child_issue_id,
|
||||
blocker_issue_id = EXCLUDED.blocker_issue_id,
|
||||
billing_code = EXCLUDED.billing_code,
|
||||
last_summary = EXCLUDED.last_summary,
|
||||
updated_at = now()`,
|
||||
[
|
||||
randomUUID(),
|
||||
input.issueId,
|
||||
child.id,
|
||||
blocker.id,
|
||||
billingCode,
|
||||
JSON.stringify(summarySnapshot),
|
||||
],
|
||||
);
|
||||
|
||||
return {
|
||||
rootIssueId: input.issueId,
|
||||
childIssueId: child.id,
|
||||
blockerIssueId: blocker.id,
|
||||
billingCode,
|
||||
joinedRows: await ctx.db.query(
|
||||
`SELECT s.id, s.billing_code, i.title AS root_title
|
||||
FROM ${tableName(ctx.db.namespace)} s
|
||||
JOIN public.issues i ON i.id = s.root_issue_id
|
||||
WHERE s.root_issue_id = $1`,
|
||||
[input.issueId],
|
||||
),
|
||||
subtreeIssueIds: orchestration.subtreeIssueIds,
|
||||
wakeupQueued: wakeup.queued,
|
||||
};
|
||||
};
|
||||
|
||||
ctx.data.register("surface-status", async (params) => {
|
||||
const companyId = stringField(params.companyId);
|
||||
const issueId = stringField(params.issueId);
|
||||
return {
|
||||
status: "ok",
|
||||
checkedAt: new Date().toISOString(),
|
||||
databaseNamespace: ctx.db.namespace,
|
||||
routeKeys: (ctx.manifest.apiRoutes ?? []).map((route) => route.routeKey),
|
||||
capabilities: ctx.manifest.capabilities,
|
||||
summary: companyId && issueId ? await readSmokeSummary?.(companyId, issueId) ?? null : null,
|
||||
};
|
||||
});
|
||||
|
||||
ctx.actions.register("initialize-smoke", async (params) => {
|
||||
const companyId = stringField(params.companyId);
|
||||
const issueId = stringField(params.issueId);
|
||||
if (!companyId || !issueId) throw new Error("companyId and issueId are required");
|
||||
if (!initializeSmoke) throw new Error("Smoke initializer is not ready");
|
||||
return initializeSmoke({
|
||||
companyId,
|
||||
issueId,
|
||||
assigneeAgentId: stringField(params.assigneeAgentId),
|
||||
actorAgentId: stringField(params.actorAgentId),
|
||||
actorUserId: stringField(params.actorUserId),
|
||||
actorRunId: stringField(params.actorRunId),
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
async onApiRequest(input: PluginApiRequestInput) {
|
||||
if (input.routeKey === "summary") {
|
||||
const issueId = input.params.issueId;
|
||||
return {
|
||||
body: await readSmokeSummary?.(input.companyId, issueId) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.routeKey === "initialize") {
|
||||
if (!initializeSmoke) throw new Error("Smoke initializer is not ready");
|
||||
const body = input.body as Record<string, unknown> | null;
|
||||
return {
|
||||
status: 201,
|
||||
body: await initializeSmoke({
|
||||
companyId: input.companyId,
|
||||
issueId: input.params.issueId,
|
||||
assigneeAgentId: stringField(body?.assigneeAgentId),
|
||||
actorAgentId: input.actor.agentId ?? null,
|
||||
actorUserId: input.actor.userId ?? null,
|
||||
actorRunId: input.actor.runId ?? null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 404,
|
||||
body: { error: `Unknown orchestration smoke route: ${input.routeKey}` },
|
||||
};
|
||||
},
|
||||
|
||||
async onHealth() {
|
||||
return {
|
||||
status: "ok",
|
||||
message: "Orchestration smoke plugin worker is running",
|
||||
details: {
|
||||
surfaces: ["database", "scoped-api-route", "issue-panel", "orchestration-apis"],
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
runWorker(plugin, import.meta.url);
|
||||
@@ -0,0 +1,162 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { pluginManifestV1Schema, type Issue } from "@paperclipai/shared";
|
||||
import { createTestHarness } from "@paperclipai/plugin-sdk/testing";
|
||||
import manifest from "../src/manifest.js";
|
||||
import plugin from "../src/worker.js";
|
||||
|
||||
function issue(input: Partial<Issue> & Pick<Issue, "id" | "companyId" | "title">): Issue {
|
||||
const now = new Date();
|
||||
const { id, companyId, title, ...rest } = input;
|
||||
return {
|
||||
id,
|
||||
companyId,
|
||||
projectId: null,
|
||||
projectWorkspaceId: null,
|
||||
goalId: null,
|
||||
parentId: null,
|
||||
title,
|
||||
description: null,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
checkoutRunId: null,
|
||||
executionRunId: null,
|
||||
executionAgentNameKey: null,
|
||||
executionLockedAt: null,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
issueNumber: null,
|
||||
identifier: null,
|
||||
originKind: "manual",
|
||||
originId: null,
|
||||
originRunId: null,
|
||||
requestDepth: 0,
|
||||
billingCode: null,
|
||||
assigneeAdapterOverrides: null,
|
||||
executionWorkspaceId: null,
|
||||
executionWorkspacePreference: null,
|
||||
executionWorkspaceSettings: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
cancelledAt: null,
|
||||
hiddenAt: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
|
||||
describe("orchestration smoke plugin", () => {
|
||||
it("declares the Phase 1 orchestration surfaces", () => {
|
||||
expect(pluginManifestV1Schema.parse(manifest)).toMatchObject({
|
||||
id: "paperclipai.plugin-orchestration-smoke-example",
|
||||
database: {
|
||||
migrationsDir: "migrations",
|
||||
coreReadTables: ["issues"],
|
||||
},
|
||||
apiRoutes: [
|
||||
expect.objectContaining({ routeKey: "initialize" }),
|
||||
expect.objectContaining({ routeKey: "summary" }),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("creates plugin-owned orchestration rows, issue tree, document, wakeup, and summary reads", async () => {
|
||||
const companyId = randomUUID();
|
||||
const rootIssueId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
const harness = createTestHarness({ manifest });
|
||||
harness.seed({
|
||||
issues: [
|
||||
issue({
|
||||
id: rootIssueId,
|
||||
companyId,
|
||||
title: "Root orchestration issue",
|
||||
assigneeAgentId: agentId,
|
||||
}),
|
||||
],
|
||||
});
|
||||
await plugin.definition.setup(harness.ctx);
|
||||
|
||||
const result = await harness.performAction<{
|
||||
rootIssueId: string;
|
||||
childIssueId: string;
|
||||
blockerIssueId: string;
|
||||
billingCode: string;
|
||||
subtreeIssueIds: string[];
|
||||
wakeupQueued: boolean;
|
||||
}>("initialize-smoke", {
|
||||
companyId,
|
||||
issueId: rootIssueId,
|
||||
assigneeAgentId: agentId,
|
||||
});
|
||||
|
||||
expect(result.rootIssueId).toBe(rootIssueId);
|
||||
expect(result.childIssueId).toEqual(expect.any(String));
|
||||
expect(result.blockerIssueId).toEqual(expect.any(String));
|
||||
expect(result.billingCode).toBe(`plugin-smoke:${rootIssueId}`);
|
||||
expect(result.wakeupQueued).toBe(true);
|
||||
expect(result.subtreeIssueIds).toEqual(expect.arrayContaining([rootIssueId, result.childIssueId]));
|
||||
expect(harness.dbExecutes[0]?.sql).toContain(".smoke_runs");
|
||||
expect(harness.dbQueries.some((entry) => entry.sql.includes("JOIN public.issues"))).toBe(true);
|
||||
|
||||
const relations = await harness.ctx.issues.relations.get(result.childIssueId, companyId);
|
||||
expect(relations.blockedBy).toEqual([
|
||||
expect.objectContaining({
|
||||
id: result.blockerIssueId,
|
||||
status: "done",
|
||||
}),
|
||||
]);
|
||||
const docs = await harness.ctx.issues.documents.list(result.childIssueId, companyId);
|
||||
expect(docs).toEqual([
|
||||
expect.objectContaining({
|
||||
key: "orchestration-smoke",
|
||||
title: "Orchestration Smoke",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("dispatches the scoped API route through the same smoke path", async () => {
|
||||
const companyId = randomUUID();
|
||||
const rootIssueId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
const harness = createTestHarness({ manifest });
|
||||
harness.seed({
|
||||
issues: [
|
||||
issue({
|
||||
id: rootIssueId,
|
||||
companyId,
|
||||
title: "Scoped API root",
|
||||
assigneeAgentId: agentId,
|
||||
}),
|
||||
],
|
||||
});
|
||||
await plugin.definition.setup(harness.ctx);
|
||||
|
||||
await expect(plugin.definition.onApiRequest?.({
|
||||
routeKey: "initialize",
|
||||
method: "POST",
|
||||
path: `/issues/${rootIssueId}/smoke`,
|
||||
params: { issueId: rootIssueId },
|
||||
query: {},
|
||||
body: { assigneeAgentId: agentId },
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: "board",
|
||||
userId: "board",
|
||||
agentId: null,
|
||||
runId: null,
|
||||
},
|
||||
companyId,
|
||||
headers: {},
|
||||
})).resolves.toMatchObject({
|
||||
status: 201,
|
||||
body: expect.objectContaining({
|
||||
rootIssueId,
|
||||
wakeupQueued: true,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": [
|
||||
"ES2022",
|
||||
"DOM"
|
||||
],
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "."
|
||||
},
|
||||
"include": [
|
||||
"src",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"dist",
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["tests/**/*.spec.ts"],
|
||||
environment: "node",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-fake-sandbox",
|
||||
"version": "0.1.0",
|
||||
"description": "First-party deterministic fake sandbox provider plugin for Paperclip environments",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"paperclipPlugin": {
|
||||
"manifest": "./dist/manifest.js",
|
||||
"worker": "./dist/worker.js"
|
||||
},
|
||||
"scripts": {
|
||||
"prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf dist",
|
||||
"typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit",
|
||||
"test": "vitest run --config vitest.config.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@paperclipai/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.19.21",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.1.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as manifest } from "./manifest.js";
|
||||
export { default as plugin } from "./plugin.js";
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const PLUGIN_ID = "paperclip.fake-sandbox-provider";
|
||||
const PLUGIN_VERSION = "0.1.0";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: PLUGIN_ID,
|
||||
apiVersion: 1,
|
||||
version: PLUGIN_VERSION,
|
||||
displayName: "Fake Sandbox Provider",
|
||||
description:
|
||||
"First-party deterministic sandbox provider plugin for exercising Paperclip provider-plugin integration without external infrastructure.",
|
||||
author: "Paperclip",
|
||||
categories: ["automation"],
|
||||
capabilities: ["environment.drivers.register"],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
},
|
||||
environmentDrivers: [
|
||||
{
|
||||
driverKey: "fake-plugin",
|
||||
kind: "sandbox_provider",
|
||||
displayName: "Fake Sandbox Provider",
|
||||
description:
|
||||
"Runs commands in an isolated local temporary directory while exercising the sandbox provider plugin lifecycle.",
|
||||
supportsInteractiveSetup: true,
|
||||
interactiveSetupConnectionTypes: ["ssh"],
|
||||
supportsTemplateCapture: true,
|
||||
templateRefKind: "snapshot",
|
||||
templateConfigBinding: {
|
||||
field: "snapshot",
|
||||
unsetFields: ["image"],
|
||||
},
|
||||
supportsTemplateDelete: true,
|
||||
configSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
image: {
|
||||
type: "string",
|
||||
description: "Deterministic fake image label for metadata and matching.",
|
||||
default: "fake:latest",
|
||||
},
|
||||
timeoutMs: {
|
||||
type: "number",
|
||||
description: "Command timeout in milliseconds.",
|
||||
default: 300000,
|
||||
},
|
||||
reuseLease: {
|
||||
type: "boolean",
|
||||
description: "Whether to reuse fake leases by environment id.",
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
@@ -0,0 +1,503 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
assertEnvironmentEventOrder,
|
||||
createEnvironmentTestHarness,
|
||||
} from "@paperclipai/plugin-sdk/testing";
|
||||
import manifest from "./manifest.js";
|
||||
import plugin from "./plugin.js";
|
||||
|
||||
describe("fake sandbox provider plugin", () => {
|
||||
it("runs a deterministic provider lifecycle through environment hooks", async () => {
|
||||
const definition = plugin.definition;
|
||||
const harness = createEnvironmentTestHarness({
|
||||
manifest,
|
||||
environmentDriver: {
|
||||
driverKey: "fake-plugin",
|
||||
onValidateConfig: definition.onEnvironmentValidateConfig,
|
||||
onProbe: definition.onEnvironmentProbe,
|
||||
onAcquireLease: definition.onEnvironmentAcquireLease,
|
||||
onResumeLease: definition.onEnvironmentResumeLease,
|
||||
onReleaseLease: definition.onEnvironmentReleaseLease,
|
||||
onDestroyLease: definition.onEnvironmentDestroyLease,
|
||||
onRealizeWorkspace: definition.onEnvironmentRealizeWorkspace,
|
||||
onExecute: definition.onEnvironmentExecute,
|
||||
onStartInteractiveSetup: definition.onEnvironmentStartInteractiveSetup,
|
||||
onGetInteractiveSetup: definition.onEnvironmentGetInteractiveSetup,
|
||||
onCaptureTemplate: definition.onEnvironmentCaptureTemplate,
|
||||
onCancelInteractiveSetup: definition.onEnvironmentCancelInteractiveSetup,
|
||||
onDeleteTemplate: definition.onEnvironmentDeleteTemplate,
|
||||
},
|
||||
});
|
||||
const base = {
|
||||
driverKey: "fake-plugin",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { image: "fake:test", reuseLease: false },
|
||||
};
|
||||
|
||||
const validation = await harness.validateConfig({
|
||||
driverKey: "fake-plugin",
|
||||
config: base.config,
|
||||
});
|
||||
expect(validation).toMatchObject({
|
||||
ok: true,
|
||||
normalizedConfig: { image: "fake:test", reuseLease: false },
|
||||
});
|
||||
|
||||
const probe = await harness.probe(base);
|
||||
expect(probe).toMatchObject({
|
||||
ok: true,
|
||||
metadata: { provider: "fake-plugin", image: "fake:test" },
|
||||
});
|
||||
|
||||
const lease = await harness.acquireLease({ ...base, runId: "run-1" });
|
||||
expect(lease.providerLeaseId).toContain("fake-plugin://run-1/");
|
||||
|
||||
const realized = await harness.realizeWorkspace({
|
||||
...base,
|
||||
lease,
|
||||
workspace: { mode: "isolated_workspace" },
|
||||
});
|
||||
expect(realized.cwd).toContain("paperclip-fake-sandbox-");
|
||||
|
||||
const executed = await harness.execute({
|
||||
...base,
|
||||
lease,
|
||||
command: "sh",
|
||||
args: ["-lc", "printf fake-plugin-ok"],
|
||||
cwd: realized.cwd,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
expect(executed).toMatchObject({
|
||||
exitCode: 0,
|
||||
timedOut: false,
|
||||
stdout: "fake-plugin-ok",
|
||||
});
|
||||
|
||||
const setup = await harness.startInteractiveSetup({
|
||||
...base,
|
||||
sessionId: "setup-1",
|
||||
sourceTemplateRef: "source-template-secret",
|
||||
expiresAt: "2030-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(setup).toMatchObject({
|
||||
providerLeaseId: "fake-plugin-setup://env-1/setup-1",
|
||||
status: "waiting_for_user",
|
||||
connectionSummary: {
|
||||
type: "ssh",
|
||||
hostRedacted: true,
|
||||
portRedacted: true,
|
||||
commandRedacted: true,
|
||||
},
|
||||
connectionPayload: {
|
||||
type: "ssh",
|
||||
command: "ssh sandbox@[fake-setup-host-redacted] -p [fake-port-redacted]",
|
||||
},
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
sourceTemplateRefRedacted: true,
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(setup.metadata)).not.toContain("source-template-secret");
|
||||
|
||||
const status = await harness.getInteractiveSetup({
|
||||
...base,
|
||||
providerLeaseId: setup.providerLeaseId,
|
||||
includeConnectionPayload: false,
|
||||
});
|
||||
expect(status).toMatchObject({
|
||||
status: "waiting_for_user",
|
||||
connectionPayload: null,
|
||||
});
|
||||
|
||||
const captured = await harness.captureTemplate({
|
||||
...base,
|
||||
providerLeaseId: setup.providerLeaseId,
|
||||
sourceTemplateRef: "source-template-secret",
|
||||
previousTemplateRef: "previous-template-secret",
|
||||
templateLabel: "ignored-by-fake",
|
||||
});
|
||||
expect(captured).toMatchObject({
|
||||
templateKind: "snapshot",
|
||||
templateRef: "fake-template:env-1:setup-1",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
sourceTemplateRefRedacted: true,
|
||||
previousTemplateRefRedacted: true,
|
||||
promoted: true,
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(captured.metadata)).not.toContain("source-template-secret");
|
||||
expect(JSON.stringify(captured.metadata)).not.toContain("previous-template-secret");
|
||||
|
||||
const deleted = await harness.deleteTemplate({
|
||||
...base,
|
||||
templateRef: captured.templateRef,
|
||||
templateKind: captured.templateKind,
|
||||
});
|
||||
expect(deleted).toMatchObject({
|
||||
deleted: true,
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
templateKind: "snapshot",
|
||||
},
|
||||
});
|
||||
|
||||
const cancelled = await harness.cancelInteractiveSetup({
|
||||
...base,
|
||||
providerLeaseId: "fake-plugin-setup://env-1/setup-cancel",
|
||||
reason: "timed_out",
|
||||
});
|
||||
expect(cancelled).toMatchObject({
|
||||
status: "timed_out",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
found: false,
|
||||
},
|
||||
});
|
||||
|
||||
await harness.destroyLease({
|
||||
...base,
|
||||
providerLeaseId: lease.providerLeaseId,
|
||||
});
|
||||
|
||||
assertEnvironmentEventOrder(harness.environmentEvents, [
|
||||
"validateConfig",
|
||||
"probe",
|
||||
"acquireLease",
|
||||
"realizeWorkspace",
|
||||
"execute",
|
||||
"startInteractiveSetup",
|
||||
"getInteractiveSetup",
|
||||
"captureTemplate",
|
||||
"deleteTemplate",
|
||||
"cancelInteractiveSetup",
|
||||
"destroyLease",
|
||||
]);
|
||||
});
|
||||
|
||||
it("supports deterministic interactive setup, template capture, refresh, and rollback cleanup hooks", async () => {
|
||||
const definition = plugin.definition;
|
||||
const harness = createEnvironmentTestHarness({
|
||||
manifest,
|
||||
environmentDriver: {
|
||||
driverKey: "fake-plugin",
|
||||
onStartInteractiveSetup: definition.onEnvironmentStartInteractiveSetup,
|
||||
onGetInteractiveSetup: definition.onEnvironmentGetInteractiveSetup,
|
||||
onCaptureTemplate: definition.onEnvironmentCaptureTemplate,
|
||||
onCancelInteractiveSetup: definition.onEnvironmentCancelInteractiveSetup,
|
||||
onDeleteTemplate: definition.onEnvironmentDeleteTemplate,
|
||||
},
|
||||
});
|
||||
const base = {
|
||||
driverKey: "fake-plugin",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-setup",
|
||||
config: { image: "fake:setup", reuseLease: false },
|
||||
};
|
||||
|
||||
const setup = await harness.startInteractiveSetup({
|
||||
...base,
|
||||
sessionId: "session-1",
|
||||
sourceTemplateRef: "fake-template:base",
|
||||
expiresAt: "2030-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(setup).toMatchObject({
|
||||
providerLeaseId: "fake-plugin-setup://env-setup/session-1",
|
||||
status: "waiting_for_user",
|
||||
connectionSummary: {
|
||||
type: "ssh",
|
||||
username: "sandbox",
|
||||
hostRedacted: true,
|
||||
portRedacted: true,
|
||||
commandRedacted: true,
|
||||
},
|
||||
connectionPayload: {
|
||||
type: "ssh",
|
||||
command: "ssh sandbox@[fake-setup-host-redacted] -p [fake-port-redacted]",
|
||||
},
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: "fake:setup",
|
||||
sourceTemplateRefRedacted: true,
|
||||
redactedConnectionOnly: true,
|
||||
},
|
||||
});
|
||||
|
||||
const status = await harness.getInteractiveSetup({
|
||||
...base,
|
||||
providerLeaseId: setup.providerLeaseId,
|
||||
includeConnectionPayload: false,
|
||||
});
|
||||
expect(status.connectionPayload).toBeNull();
|
||||
expect(status.status).toBe("waiting_for_user");
|
||||
|
||||
const captured = await harness.captureTemplate({
|
||||
...base,
|
||||
providerLeaseId: setup.providerLeaseId,
|
||||
sourceTemplateRef: "fake-template:base",
|
||||
previousTemplateRef: null,
|
||||
});
|
||||
expect(captured).toEqual({
|
||||
templateRef: "fake-template:env-setup:session-1",
|
||||
templateKind: "snapshot",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: "fake:setup",
|
||||
sourceTemplateRefRedacted: true,
|
||||
previousTemplateRefRedacted: false,
|
||||
setupSessionId: "session-1",
|
||||
promoted: true,
|
||||
},
|
||||
});
|
||||
|
||||
const promotedStatus = await harness.getInteractiveSetup({
|
||||
...base,
|
||||
providerLeaseId: setup.providerLeaseId,
|
||||
includeConnectionPayload: true,
|
||||
});
|
||||
expect(promotedStatus.status).toBe("promoted");
|
||||
expect(promotedStatus.connectionPayload).toBeNull();
|
||||
|
||||
const refresh = await harness.startInteractiveSetup({
|
||||
...base,
|
||||
sessionId: "session-2",
|
||||
sourceTemplateRef: captured.templateRef,
|
||||
});
|
||||
const replacement = await harness.captureTemplate({
|
||||
...base,
|
||||
providerLeaseId: refresh.providerLeaseId,
|
||||
sourceTemplateRef: captured.templateRef,
|
||||
previousTemplateRef: captured.templateRef,
|
||||
});
|
||||
expect(replacement).toMatchObject({
|
||||
templateRef: "fake-template:env-setup:session-2",
|
||||
templateKind: "snapshot",
|
||||
metadata: {
|
||||
sourceTemplateRefRedacted: true,
|
||||
previousTemplateRefRedacted: true,
|
||||
},
|
||||
});
|
||||
|
||||
await expect(harness.deleteTemplate({
|
||||
...base,
|
||||
templateRef: replacement.templateRef,
|
||||
templateKind: replacement.templateKind,
|
||||
reason: "rollback",
|
||||
})).resolves.toMatchObject({
|
||||
deleted: true,
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
templateRef: replacement.templateRef,
|
||||
templateKind: "snapshot",
|
||||
},
|
||||
});
|
||||
|
||||
const cancelSetup = await harness.startInteractiveSetup({
|
||||
...base,
|
||||
sessionId: "session-cancel",
|
||||
sourceTemplateRef: captured.templateRef,
|
||||
});
|
||||
await expect(harness.cancelInteractiveSetup({
|
||||
...base,
|
||||
providerLeaseId: cancelSetup.providerLeaseId,
|
||||
reason: "cancelled",
|
||||
})).resolves.toMatchObject({
|
||||
status: "cancelled",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
found: true,
|
||||
},
|
||||
});
|
||||
|
||||
assertEnvironmentEventOrder(harness.environmentEvents, [
|
||||
"startInteractiveSetup",
|
||||
"getInteractiveSetup",
|
||||
"captureTemplate",
|
||||
"getInteractiveSetup",
|
||||
"startInteractiveSetup",
|
||||
"captureTemplate",
|
||||
"deleteTemplate",
|
||||
"startInteractiveSetup",
|
||||
"cancelInteractiveSetup",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps fake setup and capture payloads free of real-looking secrets, hosts, and IPs", async () => {
|
||||
const definition = plugin.definition;
|
||||
const harness = createEnvironmentTestHarness({
|
||||
manifest,
|
||||
environmentDriver: {
|
||||
driverKey: "fake-plugin",
|
||||
onStartInteractiveSetup: definition.onEnvironmentStartInteractiveSetup,
|
||||
onCaptureTemplate: definition.onEnvironmentCaptureTemplate,
|
||||
},
|
||||
});
|
||||
const base = {
|
||||
driverKey: "fake-plugin",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-redaction",
|
||||
config: { image: "fake:redaction", reuseLease: false },
|
||||
};
|
||||
|
||||
const setup = await harness.startInteractiveSetup({
|
||||
...base,
|
||||
sessionId: "session-redaction",
|
||||
});
|
||||
const captured = await harness.captureTemplate({
|
||||
...base,
|
||||
providerLeaseId: setup.providerLeaseId,
|
||||
});
|
||||
const serialized = JSON.stringify({ setup, captured, events: harness.environmentEvents });
|
||||
|
||||
expect(serialized).not.toMatch(/\b(?:\d{1,3}\.){3}\d{1,3}\b/);
|
||||
expect(serialized).not.toMatch(/\blocalhost\b/i);
|
||||
expect(serialized).not.toMatch(/BEGIN [A-Z ]*PRIVATE KEY/);
|
||||
expect(serialized).not.toMatch(/(?:api[_-]?key|access[_-]?token|refresh[_-]?token|secret)[":=]/i);
|
||||
expect(serialized).toContain("[fake-setup-host-redacted]");
|
||||
expect(serialized).toContain("[fake-port-redacted]");
|
||||
});
|
||||
|
||||
it("does not expose host-only environment variables to executed commands", async () => {
|
||||
const previousSecret = process.env.PAPERCLIP_FAKE_PLUGIN_HOST_SECRET;
|
||||
process.env.PAPERCLIP_FAKE_PLUGIN_HOST_SECRET = "should-not-leak";
|
||||
try {
|
||||
const definition = plugin.definition;
|
||||
const harness = createEnvironmentTestHarness({
|
||||
manifest,
|
||||
environmentDriver: {
|
||||
driverKey: "fake-plugin",
|
||||
onAcquireLease: definition.onEnvironmentAcquireLease,
|
||||
onDestroyLease: definition.onEnvironmentDestroyLease,
|
||||
onRealizeWorkspace: definition.onEnvironmentRealizeWorkspace,
|
||||
onExecute: definition.onEnvironmentExecute,
|
||||
},
|
||||
});
|
||||
const base = {
|
||||
driverKey: "fake-plugin",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { image: "fake:test", reuseLease: false },
|
||||
};
|
||||
const lease = await harness.acquireLease({ ...base, runId: "run-1" });
|
||||
const realized = await harness.realizeWorkspace({
|
||||
...base,
|
||||
lease,
|
||||
workspace: { mode: "isolated_workspace" },
|
||||
});
|
||||
|
||||
const executed = await harness.execute({
|
||||
...base,
|
||||
lease,
|
||||
command: "sh",
|
||||
args: ["-lc", "test -z \"${PAPERCLIP_FAKE_PLUGIN_HOST_SECRET+x}\" && printf \"$EXPLICIT_ONLY\""],
|
||||
cwd: realized.cwd,
|
||||
env: { EXPLICIT_ONLY: "visible" },
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
|
||||
expect(executed).toMatchObject({
|
||||
exitCode: 0,
|
||||
timedOut: false,
|
||||
stdout: "visible",
|
||||
});
|
||||
|
||||
await harness.destroyLease({
|
||||
...base,
|
||||
providerLeaseId: lease.providerLeaseId,
|
||||
});
|
||||
} finally {
|
||||
if (previousSecret === undefined) {
|
||||
delete process.env.PAPERCLIP_FAKE_PLUGIN_HOST_SECRET;
|
||||
} else {
|
||||
process.env.PAPERCLIP_FAKE_PLUGIN_HOST_SECRET = previousSecret;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("includes /usr/local/bin in the default PATH when no PATH override is provided", async () => {
|
||||
const definition = plugin.definition;
|
||||
const harness = createEnvironmentTestHarness({
|
||||
manifest,
|
||||
environmentDriver: {
|
||||
driverKey: "fake-plugin",
|
||||
onAcquireLease: definition.onEnvironmentAcquireLease,
|
||||
onDestroyLease: definition.onEnvironmentDestroyLease,
|
||||
onRealizeWorkspace: definition.onEnvironmentRealizeWorkspace,
|
||||
onExecute: definition.onEnvironmentExecute,
|
||||
},
|
||||
});
|
||||
const base = {
|
||||
driverKey: "fake-plugin",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { image: "fake:test", reuseLease: false },
|
||||
};
|
||||
const lease = await harness.acquireLease({ ...base, runId: "run-1" });
|
||||
const realized = await harness.realizeWorkspace({
|
||||
...base,
|
||||
lease,
|
||||
workspace: { mode: "isolated_workspace" },
|
||||
});
|
||||
|
||||
const executed = await harness.execute({
|
||||
...base,
|
||||
lease,
|
||||
command: "sh",
|
||||
args: ["-lc", "printf %s \"$PATH\""],
|
||||
cwd: realized.cwd,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
|
||||
expect(executed.stdout).toContain("/usr/local/bin");
|
||||
|
||||
await harness.destroyLease({
|
||||
...base,
|
||||
providerLeaseId: lease.providerLeaseId,
|
||||
});
|
||||
});
|
||||
|
||||
it("escalates to SIGKILL after timeout if the child ignores SIGTERM", async () => {
|
||||
const definition = plugin.definition;
|
||||
const harness = createEnvironmentTestHarness({
|
||||
manifest,
|
||||
environmentDriver: {
|
||||
driverKey: "fake-plugin",
|
||||
onAcquireLease: definition.onEnvironmentAcquireLease,
|
||||
onDestroyLease: definition.onEnvironmentDestroyLease,
|
||||
onRealizeWorkspace: definition.onEnvironmentRealizeWorkspace,
|
||||
onExecute: definition.onEnvironmentExecute,
|
||||
},
|
||||
});
|
||||
const base = {
|
||||
driverKey: "fake-plugin",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { image: "fake:test", reuseLease: false },
|
||||
};
|
||||
const lease = await harness.acquireLease({ ...base, runId: "run-1" });
|
||||
const realized = await harness.realizeWorkspace({
|
||||
...base,
|
||||
lease,
|
||||
workspace: { mode: "isolated_workspace" },
|
||||
});
|
||||
|
||||
const executed = await harness.execute({
|
||||
...base,
|
||||
lease,
|
||||
command: "sh",
|
||||
args: ["-lc", "trap '' TERM; while :; do sleep 1; done"],
|
||||
cwd: realized.cwd,
|
||||
timeoutMs: 100,
|
||||
});
|
||||
|
||||
expect(executed.timedOut).toBe(true);
|
||||
expect(executed.exitCode).toBeNull();
|
||||
|
||||
await harness.destroyLease({
|
||||
...base,
|
||||
providerLeaseId: lease.providerLeaseId,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,500 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { definePlugin } from "@paperclipai/plugin-sdk";
|
||||
import type {
|
||||
PluginEnvironmentAcquireLeaseParams,
|
||||
PluginEnvironmentCancelInteractiveSetupParams,
|
||||
PluginEnvironmentCancelInteractiveSetupResult,
|
||||
PluginEnvironmentCaptureTemplateParams,
|
||||
PluginEnvironmentCaptureTemplateResult,
|
||||
PluginEnvironmentDeleteTemplateParams,
|
||||
PluginEnvironmentDeleteTemplateResult,
|
||||
PluginEnvironmentDestroyLeaseParams,
|
||||
PluginEnvironmentExecuteParams,
|
||||
PluginEnvironmentExecuteResult,
|
||||
PluginEnvironmentGetInteractiveSetupParams,
|
||||
PluginEnvironmentInteractiveSetupSession,
|
||||
PluginEnvironmentLease,
|
||||
PluginEnvironmentProbeParams,
|
||||
PluginEnvironmentProbeResult,
|
||||
PluginEnvironmentRealizeWorkspaceParams,
|
||||
PluginEnvironmentRealizeWorkspaceResult,
|
||||
PluginEnvironmentReleaseLeaseParams,
|
||||
PluginEnvironmentResumeLeaseParams,
|
||||
PluginEnvironmentStartInteractiveSetupParams,
|
||||
PluginEnvironmentValidateConfigParams,
|
||||
PluginEnvironmentValidationResult,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
|
||||
interface FakeDriverConfig {
|
||||
image: string;
|
||||
timeoutMs: number;
|
||||
reuseLease: boolean;
|
||||
}
|
||||
|
||||
interface FakeLeaseState {
|
||||
providerLeaseId: string;
|
||||
rootDir: string;
|
||||
remoteCwd: string;
|
||||
image: string;
|
||||
reuseLease: boolean;
|
||||
}
|
||||
|
||||
interface FakeSetupState {
|
||||
providerLeaseId: string;
|
||||
environmentId: string;
|
||||
sessionId: string;
|
||||
image: string;
|
||||
sourceTemplateRef: string | null;
|
||||
expiresAt: string | null;
|
||||
status: "waiting_for_user" | "capturing" | "promoted" | "cancelled" | "timed_out" | "failed";
|
||||
capturedTemplateRef: string | null;
|
||||
}
|
||||
|
||||
interface FakeTemplateState {
|
||||
templateRef: string;
|
||||
environmentId: string;
|
||||
sessionId: string;
|
||||
image: string;
|
||||
sourceTemplateRef: string | null;
|
||||
previousTemplateRef: string | null;
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
const leases = new Map<string, FakeLeaseState>();
|
||||
const setupSessions = new Map<string, FakeSetupState>();
|
||||
const templates = new Map<string, FakeTemplateState>();
|
||||
const DEFAULT_FAKE_SANDBOX_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
|
||||
const FAKE_SANDBOX_SIGKILL_GRACE_MS = 250;
|
||||
const REDACTED_FAKE_SSH_COMMAND = "ssh sandbox@[fake-setup-host-redacted] -p [fake-port-redacted]";
|
||||
|
||||
function parseConfig(raw: Record<string, unknown>): FakeDriverConfig {
|
||||
return {
|
||||
image: typeof raw.image === "string" && raw.image.trim().length > 0 ? raw.image.trim() : "fake:latest",
|
||||
timeoutMs: typeof raw.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? raw.timeoutMs : 300_000,
|
||||
reuseLease: raw.reuseLease === true,
|
||||
};
|
||||
}
|
||||
|
||||
async function createLeaseState(input: {
|
||||
providerLeaseId: string;
|
||||
image: string;
|
||||
reuseLease: boolean;
|
||||
}): Promise<FakeLeaseState> {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-fake-sandbox-"));
|
||||
const remoteCwd = path.join(rootDir, "workspace");
|
||||
await mkdir(remoteCwd, { recursive: true });
|
||||
const state = {
|
||||
providerLeaseId: input.providerLeaseId,
|
||||
rootDir,
|
||||
remoteCwd,
|
||||
image: input.image,
|
||||
reuseLease: input.reuseLease,
|
||||
};
|
||||
leases.set(input.providerLeaseId, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
function leaseMetadata(state: FakeLeaseState) {
|
||||
return {
|
||||
provider: "fake-plugin",
|
||||
image: state.image,
|
||||
reuseLease: state.reuseLease,
|
||||
remoteCwd: state.remoteCwd,
|
||||
fakeRootDir: state.rootDir,
|
||||
};
|
||||
}
|
||||
|
||||
function encodeRefPart(value: string): string {
|
||||
return encodeURIComponent(value).replace(/%/g, "_");
|
||||
}
|
||||
|
||||
function buildSetupProviderLeaseId(environmentId: string, sessionId: string): string {
|
||||
return `fake-plugin-setup://${encodeRefPart(environmentId)}/${encodeRefPart(sessionId)}`;
|
||||
}
|
||||
|
||||
function buildTemplateRef(environmentId: string, sessionId: string): string {
|
||||
return `fake-template:${encodeRefPart(environmentId)}:${encodeRefPart(sessionId)}`;
|
||||
}
|
||||
|
||||
function setupMetadata(state: FakeSetupState): Record<string, unknown> {
|
||||
return {
|
||||
provider: "fake-plugin",
|
||||
image: state.image,
|
||||
sourceTemplateRefRedacted: Boolean(state.sourceTemplateRef),
|
||||
setupSessionId: state.sessionId,
|
||||
redactedConnectionOnly: true,
|
||||
capturedTemplateRefRedacted: Boolean(state.capturedTemplateRef),
|
||||
};
|
||||
}
|
||||
|
||||
function setupConnectionSummary(): PluginEnvironmentInteractiveSetupSession["connectionSummary"] {
|
||||
return {
|
||||
type: "ssh",
|
||||
username: "sandbox",
|
||||
hostRedacted: true,
|
||||
portRedacted: true,
|
||||
commandRedacted: true,
|
||||
metadata: {
|
||||
placeholderOnly: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function setupConnectionPayload(expiresAt: string | null): PluginEnvironmentInteractiveSetupSession["connectionPayload"] {
|
||||
return {
|
||||
type: "ssh",
|
||||
command: REDACTED_FAKE_SSH_COMMAND,
|
||||
expiresAt,
|
||||
metadata: {
|
||||
placeholderOnly: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function presentSetupSession(
|
||||
state: FakeSetupState,
|
||||
options: { includeConnectionPayload: boolean },
|
||||
): PluginEnvironmentInteractiveSetupSession {
|
||||
const canConnect = state.status === "waiting_for_user";
|
||||
return {
|
||||
providerLeaseId: state.providerLeaseId,
|
||||
status: state.status,
|
||||
connectionSummary: canConnect ? setupConnectionSummary() : null,
|
||||
connectionPayload: canConnect && options.includeConnectionPayload ? setupConnectionPayload(state.expiresAt) : null,
|
||||
expiresAt: state.expiresAt,
|
||||
metadata: setupMetadata(state),
|
||||
};
|
||||
}
|
||||
|
||||
function cancelStatusFromReason(
|
||||
reason: string | null | undefined,
|
||||
): Extract<FakeSetupState["status"], "cancelled" | "timed_out" | "failed"> {
|
||||
if (reason === "timed_out") return "timed_out";
|
||||
if (reason === "failed") return "failed";
|
||||
return "cancelled";
|
||||
}
|
||||
|
||||
async function removeLease(providerLeaseId: string | null | undefined): Promise<void> {
|
||||
if (!providerLeaseId) return;
|
||||
const state = leases.get(providerLeaseId);
|
||||
leases.delete(providerLeaseId);
|
||||
if (state) {
|
||||
await rm(state.rootDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function buildCommandLine(command: string, args: string[] | undefined): string {
|
||||
return [command, ...(args ?? [])].join(" ");
|
||||
}
|
||||
|
||||
function buildCommandEnvironment(explicitEnv: Record<string, string> | undefined): Record<string, string> {
|
||||
return {
|
||||
PATH: explicitEnv?.PATH ?? DEFAULT_FAKE_SANDBOX_PATH,
|
||||
...(explicitEnv ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function runCommand(params: PluginEnvironmentExecuteParams, timeoutMs: number): Promise<PluginEnvironmentExecuteResult> {
|
||||
const cwd = typeof params.cwd === "string" && params.cwd.length > 0 ? params.cwd : process.cwd();
|
||||
const startedAt = new Date().toISOString();
|
||||
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(params.command, params.args ?? [], {
|
||||
cwd,
|
||||
env: buildCommandEnvironment(params.env),
|
||||
shell: false,
|
||||
stdio: [params.stdin != null ? "pipe" : "ignore", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let timedOut = false;
|
||||
let killTimer: NodeJS.Timeout | null = null;
|
||||
const timer = timeoutMs > 0
|
||||
? setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
killTimer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
}, FAKE_SANDBOX_SIGKILL_GRACE_MS);
|
||||
}, timeoutMs)
|
||||
: null;
|
||||
|
||||
child.stdout?.on("data", (chunk) => {
|
||||
stdout += String(chunk);
|
||||
});
|
||||
child.stderr?.on("data", (chunk) => {
|
||||
stderr += String(chunk);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
if (timer) clearTimeout(timer);
|
||||
if (killTimer) clearTimeout(killTimer);
|
||||
reject(error);
|
||||
});
|
||||
child.on("close", (code, signal) => {
|
||||
if (timer) clearTimeout(timer);
|
||||
if (killTimer) clearTimeout(killTimer);
|
||||
resolve({
|
||||
exitCode: timedOut ? null : code,
|
||||
signal,
|
||||
timedOut,
|
||||
stdout,
|
||||
stderr,
|
||||
metadata: {
|
||||
startedAt,
|
||||
commandLine: buildCommandLine(params.command, params.args),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
if (params.stdin != null && child.stdin) {
|
||||
child.stdin.write(params.stdin);
|
||||
child.stdin.end();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const plugin = definePlugin({
|
||||
async setup(ctx) {
|
||||
ctx.logger.info("Fake sandbox provider plugin ready");
|
||||
},
|
||||
|
||||
async onHealth() {
|
||||
return { status: "ok", message: "Fake sandbox provider plugin healthy" };
|
||||
},
|
||||
|
||||
async onEnvironmentValidateConfig(
|
||||
params: PluginEnvironmentValidateConfigParams,
|
||||
): Promise<PluginEnvironmentValidationResult> {
|
||||
const config = parseConfig(params.config);
|
||||
return {
|
||||
ok: true,
|
||||
normalizedConfig: { ...config },
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentProbe(
|
||||
params: PluginEnvironmentProbeParams,
|
||||
): Promise<PluginEnvironmentProbeResult> {
|
||||
const config = parseConfig(params.config);
|
||||
return {
|
||||
ok: true,
|
||||
summary: `Fake sandbox provider is ready for image ${config.image}.`,
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: config.image,
|
||||
timeoutMs: config.timeoutMs,
|
||||
reuseLease: config.reuseLease,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentAcquireLease(
|
||||
params: PluginEnvironmentAcquireLeaseParams,
|
||||
): Promise<PluginEnvironmentLease> {
|
||||
const config = parseConfig(params.config);
|
||||
const providerLeaseId = config.reuseLease
|
||||
? `fake-plugin://${params.environmentId}`
|
||||
: `fake-plugin://${params.runId}/${randomUUID()}`;
|
||||
const existing = leases.get(providerLeaseId);
|
||||
const state = existing ?? await createLeaseState({
|
||||
providerLeaseId,
|
||||
image: config.image,
|
||||
reuseLease: config.reuseLease,
|
||||
});
|
||||
|
||||
return {
|
||||
providerLeaseId,
|
||||
metadata: {
|
||||
...leaseMetadata(state),
|
||||
resumedLease: Boolean(existing),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentResumeLease(
|
||||
params: PluginEnvironmentResumeLeaseParams,
|
||||
): Promise<PluginEnvironmentLease> {
|
||||
const config = parseConfig(params.config);
|
||||
const existing = leases.get(params.providerLeaseId);
|
||||
const state = existing ?? await createLeaseState({
|
||||
providerLeaseId: params.providerLeaseId,
|
||||
image: config.image,
|
||||
reuseLease: config.reuseLease,
|
||||
});
|
||||
|
||||
return {
|
||||
providerLeaseId: state.providerLeaseId,
|
||||
metadata: {
|
||||
...leaseMetadata(state),
|
||||
resumedLease: true,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentReleaseLease(
|
||||
params: PluginEnvironmentReleaseLeaseParams,
|
||||
): Promise<void> {
|
||||
const config = parseConfig(params.config);
|
||||
if (!config.reuseLease) {
|
||||
await removeLease(params.providerLeaseId);
|
||||
}
|
||||
},
|
||||
|
||||
async onEnvironmentDestroyLease(
|
||||
params: PluginEnvironmentDestroyLeaseParams,
|
||||
): Promise<void> {
|
||||
await removeLease(params.providerLeaseId);
|
||||
},
|
||||
|
||||
async onEnvironmentRealizeWorkspace(
|
||||
params: PluginEnvironmentRealizeWorkspaceParams,
|
||||
): Promise<PluginEnvironmentRealizeWorkspaceResult> {
|
||||
const state = params.lease.providerLeaseId
|
||||
? leases.get(params.lease.providerLeaseId)
|
||||
: null;
|
||||
const remoteCwd =
|
||||
state?.remoteCwd ??
|
||||
(typeof params.lease.metadata?.remoteCwd === "string" ? params.lease.metadata.remoteCwd : null) ??
|
||||
params.workspace.remotePath ??
|
||||
params.workspace.localPath ??
|
||||
path.join(os.tmpdir(), "paperclip-fake-sandbox-workspace");
|
||||
|
||||
await mkdir(remoteCwd, { recursive: true });
|
||||
|
||||
return {
|
||||
cwd: remoteCwd,
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
remoteCwd,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentExecute(
|
||||
params: PluginEnvironmentExecuteParams,
|
||||
): Promise<PluginEnvironmentExecuteResult> {
|
||||
const config = parseConfig(params.config);
|
||||
return await runCommand(params, params.timeoutMs ?? config.timeoutMs);
|
||||
},
|
||||
|
||||
async onEnvironmentStartInteractiveSetup(
|
||||
params: PluginEnvironmentStartInteractiveSetupParams,
|
||||
): Promise<PluginEnvironmentInteractiveSetupSession> {
|
||||
const config = parseConfig(params.config);
|
||||
const providerLeaseId = buildSetupProviderLeaseId(params.environmentId, params.sessionId);
|
||||
const state = setupSessions.get(providerLeaseId) ?? {
|
||||
providerLeaseId,
|
||||
environmentId: params.environmentId,
|
||||
sessionId: params.sessionId,
|
||||
image: config.image,
|
||||
sourceTemplateRef: params.sourceTemplateRef ?? null,
|
||||
expiresAt: params.expiresAt ?? null,
|
||||
status: "waiting_for_user" as const,
|
||||
capturedTemplateRef: null,
|
||||
};
|
||||
setupSessions.set(providerLeaseId, state);
|
||||
return presentSetupSession(state, { includeConnectionPayload: true });
|
||||
},
|
||||
|
||||
async onEnvironmentGetInteractiveSetup(
|
||||
params: PluginEnvironmentGetInteractiveSetupParams,
|
||||
): Promise<PluginEnvironmentInteractiveSetupSession> {
|
||||
const state = params.providerLeaseId ? setupSessions.get(params.providerLeaseId) : undefined;
|
||||
if (!state) {
|
||||
return {
|
||||
providerLeaseId: params.providerLeaseId,
|
||||
status: "missing",
|
||||
connectionSummary: null,
|
||||
connectionPayload: null,
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
found: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
return presentSetupSession(state, { includeConnectionPayload: params.includeConnectionPayload === true });
|
||||
},
|
||||
|
||||
async onEnvironmentCaptureTemplate(
|
||||
params: PluginEnvironmentCaptureTemplateParams,
|
||||
): Promise<PluginEnvironmentCaptureTemplateResult> {
|
||||
const config = parseConfig(params.config);
|
||||
const state = params.providerLeaseId ? setupSessions.get(params.providerLeaseId) : undefined;
|
||||
if (!state) {
|
||||
throw new Error("Fake setup session not found.");
|
||||
}
|
||||
if (state.status === "cancelled" || state.status === "timed_out" || state.status === "failed") {
|
||||
throw new Error(`Fake setup session cannot be captured from status ${state.status}.`);
|
||||
}
|
||||
|
||||
state.status = "capturing";
|
||||
const templateRef = buildTemplateRef(state.environmentId, state.sessionId);
|
||||
const template: FakeTemplateState = {
|
||||
templateRef,
|
||||
environmentId: state.environmentId,
|
||||
sessionId: state.sessionId,
|
||||
image: config.image,
|
||||
sourceTemplateRef: params.sourceTemplateRef ?? state.sourceTemplateRef,
|
||||
previousTemplateRef: params.previousTemplateRef ?? null,
|
||||
deleted: false,
|
||||
};
|
||||
templates.set(templateRef, template);
|
||||
state.status = "promoted";
|
||||
state.capturedTemplateRef = templateRef;
|
||||
await removeLease(state.providerLeaseId);
|
||||
|
||||
return {
|
||||
templateRef,
|
||||
templateKind: "snapshot",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: template.image,
|
||||
sourceTemplateRefRedacted: Boolean(template.sourceTemplateRef),
|
||||
previousTemplateRefRedacted: Boolean(template.previousTemplateRef),
|
||||
setupSessionId: state.sessionId,
|
||||
promoted: true,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentCancelInteractiveSetup(
|
||||
params: PluginEnvironmentCancelInteractiveSetupParams,
|
||||
): Promise<PluginEnvironmentCancelInteractiveSetupResult> {
|
||||
const status = cancelStatusFromReason(params.reason);
|
||||
const state = params.providerLeaseId ? setupSessions.get(params.providerLeaseId) : undefined;
|
||||
if (state) {
|
||||
state.status = status;
|
||||
await removeLease(state.providerLeaseId);
|
||||
}
|
||||
return {
|
||||
status,
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
found: Boolean(state),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async onEnvironmentDeleteTemplate(
|
||||
params: PluginEnvironmentDeleteTemplateParams,
|
||||
): Promise<PluginEnvironmentDeleteTemplateResult> {
|
||||
const template = templates.get(params.templateRef);
|
||||
if (template) {
|
||||
template.deleted = true;
|
||||
}
|
||||
return {
|
||||
deleted: Boolean(template),
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
templateRef: params.templateRef,
|
||||
templateKind: params.templateKind ?? "snapshot",
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default plugin;
|
||||
@@ -0,0 +1,5 @@
|
||||
import { runWorker } from "@paperclipai/plugin-sdk";
|
||||
import plugin from "./plugin.js";
|
||||
|
||||
export default plugin;
|
||||
runWorker(plugin, import.meta.url);
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node", "vitest"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/**/*.test.ts"],
|
||||
environment: "node",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
dist
|
||||
node_modules
|
||||
.paperclip-sdk
|
||||
screenshots
|
||||
@@ -0,0 +1,160 @@
|
||||
# LLM Wiki
|
||||
|
||||
Local-file LLM Wiki plugin for source ingestion, wiki browsing, query, lint, and maintenance workflows.
|
||||
|
||||
## Scope
|
||||
|
||||
This package is the standalone home for LLM Wiki behavior. Wiki-specific routes,
|
||||
UI, prompts, tools, local-folder templates, migrations, fixtures, and tests live
|
||||
here rather than in Paperclip core.
|
||||
|
||||
The alpha surface includes:
|
||||
|
||||
- manifest-declared Wiki page, sidebar entry, and settings page
|
||||
- trusted local folder declaration for `raw/`, `wiki/`, `AGENTS.md`, `IDEA.md`, `wiki/index.md`, and `wiki/log.md`
|
||||
- plugin database namespace migration for wiki instances, sources, pages, operations, query sessions, and resource bindings
|
||||
- managed `Wiki Maintainer` agent, managed `LLM Wiki` project, and paused managed routines for wiki update processing, lint, and index refresh
|
||||
- plugin-operation issue creation using `surfaceVisibility: "plugin_operation"`
|
||||
- local source capture into `raw/` with metadata rows in the plugin DB namespace
|
||||
- opt-in company-scoped Paperclip event ingestion controls for issues, comments, and documents; event ingestion is disabled by default and routes captured raw provenance into the default space only
|
||||
- manual Paperclip project/root issue distillation and bounded backfill actions with explicit work items, operation issues, source caps, and estimated cost recording
|
||||
- Paperclip-derived distillation (cursor windows, manual `distill-now`, backfill) always writes into the default wiki space in Phase 1; non-default spaces remain on manual / raw-file ingest until per-space Paperclip ingestion profiles ship
|
||||
- Paperclip-derived distillation maintains `wiki/projects/<slug>/standup.md` as the executive current-state view for each represented project, alongside durable `wiki/projects/<slug>/index.md` knowledge pages
|
||||
- wiki page writes with plugin path validation, atomic local-folder writes, metadata/revision rows, backlink extraction, and optional stale-hash protection
|
||||
- wiki tools for search/read/write/propose patch/source/log/index/backlinks workflows
|
||||
|
||||
## Phase 5 Security Gate
|
||||
|
||||
Paperclip-derived text ingestion stays limited to issue titles/descriptions, issue comments, and issue documents.
|
||||
|
||||
- Issue attachments/assets are **metadata-only** in Phase 5.
|
||||
- Issue work products are **metadata-only** in Phase 5.
|
||||
- The wiki must not fetch `/api/assets/:id/content`, dereference work-product `url` fields, or store those capability-bearing links in source bundles/snapshots.
|
||||
|
||||
The accepted policy lives in [doc/plans/2026-05-06-llm-wiki-paperclip-asset-security-gate.md](../../../doc/plans/2026-05-06-llm-wiki-paperclip-asset-security-gate.md).
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev # watch builds
|
||||
pnpm dev:ui # local dev server with hot-reload events
|
||||
pnpm test
|
||||
```
|
||||
|
||||
From the Paperclip repo root:
|
||||
|
||||
```bash
|
||||
pnpm --filter @paperclipai/plugin-llm-wiki typecheck
|
||||
pnpm --filter @paperclipai/plugin-llm-wiki test
|
||||
pnpm --filter @paperclipai/plugin-llm-wiki build
|
||||
```
|
||||
|
||||
## Alpha Verification
|
||||
|
||||
Run these commands from the Paperclip repo root before handing off alpha plugin
|
||||
changes:
|
||||
|
||||
```bash
|
||||
pnpm --filter @paperclipai/plugin-llm-wiki typecheck
|
||||
pnpm --filter @paperclipai/plugin-llm-wiki test
|
||||
pnpm --filter @paperclipai/plugin-llm-wiki build
|
||||
```
|
||||
|
||||
The focused Vitest suite covers:
|
||||
|
||||
- standalone package boundaries and package-local harness dependencies
|
||||
- required local folder bootstrap writes
|
||||
- raw source capture plus ingest metadata persistence
|
||||
- hidden plugin-operation issue creation for ingest/query/file-as-page workflows
|
||||
- disabled and enabled Paperclip event ingestion paths
|
||||
- managed routine declarations, manual distill/backfill work items, source cap handling, and backfill project/date scoping
|
||||
- atomic page writes, metadata/revision rows, backlinks, and stale-hash refusal
|
||||
- query session creation, run-id recording, stream event forwarding, and completion updates
|
||||
- filing a streamed query answer back into the wiki through a hidden operation
|
||||
|
||||
Remaining alpha gaps:
|
||||
|
||||
- Browser screenshot capture is maintained separately under `tests/screenshots`;
|
||||
generated `screenshots/` outputs are local artifacts and are ignored by git.
|
||||
- Host-level plugin install and live agent invocation still need Paperclip
|
||||
server/runtime smoke coverage when preparing a release candidate.
|
||||
|
||||
|
||||
|
||||
## Install Into Paperclip
|
||||
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:3100/api/plugins/install \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"packageName":"/Users/dotta/paperclip/.paperclip/worktrees/PAP-3179-design-a-llm-wiki-plugin/packages/plugins/plugin-llm-wiki","isLocalPath":true}'
|
||||
```
|
||||
|
||||
## Build Options
|
||||
|
||||
- `pnpm build` uses esbuild presets from `@paperclipai/plugin-sdk/bundlers`.
|
||||
- `pnpm build:rollup` uses rollup presets from the same SDK.
|
||||
|
||||
After changing manifest-loaded assets such as skills, agent instructions, or
|
||||
templates, recompile the local plugin before re-enabling it:
|
||||
|
||||
```bash
|
||||
pnpm --filter @paperclipai/plugin-llm-wiki build
|
||||
```
|
||||
|
||||
The package-local `dist/` directory is ignored by git, but local Paperclip
|
||||
installs load the compiled `dist/manifest.js` and `dist/worker.js` files at
|
||||
runtime. If activation failed before the rebuild, re-enable the plugin or
|
||||
restart the Paperclip dev server so the host imports the fresh bundle.
|
||||
|
||||
## Local File Layout
|
||||
|
||||
```text
|
||||
<configured-wiki-root>/
|
||||
AGENTS.md
|
||||
IDEA.md
|
||||
.gitignore
|
||||
raw/
|
||||
.gitkeep
|
||||
wiki/
|
||||
index.md
|
||||
log.md
|
||||
sources/
|
||||
.gitkeep
|
||||
projects/
|
||||
.gitkeep
|
||||
<project-slug>/
|
||||
index.md
|
||||
standup.md
|
||||
decisions.md
|
||||
history.md
|
||||
entities/
|
||||
.gitkeep
|
||||
concepts/
|
||||
.gitkeep
|
||||
synthesis/
|
||||
.gitkeep
|
||||
```
|
||||
|
||||
Use the settings page or `bootstrap-root` action to configure the folder and
|
||||
write the starter files. The plugin uses Paperclip's local folder API for path
|
||||
containment, symlink checks, read/write validation, and atomic writes.
|
||||
|
||||
Bootstrap preserves existing files rather than overwriting operator edits. The
|
||||
default first-install skeleton is copied from the vanilla LLM Wiki layout, with
|
||||
`CLAUDE.md` renamed to `AGENTS.md` and Paperclip project overviews, standups,
|
||||
decisions, and history kept together under `wiki/projects/<slug>/`.
|
||||
|
||||
## Managed Agent Instructions
|
||||
|
||||
Plugin-managed agent instruction bundles live under:
|
||||
|
||||
```text
|
||||
agents/<agent-key>/AGENTS.md
|
||||
```
|
||||
|
||||
For this plugin the Wiki Maintainer source bundle is `agents/wiki-maintainer/AGENTS.md`.
|
||||
Any additional files in that folder are installed as sibling instruction files
|
||||
for the managed agent. The settings health check reports drift from these
|
||||
defaults, and resetting the managed agent asks for confirmation before replacing
|
||||
customized instructions.
|
||||
@@ -0,0 +1,65 @@
|
||||
# LLM Wiki Maintainer
|
||||
|
||||
You are the maintainer of this personal wiki. The wiki is a persistent, interlinked knowledge base built from raw source documents. You read sources, extract knowledge, and integrate it into evolving wiki pages. The user curates sources, directs analysis, and asks questions; you handle the bookkeeping.
|
||||
|
||||
## Wiki Root
|
||||
|
||||
The wiki root folder is:
|
||||
|
||||
`{{localFolders.wiki-root.path}}`
|
||||
|
||||
The wiki's default operating schema is:
|
||||
|
||||
`{{localFolders.wiki-root.agentsPath}}`
|
||||
|
||||
Before ingest, query, lint, index, or maintenance work, read that wiki-root `AGENTS.md` file. It is the source of truth for page layout, citation style, log format, and wiki conventions. If the path above says `(not configured)`, stop and ask for the LLM Wiki root folder to be configured in plugin settings before doing file work.
|
||||
|
||||
## Identity
|
||||
|
||||
- You maintain the LLM Wiki, not the application codebase.
|
||||
- You keep raw source material in `raw/` immutable.
|
||||
- You keep Paperclip project operating summaries current in `wiki/projects/<project-slug>/standup.md`.
|
||||
- You create and update durable wiki pages under `wiki/`.
|
||||
- You keep `wiki/index.md` and `wiki/log.md` accurate after changes.
|
||||
- You cite wiki pages and raw sources in answers.
|
||||
|
||||
## Operating Loop
|
||||
|
||||
1. Resolve the configured wiki root folder and the target space named in the operation issue.
|
||||
2. Read the target space's `AGENTS.md`.
|
||||
3. Read the target space's `wiki/index.md` and recent `wiki/log.md` entries before choosing files.
|
||||
4. Pick the right operation skill (see below) and follow it.
|
||||
5. Use the LLM Wiki plugin tools for file reads, file writes, search, and logging. Always pass the operation issue's `wikiId` and `spaceSlug` arguments.
|
||||
6. Keep changes focused and append a concise log entry for durable updates.
|
||||
|
||||
All operation paths are relative to the target space root. Paperclip-derived operations (`distill`, `backfill`, cursor-window distillation, event capture) always target the default space in Phase 1 — pass `spaceSlug: "default"` and reject any prompt that asks you to write Paperclip-derived pages into a non-default space. Manual ingest (`ingest`, `query`, `lint`, `index`, `file-as-page`) follows whatever space the operation issue names; do not cross into another space unless the operation issue explicitly requests a multi-space sweep.
|
||||
|
||||
For Paperclip-derived project work, maintain two layers:
|
||||
|
||||
- `wiki/projects/<project-slug>/standup.md` — the executive standup for live project status, recent work, blockers/risks, and next actions. Rewrite it to the current truth instead of appending dated diary sections.
|
||||
- `wiki/projects/<project-slug>/index.md` and optional `wiki/projects/<project-slug>/decisions.md` / `history.md` — durable knowledge pages for context, decisions, and meaningful history.
|
||||
|
||||
Project pages and standups should read like human executive synthesis. Group work by concept, decision, blocker, and next action; use readable Paperclip issue links as evidence, but do not dump UUIDs, dates, statuses, or one-line issue inventories into the wiki narrative.
|
||||
|
||||
## Skills
|
||||
|
||||
Each operation has a dedicated LLM Wiki skill installed on this agent. Use the matching skill before improvising — they encode the page conventions, voice, and verification checklist for each operation.
|
||||
|
||||
- `wiki-ingest` — a captured `raw/` source needs to become durable wiki pages.
|
||||
- `wiki-query` — answer a question from the wiki with citations; offer durable synthesis.
|
||||
- `wiki-lint` — read-only audit for contradictions, orphans, weak provenance, missing concept pages.
|
||||
- `paperclip-distill` — turn a Paperclip source bundle (cursor-window, distill, or backfill) into wiki-insightful project pages, decisions, and history. Replaces the stiff, datestamp-heavy templated output.
|
||||
- `index-refresh` — keep `wiki/index.md` accurate and scannable.
|
||||
|
||||
The operation issue's `originKind` (`plugin:llm-wiki:operation:<type>`) tells you which skill to load:
|
||||
|
||||
| `operationType` | Skill |
|
||||
| --------------------- | ---------------------------------------------- |
|
||||
| `ingest` | `wiki-ingest` |
|
||||
| `query` | `wiki-query` |
|
||||
| `lint` | `wiki-lint` |
|
||||
| `distill`, `backfill` | `paperclip-distill` |
|
||||
| `index` | `index-refresh` |
|
||||
| `file-as-page` | `wiki-query` (filing synthesis from an answer) |
|
||||
|
||||
If a skill conflicts with this file, follow this file for identity. If a skill conflicts with the wiki-root `AGENTS.md`, follow that for page structure and voice.
|
||||
@@ -0,0 +1,17 @@
|
||||
import esbuild from "esbuild";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
const watch = process.argv.includes("--watch");
|
||||
|
||||
const workerCtx = await esbuild.context(presets.esbuild.worker);
|
||||
const manifestCtx = await esbuild.context(presets.esbuild.manifest);
|
||||
const uiCtx = await esbuild.context(presets.esbuild.ui);
|
||||
|
||||
if (watch) {
|
||||
await Promise.all([workerCtx.watch(), manifestCtx.watch(), uiCtx.watch()]);
|
||||
console.log("esbuild watch mode enabled for worker, manifest, and ui");
|
||||
} else {
|
||||
await Promise.all([workerCtx.rebuild(), manifestCtx.rebuild(), uiCtx.rebuild()]);
|
||||
await Promise.all([workerCtx.dispose(), manifestCtx.dispose(), uiCtx.dispose()]);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
.DS_Store
|
||||
.obsidian/workspace*
|
||||
.obsidian/cache
|
||||
@@ -0,0 +1,137 @@
|
||||
# AGENTS.md — LLM Wiki Schema
|
||||
|
||||
You are the maintainer of this personal wiki. The wiki is a persistent, interlinked knowledge base built from raw source documents. You read sources, extract knowledge, and integrate it into evolving wiki pages. The user curates sources, directs analysis, and asks questions; you handle the bookkeeping.
|
||||
|
||||
The underlying pattern is described in `IDEA.md` (Karpathy's "LLM Wiki" gist). Read it if you need the philosophy; this file is the operational schema.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
.
|
||||
├── AGENTS.md # this file — your operating instructions
|
||||
├── IDEA.md # the pattern this wiki follows
|
||||
├── raw/ # immutable source documents (you read, never write)
|
||||
└── wiki/ # generated, owned by you
|
||||
├── index.md # catalog of all pages
|
||||
├── log.md # append-only timeline of operations
|
||||
├── sources/ # one summary page per source
|
||||
├── projects/ # Paperclip project overviews, standups, decisions, and history
|
||||
│ └── <slug>/
|
||||
│ ├── index.md
|
||||
│ ├── standup.md
|
||||
│ ├── decisions.md
|
||||
│ └── history.md
|
||||
├── entities/ # people, organizations, products, places
|
||||
├── concepts/ # ideas, frameworks, definitions
|
||||
└── synthesis/ # cross-cutting analysis, comparisons, theses
|
||||
```
|
||||
|
||||
The subdirectories under `wiki/` are conventional, not enforced. Add new categories (e.g. `wiki/papers/`) as the domain demands — and update this file when you do.
|
||||
|
||||
Paperclip project material lives only under `wiki/projects/<project-slug>/`. Do not create a top-level `projects/` directory.
|
||||
|
||||
- `wiki/projects/<project-slug>/standup.md` is the executive-level project standup. It answers where the project stands today, what changed recently, current blockers/risks, and the next concrete actions.
|
||||
- `wiki/projects/<project-slug>/index.md` is the durable knowledge page. It explains what the project is, why it exists, decisions made, history, and long-lived context.
|
||||
- Keep the two linked. A standup should link to the durable project page, and the durable project page should point at the current standup for live status.
|
||||
- Update `standup.md` whenever Paperclip project, issue, plan, comment, blocker, approval, or status history materially changes the project's current state. Do not append endless dated sections; rewrite it as today's concise status.
|
||||
- Project writing should be editorial and concept-grouped. Do not dump issue queues, UUIDs, raw metadata, or date-heavy ledgers into project pages. Reference Paperclip tasks with human issue links where useful, but make headings and paragraphs explain the concepts, decisions, completed work, next work, and blockers in plain executive language.
|
||||
|
||||
## Page conventions
|
||||
|
||||
- **Filename:** kebab-case, `.md`. Treat filenames as stable; do not rename without updating backlinks.
|
||||
- **Frontmatter:** YAML at the top of every wiki page.
|
||||
```yaml
|
||||
---
|
||||
title: Human-readable title
|
||||
type: source | project | entity | concept | synthesis
|
||||
tags: [tag-a, tag-b]
|
||||
sources: [raw/doc.pdf] # for source pages and synthesis pages
|
||||
created: YYYY-MM-DD
|
||||
updated: YYYY-MM-DD
|
||||
---
|
||||
```
|
||||
- **Cross-links:** Obsidian-style `[[wiki/entities/some-page]]` (or `[[some-page]]` when unambiguous). When you mention a concept or entity that has — or should have — its own page, link it.
|
||||
- **Citations:** cite the source inline whenever a claim comes from one: `(see [[wiki/sources/some-slug]])`.
|
||||
- **Voice:** terse, factual, neutral. The wiki is reference material, not narrative.
|
||||
|
||||
## Operations
|
||||
|
||||
### Ingest
|
||||
|
||||
Triggered when the user drops a file in `raw/` and asks to process it (or just says "ingest").
|
||||
|
||||
1. Read the source end to end.
|
||||
2. Briefly discuss key takeaways with the user before writing — confirm what to emphasize.
|
||||
3. Create `wiki/sources/<slug>.md`: a summary page (~300–800 words) covering the source's main claims, structure, and notable quotes or data.
|
||||
4. Update or create relevant pages in `entities/`, `concepts/`, `synthesis/`. A typical ingest touches 5–15 pages.
|
||||
5. Add any new pages to `wiki/index.md`.
|
||||
6. Append a log entry:
|
||||
```
|
||||
## [YYYY-MM-DD] ingest | <source title>
|
||||
- source: raw/<filename>
|
||||
- new pages: [[...]], [[...]]
|
||||
- updated pages: [[...]], [[...]]
|
||||
- notes: <one-line synthesis, contradiction flagged, or open question>
|
||||
```
|
||||
|
||||
When new information contradicts an existing page, do **not** silently overwrite. Flag the contradiction on the page (a `> ⚠ contradicted by [[...]] (YYYY-MM-DD)` callout) and note it in the log.
|
||||
|
||||
### Project updates
|
||||
|
||||
Triggered when Paperclip project, issue, plan, comment, blocker, or status history is distilled into the wiki.
|
||||
|
||||
1. Create or update `wiki/projects/<project-slug>/standup.md` first. Every Paperclip project represented in the wiki must have one. Keep stable sections for executive readout, what changed, decisions, blockers/risks, next actions, and links.
|
||||
2. Create or update `wiki/projects/<project-slug>/index.md` as the durable project overview. Keep stable sections for overview, current direction, workstreams, decisions, open risks/blockers, and references.
|
||||
3. Use `wiki/projects/<project-slug>/decisions.md` for accepted/rejected plans, architectural decisions, approval outcomes, and reversals when a project has enough decision history to warrant a separate page.
|
||||
4. Use `wiki/projects/<project-slug>/history.md` for compact narrative history of meaningful project movement. Group by phase or concept; do not mirror every issue comment.
|
||||
5. Always cite Paperclip source material with readable links to issue identifiers, document keys, issue documents, approvals, and raw/source pages. Do not put UUIDs in prose unless the UUID itself is the subject.
|
||||
6. Update `wiki/index.md` under Projects and append a `project` log entry to `wiki/log.md`.
|
||||
|
||||
### Query
|
||||
|
||||
The user asks a question. You:
|
||||
|
||||
1. Read `wiki/index.md` to find candidate pages.
|
||||
2. Read those pages; follow links as needed.
|
||||
3. Answer with citations back to wiki pages, and ultimately to raw sources.
|
||||
4. If the answer is substantial (a comparison, analysis, new synthesis), offer to file it under `wiki/synthesis/` so the work compounds rather than disappearing into chat history.
|
||||
|
||||
If the wiki lacks what the question needs, say so plainly and suggest sources to ingest or web searches to run.
|
||||
|
||||
### Lint
|
||||
|
||||
On request ("lint", "health check"), scan for:
|
||||
|
||||
- contradictions across pages
|
||||
- claims a newer source has superseded
|
||||
- orphan pages (not linked from `index.md` or any other page)
|
||||
- concepts mentioned in multiple places but lacking a dedicated page
|
||||
- broken `[[wiki-links]]`
|
||||
- gaps where a web search or new source would help
|
||||
|
||||
Report findings as a checklist and ask the user which to act on.
|
||||
|
||||
## index.md format
|
||||
|
||||
A catalog organized by category. Each line: `- [[path]] — one-line summary`. Keep it scannable; this is your primary navigation aid before opening pages.
|
||||
|
||||
## log.md format
|
||||
|
||||
Append new entries to the bottom. Every entry header follows:
|
||||
|
||||
```
|
||||
## [YYYY-MM-DD] <op> | <subject>
|
||||
```
|
||||
|
||||
so `grep "^## \[" wiki/log.md | tail -10` always returns recent activity. Operations: `ingest`, `query`, `lint`, `setup`, `refactor`.
|
||||
|
||||
## Customization
|
||||
|
||||
This schema is intentionally generic. As the wiki's domain becomes clear, evolve it:
|
||||
|
||||
- add domain-specific page types and subdirectories
|
||||
- adjust frontmatter fields
|
||||
- specify preferred output formats for queries (Marp slides, charts, tables)
|
||||
- record workflow preferences (one-at-a-time vs batch ingest, level of human supervision)
|
||||
|
||||
When you and the user agree on a convention, **write it into this file**. The schema is the wiki's source of truth for how the wiki is built.
|
||||
@@ -0,0 +1,75 @@
|
||||
# LLM Wiki
|
||||
|
||||
A pattern for building personal knowledge bases using LLMs.
|
||||
|
||||
This is an idea file, it is designed to be copy pasted to your own LLM Agent (e.g. OpenAI Codex, Claude Code, OpenCode / Pi, or etc.). Its goal is to communicate the high level idea, but your agent will build out the specifics in collaboration with you.
|
||||
|
||||
## The core idea
|
||||
|
||||
Most people's experience with LLMs and documents looks like RAG: you upload a collection of files, the LLM retrieves relevant chunks at query time, and generates an answer. This works, but the LLM is rediscovering knowledge from scratch on every question. There's no accumulation. Ask a subtle question that requires synthesizing five documents, and the LLM has to find and piece together the relevant fragments every time. Nothing is built up. NotebookLM, ChatGPT file uploads, and most RAG systems work this way.
|
||||
|
||||
The idea here is different. Instead of just retrieving from raw documents at query time, the LLM **incrementally builds and maintains a persistent wiki** — a structured, interlinked collection of markdown files that sits between you and the raw sources. When you add a new source, the LLM doesn't just index it for later retrieval. It reads it, extracts the key information, and integrates it into the existing wiki — updating entity pages, revising topic summaries, noting where new data contradicts old claims, strengthening or challenging the evolving synthesis. The knowledge is compiled once and then *kept current*, not re-derived on every query.
|
||||
|
||||
This is the key difference: **the wiki is a persistent, compounding artifact.** The cross-references are already there. The contradictions have already been flagged. The synthesis already reflects everything you've read. The wiki keeps getting richer with every source you add and every question you ask.
|
||||
|
||||
You never (or rarely) write the wiki yourself — the LLM writes and maintains all of it. You're in charge of sourcing, exploration, and asking the right questions. The LLM does all the grunt work — the summarizing, cross-referencing, filing, and bookkeeping that makes a knowledge base actually useful over time. In practice, I have the LLM agent open on one side and Obsidian open on the other. The LLM makes edits based on our conversation, and I browse the results in real time — following links, checking the graph view, reading the updated pages. Obsidian is the IDE; the LLM is the programmer; the wiki is the codebase.
|
||||
|
||||
This can apply to a lot of different contexts. A few examples:
|
||||
|
||||
- **Personal**: tracking your own goals, health, psychology, self-improvement — filing journal entries, articles, podcast notes, and building up a structured picture of yourself over time.
|
||||
- **Research**: going deep on a topic over weeks or months — reading papers, articles, reports, and incrementally building a comprehensive wiki with an evolving thesis.
|
||||
- **Reading a book**: filing each chapter as you go, building out pages for characters, themes, plot threads, and how they connect. By the end you have a rich companion wiki. Think of fan wikis like [Tolkien Gateway](https://tolkiengateway.net/wiki/Main_Page) — thousands of interlinked pages covering characters, places, events, languages, built by a community of volunteers over years. You could build something like that personally as you read, with the LLM doing all the cross-referencing and maintenance.
|
||||
- **Business/team**: an internal wiki maintained by LLMs, fed by Slack threads, meeting transcripts, project documents, customer calls. Possibly with humans in the loop reviewing updates. The wiki stays current because the LLM does the maintenance that no one on the team wants to do.
|
||||
- **Competitive analysis, due diligence, trip planning, course notes, hobby deep-dives** — anything where you're accumulating knowledge over time and want it organized rather than scattered.
|
||||
|
||||
## Architecture
|
||||
|
||||
There are three layers:
|
||||
|
||||
**Raw sources** — your curated collection of source documents. Articles, papers, images, data files. These are immutable — the LLM reads from them but never modifies them. This is your source of truth.
|
||||
|
||||
**The wiki** — a directory of LLM-generated markdown files. Summaries, entity pages, concept pages, comparisons, an overview, a synthesis. The LLM owns this layer entirely. It creates pages, updates them when new sources arrive, maintains cross-references, and keeps everything consistent. You read it; the LLM writes it.
|
||||
|
||||
**The schema** — a document (e.g. AGENTS.md for Paperclip agents) that tells the LLM how the wiki is structured, what the conventions are, and what workflows to follow when ingesting sources, answering questions, or maintaining the wiki. This is the key configuration file — it's what makes the LLM a disciplined wiki maintainer rather than a generic chatbot. You and the LLM co-evolve this over time as you figure out what works for your domain.
|
||||
|
||||
## Operations
|
||||
|
||||
**Ingest.** You drop a new source into the raw collection and tell the LLM to process it. An example flow: the LLM reads the source, discusses key takeaways with you, writes a summary page in the wiki, updates the index, updates relevant entity and concept pages across the wiki, and appends an entry to the log. A single source might touch 10-15 wiki pages. Personally I prefer to ingest sources one at a time and stay involved — I read the summaries, check the updates, and guide the LLM on what to emphasize. But you could also batch-ingest many sources at once with less supervision. It's up to you to develop the workflow that fits your style and document it in the schema for future sessions.
|
||||
|
||||
**Query.** You ask questions against the wiki. The LLM searches for relevant pages, reads them, and synthesizes an answer with citations. Answers can take different forms depending on the question — a markdown page, a comparison table, a slide deck (Marp), a chart (matplotlib), a canvas. The important insight: **good answers can be filed back into the wiki as new pages.** A comparison you asked for, an analysis, a connection you discovered — these are valuable and shouldn't disappear into chat history. This way your explorations compound in the knowledge base just like ingested sources do.
|
||||
|
||||
**Lint.** Periodically, ask the LLM to health-check the wiki. Look for: contradictions between pages, stale claims that newer sources have superseded, orphan pages with no inbound links, important concepts mentioned but lacking their own page, missing cross-references, data gaps that could be filled with a web search. The LLM is good at suggesting new questions to investigate and new sources to look for. This keeps the wiki healthy as it grows.
|
||||
|
||||
## Indexing and logging
|
||||
|
||||
Two special files help the LLM (and you) navigate the wiki as it grows. They serve different purposes:
|
||||
|
||||
**index.md** is content-oriented. It's a catalog of everything in the wiki — each page listed with a link, a one-line summary, and optionally metadata like date or source count. Organized by category (entities, concepts, sources, etc.). The LLM updates it on every ingest. When answering a query, the LLM reads the index first to find relevant pages, then drills into them. This works surprisingly well at moderate scale (~100 sources, ~hundreds of pages) and avoids the need for embedding-based RAG infrastructure.
|
||||
|
||||
**log.md** is chronological. It's an append-only record of what happened and when — ingests, queries, lint passes. A useful tip: if each entry starts with a consistent prefix (e.g. `## [2026-04-02] ingest | Article Title`), the log becomes parseable with simple unix tools — `grep "^## \[" log.md | tail -5` gives you the last 5 entries. The log gives you a timeline of the wiki's evolution and helps the LLM understand what's been done recently.
|
||||
|
||||
## Optional: CLI tools
|
||||
|
||||
At some point you may want to build small tools that help the LLM operate on the wiki more efficiently. A search engine over the wiki pages is the most obvious one — at small scale the index file is enough, but as the wiki grows you want proper search. [qmd](https://github.com/tobi/qmd) is a good option: it's a local search engine for markdown files with hybrid BM25/vector search and LLM re-ranking, all on-device. It has both a CLI (so the LLM can shell out to it) and an MCP server (so the LLM can use it as a native tool). You could also build something simpler yourself — the LLM can help you vibe-code a naive search script as the need arises.
|
||||
|
||||
## Tips and tricks
|
||||
|
||||
- **Obsidian Web Clipper** is a browser extension that converts web articles to markdown. Very useful for quickly getting sources into your raw collection.
|
||||
- **Download images locally.** In Obsidian Settings → Files and links, set "Attachment folder path" to a fixed directory (e.g. `raw/assets/`). Then in Settings → Hotkeys, search for "Download" to find "Download attachments for current file" and bind it to a hotkey (e.g. Ctrl+Shift+D). After clipping an article, hit the hotkey and all images get downloaded to local disk. This is optional but useful — it lets the LLM view and reference images directly instead of relying on URLs that may break. Note that LLMs can't natively read markdown with inline images in one pass — the workaround is to have the LLM read the text first, then view some or all of the referenced images separately to gain additional context. It's a bit clunky but works well enough.
|
||||
- **Obsidian's graph view** is the best way to see the shape of your wiki — what's connected to what, which pages are hubs, which are orphans.
|
||||
- **Marp** is a markdown-based slide deck format. Obsidian has a plugin for it. Useful for generating presentations directly from wiki content.
|
||||
- **Dataview** is an Obsidian plugin that runs queries over page frontmatter. If your LLM adds YAML frontmatter to wiki pages (tags, dates, source counts), Dataview can generate dynamic tables and lists.
|
||||
- The wiki is just a git repo of markdown files. You get version history, branching, and collaboration for free.
|
||||
|
||||
## Why this works
|
||||
|
||||
The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping. Updating cross-references, keeping summaries current, noting when new data contradicts old claims, maintaining consistency across dozens of pages. Humans abandon wikis because the maintenance burden grows faster than the value. LLMs don't get bored, don't forget to update a cross-reference, and can touch 15 files in one pass. The wiki stays maintained because the cost of maintenance is near zero.
|
||||
|
||||
The human's job is to curate sources, direct the analysis, ask good questions, and think about what it all means. The LLM's job is everything else.
|
||||
|
||||
The idea is related in spirit to Vannevar Bush's Memex (1945) — a personal, curated knowledge store with associative trails between documents. Bush's vision was closer to this than to what the web became: private, actively curated, with the connections between documents as valuable as the documents themselves. The part he couldn't solve was who does the maintenance. The LLM handles that.
|
||||
|
||||
|
||||
## Note
|
||||
|
||||
This document is intentionally abstract. It describes the idea, not a specific implementation. The exact directory structure, the schema conventions, the page formats, the tooling — all of that will depend on your domain, your preferences, and your LLM of choice. Everything mentioned above is optional and modular — pick what's useful, ignore what isn't. For example: your sources might be text-only, so you don't need image handling at all. Your wiki might be small enough that the index file is all you need, no search engine required. You might not care about slide decks and just want markdown pages. You might want a completely different set of output formats. The right way to use this is to share it with your LLM agent and work together to instantiate a version that fits your needs. The document's only job is to communicate the pattern. Your LLM can figure out the rest.
|
||||
Whitespace-only changes.
@@ -0,0 +1,3 @@
|
||||
# Raw Source
|
||||
|
||||
LLM Wiki code must live in the standalone plugin package.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Knowledge
|
||||
|
||||
The wiki stores durable knowledge as local markdown files.
|
||||
Whitespace-only changes.
+3
@@ -0,0 +1,3 @@
|
||||
# Plugin Boundaries
|
||||
|
||||
LLM Wiki routes, prompts, UI, tools, and migrations belong inside the plugin.
|
||||
Whitespace-only changes.
@@ -0,0 +1,23 @@
|
||||
# Index
|
||||
|
||||
Catalog of durable wiki pages and linked project standups. Updated on every ingest or Paperclip distill.
|
||||
|
||||
## Sources
|
||||
|
||||
_(none yet)_
|
||||
|
||||
## Projects
|
||||
|
||||
_(none yet)_
|
||||
|
||||
## Entities
|
||||
|
||||
_(none yet)_
|
||||
|
||||
## Concepts
|
||||
|
||||
_(none yet)_
|
||||
|
||||
## Synthesis
|
||||
|
||||
_(none yet)_
|
||||
@@ -0,0 +1,10 @@
|
||||
# Log
|
||||
|
||||
Append-only chronological record of wiki operations.
|
||||
|
||||
## [2026-05-03] setup | wiki initialized
|
||||
- created `AGENTS.md` (schema)
|
||||
- created `raw/` for source documents
|
||||
- created `wiki/` skeleton: `index.md`, `log.md`, `sources/`, `projects/`, `entities/`, `concepts/`, `synthesis/`
|
||||
- created `wiki/projects/` for Paperclip project overviews and standups
|
||||
- pattern reference: `IDEA.md` (Karpathy "LLM Wiki" gist, https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f)
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,101 @@
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_instances (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
root_folder_key text NOT NULL DEFAULT 'wiki-root',
|
||||
configured_root_path text,
|
||||
schema_version integer NOT NULL DEFAULT 1,
|
||||
settings jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
managed_agent_key text,
|
||||
managed_project_key text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, wiki_id)
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_sources (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
source_type text NOT NULL,
|
||||
title text,
|
||||
url text,
|
||||
raw_path text NOT NULL,
|
||||
content_hash text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'captured',
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_pages (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
path text NOT NULL,
|
||||
title text,
|
||||
page_type text,
|
||||
frontmatter jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
source_refs jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
backlinks jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
content_hash text,
|
||||
current_revision_id uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, wiki_id, path)
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
page_id uuid REFERENCES plugin_llm_wiki_8f50da974f.wiki_pages(id) ON DELETE CASCADE,
|
||||
operation_id uuid,
|
||||
path text NOT NULL,
|
||||
content_hash text NOT NULL,
|
||||
summary text,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_operations (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
operation_type text NOT NULL,
|
||||
status text NOT NULL,
|
||||
hidden_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
project_id uuid REFERENCES public.projects(id) ON DELETE SET NULL,
|
||||
run_ids jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
cost_cents integer NOT NULL DEFAULT 0,
|
||||
warnings jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
affected_pages jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
hidden_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
agent_session_id text,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
filed_outputs jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_resource_bindings (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
resource_kind text NOT NULL,
|
||||
resource_key text NOT NULL,
|
||||
resolved_id uuid,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, wiki_id, resource_kind, resource_key)
|
||||
);
|
||||
@@ -0,0 +1,88 @@
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
source_scope text NOT NULL,
|
||||
scope_key text NOT NULL,
|
||||
project_id uuid REFERENCES public.projects(id) ON DELETE CASCADE,
|
||||
root_issue_id uuid REFERENCES public.issues(id) ON DELETE CASCADE,
|
||||
source_kind text NOT NULL DEFAULT 'paperclip_issue_history',
|
||||
last_processed_at timestamptz,
|
||||
last_observed_at timestamptz,
|
||||
pending_event_count integer NOT NULL DEFAULT 0,
|
||||
last_successful_run_id uuid,
|
||||
last_source_hash text,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, wiki_id, source_scope, scope_key, source_kind)
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
work_item_kind text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'pending',
|
||||
priority text NOT NULL DEFAULT 'medium',
|
||||
project_id uuid REFERENCES public.projects(id) ON DELETE CASCADE,
|
||||
root_issue_id uuid REFERENCES public.issues(id) ON DELETE CASCADE,
|
||||
requested_by_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
idempotency_key text,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, wiki_id, idempotency_key)
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
cursor_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors(id) ON DELETE SET NULL,
|
||||
work_item_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items(id) ON DELETE SET NULL,
|
||||
project_id uuid REFERENCES public.projects(id) ON DELETE SET NULL,
|
||||
root_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
source_window_start timestamptz,
|
||||
source_window_end timestamptz,
|
||||
source_hash text,
|
||||
status text NOT NULL,
|
||||
operation_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
retry_count integer NOT NULL DEFAULT 0,
|
||||
cost_cents integer NOT NULL DEFAULT 0,
|
||||
warnings jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
distillation_run_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_runs(id) ON DELETE CASCADE,
|
||||
project_id uuid REFERENCES public.projects(id) ON DELETE SET NULL,
|
||||
root_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
|
||||
source_hash text NOT NULL,
|
||||
max_characters integer NOT NULL,
|
||||
clipped boolean NOT NULL DEFAULT false,
|
||||
source_refs jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
bundle_markdown text NOT NULL,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL,
|
||||
project_id uuid REFERENCES public.projects(id) ON DELETE CASCADE,
|
||||
root_issue_id uuid REFERENCES public.issues(id) ON DELETE CASCADE,
|
||||
page_path text NOT NULL,
|
||||
last_applied_source_hash text,
|
||||
last_distillation_run_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_runs(id) ON DELETE SET NULL,
|
||||
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, wiki_id, page_path)
|
||||
);
|
||||
@@ -0,0 +1,213 @@
|
||||
CREATE TABLE IF NOT EXISTS plugin_llm_wiki_8f50da974f.wiki_spaces (
|
||||
id uuid PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
wiki_id text NOT NULL DEFAULT 'default',
|
||||
slug text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
space_type text NOT NULL DEFAULT 'local_folder',
|
||||
folder_mode text NOT NULL DEFAULT 'managed_subfolder',
|
||||
root_folder_key text NOT NULL DEFAULT 'wiki-root',
|
||||
path_prefix text,
|
||||
configured_root_path text,
|
||||
access_scope text NOT NULL DEFAULT 'shared',
|
||||
owner_user_id text,
|
||||
owner_agent_id uuid REFERENCES public.agents(id) ON DELETE SET NULL,
|
||||
team_key text,
|
||||
settings jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, wiki_id, slug)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS wiki_spaces_company_status_idx
|
||||
ON plugin_llm_wiki_8f50da974f.wiki_spaces (company_id, wiki_id, status);
|
||||
|
||||
WITH wiki_pairs AS (
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_instances
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_sources
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_pages
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_page_revisions
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_operations
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_query_sessions
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_distillation_runs
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_source_snapshots
|
||||
UNION
|
||||
SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_page_bindings
|
||||
)
|
||||
INSERT INTO plugin_llm_wiki_8f50da974f.wiki_spaces
|
||||
(id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key, path_prefix, access_scope, status)
|
||||
SELECT (
|
||||
substr(md5(company_id::text || ':' || wiki_id || ':default'), 1, 8) || '-' ||
|
||||
substr(md5(company_id::text || ':' || wiki_id || ':default'), 9, 4) || '-' ||
|
||||
'4' || substr(md5(company_id::text || ':' || wiki_id || ':default'), 14, 3) || '-' ||
|
||||
'8' || substr(md5(company_id::text || ':' || wiki_id || ':default'), 18, 3) || '-' ||
|
||||
substr(md5(company_id::text || ':' || wiki_id || ':default'), 21, 12)
|
||||
)::uuid,
|
||||
company_id,
|
||||
wiki_id,
|
||||
'default',
|
||||
'default',
|
||||
'local_folder',
|
||||
'managed_subfolder',
|
||||
'wiki-root',
|
||||
NULL,
|
||||
'shared',
|
||||
'active'
|
||||
FROM wiki_pairs
|
||||
ON CONFLICT (company_id, wiki_id, slug) DO NOTHING;
|
||||
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings ADD COLUMN IF NOT EXISTS space_id uuid;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.wiki_sources t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.wiki_pages t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.wiki_page_revisions t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.wiki_operations t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.wiki_query_sessions t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
UPDATE plugin_llm_wiki_8f50da974f.paperclip_page_bindings t
|
||||
SET space_id = s.id
|
||||
FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
|
||||
WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
|
||||
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots ALTER COLUMN space_id SET NOT NULL;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings ALTER COLUMN space_id SET NOT NULL;
|
||||
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
|
||||
DROP CONSTRAINT IF EXISTS wiki_pages_company_id_wiki_id_path_key;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
|
||||
DROP CONSTRAINT IF EXISTS paperclip_distillation_cursor_company_id_wiki_id_source_sco_key;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
|
||||
DROP CONSTRAINT IF EXISTS paperclip_distillation_work_i_company_id_wiki_id_idempotenc_key;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
|
||||
DROP CONSTRAINT IF EXISTS paperclip_page_bindings_company_id_wiki_id_page_path_key;
|
||||
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
|
||||
DROP CONSTRAINT IF EXISTS wiki_pages_company_wiki_space_path_key;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
|
||||
ADD CONSTRAINT wiki_pages_company_wiki_space_path_key UNIQUE (company_id, wiki_id, space_id, path);
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
|
||||
DROP CONSTRAINT IF EXISTS distillation_cursors_company_wiki_space_scope_key;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
|
||||
ADD CONSTRAINT distillation_cursors_company_wiki_space_scope_key UNIQUE (company_id, wiki_id, space_id, source_scope, scope_key, source_kind);
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
|
||||
DROP CONSTRAINT IF EXISTS distillation_work_items_company_wiki_space_idempotency_key;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
|
||||
ADD CONSTRAINT distillation_work_items_company_wiki_space_idempotency_key UNIQUE (company_id, wiki_id, space_id, idempotency_key);
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
|
||||
DROP CONSTRAINT IF EXISTS page_bindings_company_wiki_space_page_path_key;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
|
||||
ADD CONSTRAINT page_bindings_company_wiki_space_page_path_key UNIQUE (company_id, wiki_id, space_id, page_path);
|
||||
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources
|
||||
DROP CONSTRAINT IF EXISTS wiki_sources_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources
|
||||
ADD CONSTRAINT wiki_sources_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
|
||||
DROP CONSTRAINT IF EXISTS wiki_pages_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
|
||||
ADD CONSTRAINT wiki_pages_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions
|
||||
DROP CONSTRAINT IF EXISTS wiki_page_revisions_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions
|
||||
ADD CONSTRAINT wiki_page_revisions_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations
|
||||
DROP CONSTRAINT IF EXISTS wiki_operations_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations
|
||||
ADD CONSTRAINT wiki_operations_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions
|
||||
DROP CONSTRAINT IF EXISTS wiki_query_sessions_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions
|
||||
ADD CONSTRAINT wiki_query_sessions_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
|
||||
DROP CONSTRAINT IF EXISTS paperclip_distillation_cursors_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
|
||||
ADD CONSTRAINT paperclip_distillation_cursors_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
|
||||
DROP CONSTRAINT IF EXISTS paperclip_distillation_work_items_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
|
||||
ADD CONSTRAINT paperclip_distillation_work_items_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs
|
||||
DROP CONSTRAINT IF EXISTS paperclip_distillation_runs_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs
|
||||
ADD CONSTRAINT paperclip_distillation_runs_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots
|
||||
DROP CONSTRAINT IF EXISTS paperclip_source_snapshots_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots
|
||||
ADD CONSTRAINT paperclip_source_snapshots_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
|
||||
DROP CONSTRAINT IF EXISTS paperclip_page_bindings_space_id_fk;
|
||||
ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
|
||||
ADD CONSTRAINT paperclip_page_bindings_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS wiki_sources_space_idx ON plugin_llm_wiki_8f50da974f.wiki_sources (company_id, wiki_id, space_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS wiki_operations_space_idx ON plugin_llm_wiki_8f50da974f.wiki_operations (company_id, wiki_id, space_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS wiki_query_sessions_space_idx ON plugin_llm_wiki_8f50da974f.wiki_query_sessions (company_id, wiki_id, space_id, updated_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS distillation_runs_space_idx ON plugin_llm_wiki_8f50da974f.paperclip_distillation_runs (company_id, wiki_id, space_id, created_at DESC);
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-llm-wiki",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"description": "Local-file LLM Wiki plugin for source ingestion, wiki browsing, query, lint, and maintenance workflows.",
|
||||
"files": [
|
||||
"agents",
|
||||
"dist",
|
||||
"migrations",
|
||||
"skills",
|
||||
"templates",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
|
||||
"build": "node ./esbuild.config.mjs",
|
||||
"build:rollup": "rollup -c",
|
||||
"dev": "node ./esbuild.config.mjs --watch",
|
||||
"dev:ui": "paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177",
|
||||
"test": "vitest run --config ./vitest.config.ts",
|
||||
"typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit"
|
||||
},
|
||||
"paperclipPlugin": {
|
||||
"manifest": "./dist/manifest.js",
|
||||
"worker": "./dist/worker.js",
|
||||
"ui": "./dist/ui/"
|
||||
},
|
||||
"keywords": [
|
||||
"paperclip",
|
||||
"plugin",
|
||||
"automation",
|
||||
"wiki",
|
||||
"knowledge"
|
||||
],
|
||||
"author": "Paperclip",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@paperclipai/plugin-sdk": "workspace:*",
|
||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"@types/node": "^22.19.21",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"esbuild": "^0.28.1",
|
||||
"react-dom": "^19.2.7",
|
||||
"rollup": "^4.62.2",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.1.8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
|
||||
|
||||
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
|
||||
|
||||
function withPlugins(config) {
|
||||
if (!config) return null;
|
||||
return {
|
||||
...config,
|
||||
plugins: [
|
||||
nodeResolve({
|
||||
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"],
|
||||
}),
|
||||
typescript({
|
||||
tsconfig: "./tsconfig.json",
|
||||
declaration: false,
|
||||
declarationMap: false,
|
||||
}),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export default [
|
||||
withPlugins(presets.rollup.manifest),
|
||||
withPlugins(presets.rollup.worker),
|
||||
withPlugins(presets.rollup.ui),
|
||||
].filter(Boolean);
|
||||
@@ -0,0 +1,34 @@
|
||||
# LLM Wiki Maintainer Skills
|
||||
|
||||
This folder is the plugin-level source for LLM Wiki managed company skills. Paperclip installs these skills into the company skill library and syncs them onto the Wiki Maintainer agent. The Wiki Maintainer's identity and operating loop live in `agents/wiki-maintainer/AGENTS.md`; the wiki-root `AGENTS.md` remains the wiki schema for page layout, citation style, and log format.
|
||||
|
||||
Each skill is an isolated SKILL.md describing one job — when to invoke it, the inputs that must be true before starting, the steps, and the durable output the operation must leave behind.
|
||||
|
||||
## Skill registry
|
||||
|
||||
| Skill | When to invoke |
|
||||
|---|---|
|
||||
| [`wiki-maintainer`](./wiki-maintainer/SKILL.md) | General LLM Wiki maintenance and tool-use guidance shared by the operation skills. |
|
||||
| [`wiki-ingest`](./wiki-ingest/SKILL.md) | A new file landed in `raw/` and the operation issue says "ingest" — turn the source into durable wiki pages. |
|
||||
| [`wiki-query`](./wiki-query/SKILL.md) | The user asked the wiki a question; answer with citations and offer to file durable synthesis back into `wiki/`. |
|
||||
| [`wiki-lint`](./wiki-lint/SKILL.md) | A lint or health-check operation — audit for contradictions, orphan pages, weak provenance, broken links, missing concept pages. |
|
||||
| [`paperclip-distill`](./paperclip-distill/SKILL.md) | Cursor-window, distill, or backfill operation on Paperclip activity — write a wiki-insightful project page, decisions log, and history note. |
|
||||
| [`index-refresh`](./index-refresh/SKILL.md) | Refresh `wiki/index.md` so each entry has a tight, scannable summary; flag drift between the index and recent log activity. |
|
||||
|
||||
## Layering
|
||||
|
||||
```
|
||||
AGENTS.md (wiki root) ← schema for the wiki itself: page conventions, frontmatter, voice
|
||||
agents/wiki-maintainer/AGENTS.md ← agent identity and operating loop
|
||||
skills/<skill>/SKILL.md ← plugin-managed company skills installed onto the maintainer
|
||||
```
|
||||
|
||||
When a skill conflicts with the wiki-root `AGENTS.md`, the wiki schema wins for page format/voice and the skill wins for operation flow. When a skill conflicts with the agent's `AGENTS.md`, the agent file wins for identity and the skill wins for the operation procedure.
|
||||
|
||||
## Skill conventions
|
||||
|
||||
- Front matter has `name` (kebab-case) and `description` (one or two sentences with the trigger condition).
|
||||
- Each skill names the input it expects (e.g. an operation issue with `originKind` ending in `:ingest`, a captured `raw/` path, a Paperclip source bundle).
|
||||
- Each skill ends with a verification checklist — what must be true before the operation issue is closed `done`.
|
||||
- Skills cite the wiki-plugin tools they rely on (`wiki_search`, `wiki_read_page`, `wiki_write_page`, `wiki_read_source`, `wiki_list_sources`).
|
||||
- Skills do not duplicate the page conventions from the wiki root `AGENTS.md`. They reference it instead.
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
name: index-refresh
|
||||
description: Use when an operation issue is an index refresh — typically the hourly index-refresh routine. Rebuild `wiki/index.md` so each entry has a tight, scannable one-line summary and the catalog tracks the actual contents of `wiki/`. Resolve drift between the index and recent log activity, but do not edit page content.
|
||||
---
|
||||
|
||||
# Index Refresh
|
||||
|
||||
Keep `wiki/index.md` accurate and scannable. The index is the maintainer's first stop for navigation — its quality determines how cheap every subsequent operation becomes.
|
||||
|
||||
## Inputs
|
||||
|
||||
- An operation issue with `operationType: "index"` (or the `index-refresh` routine title).
|
||||
- The operation issue's target `wikiId`, `spaceSlug`, and space root. Refresh only that space unless the issue explicitly says this is a multi-space sweep.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Read the target space's `wiki/index.md`** as it currently stands.
|
||||
2. **Walk the target space's `wiki/`.** `wiki/projects/<slug>/standup.md` entries are current-state companions for durable `wiki/projects/<slug>/index.md` pages; index them only as links attached to the matching project entry. Walk `wiki/` by category (`sources/`, `projects/`, `entities/`, `concepts/`, `synthesis/`, plus any custom subdirectories the wiki schema added).
|
||||
3. **Read the target space's last ~50 entries of `wiki/log.md`** to spot pages that were created or substantially changed but never made it to the index.
|
||||
4. **Per category, produce sorted entries** of the form:
|
||||
```
|
||||
- [[<path>]] — <one-line summary>
|
||||
```
|
||||
The summary is one factual sentence pulled from the page's first paragraph or its title. **No status, no datestamps in the index** — those belong in the page itself or in the log.
|
||||
5. **Drop entries whose page no longer exists.** Note the deletion in the log:
|
||||
```
|
||||
## [YYYY-MM-DD] index-refresh | reconciled
|
||||
- removed: [[wiki/old-page]] (page deleted)
|
||||
- added: [[wiki/new-page]] — <summary>
|
||||
```
|
||||
6. **Add entries for pages that exist on disk but were missing from the index.** Skip `wiki/log.md` and `wiki/index.md` themselves. For standalone `wiki/projects/<slug>/standup.md` without a matching durable project page, add it under Projects and flag it for later durable-page distillation.
|
||||
7. **Write project entries editorially.** The Projects section should group work by the project's concept and purpose, not by issue ids, dates, statuses, UUIDs, or source metadata. Link task identifiers only as supporting evidence.
|
||||
8. **Preserve custom categories.** If the wiki has added e.g. `wiki/papers/` or `wiki/runbooks/`, keep its index section. Do not collapse to the default five categories.
|
||||
9. **Append a log entry** with counts:
|
||||
```
|
||||
## [YYYY-MM-DD] index-refresh | added=N removed=M
|
||||
- operation issue: <issue identifier>
|
||||
```
|
||||
If the index was already accurate, the log entry says `added=0 removed=0` — still write it so future audits can see the run happened.
|
||||
|
||||
## What this skill does NOT do
|
||||
|
||||
- Does not change page content.
|
||||
- Does not resolve contradictions, fix broken links, or fill concept gaps. Those go to the next `wiki-lint` run.
|
||||
- Does not write summaries that are not already supported by the page itself. If a page lacks a clear first paragraph to summarise, flag it for `wiki-lint`.
|
||||
|
||||
## Voice
|
||||
|
||||
- Index entries are one factual line per page, present tense.
|
||||
- No emojis, no statuses, no dates in `wiki/index.md`. Dates live in the log.
|
||||
|
||||
## Verification
|
||||
|
||||
Before closing the operation issue:
|
||||
|
||||
- [ ] `wiki/index.md` matches the actual contents of `wiki/` — no missing pages, no dangling entries.
|
||||
- [ ] Project entries include current `wiki/projects/<slug>/standup.md` links when standups exist.
|
||||
- [ ] Each index line has the form `- [[path]] — <summary>`.
|
||||
- [ ] Custom category sections are preserved.
|
||||
- [ ] `wiki/log.md` has the index-refresh entry with counts (even if the counts are zero).
|
||||
- [ ] No page bodies were modified. No file under `raw/` was modified.
|
||||
|
||||
## Tools
|
||||
|
||||
`wiki_search`, `wiki_read_page`, `wiki_write_page` (for `wiki/index.md` and `wiki/log.md` only). Always include the operation issue's `wikiId` and `spaceSlug`.
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
name: paperclip-distill
|
||||
description: Use when an operation issue is a Paperclip cursor-window, distill, or backfill — `operationType: "distill"` or `"backfill"` and the body references a Paperclip source bundle for a project or root issue. Turn raw Paperclip activity into a wiki-insightful project page, decisions log, and history note. This skill exists specifically to replace the stiff, datestamp-heavy templated output that the deterministic distiller produces.
|
||||
---
|
||||
|
||||
# Paperclip Distill
|
||||
|
||||
Distill Paperclip project, issue, comment, and document activity into durable wiki pages. The success criterion is **wiki-insightful, not procedural**: a reader who has never seen Paperclip should learn what the project is, what was decided, what is at risk, and what the current state is — without scanning a list of `## [YYYY-MM-DD]` headers.
|
||||
|
||||
## When this skill is needed
|
||||
|
||||
- Cursor-window distillation: the routine fed you a bounded source bundle of recent Paperclip activity for one project or root issue.
|
||||
- Backfill: the user asked to seed the wiki with the historical activity of a project or root issue. Source window may be wide.
|
||||
- Manual `distill-paperclip-now` request from the UI.
|
||||
|
||||
If the operation issue is `operationType: "ingest"` (raw file) or `operationType: "query"`, this is the wrong skill — use `wiki-ingest` or `wiki-query`.
|
||||
|
||||
## Destination space
|
||||
|
||||
In Phase 1, every Paperclip distill, backfill, and cursor-window operation writes into the
|
||||
default wiki space. The operation issue should always carry `spaceSlug: "default"`. If an
|
||||
operation issue passes any other slug, stop and surface the mismatch in a comment — do not
|
||||
write Paperclip-derived pages into a non-default space.
|
||||
|
||||
This rule is destination-only. The Paperclip source scope (which projects, root issues,
|
||||
comments, documents are read) is set elsewhere in the operation issue and is independent of
|
||||
the destination.
|
||||
|
||||
## Inputs
|
||||
|
||||
- A Paperclip source bundle (issue list, comment refs, document refs, source hash, cursor window).
|
||||
- An existing or planned `wiki/projects/<slug>/standup.md` page path.
|
||||
- An existing or planned `wiki/projects/<slug>/index.md` page path.
|
||||
- The operation issue's target `wikiId`, `spaceSlug`, space root, and the target space's `AGENTS.md` for page conventions.
|
||||
- The current `wiki/projects/<slug>/standup.md`, `wiki/projects/<slug>/index.md`, `decisions.md`, and `history.md` if they already exist (so you write a *patch*, not a rewrite).
|
||||
|
||||
## Paperclip Asset Gate
|
||||
|
||||
Do not treat Paperclip assets/attachments or issue work products as source text for this skill.
|
||||
|
||||
- Allowed Paperclip body text: issue descriptions, comment bodies, document bodies.
|
||||
- Assets/attachments are metadata-only until a separate approved extraction policy exists.
|
||||
- Work products are metadata-only until a separate approved extraction policy exists.
|
||||
- Never fetch `/api/assets/:id/content`.
|
||||
- Never dereference a work-product `url`, preview URL, artifact URL, or other linked destination from this skill.
|
||||
- If an operator asks for attachment/work-product content distillation, stop and point them at the Phase 5 asset/work-product security gate policy instead of improvising.
|
||||
|
||||
## Anti-patterns to avoid
|
||||
|
||||
The deterministic templating this skill replaces produced these failure modes — do not reproduce them:
|
||||
|
||||
1. **Datestamp-as-section-header.** Lines like `## [2026-04-15] paperclip-distill | proposed` belong in `wiki/log.md`, not in the project page. The project page is durable knowledge; the log is the audit trail.
|
||||
2. **Procedural status lists.** `Issue mix: 3 todo, 5 in_progress, 2 done` tells the reader nothing they could not read off Paperclip directly. State *what is happening and why it matters*, then cite the issues that constitute the evidence.
|
||||
3. **One-line-per-issue dumps.** A page that is mostly `- PAP-1234: title (in_progress, updated 2026-...)` is an issue list, not a wiki page. Group issues by what they are *about* (a decision, a risk, a workstream) and cite multiple issues per bullet when they share a story.
|
||||
4. **Mechanical "Current as of" timestamps everywhere.** One `current_as_of` in frontmatter is enough.
|
||||
5. **No interpretation.** "Active issues: PAP-A, PAP-B, PAP-C" is bookkeeping. "The team is concentrating on the schema migration ([PAP-A], [PAP-B]) and has parked the index work pending capacity ([PAP-C])." is wiki-insightful.
|
||||
6. **Opaque identifiers in prose.** UUIDs, cursor ids, source hashes, run ids, and raw metadata belong in logs or frontmatter when needed, not in executive-facing project narrative.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Read the bundle in full.** Don't sample. Read every issue title, every comment, every document key the bundle includes. Note: which issues are decisions, which are risks/blockers, which are recently completed, which are inflight.
|
||||
2. **Read the existing project page** (if any) so you write a patch, not a rewrite. The "Decisions" section in particular accumulates over time — never wipe accepted decisions; supersede them with `> ⚠ reversed by ...` callouts when something later overrides them.
|
||||
3. **Read the target space's `AGENTS.md`** for page conventions: filename style, YAML frontmatter shape, link style, voice. Always pass the operation issue's `wikiId` and `spaceSlug` to LLM Wiki tools.
|
||||
4. **Write `wiki/projects/<slug>/standup.md` first.** Every Paperclip project represented in the wiki must have this file. It is the executive standup: where the project stands today, what changed recently, what is blocked or risky, and what happens next. Use stable sections, in this order:
|
||||
- Frontmatter (`type: project-standup`, `project: <slug>`, `current_as_of: YYYY-MM-DD`, `sources`).
|
||||
- **Executive Readout** — one short paragraph that explains the current project posture in plain language.
|
||||
- **What Changed** — the meaningful work completed or advanced since the last window. Group by concept; cite issues/comments/documents only as evidence.
|
||||
- **Decisions** — accepted/rejected/reversed decisions that changed the project direction. Omit when none exist.
|
||||
- **Blockers / Risks** — current blockers and risks with named owner or next action when the source provides one.
|
||||
- **Next Actions** — concrete next actions and owners inferred from Paperclip issues, not vague aspirations.
|
||||
- **Links** — durable wiki project page and relevant Paperclip project/issues/documents.
|
||||
Rewrite the standup to today's state. Do not append endless dated sections; the audit trail belongs in `wiki/log.md` and Paperclip comments.
|
||||
5. **Write `wiki/projects/<slug>/index.md`** with these stable sections, in this order:
|
||||
- Frontmatter (`type: project`, `current_as_of: YYYY-MM-DD`, `tags`, `sources`).
|
||||
- **Overview** — 2–4 sentences saying what the project is and why it exists. Use the project description if it exists; otherwise synthesise it from the root issue.
|
||||
- **Current Direction** — narrative paragraph naming the active workstreams, the immediate next concrete deliverable, and the stance on risks. Cite 2–4 issues, do not list 20.
|
||||
- **Workstreams** — a short, grouped list. Each line is a workstream or idea, not an issue.
|
||||
- **Decisions** — accepted and reversed decisions with one paragraph each. Each decision cites the issue / approval / comment that ratified it. Format: `### Decision — short title` then a paragraph; never a bare bullet list.
|
||||
- **Open Risks / Blockers** — what could derail the project, with the issue ref that surfaces it. Skip this section when the bundle has no risk signal — do not pad with `_(none)_`.
|
||||
- **References** — readable links to the current standup and supporting Paperclip tasks/documents. Keep hashes and cursor ids out of the narrative.
|
||||
6. **Optionally write `wiki/projects/<slug>/decisions.md`** when the project has accumulated more decisions than the project page can carry without becoming a wall of text. Each decision is a `## ` section with: short title, accepted/reversed/superseded status, one-paragraph rationale, citing the source. *Do not* duplicate decisions already on the project page — link instead.
|
||||
7. **Optionally write `wiki/projects/<slug>/history.md`** for a compact narrative timeline of meaningful project changes. **Not** an issue dump — group by phase ("Discovery", "Architecture", "Build", "Stabilisation"), not by date. Each phase is a paragraph that cites the 2–4 issues that defined it.
|
||||
8. **Refresh `wiki/index.md`** under the `## Projects` section — one line per durable project page with a one-sentence summary of the project's purpose, plus a link to the current `wiki/projects/<slug>/standup.md` when present.
|
||||
9. **Append `wiki/log.md`** entry — this is where the datestamp belongs:
|
||||
```
|
||||
## [YYYY-MM-DD] paperclip-distill | <project name>
|
||||
- standup: wiki/projects/<slug>/standup.md
|
||||
- page: wiki/projects/<slug>/index.md
|
||||
- source hash: `<hash>`
|
||||
- cursor window: <start> → <end>
|
||||
- notes: <one line on what changed in this distill, e.g. "decisions section grew with PAP-X reversal", "low-signal window, no page changes">
|
||||
```
|
||||
10. **Surface bundle warnings** (clipped sources, low signal, stale hash). Bundle warnings → `human_review_required: true` on the patch. Do not paper over them.
|
||||
|
||||
## Voice
|
||||
|
||||
- Past-tense for completed work, present-tense for current state, future-tense only with citation ("the team plans to … per [[…]]").
|
||||
- Cite Paperclip source refs inline using their issue identifier (e.g. `PAP-3179`), not opaque UUIDs.
|
||||
- Use issue links as evidence, not as the shape of the page. Headings and paragraphs should be organized by concepts, workstreams, decisions, and blockers.
|
||||
- Wiki voice: terse, factual, neutral. No "the team is excited to" or "this initiative aims to".
|
||||
- Headings are about *content*, not metadata. `## Schema migration` not `## Active Issues`.
|
||||
|
||||
## When the bundle has no signal
|
||||
|
||||
If the bundle has no durable signal — no decisions, no risk, no completed work, only routine status churn — do **not** write a project page. Instead:
|
||||
|
||||
- Append a `paperclip-distill | low-signal skip` log entry naming the cursor window.
|
||||
- Close the operation issue with a one-line "no durable change in this window" comment.
|
||||
- Do not bump the source hash on a binding that has no proposed page.
|
||||
|
||||
## Verification
|
||||
|
||||
Before closing the operation issue:
|
||||
|
||||
- [ ] The project page reads as wiki content, not as a Paperclip status report. A reader new to the company should understand what the project is.
|
||||
- [ ] `wiki/projects/<slug>/standup.md` exists for the represented project and reads as an executive current-state update, not a raw issue dump.
|
||||
- [ ] Decisions section names decisions, not issues — every decision has a one-paragraph rationale and a citation.
|
||||
- [ ] The page contains exactly one `current_as_of` (in frontmatter), zero `## [YYYY-MM-DD]` headings (those go to the log).
|
||||
- [ ] Bundle warnings (clipped, low signal, stale hash) are surfaced; the patch carries `human_review_required: true` when the deployment is authenticated/public.
|
||||
- [ ] `wiki/index.md` and `wiki/log.md` are updated.
|
||||
- [ ] No file under `raw/` was modified.
|
||||
|
||||
## Tools
|
||||
|
||||
`wiki_search`, `wiki_read_page`, `wiki_write_page`, `wiki_list_sources`, `wiki_read_source`. Always include the operation issue's `wikiId` and `spaceSlug`. The Paperclip source bundle arrives as part of the operation context — you do not need to assemble it.
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: wiki-ingest
|
||||
description: Use when an operation issue asks you to ingest a captured source from `raw/` into the LLM Wiki, or when the user explicitly says "ingest <slug>". The issue body will name a file under `raw/` (e.g. `raw/karpathy-llm-wiki.md`) and ask for durable wiki pages. Do not invoke this skill for Paperclip activity bundles — those use `paperclip-distill` instead.
|
||||
---
|
||||
|
||||
# Wiki Ingest
|
||||
|
||||
Turn one source document into durable, interlinked wiki knowledge.
|
||||
|
||||
## Inputs
|
||||
|
||||
- An operation issue with `operationType: "ingest"` assigned to you.
|
||||
- A `raw/` path mentioned in the issue body (always treat `raw/` as immutable).
|
||||
- The operation issue's target `wikiId`, `spaceSlug`, and space root (otherwise stop and surface the missing config to the requester).
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Read context first.**
|
||||
- Read the target space's `AGENTS.md` for page conventions (filenames, frontmatter, voice, citation style).
|
||||
- Read the target space's `wiki/index.md` to see what already exists.
|
||||
- Read the target space's last ~20 entries of `wiki/log.md` to avoid re-ingesting a source or re-resolving a contradiction someone else already filed.
|
||||
2. **Read the source end to end** with `wiki_read_source`, passing the operation issue's `wikiId` and `spaceSlug`. Do not skim. Note the source's structure, claims, dates, and anything that contradicts existing pages.
|
||||
3. **Plan, then confirm — but only if the user is in the loop.** If the operation came from a routine (no live user), proceed. If a user is asking interactively, summarise the 3–5 takeaways you intend to file and ask which to emphasise before writing.
|
||||
4. **Write the source page** at `wiki/sources/<slug>.md` — ~300–800 words, frontmatter per the wiki schema, neutral voice, key claims with quoted excerpts where they carry weight. The source page is the canonical citation target for everything else this skill writes.
|
||||
5. **Update or create downstream pages** in `entities/`, `concepts/`, and `synthesis/`. A typical ingest touches 5–15 pages; resist creating pages for ideas that only appear once.
|
||||
6. **Wire the cross-links.** Every claim that comes from the source cites it as `(see [[wiki/sources/<slug>]])`. Every entity / concept mentioned by name on more than one page links to its dedicated page.
|
||||
7. **Flag contradictions; do not silently overwrite.** When new material disagrees with an existing page, append a `> ⚠ contradicted by [[wiki/sources/<slug>]] (YYYY-MM-DD)` callout to the older page and note the conflict in the log.
|
||||
8. **Refresh `wiki/index.md`** with one-line summaries for any new pages.
|
||||
9. **Append a log entry** in `wiki/log.md`:
|
||||
```
|
||||
## [YYYY-MM-DD] ingest | <source title>
|
||||
- source: raw/<filename>
|
||||
- new pages: [[...]], [[...]]
|
||||
- updated pages: [[...]], [[...]]
|
||||
- notes: <one-line synthesis or open question>
|
||||
```
|
||||
|
||||
## Voice
|
||||
|
||||
- Terse, factual, neutral. Reference material, not narrative.
|
||||
- No "Today I learned" or "This is interesting because" framing.
|
||||
- Quote the source verbatim when paraphrasing would lose precision.
|
||||
|
||||
## Verification
|
||||
|
||||
Before closing the operation issue:
|
||||
|
||||
- [ ] Source page exists at `wiki/sources/<slug>.md` with valid frontmatter and a `sources:` field pointing to the raw path.
|
||||
- [ ] Every new or updated page links back to the source page or a downstream page that does.
|
||||
- [ ] `wiki/index.md` lists every new page under the right category with a one-line summary.
|
||||
- [ ] `wiki/log.md` has the ingest entry with the exact filename heading format (so `grep "^## \[" wiki/log.md` keeps working).
|
||||
- [ ] Any contradiction between the new source and an older page is annotated, not silently overwritten.
|
||||
- [ ] No file under `raw/` was modified.
|
||||
|
||||
## Tools
|
||||
|
||||
`wiki_list_sources`, `wiki_read_source`, `wiki_search`, `wiki_read_page`, `wiki_write_page`. Always include the operation issue's `wikiId` and `spaceSlug`.
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: wiki-lint
|
||||
description: Use when an operation issue is a lint or health-check (`operationType: "lint"`) — typically the nightly lint routine or a manual "Run lint" from the UI. Audit the wiki for contradictions, orphans, weak provenance, broken links, and missing concept pages, and return a triage list — do not auto-fix.
|
||||
---
|
||||
|
||||
# Wiki Lint
|
||||
|
||||
Audit, do not edit. Return findings the maintainer (human or agent) can triage.
|
||||
|
||||
## Inputs
|
||||
|
||||
- An operation issue with `operationType: "lint"`.
|
||||
- The operation issue's target `wikiId`, `spaceSlug`, and space root. Lint only that space unless the issue explicitly says this is a multi-space sweep.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Walk the target space's `wiki/index.md` and wiki tree** with `wiki_search` and `wiki_read_page`, always passing the operation issue's `wikiId` and `spaceSlug`. Build a mental map of: pages that exist, pages referenced from `index.md`, pages referenced from other pages, and raw sources.
|
||||
2. **Check for the seven recurring issues**, in this order:
|
||||
1. **Contradictions** — two pages making incompatible claims about the same entity, decision, or status. Flag both pages, name the conflicting claims, and quote evidence.
|
||||
2. **Stale claims** — a page asserts X, but a newer source under `raw/` has superseded it. Flag the older page; never overwrite.
|
||||
3. **Orphan pages** — a `wiki/` page is not linked from `index.md` and not referenced from any other wiki page. Either it should be linked, removed, or merged.
|
||||
4. **Concept gaps** — a term appears on three or more pages but has no dedicated `wiki/concepts/<slug>.md`. Recommend creating one.
|
||||
5. **Broken `[[wiki-links]]`** — a link target file does not exist.
|
||||
6. **Weak provenance** — a non-trivial claim is uncited or cites only the wiki itself in a circle. The original source ref should be findable.
|
||||
7. **Index / log drift** — pages exist that are not in `index.md`, or `index.md` lists pages that no longer exist. Recent operations in `wiki/log.md` that did not produce a corresponding page change.
|
||||
3. **Return a triage list**, grouped by severity:
|
||||
- **critical**: contradictions, broken links to active pages, fabricated citations.
|
||||
- **medium**: stale claims, weak provenance, large concept gaps.
|
||||
- **low**: orphans, log drift, small index gaps.
|
||||
Each item has: file path, evidence (a 1–2 line quote), suggested fix, and the operation that should follow up (`ingest`, `paperclip-distill`, `index-refresh`, manual review).
|
||||
4. **Do not write to `wiki/`.** Lint is read-only by design — the maintainer or the routine that follows decides which findings to act on.
|
||||
5. **Append a log entry** describing the run:
|
||||
```
|
||||
## [YYYY-MM-DD] lint | <N findings, M critical>
|
||||
- operation issue: <issue identifier>
|
||||
- critical: <count>
|
||||
- medium: <count>
|
||||
- low: <count>
|
||||
```
|
||||
|
||||
## Voice
|
||||
|
||||
- Lead with the count by severity.
|
||||
- Each finding is one bullet. Resist commentary.
|
||||
- When in doubt about severity, say so and surface it as medium with a "verify" note.
|
||||
|
||||
## Verification
|
||||
|
||||
Before closing the operation issue:
|
||||
|
||||
- [ ] Findings are grouped by severity with file paths, evidence, and suggested fix per item.
|
||||
- [ ] No files under `raw/` were modified. No files under `wiki/` were modified except `wiki/log.md`.
|
||||
- [ ] If the run found nothing, the issue is closed with "no findings" and the log entry still exists so future audits can see this run happened.
|
||||
|
||||
## Tools
|
||||
|
||||
`wiki_search`, `wiki_read_page`, `wiki_list_sources`, `wiki_read_source`, `wiki_write_page` (only `wiki/log.md`). Always include the operation issue's `wikiId` and `spaceSlug`.
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
name: "LLM Wiki Maintainer"
|
||||
description: "Use the LLM Wiki plugin tools to maintain a cited local company wiki."
|
||||
---
|
||||
|
||||
# LLM Wiki Maintainer
|
||||
|
||||
Use this skill when maintaining the company LLM Wiki, answering questions from it, ingesting durable source material, refreshing the index, or linting wiki structure.
|
||||
|
||||
Before changing wiki files, resolve the configured wiki root, read its AGENTS.md, inspect wiki/index.md and recent wiki/log.md entries, then use the LLM Wiki plugin tools for source reads, page writes, patch proposals, backlinks, and logging.
|
||||
|
||||
Keep raw sources immutable, cite wiki pages and raw paths, update wiki/index.md when page navigation changes, and append a concise wiki/log.md entry for durable updates. For Paperclip project work, keep `wiki/projects/<project-slug>/standup.md` current as the executive status view and use `wiki/projects/<project-slug>/index.md` for durable project knowledge. Write project material as concept-grouped executive synthesis, not issue-id lists or metadata dumps.
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
name: wiki-query
|
||||
description: Use when an operation issue asks you to answer a question from the LLM Wiki — `operationType: "query"` and a question in the issue body. Answer with citations to wiki pages and raw sources, and offer to file durable synthesis back into `wiki/synthesis/` so the work compounds instead of disappearing into a chat thread.
|
||||
---
|
||||
|
||||
# Wiki Query
|
||||
|
||||
Answer a question from what the wiki actually contains, with citations.
|
||||
|
||||
## Inputs
|
||||
|
||||
- An operation issue with `operationType: "query"` and the question in the body.
|
||||
- The operation issue's target `wikiId`, `spaceSlug`, and space root.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Open the target space's `wiki/index.md` first** — it is the navigation aid. Identify candidate pages.
|
||||
2. **Read the candidate pages** end to end with `wiki_read_page`, always passing the operation issue's `wikiId` and `spaceSlug`. Follow `[[wiki-links]]` to neighbouring pages when the question spans entities or concepts.
|
||||
3. **Inspect raw sources** when a wiki page's claim feels thin. The wiki points to `raw/` precisely so you can verify before answering. Use `wiki_read_source`.
|
||||
4. **Answer the question** in the operation issue thread. Structure:
|
||||
- Direct answer first, in 1–4 sentences.
|
||||
- Then the supporting facts as bullet points, each with an inline citation: `(see [[wiki/concepts/managed-resources]])` or `(see raw/<filename>)`.
|
||||
- If you needed to read a raw source the wiki did not summarise, name that as a gap.
|
||||
5. **Decide whether the answer is durable.** If the question forced you to do real synthesis (a comparison, a tradeoff, a definition of something that isn't already a page), offer to file it under `wiki/synthesis/<slug>.md`. Do not write the synthesis page silently — it is opt-in. If the user accepts, write the page, link it from `wiki/index.md`, and append a `query | filed synthesis` log entry.
|
||||
6. **When the wiki cannot answer**, say so plainly. Suggest a source the user should ingest, a Paperclip project that would help if distilled, or a web lookup. Never bluff.
|
||||
|
||||
## Voice
|
||||
|
||||
- Lead with the answer.
|
||||
- Cite as you go, not in a footnote block at the end.
|
||||
- Use the wiki's terse, factual voice. The query response is itself a candidate for filing into `wiki/synthesis/`.
|
||||
|
||||
## Verification
|
||||
|
||||
Before closing the operation issue:
|
||||
|
||||
- [ ] Every claim in the answer cites a wiki page or raw source.
|
||||
- [ ] If the wiki was insufficient, that is stated directly with a concrete next step (ingest source X, distill project Y, web search Z).
|
||||
- [ ] If you wrote a synthesis page, `wiki/index.md` lists it and `wiki/log.md` has a `query | filed synthesis` entry.
|
||||
- [ ] No file under `raw/` was modified.
|
||||
|
||||
## Tools
|
||||
|
||||
`wiki_search`, `wiki_read_page`, `wiki_list_sources`, `wiki_read_source`, `wiki_write_page` (only when filing synthesis). Always include the operation issue's `wikiId` and `spaceSlug`.
|
||||
@@ -0,0 +1,601 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
import { DEFAULT_AGENT_INSTRUCTION_FILES, DEFAULT_AGENT_INSTRUCTIONS } from "./templates.js";
|
||||
|
||||
export const PLUGIN_ID = "paperclipai.plugin-llm-wiki";
|
||||
export const WIKI_ROOT_FOLDER_KEY = "wiki-root";
|
||||
export const WIKI_MAINTAINER_AGENT_KEY = "wiki-maintainer";
|
||||
export const WIKI_MAINTAINER_SKILL_KEY = "wiki-maintainer";
|
||||
export const WIKI_INGEST_SKILL_KEY = "wiki-ingest";
|
||||
export const WIKI_QUERY_SKILL_KEY = "wiki-query";
|
||||
export const WIKI_LINT_SKILL_KEY = "wiki-lint";
|
||||
export const PAPERCLIP_DISTILL_SKILL_KEY = "paperclip-distill";
|
||||
export const INDEX_REFRESH_SKILL_KEY = "index-refresh";
|
||||
export const WIKI_PROJECT_KEY = "llm-wiki";
|
||||
export const CURSOR_WINDOW_ROUTINE_KEY = "cursor-window-processing";
|
||||
export const NIGHTLY_LINT_ROUTINE_KEY = "nightly-wiki-lint";
|
||||
export const INDEX_REFRESH_ROUTINE_KEY = "index-refresh";
|
||||
export const DEFAULT_MAX_SOURCE_BYTES = 250000;
|
||||
export const DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS = 12000;
|
||||
export const DEFAULT_MAX_PAPERCLIP_CURSOR_WINDOW_CHARS = 60000;
|
||||
export const DEFAULT_MAX_PAPERCLIP_ROUTINE_RUN_CHARS = 120000;
|
||||
export const DEFAULT_PAPERCLIP_COST_CENTS_PER_1K_CHARS = 1;
|
||||
export const WIKI_MAINTENANCE_ROUTINE_KEYS = [
|
||||
CURSOR_WINDOW_ROUTINE_KEY,
|
||||
NIGHTLY_LINT_ROUTINE_KEY,
|
||||
INDEX_REFRESH_ROUTINE_KEY,
|
||||
] as const;
|
||||
export const WIKI_MANAGED_SKILL_KEYS = [
|
||||
WIKI_MAINTAINER_SKILL_KEY,
|
||||
WIKI_INGEST_SKILL_KEY,
|
||||
WIKI_QUERY_SKILL_KEY,
|
||||
WIKI_LINT_SKILL_KEY,
|
||||
PAPERCLIP_DISTILL_SKILL_KEY,
|
||||
INDEX_REFRESH_SKILL_KEY,
|
||||
] as const;
|
||||
|
||||
function canonicalSkillKey(skillKey: string) {
|
||||
return `plugin/paperclipai-plugin-llm-wiki/${skillKey}`;
|
||||
}
|
||||
|
||||
function skillMarkdown(skillKey: (typeof WIKI_MANAGED_SKILL_KEYS)[number]) {
|
||||
return readFileSync(new URL(`../skills/${skillKey}/SKILL.md`, import.meta.url), "utf8");
|
||||
}
|
||||
|
||||
export const WIKI_MAINTAINER_SKILL_CANONICAL_KEY = canonicalSkillKey(WIKI_MAINTAINER_SKILL_KEY);
|
||||
export const WIKI_MANAGED_SKILL_CANONICAL_KEYS = WIKI_MANAGED_SKILL_KEYS.map(canonicalSkillKey);
|
||||
|
||||
const CURSOR_WINDOW_ROUTINE_DESCRIPTION = `Process bounded Paperclip issue-history windows into the LLM Wiki.
|
||||
|
||||
Run procedure:
|
||||
Target space: default (slug: default). Paperclip-derived indexing currently writes only into the default space, so this routine never sweeps other spaces. Per-space Paperclip ingestion profiles are a later phase; until they ship, treat any prompt to operate on a non-default space here as a bug and stop.
|
||||
1. Resolve the configured wiki root, then read the default space AGENTS.md, wiki/index.md, and the recent entries in wiki/log.md.
|
||||
2. Review recent Paperclip issue, comment, and document activity for non-plugin-operation work. Skip LLM Wiki operation issues so routine output does not feed back into itself.
|
||||
3. Synthesize Paperclip project state into wiki/projects/<slug>/standup.md for the executive current-state view, then durable project or root-issue knowledge into focused pages under wiki/projects/<slug>/index.md, wiki/concepts/, or wiki/synthesis/. Keep transient run logs out of durable pages unless they change the project's state or decisions.
|
||||
4. Write project material as concept-grouped executive synthesis. Link readable issue identifiers when useful, but do not turn project pages into issue-ID lists, UUID dumps, date ledgers, or metadata reports. Always pass wikiId \`default\` and spaceSlug \`default\` to LLM Wiki tools.
|
||||
5. Refresh wiki/index.md and append a short wiki/log.md entry listing the source window, affected pages, skipped windows, warnings, and any follow-up issue needed.
|
||||
6. If there is no new durable signal, record that in wiki/log.md and close the routine issue with a concise note.`;
|
||||
|
||||
const NIGHTLY_LINT_ROUTINE_DESCRIPTION = `Lint the LLM Wiki for structure, provenance, and stale synthesis.
|
||||
|
||||
Run procedure:
|
||||
Target space: default (slug: default). Paperclip-derived indexing currently writes only into the default space, so this routine never sweeps other spaces. Per-space Paperclip ingestion profiles are a later phase; until they ship, treat any prompt to operate on a non-default space here as a bug and stop.
|
||||
1. Resolve the configured wiki root, then read the default space AGENTS.md, wiki/index.md, wiki/log.md, and the current page list.
|
||||
2. Check for orphan pages, missing backlinks, stale source provenance, weak citations, duplicate concepts, contradictory claims, and index/log drift.
|
||||
3. Inspect the relevant wiki pages and raw sources before changing content. Do not invent missing provenance.
|
||||
4. Apply low-risk fixes directly: refresh backlinks, repair index entries, add missing source links, and append a wiki/log.md lint entry. Always pass wikiId \`default\` and spaceSlug \`default\` to LLM Wiki tools.
|
||||
5. For ambiguous contradictions or major rewrites, leave the pages unchanged and create or comment a follow-up Paperclip issue with the exact files and evidence.
|
||||
6. Close the routine issue with counts by severity, files changed, and unresolved findings.`;
|
||||
|
||||
const INDEX_REFRESH_ROUTINE_DESCRIPTION = `Refresh the LLM Wiki navigation and change log.
|
||||
|
||||
Run procedure:
|
||||
Target space: default (slug: default). Paperclip-derived indexing currently writes only into the default space, so this routine never sweeps other spaces. Per-space Paperclip ingestion profiles are a later phase; until they ship, treat any prompt to operate on a non-default space here as a bug and stop.
|
||||
1. Resolve the configured wiki root, then read the default space AGENTS.md, wiki/index.md, wiki/log.md, and the current page list.
|
||||
2. Rebuild wiki/index.md so it lists current wiki pages by category with concise summaries and valid wikilinks, and attaches wiki/projects/<slug>/standup.md links to matching project entries.
|
||||
3. Verify recently changed wiki pages and project standups are present in the index and that removed or renamed pages no longer appear.
|
||||
4. Do not rewrite content pages unless a broken title or link prevents the index from being accurate. Always pass wikiId \`default\` and spaceSlug \`default\` to LLM Wiki tools.
|
||||
5. Append a wiki/log.md entry with the index refresh time, page counts by category, and any unresolved indexing problems.
|
||||
6. Close the routine issue with the index changes and any follow-up needed.`;
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: PLUGIN_ID,
|
||||
apiVersion: 1,
|
||||
version: "0.1.0",
|
||||
displayName: "LLM Wiki",
|
||||
description: "Local-file LLM Wiki plugin for source ingestion, wiki browsing, query, lint, and maintenance workflows.",
|
||||
author: "Paperclip",
|
||||
categories: ["automation", "ui"],
|
||||
capabilities: [
|
||||
"events.subscribe",
|
||||
"api.routes.register",
|
||||
"database.namespace.migrate",
|
||||
"database.namespace.read",
|
||||
"database.namespace.write",
|
||||
"companies.read",
|
||||
"projects.read",
|
||||
"projects.managed",
|
||||
"skills.managed",
|
||||
"issues.read",
|
||||
"issue.subtree.read",
|
||||
"issues.create",
|
||||
"issues.update",
|
||||
"issues.wakeup",
|
||||
"issues.orchestration.read",
|
||||
"issue.comments.read",
|
||||
"issue.comments.create",
|
||||
"issue.documents.read",
|
||||
"issue.documents.write",
|
||||
"agents.read",
|
||||
"agents.managed",
|
||||
"agent.sessions.create",
|
||||
"agent.sessions.list",
|
||||
"agent.sessions.send",
|
||||
"agent.sessions.close",
|
||||
"routines.managed",
|
||||
"local.folders",
|
||||
"agent.tools.register",
|
||||
"metrics.write",
|
||||
"activity.log.write",
|
||||
"plugin.state.read",
|
||||
"plugin.state.write",
|
||||
"ui.sidebar.register",
|
||||
"ui.page.register"
|
||||
],
|
||||
entrypoints: {
|
||||
worker: "./dist/worker.js",
|
||||
ui: "./dist/ui"
|
||||
},
|
||||
database: {
|
||||
namespaceSlug: "llm_wiki",
|
||||
migrationsDir: "migrations",
|
||||
coreReadTables: ["companies", "issues", "projects", "agents"]
|
||||
},
|
||||
localFolders: [
|
||||
{
|
||||
folderKey: WIKI_ROOT_FOLDER_KEY,
|
||||
displayName: "Wiki root",
|
||||
description: "Company-scoped local folder that stores raw sources, wiki pages, Paperclip project standups under wiki/projects/, AGENTS.md, IDEA.md, wiki/index.md, and wiki/log.md.",
|
||||
access: "readWrite",
|
||||
requiredDirectories: [
|
||||
"raw",
|
||||
"wiki",
|
||||
"wiki/sources",
|
||||
"wiki/projects",
|
||||
"wiki/entities",
|
||||
"wiki/concepts",
|
||||
"wiki/synthesis"
|
||||
],
|
||||
requiredFiles: ["AGENTS.md", "IDEA.md", "wiki/index.md", "wiki/log.md"]
|
||||
}
|
||||
],
|
||||
agents: [
|
||||
{
|
||||
agentKey: WIKI_MAINTAINER_AGENT_KEY,
|
||||
displayName: "Wiki Maintainer",
|
||||
role: "knowledge-maintainer",
|
||||
title: "LLM Wiki Maintainer",
|
||||
icon: "book-open",
|
||||
capabilities: "Ingests source material, maintains local wiki pages, answers cited questions, and runs wiki lint/maintenance through plugin tools.",
|
||||
adapterType: "claude_local",
|
||||
adapterPreference: ["claude_local", "codex_local", "gemini_local", "opencode_local", "cursor", "pi_local"],
|
||||
adapterConfig: {
|
||||
dangerouslySkipPermissions: false,
|
||||
dangerouslyBypassApprovalsAndSandbox: false,
|
||||
sandbox: true,
|
||||
paperclipSkillSync: {
|
||||
desiredSkills: WIKI_MANAGED_SKILL_CANONICAL_KEYS
|
||||
}
|
||||
},
|
||||
runtimeConfig: {
|
||||
modelProfiles: {
|
||||
cheap: {
|
||||
purpose: "classification, lint planning, index maintenance"
|
||||
}
|
||||
}
|
||||
},
|
||||
permissions: {
|
||||
pluginTools: [PLUGIN_ID]
|
||||
},
|
||||
status: "paused",
|
||||
budgetMonthlyCents: 0,
|
||||
instructions: {
|
||||
entryFile: "AGENTS.md",
|
||||
content: DEFAULT_AGENT_INSTRUCTIONS,
|
||||
files: DEFAULT_AGENT_INSTRUCTION_FILES,
|
||||
assetPath: "agents/wiki-maintainer"
|
||||
}
|
||||
}
|
||||
],
|
||||
projects: [
|
||||
{
|
||||
projectKey: WIKI_PROJECT_KEY,
|
||||
displayName: "LLM Wiki",
|
||||
description: "Plugin-managed inspection area for LLM Wiki ingest, query, lint, and maintenance operation issues.",
|
||||
status: "in_progress",
|
||||
color: "#2563eb"
|
||||
}
|
||||
],
|
||||
skills: [
|
||||
{
|
||||
skillKey: WIKI_MAINTAINER_SKILL_KEY,
|
||||
displayName: "LLM Wiki Maintainer",
|
||||
slug: "llm-wiki-maintainer",
|
||||
description: "Use the LLM Wiki plugin tools to maintain a cited local company wiki.",
|
||||
markdown: skillMarkdown(WIKI_MAINTAINER_SKILL_KEY)
|
||||
},
|
||||
{
|
||||
skillKey: WIKI_INGEST_SKILL_KEY,
|
||||
displayName: "Wiki Ingest",
|
||||
slug: WIKI_INGEST_SKILL_KEY,
|
||||
description: "Turn captured raw source material into cited durable LLM Wiki pages.",
|
||||
markdown: skillMarkdown(WIKI_INGEST_SKILL_KEY)
|
||||
},
|
||||
{
|
||||
skillKey: WIKI_QUERY_SKILL_KEY,
|
||||
displayName: "Wiki Query",
|
||||
slug: WIKI_QUERY_SKILL_KEY,
|
||||
description: "Answer questions from the LLM Wiki with citations and optional durable synthesis.",
|
||||
markdown: skillMarkdown(WIKI_QUERY_SKILL_KEY)
|
||||
},
|
||||
{
|
||||
skillKey: WIKI_LINT_SKILL_KEY,
|
||||
displayName: "Wiki Lint",
|
||||
slug: WIKI_LINT_SKILL_KEY,
|
||||
description: "Audit the LLM Wiki for contradictions, orphan pages, weak provenance, broken links, and missing concepts.",
|
||||
markdown: skillMarkdown(WIKI_LINT_SKILL_KEY)
|
||||
},
|
||||
{
|
||||
skillKey: PAPERCLIP_DISTILL_SKILL_KEY,
|
||||
displayName: "Paperclip Distill",
|
||||
slug: PAPERCLIP_DISTILL_SKILL_KEY,
|
||||
description: "Turn Paperclip cursor-window, distill, or backfill source bundles into wiki-insightful project knowledge.",
|
||||
markdown: skillMarkdown(PAPERCLIP_DISTILL_SKILL_KEY)
|
||||
},
|
||||
{
|
||||
skillKey: INDEX_REFRESH_SKILL_KEY,
|
||||
displayName: "Index Refresh",
|
||||
slug: INDEX_REFRESH_SKILL_KEY,
|
||||
description: "Refresh wiki/index.md so it accurately catalogs current wiki pages.",
|
||||
markdown: skillMarkdown(INDEX_REFRESH_SKILL_KEY)
|
||||
}
|
||||
],
|
||||
routines: [
|
||||
{
|
||||
routineKey: CURSOR_WINDOW_ROUTINE_KEY,
|
||||
title: "Process LLM Wiki updates",
|
||||
description: CURSOR_WINDOW_ROUTINE_DESCRIPTION,
|
||||
status: "paused",
|
||||
priority: "low",
|
||||
assigneeRef: { resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY },
|
||||
projectRef: { resourceKind: "project", resourceKey: WIKI_PROJECT_KEY },
|
||||
concurrencyPolicy: "skip_if_active",
|
||||
catchUpPolicy: "skip_missed",
|
||||
triggers: [
|
||||
{
|
||||
kind: "schedule",
|
||||
label: "Every 6 hours",
|
||||
enabled: false,
|
||||
cronExpression: "0 */6 * * *",
|
||||
timezone: "UTC",
|
||||
signingMode: null,
|
||||
replayWindowSec: null
|
||||
}
|
||||
],
|
||||
issueTemplate: {
|
||||
surfaceVisibility: "plugin_operation",
|
||||
originId: "routine:cursor-window-processing",
|
||||
billingCode: "plugin-llm-wiki:distillation"
|
||||
}
|
||||
},
|
||||
{
|
||||
routineKey: NIGHTLY_LINT_ROUTINE_KEY,
|
||||
title: "Run LLM Wiki lint",
|
||||
description: NIGHTLY_LINT_ROUTINE_DESCRIPTION,
|
||||
status: "paused",
|
||||
priority: "low",
|
||||
assigneeRef: { resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY },
|
||||
projectRef: { resourceKind: "project", resourceKey: WIKI_PROJECT_KEY },
|
||||
concurrencyPolicy: "skip_if_active",
|
||||
catchUpPolicy: "skip_missed",
|
||||
triggers: [
|
||||
{
|
||||
kind: "schedule",
|
||||
label: "Nightly",
|
||||
enabled: false,
|
||||
cronExpression: "0 3 * * *",
|
||||
timezone: "UTC",
|
||||
signingMode: null,
|
||||
replayWindowSec: null
|
||||
}
|
||||
],
|
||||
issueTemplate: {
|
||||
surfaceVisibility: "plugin_operation",
|
||||
originId: "routine:nightly-wiki-lint",
|
||||
billingCode: "plugin-llm-wiki:maintenance"
|
||||
}
|
||||
},
|
||||
{
|
||||
routineKey: INDEX_REFRESH_ROUTINE_KEY,
|
||||
title: "Refresh LLM Wiki index",
|
||||
description: INDEX_REFRESH_ROUTINE_DESCRIPTION,
|
||||
status: "paused",
|
||||
priority: "low",
|
||||
assigneeRef: { resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY },
|
||||
projectRef: { resourceKind: "project", resourceKey: WIKI_PROJECT_KEY },
|
||||
concurrencyPolicy: "skip_if_active",
|
||||
catchUpPolicy: "skip_missed",
|
||||
triggers: [
|
||||
{
|
||||
kind: "schedule",
|
||||
label: "Hourly",
|
||||
enabled: false,
|
||||
cronExpression: "0 * * * *",
|
||||
timezone: "UTC",
|
||||
signingMode: null,
|
||||
replayWindowSec: null
|
||||
}
|
||||
],
|
||||
issueTemplate: {
|
||||
surfaceVisibility: "plugin_operation",
|
||||
originId: "routine:index-refresh",
|
||||
billingCode: "plugin-llm-wiki:maintenance"
|
||||
}
|
||||
}
|
||||
],
|
||||
tools: [
|
||||
{
|
||||
name: "wiki_search",
|
||||
displayName: "Search Wiki",
|
||||
description: "Search indexed wiki page and source metadata for one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
query: { type: "string" },
|
||||
limit: { type: "number" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "query"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_read_page",
|
||||
displayName: "Read Wiki Page",
|
||||
description: "Read a markdown wiki page from one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
path: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "path"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_write_page",
|
||||
displayName: "Write Wiki Page",
|
||||
description: "Atomically write a markdown wiki page in one wiki space after plugin path validation and optional hash conflict checks. Operation agents should pass the issue's spaceSlug; omitting it uses the default space. Protected control files such as AGENTS.md and IDEA.md are excluded from agent-tool writes.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
path: { type: "string" },
|
||||
contents: { type: "string" },
|
||||
expectedHash: { type: "string" },
|
||||
summary: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "path", "contents"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_propose_patch",
|
||||
displayName: "Propose Wiki Patch",
|
||||
description: "Return a structured proposed page write for one wiki space without changing files. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
path: { type: "string" },
|
||||
contents: { type: "string" },
|
||||
summary: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "path", "contents"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_list_sources",
|
||||
displayName: "List Wiki Sources",
|
||||
description: "Return captured raw source metadata from one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
limit: { type: "number" }
|
||||
},
|
||||
required: ["companyId", "wikiId"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_read_source",
|
||||
displayName: "Read Wiki Source",
|
||||
description: "Read a captured raw source from one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
rawPath: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "rawPath"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_append_log",
|
||||
displayName: "Append Wiki Log",
|
||||
description: "Append a maintenance note to one wiki space's wiki/log.md. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
entry: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "entry"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_update_index",
|
||||
displayName: "Update Wiki Index",
|
||||
description: "Atomically replace one wiki space's wiki/index.md with optional hash conflict checks. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
contents: { type: "string" },
|
||||
expectedHash: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "contents"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_list_backlinks",
|
||||
displayName: "List Wiki Backlinks",
|
||||
description: "Return indexed backlinks for a wiki page in one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" },
|
||||
path: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId", "path"]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "wiki_list_pages",
|
||||
displayName: "List Wiki Pages",
|
||||
description: "Return the known page index from one wiki space's plugin metadata. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
|
||||
parametersSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
companyId: { type: "string" },
|
||||
wikiId: { type: "string" },
|
||||
spaceSlug: { type: "string" }
|
||||
},
|
||||
required: ["companyId", "wikiId"]
|
||||
}
|
||||
}
|
||||
],
|
||||
apiRoutes: [
|
||||
{
|
||||
routeKey: "overview",
|
||||
method: "GET",
|
||||
path: "/overview",
|
||||
auth: "board-or-agent",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "query", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "bootstrap",
|
||||
method: "POST",
|
||||
path: "/bootstrap",
|
||||
auth: "board",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "capture-source",
|
||||
method: "POST",
|
||||
path: "/sources",
|
||||
auth: "board-or-agent",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "spaces",
|
||||
method: "GET",
|
||||
path: "/spaces",
|
||||
auth: "board-or-agent",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "query", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "create-space",
|
||||
method: "POST",
|
||||
path: "/spaces",
|
||||
auth: "board",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "update-space",
|
||||
method: "PATCH",
|
||||
path: "/spaces/:spaceSlug",
|
||||
auth: "board",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "bootstrap-space",
|
||||
method: "POST",
|
||||
path: "/spaces/:spaceSlug/bootstrap",
|
||||
auth: "board",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "archive-space",
|
||||
method: "POST",
|
||||
path: "/spaces/:spaceSlug/archive",
|
||||
auth: "board",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "operations",
|
||||
method: "GET",
|
||||
path: "/operations",
|
||||
auth: "board-or-agent",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "query", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "start-query",
|
||||
method: "POST",
|
||||
path: "/query-sessions",
|
||||
auth: "board",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
},
|
||||
{
|
||||
routeKey: "file-as-page",
|
||||
method: "POST",
|
||||
path: "/file-as-page",
|
||||
auth: "board",
|
||||
capability: "api.routes.register",
|
||||
companyResolution: { from: "body", key: "companyId" }
|
||||
}
|
||||
],
|
||||
ui: {
|
||||
slots: [
|
||||
{
|
||||
type: "sidebar",
|
||||
id: "wiki-sidebar",
|
||||
displayName: "Wiki",
|
||||
exportName: "SidebarLink",
|
||||
order: 35
|
||||
},
|
||||
{
|
||||
type: "page",
|
||||
id: "wiki-page",
|
||||
displayName: "Wiki",
|
||||
exportName: "WikiPage",
|
||||
routePath: "wiki"
|
||||
},
|
||||
{
|
||||
type: "routeSidebar",
|
||||
id: "wiki-route-sidebar",
|
||||
displayName: "Wiki",
|
||||
exportName: "WikiRouteSidebar",
|
||||
routePath: "wiki"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
export default manifest;
|
||||
@@ -0,0 +1,73 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
|
||||
export const REQUIRED_WIKI_DIRECTORIES = [
|
||||
"raw",
|
||||
"wiki",
|
||||
"wiki/sources",
|
||||
"wiki/projects",
|
||||
"wiki/entities",
|
||||
"wiki/concepts",
|
||||
"wiki/synthesis",
|
||||
] as const;
|
||||
|
||||
export const REQUIRED_WIKI_FILES = ["AGENTS.md", "IDEA.md", "wiki/index.md", "wiki/log.md"] as const;
|
||||
export const KARPATHY_LLM_WIKI_GIST_URL = "https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f";
|
||||
|
||||
function templateFile(path: string): string {
|
||||
return readFileSync(new URL(`../templates/${path}`, import.meta.url), "utf8");
|
||||
}
|
||||
|
||||
function agentInstructionFiles(agentKey: string): Record<string, string> {
|
||||
const root = new URL(`../agents/${agentKey}/`, import.meta.url);
|
||||
const files: Record<string, string> = {};
|
||||
|
||||
function walk(relativeDir: string) {
|
||||
const dirUrl = new URL(relativeDir ? `${relativeDir}/` : "./", root);
|
||||
for (const entry of readdirSync(dirUrl)) {
|
||||
if (entry === ".DS_Store") continue;
|
||||
const relativePath = relativeDir ? `${relativeDir}/${entry}` : entry;
|
||||
const entryUrl = new URL(relativePath, root);
|
||||
const stat = statSync(entryUrl);
|
||||
if (stat.isDirectory()) {
|
||||
walk(relativePath);
|
||||
} else if (stat.isFile()) {
|
||||
files[relativePath] = readFileSync(entryUrl, "utf8");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk("");
|
||||
return Object.fromEntries(Object.entries(files).sort(([left], [right]) => left.localeCompare(right)));
|
||||
}
|
||||
|
||||
export const DEFAULT_WIKI_SCHEMA = templateFile("AGENTS.md");
|
||||
export const DEFAULT_AGENT_INSTRUCTION_FILES = agentInstructionFiles("wiki-maintainer");
|
||||
export const DEFAULT_AGENT_INSTRUCTIONS = DEFAULT_AGENT_INSTRUCTION_FILES["AGENTS.md"] ?? "";
|
||||
export const DEFAULT_IDEA = templateFile("IDEA.md");
|
||||
export const DEFAULT_INDEX = templateFile("wiki/index.md");
|
||||
export const DEFAULT_LOG = templateFile("wiki/log.md");
|
||||
export const DEFAULT_GITIGNORE = templateFile("gitignore.template");
|
||||
|
||||
export const QUERY_PROMPT = `Answer from the LLM Wiki using the installed wiki-query skill.
|
||||
|
||||
Read the target space's wiki/index.md first, inspect relevant pages and raw/source references in that same space, cite the wiki page paths and raw source paths used, and say when the wiki does not contain enough evidence. Useful durable synthesis should be filed back into wiki/synthesis/ inside that same space. Always pass the operation issue's wikiId and spaceSlug to LLM Wiki tools.
|
||||
`;
|
||||
|
||||
export const LINT_PROMPT = `Lint the LLM Wiki using the installed wiki-lint skill.
|
||||
|
||||
Audit the target space only for contradictions, stale claims, orphan pages, missing backlinks, weak provenance, and wiki/index.md / wiki/log.md drift. Also look for important concepts mentioned without pages and answers that should have been filed back into wiki/. Return findings grouped by severity with concrete file paths, evidence, and suggested fixes — do not auto-apply edits. Always pass the operation issue's wikiId and spaceSlug to LLM Wiki tools.
|
||||
`;
|
||||
|
||||
export const BOOTSTRAP_FILES: ReadonlyArray<{ path: string; contents: string }> = [
|
||||
{ path: ".gitignore", contents: DEFAULT_GITIGNORE },
|
||||
{ path: "AGENTS.md", contents: DEFAULT_WIKI_SCHEMA },
|
||||
{ path: "IDEA.md", contents: DEFAULT_IDEA },
|
||||
{ path: "wiki/index.md", contents: DEFAULT_INDEX },
|
||||
{ path: "wiki/log.md", contents: DEFAULT_LOG },
|
||||
{ path: "raw/.gitkeep", contents: "" },
|
||||
{ path: "wiki/sources/.gitkeep", contents: "" },
|
||||
{ path: "wiki/projects/.gitkeep", contents: "" },
|
||||
{ path: "wiki/entities/.gitkeep", contents: "" },
|
||||
{ path: "wiki/concepts/.gitkeep", contents: "" },
|
||||
{ path: "wiki/synthesis/.gitkeep", contents: "" },
|
||||
];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
export { SidebarLink, SettingsPage, WikiPage, WikiRouteSidebar } from "./app.js";
|
||||
@@ -0,0 +1,49 @@
|
||||
type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
||||
|
||||
export type IngestSourceActionResult = {
|
||||
operation?: {
|
||||
issue?: {
|
||||
id?: unknown;
|
||||
} | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export function readIngestOperationIssueId(result: unknown): string {
|
||||
const issueId = (result as IngestSourceActionResult | null)?.operation?.issue?.id;
|
||||
if (typeof issueId === "string" && issueId.trim()) return issueId;
|
||||
throw new Error("Ingest operation did not return an issue id; the dropped file could not be attached.");
|
||||
}
|
||||
|
||||
async function readUploadError(response: Response): Promise<string> {
|
||||
const body = await response.json().catch(() => null);
|
||||
if (body && typeof body === "object") {
|
||||
const error = (body as { error?: unknown; message?: unknown }).error;
|
||||
if (typeof error === "string" && error.trim()) return error;
|
||||
const message = (body as { error?: unknown; message?: unknown }).message;
|
||||
if (typeof message === "string" && message.trim()) return message;
|
||||
}
|
||||
return `Attachment upload failed with HTTP ${response.status}.`;
|
||||
}
|
||||
|
||||
export async function uploadIssueAttachmentFile(input: {
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
file: File;
|
||||
fetchImpl?: FetchLike;
|
||||
}): Promise<unknown> {
|
||||
const fetchImpl = input.fetchImpl ?? fetch;
|
||||
const form = new FormData();
|
||||
form.append("file", input.file);
|
||||
const response = await fetchImpl(
|
||||
`/api/companies/${encodeURIComponent(input.companyId)}/issues/${encodeURIComponent(input.issueId)}/attachments`,
|
||||
{
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
body: form,
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(await readUploadError(response));
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./wiki/core.js";
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 3422 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user