opencode-workflow-guard 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -2
- package/package.json +3 -2
- package/src/lib/learning.ts +104 -0
- package/src/lib/project-memory.ts +157 -0
- package/src/lib/state.ts +16 -2
- package/src/lib/types.ts +62 -0
- package/src/lib/utils.ts +36 -3
- package/src/lib/verify.ts +38 -0
- package/src/policies/boundary.ts +71 -21
- package/src/policies/destructive.ts +41 -2
- package/src/policies/git.ts +16 -0
- package/src/policies/interpreter.ts +19 -4
- package/src/policies/secrets.ts +12 -0
- package/src/policies/shell-safety.ts +25 -6
- package/src/workflow-guard.ts +236 -58
package/README.md
CHANGED
|
@@ -25,12 +25,15 @@ Add to your project's `opencode.json` or global `~/.config/opencode/opencode.jso
|
|
|
25
25
|
|
|
26
26
|
*Requires OpenCode >= 1.18.* See [docs/installation.md](docs/installation.md) for full setup options and TUI companion badge configuration.
|
|
27
27
|
|
|
28
|
+
For the optional TUI badge, configure `"opencode-workflow-guard"` in `tui.json` as well. Do not use `opencode-workflow-guard/ui`; npm parses that unscoped slash form as GitHub shorthand rather than a package export, which can trigger Git credential prompts. The package exposes OpenCode's native `./server` and `./tui` entrypoints so the package root is sufficient in both configs.
|
|
29
|
+
|
|
28
30
|
### 2. Verification
|
|
29
31
|
|
|
30
32
|
```bash
|
|
31
33
|
npm run typecheck # Strict TypeScript check (0 errors)
|
|
32
34
|
npm test # Run 415+ unit and adversarial tests
|
|
33
|
-
npm run test:all #
|
|
35
|
+
npm run test:all # Typecheck + unit + install/load checks
|
|
36
|
+
WORKFLOW_GUARD_LIVE_E2E=1 npm run test:install # Also run model-driven OpenCode policy probes
|
|
34
37
|
```
|
|
35
38
|
|
|
36
39
|
---
|
|
@@ -41,7 +44,7 @@ The plugin enforces **24 deterministic policy rules** across four main pillars:
|
|
|
41
44
|
|
|
42
45
|
* **Branch & History Protection:** Enforces feature-branch workflows (blocks edits/commits on `main`/`master`), hard-blocks direct or forced pushes to protected branches, enforces mergeability pre-flight checks, and requires PR changelogs / changesets.
|
|
43
46
|
* **Task & Verification Discipline:** Gates file mutations on active `todowrite` tasks with subagent inheritance, blocks silent task deletion, enforces fresh test verification evidence before task completion, and journals completion claims vs. verification mismatches.
|
|
44
|
-
* **Secrets & Workspace Confinement:** Confines
|
|
47
|
+
* **Secrets & Workspace Confinement:** Confines edit tools and recognized shell/git mutations within the workspace root (including symlink and `../` escape checks), scrubs sensitive environment variables in agent subshells, and redacts `.env` reads with safe schema masks. Arbitrary executables are not OS-sandboxed; use containers or filesystem isolation when hard confinement is required.
|
|
45
48
|
* **Destructive CLI & Environment Safety:** Intercepts destructive cloud/database/infrastructure commands, stops script laundering and interpreter evasion, blocks TTY hangs (`vim`, `nano`, `sudo`), and guards against dangerous package manager flags.
|
|
46
49
|
|
|
47
50
|
For complete policy specifications and override rules, see [docs/policies.md](docs/policies.md).
|
|
@@ -72,6 +75,27 @@ For complete policy specifications and override rules, see [docs/policies.md](do
|
|
|
72
75
|
| `record_review` | Record a secondary reviewer subagent's verdict evaluated against the review rubric |
|
|
73
76
|
| `guard_worktree_create` | Create an isolated git worktree directory for concurrent subagent execution |
|
|
74
77
|
| `guard_worktree_cleanup` | Snapshot-commit remaining changes and remove an isolated worktree directory |
|
|
78
|
+
| `learning_profile` | Inspect the evidence-based local learner profile (when learning mode is enabled) |
|
|
79
|
+
| `learning_checkpoint` | Rank high-value Socratic opportunities while respecting the session intervention budget |
|
|
80
|
+
| `learning_record` | Persist concise evidence observed during a real learning interaction |
|
|
81
|
+
| `project_memory_search` | Search current durable project knowledge in the local index |
|
|
82
|
+
| `project_memory_record` | Record a durable fact, decision, constraint, or lesson with provenance |
|
|
83
|
+
| `project_memory_export` | Explicitly promote selected records to repo-local human-readable JSONL |
|
|
84
|
+
| `project_memory_import` | Import promoted repo-local knowledge into the local index |
|
|
85
|
+
|
|
86
|
+
### Experimental Socratic Learning
|
|
87
|
+
|
|
88
|
+
Learning mode is opt-in and advisory: it never blocks tool calls or weakens deterministic guardrails. Enable it by setting `WORKFLOW_GUARD_LEARNING=1` in the user environment before OpenCode starts. Project configuration cannot enable learning or expose the global profile on its own. `maxLearningInterventions` defaults to 3 per session and can be set to `0` in `.opencode/workflow-guard.json[c]` to suppress checkpoints.
|
|
89
|
+
|
|
90
|
+
The learner profile is global to the local user and follows the XDG data convention: `$XDG_DATA_HOME/opencode/workflow-guard/learner-profile.json`, or `~/.local/share/opencode/workflow-guard/learner-profile.json` when `XDG_DATA_HOME` is unset. It stores distilled concept evidence, session/project provenance, and progression (`exposed` through `critique`), not conversation transcripts or numeric grades. Unobserved concepts remain unknown rather than being labeled knowledge gaps. Back up or delete this file independently from project repositories as desired.
|
|
91
|
+
|
|
92
|
+
### Project Memory
|
|
93
|
+
|
|
94
|
+
Project memory keeps durable working knowledge between sessions without treating conversation history as project truth. Facts, decisions, constraints, and lessons are stored in a local SQLite/FTS5 index under `$XDG_DATA_HOME/opencode/workflow-guard/project-memory/`, or `~/.local/share/opencode/workflow-guard/project-memory/` when `XDG_DATA_HOME` is unset. Git repositories are identified from their common Git directory, so linked worktrees share the same local project index.
|
|
95
|
+
|
|
96
|
+
The local index is private working memory. Nothing from it is committed automatically. `project_memory_export` promotes only the explicitly selected current record IDs to `.opencode/memory/project-memory.jsonl`, a human-readable portable representation that another clone can import. The plugin adds `.opencode/memory/` to the clone-local `.git/info/exclude` by default; teams that deliberately want to version promoted knowledge can remove that exclusion or force-add the JSONL file. SQLite databases themselves should not be committed.
|
|
97
|
+
|
|
98
|
+
Memory is supporting context, not authority. Superseded records are excluded from normal retrieval, recording and plugin imports reject content recognized by Workflow Guard's secret detector, and compaction injects at most eight recent current local records. Portable repository records are never injected automatically; they are available through explicit memory search after import. A local record tied to repository paths and a Git commit is omitted from compaction when those paths have committed, staged, or unstaged changes after that commit. Always prefer current repository state when it conflicts with historical memory.
|
|
75
99
|
|
|
76
100
|
---
|
|
77
101
|
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-workflow-guard",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "OpenCode plugin enforcing workflow discipline through deterministic tool.execute.before hooks",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "src/workflow-guard.ts",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": "./src/workflow-guard.ts",
|
|
10
|
-
"./
|
|
10
|
+
"./server": "./src/workflow-guard.ts",
|
|
11
|
+
"./tui": "./src/workflow-guard-ui.ts"
|
|
11
12
|
},
|
|
12
13
|
"publishConfig": {
|
|
13
14
|
"access": "public"
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
LearnerProfile,
|
|
3
|
+
LearningEvidence,
|
|
4
|
+
LearningOpportunity,
|
|
5
|
+
LearningStage,
|
|
6
|
+
} from "./types.ts";
|
|
7
|
+
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
|
|
11
|
+
const STAGE_ORDER: LearningStage[] = ["exposed", "developing", "demonstrated", "independent", "critique"];
|
|
12
|
+
const TYPE_WEIGHT = { design: 0.3, debugging: 0.3, "new-concept": 0.2 } as const;
|
|
13
|
+
|
|
14
|
+
export function createLearnerProfile(): LearnerProfile {
|
|
15
|
+
return { version: 1, concepts: {} };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function getLearnerProfilePath(): string {
|
|
19
|
+
const dataRoot = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
|
|
20
|
+
return join(dataRoot, "opencode", "workflow-guard", "learner-profile.json");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function loadLearnerProfile(path = getLearnerProfilePath()): LearnerProfile {
|
|
24
|
+
try {
|
|
25
|
+
const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<LearnerProfile>;
|
|
26
|
+
const validConcepts = parsed.concepts && typeof parsed.concepts === "object" && !Array.isArray(parsed.concepts) &&
|
|
27
|
+
Object.values(parsed.concepts).every((concept) =>
|
|
28
|
+
concept && typeof concept === "object" &&
|
|
29
|
+
STAGE_ORDER.includes(concept.stage) &&
|
|
30
|
+
typeof concept.lastObservedAt === "number" && Number.isFinite(concept.lastObservedAt) &&
|
|
31
|
+
Array.isArray(concept.evidence),
|
|
32
|
+
);
|
|
33
|
+
if (parsed.version === 1 && validConcepts) {
|
|
34
|
+
return parsed as LearnerProfile;
|
|
35
|
+
}
|
|
36
|
+
} catch {}
|
|
37
|
+
return createLearnerProfile();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function saveLearnerProfile(profile: LearnerProfile, path = getLearnerProfilePath()): void {
|
|
41
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
42
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
43
|
+
writeFileSync(temporary, JSON.stringify(profile, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
|
|
44
|
+
renameSync(temporary, path);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function updateLearnerProfile(
|
|
48
|
+
update: (profile: LearnerProfile) => void,
|
|
49
|
+
path = getLearnerProfilePath(),
|
|
50
|
+
): LearnerProfile {
|
|
51
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
52
|
+
const lockPath = `${path}.lock`;
|
|
53
|
+
let lock: number;
|
|
54
|
+
try {
|
|
55
|
+
lock = openSync(lockPath, "wx", 0o600);
|
|
56
|
+
} catch {
|
|
57
|
+
throw new Error("Learner profile is busy; evidence was not recorded. Remove a stale .lock file before retrying if its owning process has terminated.");
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
writeFileSync(lock, String(process.pid));
|
|
61
|
+
const profile = loadLearnerProfile(path);
|
|
62
|
+
update(profile);
|
|
63
|
+
saveLearnerProfile(profile, path);
|
|
64
|
+
return profile;
|
|
65
|
+
} finally {
|
|
66
|
+
closeSync(lock);
|
|
67
|
+
try { unlinkSync(lockPath); } catch {}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function recordLearningEvidence(profile: LearnerProfile, evidence: LearningEvidence): void {
|
|
72
|
+
const current = profile.concepts[evidence.concept];
|
|
73
|
+
const evidenceStage = evidence.kind === "needs-reinforcement" ? undefined : evidence.kind;
|
|
74
|
+
const stage = evidenceStage ?? current?.stage ?? "exposed";
|
|
75
|
+
const nextStage = current && STAGE_ORDER.indexOf(current.stage) > STAGE_ORDER.indexOf(stage)
|
|
76
|
+
? current.stage
|
|
77
|
+
: stage;
|
|
78
|
+
|
|
79
|
+
profile.concepts[evidence.concept] = {
|
|
80
|
+
stage: nextStage,
|
|
81
|
+
lastObservedAt: evidence.timestamp,
|
|
82
|
+
evidence: [...(current?.evidence ?? []), evidence].slice(-20),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function selectLearningOpportunity(
|
|
87
|
+
profile: LearnerProfile,
|
|
88
|
+
opportunities: LearningOpportunity[],
|
|
89
|
+
options: { interventionsThisSession?: number; maxInterventionsPerSession?: number } = {},
|
|
90
|
+
): LearningOpportunity | undefined {
|
|
91
|
+
const used = options.interventionsThisSession ?? 0;
|
|
92
|
+
const budget = options.maxInterventionsPerSession ?? 3;
|
|
93
|
+
if (used >= budget) return undefined;
|
|
94
|
+
|
|
95
|
+
let best: { opportunity: LearningOpportunity; score: number } | undefined;
|
|
96
|
+
for (const opportunity of opportunities) {
|
|
97
|
+
const known = profile.concepts[opportunity.concept];
|
|
98
|
+
const needsReinforcement = known?.evidence.at(-1)?.kind === "needs-reinforcement";
|
|
99
|
+
const gap = needsReinforcement ? 1 : known ? 1 - (STAGE_ORDER.indexOf(known.stage) + 1) / STAGE_ORDER.length : 1;
|
|
100
|
+
const score = opportunity.relevance * 0.4 + opportunity.consequence * 0.3 + gap * 0.3 + TYPE_WEIGHT[opportunity.type];
|
|
101
|
+
if (!best || score > best.score) best = { opportunity, score };
|
|
102
|
+
}
|
|
103
|
+
return best && best.score >= 0.75 ? best.opportunity : undefined;
|
|
104
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { DatabaseSync } from "node:sqlite";
|
|
6
|
+
import type { ProjectMemoryInput, ProjectMemoryKind, ProjectMemoryRecord, ProjectMemorySource } from "./types.ts";
|
|
7
|
+
|
|
8
|
+
const KINDS = new Set<ProjectMemoryKind>(["fact", "decision", "constraint", "lesson"]);
|
|
9
|
+
const SOURCES = new Set<ProjectMemorySource>(["user", "file", "git", "tool", "agent", "portable"]);
|
|
10
|
+
|
|
11
|
+
export interface ProjectMemoryStore {
|
|
12
|
+
db: DatabaseSync;
|
|
13
|
+
projectId: string;
|
|
14
|
+
close(): void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function getProjectMemoryDir(): string {
|
|
18
|
+
const base = process.env.XDG_DATA_HOME || join(process.env.HOME || process.cwd(), ".local", "share");
|
|
19
|
+
return join(base, "opencode", "workflow-guard", "project-memory");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function getProjectMemoryIdentity(root: string): string {
|
|
23
|
+
const result = spawnSync("git", ["-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8" });
|
|
24
|
+
const identity = result.status === 0 && result.stdout.trim() ? resolve(result.stdout.trim()) : resolve(root);
|
|
25
|
+
return createHash("sha256").update(identity).digest("hex").slice(0, 24);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function ensureProjectMemoryExcluded(root: string): boolean {
|
|
29
|
+
const result = spawnSync("git", ["-C", root, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8" });
|
|
30
|
+
if (result.status !== 0 || !result.stdout.trim()) return false;
|
|
31
|
+
const path = resolve(root, result.stdout.trim());
|
|
32
|
+
let current = "";
|
|
33
|
+
try { current = readFileSync(path, "utf8"); } catch {}
|
|
34
|
+
if (current.split("\n").some((line) => line.trim() === ".opencode/memory/")) return true;
|
|
35
|
+
appendFileSync(path, `${current && !current.endsWith("\n") ? "\n" : ""}.opencode/memory/\n`);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isProjectMemoryFresh(memory: ProjectMemoryRecord, root: string): boolean {
|
|
40
|
+
if (!memory.commit || memory.paths.length === 0) return true;
|
|
41
|
+
if (!/^[0-9a-f]{7,64}$/i.test(memory.commit)) return false;
|
|
42
|
+
const result = spawnSync("git", ["-C", root, "diff", "--quiet", memory.commit, "--", ...memory.paths], { encoding: "utf8" });
|
|
43
|
+
if (result.status !== 0) return false;
|
|
44
|
+
const untracked = spawnSync("git", ["-C", root, "ls-files", "--others", "--exclude-standard", "--", ...memory.paths], { encoding: "utf8" });
|
|
45
|
+
return untracked.status === 0 && !untracked.stdout.trim();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function openProjectMemory(projectId: string, directory = getProjectMemoryDir()): ProjectMemoryStore {
|
|
49
|
+
if (!projectId || projectId.length > 200) throw new Error("Invalid project memory identity.");
|
|
50
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
51
|
+
const db = new DatabaseSync(join(directory, `${projectId.replace(/[^a-zA-Z0-9._-]/g, "_")}.sqlite`));
|
|
52
|
+
db.exec(`
|
|
53
|
+
PRAGMA journal_mode = WAL;
|
|
54
|
+
PRAGMA busy_timeout = 2000;
|
|
55
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
56
|
+
id TEXT PRIMARY KEY, project_id TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL,
|
|
57
|
+
source TEXT NOT NULL, created_at INTEGER NOT NULL, session_id TEXT, commit_sha TEXT,
|
|
58
|
+
paths TEXT NOT NULL, supersedes TEXT, status TEXT NOT NULL DEFAULT 'current'
|
|
59
|
+
);
|
|
60
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(id UNINDEXED, content);
|
|
61
|
+
`);
|
|
62
|
+
return { db, projectId, close: () => db.close() };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function validateInput(input: ProjectMemoryInput): void {
|
|
66
|
+
if (!KINDS.has(input.kind) || !SOURCES.has(input.source)) throw new Error("Invalid project memory kind or source.");
|
|
67
|
+
if (!input.content.trim() || input.content.length > 4000) throw new Error("Project memory content must be 1-4000 characters.");
|
|
68
|
+
if ((input.paths?.length ?? 0) > 20 || input.paths?.some((path) => !path || path.length > 500 || isAbsolute(path) || path.split(/[\\/]/).includes("..") || /[\0\r\n]/.test(path))) throw new Error("Invalid project memory paths.");
|
|
69
|
+
if (input.sessionID && input.sessionID.length > 200) throw new Error("Invalid project memory session ID.");
|
|
70
|
+
if (input.commit && !/^[0-9a-f]{7,64}$/i.test(input.commit)) throw new Error("Invalid project memory commit.");
|
|
71
|
+
if (input.supersedes && (input.supersedes.length > 200 || /[\0\r\n]/.test(input.supersedes))) throw new Error("Invalid superseded project memory ID.");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function rowToRecord(row: Record<string, unknown>): ProjectMemoryRecord {
|
|
75
|
+
return {
|
|
76
|
+
id: String(row.id), projectId: String(row.project_id), kind: String(row.kind) as ProjectMemoryKind,
|
|
77
|
+
content: String(row.content), source: String(row.source) as ProjectMemorySource, createdAt: Number(row.created_at),
|
|
78
|
+
sessionID: row.session_id ? String(row.session_id) : undefined, commit: row.commit_sha ? String(row.commit_sha) : undefined,
|
|
79
|
+
paths: JSON.parse(String(row.paths)) as string[], supersedes: row.supersedes ? String(row.supersedes) : undefined,
|
|
80
|
+
status: String(row.status) as "current" | "superseded",
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function recordProjectMemory(store: ProjectMemoryStore, input: ProjectMemoryInput, id: string = randomUUID()): ProjectMemoryRecord {
|
|
85
|
+
validateInput(input);
|
|
86
|
+
const createdAt = Date.now();
|
|
87
|
+
store.db.exec("BEGIN IMMEDIATE");
|
|
88
|
+
try {
|
|
89
|
+
if (input.supersedes) store.db.prepare("UPDATE memories SET status = 'superseded' WHERE id = ? AND project_id = ?").run(input.supersedes, store.projectId);
|
|
90
|
+
store.db.prepare("INSERT INTO memories VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'current')").run(
|
|
91
|
+
id, store.projectId, input.kind, input.content.trim(), input.source, createdAt,
|
|
92
|
+
input.sessionID ?? null, input.commit ?? null, JSON.stringify(input.paths ?? []), input.supersedes ?? null,
|
|
93
|
+
);
|
|
94
|
+
store.db.prepare("INSERT INTO memories_fts(id, content) VALUES (?, ?)").run(id, input.content.trim());
|
|
95
|
+
store.db.exec("COMMIT");
|
|
96
|
+
} catch (error) {
|
|
97
|
+
store.db.exec("ROLLBACK");
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
return { id, projectId: store.projectId, ...input, content: input.content.trim(), paths: input.paths ?? [], createdAt, status: "current" };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function searchProjectMemory(store: ProjectMemoryStore, query: string, limit = 8): ProjectMemoryRecord[] {
|
|
104
|
+
const terms = query.match(/[\p{L}\p{N}_-]+/gu)?.slice(0, 12) ?? [];
|
|
105
|
+
if (terms.length === 0) return [];
|
|
106
|
+
const ftsQuery = terms.map((term) => `"${term.replaceAll('"', '""')}"`).join(" OR ");
|
|
107
|
+
const rows = store.db.prepare(`
|
|
108
|
+
SELECT m.* FROM memories_fts f JOIN memories m ON m.id = f.id
|
|
109
|
+
WHERE memories_fts MATCH ? AND m.project_id = ? AND m.status = 'current'
|
|
110
|
+
ORDER BY bm25(memories_fts), m.created_at DESC LIMIT ?
|
|
111
|
+
`).all(ftsQuery, store.projectId, Math.max(1, Math.min(limit, 20))) as Record<string, unknown>[];
|
|
112
|
+
return rows.map(rowToRecord);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function getRecentProjectMemory(store: ProjectMemoryStore, limit = 8): ProjectMemoryRecord[] {
|
|
116
|
+
const rows = store.db.prepare("SELECT * FROM memories WHERE project_id = ? AND status = 'current' ORDER BY created_at DESC LIMIT ?")
|
|
117
|
+
.all(store.projectId, Math.max(1, Math.min(limit, 20))) as Record<string, unknown>[];
|
|
118
|
+
return rows.map(rowToRecord);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function exportProjectKnowledge(store: ProjectMemoryStore, ids: string[], path: string, rejectContent: (content: string) => boolean = () => false): number {
|
|
122
|
+
const selected = ids.slice(0, 100).flatMap((id) => {
|
|
123
|
+
const row = store.db.prepare("SELECT * FROM memories WHERE id = ? AND project_id = ? AND status = 'current'").get(id, store.projectId) as Record<string, unknown> | undefined;
|
|
124
|
+
if (!row) return [];
|
|
125
|
+
const record = rowToRecord(row);
|
|
126
|
+
return rejectContent(record.content) ? [] : [record];
|
|
127
|
+
});
|
|
128
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
129
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
130
|
+
writeFileSync(temporary, selected.map((record) => JSON.stringify(record)).join("\n") + (selected.length ? "\n" : ""), { mode: 0o600 });
|
|
131
|
+
renameSync(temporary, path);
|
|
132
|
+
return selected.length;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function importProjectKnowledge(store: ProjectMemoryStore, path: string, rejectContent: (content: string) => boolean = () => false): number {
|
|
136
|
+
let text: string;
|
|
137
|
+
try {
|
|
138
|
+
if (statSync(path).size > 1_000_000) return 0;
|
|
139
|
+
text = readFileSync(path, "utf8");
|
|
140
|
+
} catch { return 0; }
|
|
141
|
+
let imported = 0;
|
|
142
|
+
for (const line of text.split("\n").filter(Boolean).slice(0, 1000)) {
|
|
143
|
+
try {
|
|
144
|
+
const parsed = JSON.parse(line) as Partial<ProjectMemoryRecord>;
|
|
145
|
+
if (!parsed.id || typeof parsed.id !== "string" || parsed.id.length > 200 || /[\0\r\n]/.test(parsed.id) || typeof parsed.content !== "string" || rejectContent(parsed.content) || !KINDS.has(parsed.kind as ProjectMemoryKind)) continue;
|
|
146
|
+
const exists = store.db.prepare("SELECT 1 FROM memories WHERE id = ? AND project_id = ?").get(parsed.id, store.projectId);
|
|
147
|
+
if (exists) continue;
|
|
148
|
+
const superseded = typeof parsed.supersedes === "string"
|
|
149
|
+
? store.db.prepare("SELECT source FROM memories WHERE id = ? AND project_id = ?").get(parsed.supersedes, store.projectId) as { source?: string } | undefined
|
|
150
|
+
: undefined;
|
|
151
|
+
const supersedes = superseded?.source === "portable" ? parsed.supersedes : undefined;
|
|
152
|
+
recordProjectMemory(store, { kind: parsed.kind as ProjectMemoryKind, content: parsed.content, source: "portable", paths: Array.isArray(parsed.paths) ? parsed.paths : [], commit: parsed.commit, supersedes }, parsed.id);
|
|
153
|
+
imported++;
|
|
154
|
+
} catch {}
|
|
155
|
+
}
|
|
156
|
+
return imported;
|
|
157
|
+
}
|
package/src/lib/state.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { realpathSync, readFileSync } from "node:fs";
|
|
|
2
2
|
import { join, resolve } from "node:path";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
import { persistVerifyCache } from "./audit.ts";
|
|
5
|
-
import { snipVerifyOutput, getCurrentGitCommitHash, getGitStatusSummary } from "./verify.ts";
|
|
5
|
+
import { snipVerifyOutput, getCurrentGitCommitHash, getGitStatusSummary, getGitWorktreeFingerprint } from "./verify.ts";
|
|
6
6
|
import type {
|
|
7
7
|
TodoSdkClient,
|
|
8
8
|
ProjectConfig,
|
|
@@ -149,13 +149,17 @@ export function recordReviewResult(
|
|
|
149
149
|
targetSessionID?: string,
|
|
150
150
|
workspace?: string,
|
|
151
151
|
): void {
|
|
152
|
+
const root = resolve(workspace ?? getWorkspaceRoot());
|
|
152
153
|
lastReview = {
|
|
153
154
|
reviewer,
|
|
154
155
|
summary: summary.slice(-4000),
|
|
155
156
|
passed,
|
|
156
157
|
timestamp: Date.now(),
|
|
157
158
|
targetSessionID,
|
|
158
|
-
workspace,
|
|
159
|
+
workspace: root,
|
|
160
|
+
commitHash: getCurrentGitCommitHash(root),
|
|
161
|
+
gitStatus: getGitStatusSummary(root),
|
|
162
|
+
worktreeFingerprint: getGitWorktreeFingerprint(root),
|
|
159
163
|
};
|
|
160
164
|
if (targetSessionID) sessionReviews.set(targetSessionID, lastReview);
|
|
161
165
|
}
|
|
@@ -287,3 +291,13 @@ export function getSubagentMutationBudget(root: string): number {
|
|
|
287
291
|
}
|
|
288
292
|
return 50;
|
|
289
293
|
}
|
|
294
|
+
|
|
295
|
+
export function isLearningEnabled(root: string): boolean {
|
|
296
|
+
return process.env.WORKFLOW_GUARD_LEARNING === "1";
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function getLearningInterventionBudget(root: string): number {
|
|
300
|
+
const configured = getProjectConfig(root).maxLearningInterventions;
|
|
301
|
+
if (typeof configured === "number" && configured >= 0) return Math.floor(configured);
|
|
302
|
+
return 3;
|
|
303
|
+
}
|
package/src/lib/types.ts
CHANGED
|
@@ -22,6 +22,7 @@ export interface ProjectConfig {
|
|
|
22
22
|
requireReview?: boolean;
|
|
23
23
|
requireDocumentation?: boolean;
|
|
24
24
|
maxSubagentMutations?: number;
|
|
25
|
+
maxLearningInterventions?: number;
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
export interface VerifyResult {
|
|
@@ -42,6 +43,9 @@ export interface ReviewResult {
|
|
|
42
43
|
timestamp: number;
|
|
43
44
|
targetSessionID?: string;
|
|
44
45
|
workspace?: string;
|
|
46
|
+
commitHash?: string;
|
|
47
|
+
gitStatus?: string;
|
|
48
|
+
worktreeFingerprint?: string;
|
|
45
49
|
}
|
|
46
50
|
|
|
47
51
|
export interface AuditEntry {
|
|
@@ -74,3 +78,61 @@ export interface ShellMutation {
|
|
|
74
78
|
target?: string;
|
|
75
79
|
what: string;
|
|
76
80
|
}
|
|
81
|
+
|
|
82
|
+
export type LearningStage = "exposed" | "developing" | "demonstrated" | "independent" | "critique";
|
|
83
|
+
export type LearningEvidenceKind = LearningStage | "needs-reinforcement";
|
|
84
|
+
export type LearningOpportunityType = "design" | "debugging" | "new-concept";
|
|
85
|
+
|
|
86
|
+
export interface LearningEvidence {
|
|
87
|
+
concept: string;
|
|
88
|
+
kind: LearningEvidenceKind;
|
|
89
|
+
summary: string;
|
|
90
|
+
timestamp: number;
|
|
91
|
+
sessionID?: string;
|
|
92
|
+
project?: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface LearnerConcept {
|
|
96
|
+
stage: LearningStage;
|
|
97
|
+
lastObservedAt: number;
|
|
98
|
+
evidence: LearningEvidence[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface LearnerProfile {
|
|
102
|
+
version: 1;
|
|
103
|
+
concepts: Record<string, LearnerConcept>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface LearningOpportunity {
|
|
107
|
+
type: LearningOpportunityType;
|
|
108
|
+
concept: string;
|
|
109
|
+
relevance: number;
|
|
110
|
+
consequence: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export type ProjectMemoryKind = "fact" | "decision" | "constraint" | "lesson";
|
|
114
|
+
export type ProjectMemorySource = "user" | "file" | "git" | "tool" | "agent" | "portable";
|
|
115
|
+
|
|
116
|
+
export interface ProjectMemoryRecord {
|
|
117
|
+
id: string;
|
|
118
|
+
projectId: string;
|
|
119
|
+
kind: ProjectMemoryKind;
|
|
120
|
+
content: string;
|
|
121
|
+
source: ProjectMemorySource;
|
|
122
|
+
createdAt: number;
|
|
123
|
+
sessionID?: string;
|
|
124
|
+
commit?: string;
|
|
125
|
+
paths: string[];
|
|
126
|
+
supersedes?: string;
|
|
127
|
+
status: "current" | "superseded";
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface ProjectMemoryInput {
|
|
131
|
+
kind: ProjectMemoryKind;
|
|
132
|
+
content: string;
|
|
133
|
+
source: ProjectMemorySource;
|
|
134
|
+
sessionID?: string;
|
|
135
|
+
commit?: string;
|
|
136
|
+
paths?: string[];
|
|
137
|
+
supersedes?: string;
|
|
138
|
+
}
|
package/src/lib/utils.ts
CHANGED
|
@@ -44,9 +44,42 @@ export function decodeShellEscapes(text: string): string {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export function shellWords(command: string): string[] {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
47
|
+
const words: string[] = [];
|
|
48
|
+
let word = "";
|
|
49
|
+
let quote: "'" | '"' | undefined;
|
|
50
|
+
let escaped = false;
|
|
51
|
+
let started = false;
|
|
52
|
+
for (const char of command) {
|
|
53
|
+
if (escaped) {
|
|
54
|
+
word += char;
|
|
55
|
+
escaped = false;
|
|
56
|
+
started = true;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (char === "\\" && quote !== "'") {
|
|
60
|
+
escaped = true;
|
|
61
|
+
started = true;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (char === "'" || char === '"') {
|
|
65
|
+
if (!quote) quote = char;
|
|
66
|
+
else if (quote === char) quote = undefined;
|
|
67
|
+
else word += char;
|
|
68
|
+
started = true;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (!quote && /\s/.test(char)) {
|
|
72
|
+
if (started) words.push(word);
|
|
73
|
+
word = "";
|
|
74
|
+
started = false;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
word += char;
|
|
78
|
+
started = true;
|
|
79
|
+
}
|
|
80
|
+
if (escaped) word += "\\";
|
|
81
|
+
if (started) words.push(word);
|
|
82
|
+
return words;
|
|
50
83
|
}
|
|
51
84
|
|
|
52
85
|
export function splitShellSegments(command: string): string[] {
|
package/src/lib/verify.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
2
3
|
import { readFileSync, existsSync } from "node:fs";
|
|
3
4
|
import { join } from "node:path";
|
|
4
5
|
import { getCleanEnv, normalize } from "./utils.ts";
|
|
@@ -116,6 +117,43 @@ export function getGitStatusSummary(root: string): string | undefined {
|
|
|
116
117
|
return undefined;
|
|
117
118
|
}
|
|
118
119
|
|
|
120
|
+
export function getGitWorktreeFingerprint(root: string): string | undefined {
|
|
121
|
+
try {
|
|
122
|
+
// Index listing captures the exact staged/tracked content (blob hashes);
|
|
123
|
+
// a worktree-vs-index diff captures unstaged edits; untracked file
|
|
124
|
+
// contents cover files git does not yet track. Together these bind the
|
|
125
|
+
// fingerprint to file contents regardless of whether HEAD exists, so
|
|
126
|
+
// freshly initialized (commitless) repositories are covered too.
|
|
127
|
+
const staged = spawnSync("git", ["ls-files", "--stage", "-z"], {
|
|
128
|
+
cwd: root,
|
|
129
|
+
encoding: "utf8",
|
|
130
|
+
timeout: 5_000,
|
|
131
|
+
});
|
|
132
|
+
const unstaged = spawnSync("git", ["diff", "--no-ext-diff", "--"], {
|
|
133
|
+
cwd: root,
|
|
134
|
+
encoding: "utf8",
|
|
135
|
+
timeout: 5_000,
|
|
136
|
+
});
|
|
137
|
+
const untracked = spawnSync("git", ["ls-files", "--others", "--exclude-standard", "-z"], {
|
|
138
|
+
cwd: root,
|
|
139
|
+
encoding: "utf8",
|
|
140
|
+
timeout: 5_000,
|
|
141
|
+
});
|
|
142
|
+
if (staged.status !== 0 || unstaged.status !== 0 || untracked.status !== 0) return undefined;
|
|
143
|
+
const hash = createHash("sha256").update(staged.stdout).update(unstaged.stdout);
|
|
144
|
+
for (const file of untracked.stdout.split("\0").filter(Boolean).sort()) {
|
|
145
|
+
hash.update("\0" + file + "\0");
|
|
146
|
+
try {
|
|
147
|
+
hash.update(readFileSync(join(root, file)));
|
|
148
|
+
} catch {
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return hash.digest("hex");
|
|
153
|
+
} catch {}
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
119
157
|
export async function runVerify(
|
|
120
158
|
command: string,
|
|
121
159
|
root: string,
|