@blackbelt-technology/pi-dashboard-sim-extension 0.0.0-stage → 0.12.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 CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # pi-dashboard-sim-extension — Self-Improvement Memory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Records **why** a harness edit was made, **what it predicted**, and **whether it
4
+ worked** — and gives those records back to the next agent that edits the harness.
5
+ Adapted from SIM (arXiv 2611.18856); see
6
+ `docs/research/self-improvement-memory-adaptation.md`.
7
+
8
+ The harness = `AGENTS.md` (repo root), `**/.pi/skills/**`, `**/.pi/agents/**`,
9
+ `**/.pi/prompts/**`, `.pi/settings.json`, and in the agent dir (`~/.pi/agent` or
10
+ `PI_CODING_AGENT_DIR`): `AGENTS.md`, `skills/**`, `agents/**`, `settings.json`,
11
+ `pi-hermes-memory/skills/**`, `projects-memory/**/skills/**`.
12
+
13
+ ## Install
14
+
15
+ Add `packages/sim-extension` (or the published package) to pi's extension list.
16
+ The dashboard UI is the separate `pi-dashboard-sim-plugin`.
17
+
18
+ ## What happens in a session
19
+
20
+ - Sessions that never edit the harness see nothing: the `sim` tool is registered
21
+ inactive and nothing is injected.
22
+ - On the first successful `edit`/`write` of a harness file (or a `skill_manage`
23
+ write) the `sim` tool is activated, a machine-local *unlinked draft* is written,
24
+ and the scope's records arrive once as a `sim-context` steer (framing, 8 usage
25
+ rules, problems tiered under a 12 KB budget).
26
+ - `sim record` stores one attempt: problem, what changed, files, root-cause
27
+ rationale and ≥ 1 prediction — `err:<tool>:<class>` (a failure that should stop
28
+ recurring) or an oracle command that should pass (project scope only).
29
+ Provenance (model, project, branch, pi version) and outcomes are set by the
30
+ system, never by the model. Secrets, prompt-injection markers and machine paths
31
+ are refused.
32
+ - Records made after a web tool call are `web-derived` and withheld until a human
33
+ approves them. Known limit: detection is by tool name (`web_search`,
34
+ `fetch_content`, `*browser*`, …); web content fetched through `bash curl` or
35
+ read from a downloaded file is not detected.
36
+
37
+ ## Outcomes
38
+
39
+ `pi-sim observe` (or the plugin's hourly worker) reads later session logs:
40
+
41
+ - **recurrence** — sessions containing the signature, N = 20 before vs after;
42
+ `fixed` / `reduced` / `missed` / `inconclusive`;
43
+ - **oracle** — later `bash` runs of the command (`set -o pipefail; npm test 2>&1 | tee …` counts,
44
+ `npm test || true` does not); latest run within 30 days decides.
45
+
46
+ Automatic outcomes are **local evidence** (machine-local, never committed). A
47
+ manual mark (`pi-sim mark`) is a committed event and overrides them.
48
+
49
+ ## CLI
50
+
51
+ ```bash
52
+ pi-sim observe [--redo]
53
+ pi-sim view [--scope project|global] [--query text] [id]
54
+ pi-sim drafts
55
+ pi-sim link <draft-id> --problem "<name or p-id>" --rationale "<root cause>" --predict err:bash:enoent [--predict "npm test"]
56
+ pi-sim dismiss <draft-id>
57
+ pi-sim mark <attempt-id> <prediction-index> fixed|reduced|missed|inconclusive
58
+ ```
59
+
60
+ ## On disk
61
+
62
+ | Path | Content |
63
+ |---|---|
64
+ | `<repo>/.pi/sim/attempts/*.json`, `events/*.json` | project records (commit them; immutable, merge-safe) |
65
+ | `<repo>/.pi/sim/config.json` | extra project harness globs |
66
+ | `<agent-dir>/sim/attempts|events/` | global records |
67
+ | `<agent-dir>/sim/config.json` | global globs, budget, window N, auto-observe, web tools |
68
+ | `<agent-dir>/sim/state/` | drafts, signal cache, local outcomes (machine-local) |
69
+
70
+ `PI_SIM_TRACE=<file>` writes a JSONL trace of deliveries and reconciles.
package/bin/pi-sim.mjs ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ // Thin launcher: run the TypeScript CLI via tsx.
3
+ import { spawnSync } from "node:child_process";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const here = dirname(fileURLToPath(import.meta.url));
8
+ const entry = join(here, "..", "src", "cli.ts");
9
+ const res = spawnSync(process.execPath, ["--import", "tsx", entry, ...process.argv.slice(2)], { stdio: "inherit" });
10
+ process.exit(res.status ?? 1);
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-sim-extension",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.12.0",
4
+ "description": "Self-Improvement Memory (SIM) for the pi harness: records why a harness edit (AGENTS.md, skills, agents, settings) was made and what it predicted, delivers past records to sessions that edit the harness, and observes outcomes from later sessions.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
10
+ "directory": "packages/sim-extension"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "keywords": [
16
+ "pi-package",
17
+ "pi-extension",
18
+ "self-improvement",
19
+ "harness-memory"
20
+ ],
21
+ "pi": {
22
+ "extensions": [
23
+ "src/extension.ts"
24
+ ]
25
+ },
26
+ "bin": {
27
+ "pi-sim": "bin/pi-sim.mjs"
28
+ },
29
+ "files": [
30
+ "src/",
31
+ "bin/",
32
+ "!**/__tests__",
33
+ "README.md",
34
+ "!**/AGENTS.md",
35
+ "!**/*.AGENTS.md"
36
+ ],
37
+ "exports": {
38
+ ".": "./src/extension.ts",
39
+ "./core": "./src/core/index.ts",
40
+ "./observe-worker": "./src/core/observe/worker.mjs"
41
+ },
42
+ "scripts": {
43
+ "test": "vitest run"
44
+ },
45
+ "dependencies": {
46
+ "@blackbelt-technology/pi-dashboard-session-distiller": "^0.12.0",
47
+ "@blackbelt-technology/pi-dashboard-shared": "^0.12.0",
48
+ "tsx": "^4.21.0"
49
+ },
50
+ "peerDependencies": {
51
+ "@earendil-works/pi-coding-agent": ">=1.7.0",
52
+ "typebox": ">=1.3.6"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "@earendil-works/pi-coding-agent": {
56
+ "optional": true
57
+ },
58
+ "typebox": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "devDependencies": {
63
+ "@earendil-works/pi-coding-agent": "^1.7.0",
64
+ "typebox": "^1.3.6"
65
+ }
66
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * `pi-sim` — every SIM review action without the dashboard plugin (design D1).
3
+ *
4
+ * pi-sim observe [--redo]
5
+ * pi-sim view [--scope project|global] [--query q] [id]
6
+ * pi-sim drafts
7
+ * pi-sim link <draft-id> --problem <name|p-id> [--description d] --rationale r [--what w] --predict <err:…|oracle:cmd>…
8
+ * pi-sim dismiss <draft-id>
9
+ * pi-sim mark <attempt-id> <prediction-index> <fixed|reduced|missed|inconclusive>
10
+ *
11
+ * Global options: --cwd <dir> (default: process cwd). The agent dir follows
12
+ * PI_CODING_AGENT_DIR. See change: add-self-improvement-memory.
13
+ */
14
+ import { homedir } from "node:os";
15
+ import path from "node:path";
16
+ import { SimError } from "./core/attempt.js";
17
+ import { loadGlobalConfig } from "./core/config.js";
18
+ import { agentDir, gitInfo, globalScopeRoot, projectScopeRoot } from "./core/env.js";
19
+ import { PROBLEM_ID_RE } from "./core/ids.js";
20
+ import { dismissDraft, linkDraft, listDraftsFor, parsePrediction } from "./core/link.js";
21
+ import { runObservation } from "./core/observe/run.js";
22
+ import { loadScope } from "./core/scope.js";
23
+ import { readScope, writeEvent } from "./core/store.js";
24
+ import { OUTCOME_RESULTS, type OutcomeResult, type Scope } from "./core/types.js";
25
+ import { renderView } from "./core/view.js";
26
+
27
+ interface Parsed {
28
+ positional: string[];
29
+ flags: Map<string, string[]>;
30
+ }
31
+
32
+ const BOOL_FLAGS = new Set(["redo", "help"]);
33
+
34
+ function parse(argv: string[]): Parsed {
35
+ const out: Parsed = { positional: [], flags: new Map() };
36
+ for (let i = 0; i < argv.length; i++) {
37
+ const a = argv[i];
38
+ if (a.startsWith("--")) {
39
+ const [k, inline] = a.slice(2).split("=", 2);
40
+ const v = inline ?? (BOOL_FLAGS.has(k) ? "true" : argv[++i]);
41
+ if (v === undefined) throw new SimError(`--${k} needs a value`);
42
+ out.flags.set(k, [...(out.flags.get(k) ?? []), v]);
43
+ } else out.positional.push(a);
44
+ }
45
+ return out;
46
+ }
47
+
48
+ const one = (p: Parsed, k: string): string | undefined => p.flags.get(k)?.at(-1);
49
+
50
+ function attemptRoot(agent: string, cwd: string, aid: string): string {
51
+ const g = gitInfo(cwd);
52
+ const roots = [...(g ? [projectScopeRoot(g.toplevel)] : []), globalScopeRoot(agent)];
53
+ for (const r of roots) if (readScope(r).attempts.some((a) => a.id === aid)) return r;
54
+ throw new SimError(`unknown attempt ${aid}`);
55
+ }
56
+
57
+ export async function main(argv: string[], out: (s: string) => void = (s) => process.stdout.write(`${s}\n`)): Promise<number> {
58
+ const p = parse(argv);
59
+ const [cmd, ...rest] = p.positional;
60
+ const cwd = path.resolve(one(p, "cwd") ?? process.cwd());
61
+ const agent = agentDir();
62
+ switch (cmd) {
63
+ case "observe": {
64
+ const res = await runObservation({ agentDir: agent, redo: one(p, "redo") === "true", windowN: loadGlobalConfig(agent).windowN });
65
+ const counts = Object.entries(res.counts).map(([k, v]) => `${k} ${v}`).join(", ") || "none";
66
+ out(`observed ${res.sessions} sessions (${res.filesRead} read), ${res.attempts} attempts; ${res.changed} prediction${res.changed === 1 ? "" : "s"} changed state (${counts}) in ${res.durationMs} ms`);
67
+ return 0;
68
+ }
69
+ case "view": {
70
+ const g = gitInfo(cwd);
71
+ const scopes: Scope[] = one(p, "scope") ? [one(p, "scope") as Scope] : g ? ["project", "global"] : ["global"];
72
+ for (const s of scopes) {
73
+ if (s === "project" && !g) throw new SimError("project scope: not inside a git repository");
74
+ const l = loadScope(s, { agentDir: agent, toplevel: g?.toplevel, homeDir: homedir() });
75
+ out(renderView(l.label, l.problems, { id: rest[0], query: one(p, "query"), unreadable: l.data.malformed.length }));
76
+ }
77
+ return 0;
78
+ }
79
+ case "drafts": {
80
+ const ds = listDraftsFor(agent, cwd);
81
+ if (!ds.length) out("no unlinked drafts");
82
+ for (const d of ds) out(`${d.id} ${d.at.slice(0, 19)} ${d.scope} ${d.tool} ${d.path}${d.provenance.model ? ` [${d.provenance.model}]` : ""}`);
83
+ return 0;
84
+ }
85
+ case "link": {
86
+ const id = rest[0];
87
+ if (!id) throw new SimError("usage: pi-sim link <draft-id> --problem <name|p-id> --rationale <text> --predict <spec>…");
88
+ const problemArg = one(p, "problem");
89
+ if (!problemArg) throw new SimError("--problem is required");
90
+ const problem = PROBLEM_ID_RE.test(problemArg) ? { id: problemArg } : { name: problemArg, description: one(p, "description") };
91
+ const res = linkDraft(agent, cwd, id, {
92
+ problem,
93
+ rationale: one(p, "rationale") ?? "",
94
+ what: one(p, "what"),
95
+ predicted: (p.flags.get("predict") ?? []).map(parsePrediction),
96
+ }, { homeDir: homedir() });
97
+ out(`linked ${id} → ${res.attempt.id} (problem ${res.attempt.problemId}, ${res.scope} scope)`);
98
+ return 0;
99
+ }
100
+ case "dismiss": {
101
+ if (!rest[0]) throw new SimError("usage: pi-sim dismiss <draft-id>");
102
+ if (!dismissDraft(agent, cwd, rest[0])) throw new SimError(`unknown draft ${rest[0]}`);
103
+ out(`dismissed ${rest[0]}`);
104
+ return 0;
105
+ }
106
+ case "mark": {
107
+ const [aid, idx, result] = rest;
108
+ if (!aid || idx === undefined || !OUTCOME_RESULTS.includes(result as OutcomeResult))
109
+ throw new SimError(`usage: pi-sim mark <attempt-id> <prediction-index> <${OUTCOME_RESULTS.join("|")}>`);
110
+ const e = writeEvent(attemptRoot(agent, cwd, aid), { type: "manual-outcome", attempt: aid, prediction: Number(idx), result: result as OutcomeResult });
111
+ out(`marked ${aid} prediction ${idx} ${result} (${e.id})`);
112
+ return 0;
113
+ }
114
+ default:
115
+ out("usage: pi-sim <observe|view|drafts|link|dismiss|mark> … (see packages/sim-extension/README.md)");
116
+ return cmd ? 2 : 0;
117
+ }
118
+ }
119
+
120
+ const isMain = process.argv[1] && /cli\.(ts|js|mjs)$/.test(process.argv[1]);
121
+ if (isMain) {
122
+ main(process.argv.slice(2)).then(
123
+ (code) => process.exit(code),
124
+ (err) => {
125
+ process.stderr.write(`pi-sim: ${err instanceof Error ? err.message : String(err)}\n`);
126
+ process.exit(1);
127
+ },
128
+ );
129
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * `createAttempt()` — the ONE creation path for attempts (`sim record`, plugin
3
+ * link, `pi-sim link`). Applies every D5 validation and the D8 write-time
4
+ * screen; provenance and outcomes are never accepted from the caller.
5
+ */
6
+ import path from "node:path";
7
+ import { classifyFile } from "./classify.js";
8
+ import { gitHead, gitInfo, projectNameOf, realpathOr } from "./env.js";
9
+ import { newAttemptId, PROBLEM_ID_RE, problemIdOf } from "./ids.js";
10
+ import { capsViolation } from "./problems.js";
11
+ import { type ScreenContext, screenFields } from "./screen.js";
12
+ import { mergeEdges, readScope, resolveProblemId, writeAttempt } from "./store.js";
13
+ import { type Attempt, type Prediction, type Provenance, SCHEMA, type Scope, type Trust } from "./types.js";
14
+
15
+ export class SimError extends Error {}
16
+
17
+ export interface RecordInput {
18
+ problem?: { name?: unknown; description?: unknown; id?: unknown };
19
+ what?: unknown;
20
+ files?: unknown;
21
+ rationale?: unknown;
22
+ predicted?: unknown;
23
+ [k: string]: unknown;
24
+ }
25
+
26
+ export interface CreateContext {
27
+ cwd: string;
28
+ agentDir: string;
29
+ homeDir?: string;
30
+ trust: Trust;
31
+ /**
32
+ * System-derived provenance facts (model, provider, sessionId, piVersion).
33
+ * `headSha` / `branch` / `cwdRel` override the cwd's current git facts — a
34
+ * linked draft keeps the facts of the session that made the edit (S7).
35
+ */
36
+ provenance: Pick<Provenance, "model" | "provider" | "sessionId" | "piVersion" | "headSha" | "branch" | "cwdRel">;
37
+ /** Record-time signature frequency: seen in `seen` of the last `of` cached sessions; undefined = no cache. */
38
+ signatureFrequency?: (signature: string) => { seen: number; of: number } | undefined;
39
+ now?: Date;
40
+ }
41
+
42
+ export interface CreateResult {
43
+ attempt: Attempt;
44
+ scope: Scope;
45
+ scopeRoot: string;
46
+ file: string;
47
+ warnings: string[];
48
+ }
49
+
50
+ const ALLOWED_KEYS = new Set(["problem", "what", "files", "rationale", "predicted"]);
51
+ export const SIGNATURE_RE = /^err:[A-Za-z0-9_.-]+:[a-z0-9-]{1,48}$/;
52
+
53
+ const str = (v: unknown, name: string): string => {
54
+ if (typeof v !== "string" || !v.trim()) throw new SimError(`${name} must be a non-empty string`);
55
+ return v.trim();
56
+ };
57
+
58
+ function parsePredictions(v: unknown): Prediction[] {
59
+ if (!Array.isArray(v) || v.length === 0)
60
+ throw new SimError("predicted must list at least one prediction ({kind:'signature'|'oracle', value})");
61
+ return v.map((p, i) => {
62
+ const kind = (p as { kind?: unknown })?.kind;
63
+ const value = (p as { value?: unknown })?.value;
64
+ if (kind !== "signature" && kind !== "oracle") throw new SimError(`predicted[${i}].kind must be 'signature' or 'oracle'`);
65
+ const val = str(value, `predicted[${i}].value`);
66
+ if (kind === "signature" && !SIGNATURE_RE.test(val))
67
+ throw new SimError(`predicted[${i}].value must look like err:<tool>:<class> (got ${val})`);
68
+ return { kind, value: val };
69
+ });
70
+ }
71
+
72
+ /** Validate + screen + write one attempt. Throws `SimError` with no file written on any refusal. */
73
+ export function createAttempt(input: RecordInput, ctx: CreateContext): CreateResult {
74
+ if (!input || typeof input !== "object") throw new SimError("record input must be an object");
75
+ for (const k of ["provenance", "outcomes", "outcome", "trust", "backfilled", "id", "at", "status"]) {
76
+ if (k in input) throw new SimError(`${k} is set by the system, not the caller — remove it`);
77
+ }
78
+ const unknown = Object.keys(input).filter((k) => !ALLOWED_KEYS.has(k));
79
+ if (unknown.length) throw new SimError(`unknown field(s): ${unknown.join(", ")}`);
80
+
81
+ const what = str(input.what, "what");
82
+ const rationale = str(input.rationale, "rationale");
83
+ const predicted = parsePredictions(input.predicted);
84
+ if (!Array.isArray(input.files) || input.files.length === 0) throw new SimError("files must list the harness files edited");
85
+ const rawFiles = input.files.map((f, i) => str(f, `files[${i}]`));
86
+
87
+ // Scope = scope of files[].
88
+ const classified = rawFiles.map((f) => ({ f, c: classifyFile(f, ctx.cwd, ctx.agentDir) }));
89
+ const notHarness = classified.filter((x) => !x.c).map((x) => x.f);
90
+ if (notHarness.length) throw new SimError(`not harness files (no harness glob matches): ${notHarness.join(", ")}`);
91
+ const scopes = new Set(classified.map((x) => x.c?.scope));
92
+ if (scopes.size > 1) throw new SimError("files span project and global scope — record one attempt per scope (split the record)");
93
+ const scope = [...scopes][0] as Scope;
94
+ const roots = new Set(classified.map((x) => x.c?.scopeRoot));
95
+ if (scope === "project" && roots.has(null))
96
+ throw new SimError("project-scope harness files must be inside a git repository (no git checkout found for the cwd)");
97
+ if (roots.size > 1) throw new SimError("files span several repositories — record one attempt per repository");
98
+ const scopeRoot = [...roots][0] as string;
99
+ const files = [...new Set(classified.map((x) => (x.c as { key: string }).key))];
100
+ if (scope === "global" && predicted.some((p) => p.kind === "oracle"))
101
+ throw new SimError("oracle predictions are project-scope only (a global harness edit has no single project to run them)");
102
+
103
+ // Problem.
104
+ const pin = input.problem ?? {};
105
+ let problemId: string;
106
+ let problemName: string;
107
+ let problemDescription: string | undefined;
108
+ if (pin.id !== undefined) {
109
+ const id = str(pin.id, "problem.id");
110
+ if (!PROBLEM_ID_RE.test(id)) throw new SimError(`problem.id must look like p-<12 hex> (got ${id})`);
111
+ const data = readScope(scopeRoot);
112
+ const edges = mergeEdges(data.events);
113
+ const target = resolveProblemId(id, edges);
114
+ const member = data.attempts.find((a) => resolveProblemId(a.problemId, edges) === target);
115
+ if (!member) throw new SimError(`unknown problem ${id} in ${scope} scope — pass {name, description} to create it`);
116
+ problemId = target;
117
+ problemName = data.attempts.find((a) => a.problemId === target)?.problemName ?? member.problemName;
118
+ } else {
119
+ problemName = str(pin.name, "problem.name");
120
+ problemId = problemIdOf(problemName);
121
+ if (pin.description !== undefined) problemDescription = str(pin.description, "problem.description");
122
+ }
123
+
124
+ // Length caps first (keeps the screen linear), then the write-time screen (D8).
125
+ const cap = capsViolation({ problemName, problemDescription, what, rationale, files, predicted });
126
+ if (cap) throw new SimError(`${cap} — keep records short`);
127
+ const git = gitInfo(ctx.cwd);
128
+ const screenCtx: ScreenContext = { homeDir: ctx.homeDir, agentDir: ctx.agentDir, toplevel: git?.toplevel };
129
+ const screened = screenFields(
130
+ [
131
+ ["problem.name", problemName],
132
+ ["problem.description", problemDescription],
133
+ ["what", what],
134
+ ["rationale", rationale],
135
+ ...files.map((f, i): [string, string] => [`files[${i}]`, f]),
136
+ ...predicted.map((p, i): [string, string] => [`predicted[${i}].value`, p.value]),
137
+ ],
138
+ screenCtx,
139
+ );
140
+ if (!screened.ok) throw new SimError(`refused by content screen — ${screened.reason}`);
141
+
142
+ // Provenance (system-derived; no absolute paths).
143
+ const provenance: Provenance = {
144
+ projectName: projectNameOf(ctx.cwd),
145
+ ...(git ? { cwdRel: path.relative(git.toplevel, realpathOr(ctx.cwd)).split(path.sep).join("/") || "." } : {}),
146
+ ...(git ? gitHead(ctx.cwd) : {}),
147
+ ...strip(ctx.provenance),
148
+ };
149
+
150
+ const warnings: string[] = [];
151
+ for (const p of predicted) {
152
+ if (p.kind !== "signature") continue;
153
+ const f = ctx.signatureFrequency?.(p.value);
154
+ if (f && f.seen < 2)
155
+ warnings.push(
156
+ `signature ${p.value} was seen in only ${f.seen} of the last ${f.of} sessions of this project — recurrence will likely be inconclusive; consider an oracle prediction`,
157
+ );
158
+ }
159
+
160
+ const attempt: Attempt = {
161
+ schema: SCHEMA,
162
+ id: newAttemptId(),
163
+ problemId,
164
+ problemName,
165
+ ...(problemDescription ? { problemDescription } : {}),
166
+ at: (ctx.now ?? new Date()).toISOString(),
167
+ what,
168
+ files,
169
+ rationale,
170
+ predicted,
171
+ provenance,
172
+ trust: ctx.trust,
173
+ backfilled: false,
174
+ };
175
+ const file = writeAttempt(scopeRoot, attempt);
176
+ return { attempt, scope, scopeRoot, file, warnings };
177
+ }
178
+
179
+ function strip<T extends object>(o: T): Partial<T> {
180
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== "")) as Partial<T>;
181
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Harness path classification + normalisation (design D2, D3).
3
+ *
4
+ * A path is normalised to ONE string form so drafts, records and delivery tier
5
+ * 1 compare by equality: project scope → relative to the toplevel; global
6
+ * scope → relative to the agent dir, except skill files, which become a skill
7
+ * key (`skill:<name>@global` / `skill:<name>@project`) so both edit routes
8
+ * (`edit` on the file, `skill_manage`) match.
9
+ */
10
+ import path from "node:path";
11
+ import { loadGlobalConfig, loadProjectConfig } from "./config.js";
12
+ import { gitInfo, globalScopeRoot, projectScopeRoot, realpathOr } from "./env.js";
13
+ import { matchesGlob } from "./glob.js";
14
+
15
+ export type Classified =
16
+ | { scope: "project"; key: string; scopeRoot: string; toplevel: string }
17
+ | { scope: "global"; key: string; scopeRoot: string }
18
+ /** A project harness path in a cwd that is not inside a git checkout. */
19
+ | { scope: "project"; key: string; scopeRoot: null; toplevel: null };
20
+
21
+ const SKILL_KEY_RE = /^skill:([^@/\s]+)@(global|project)$/;
22
+ const SKILL_MANAGE_WRITES = new Set(["create", "patch", "update", "edit", "delete"]);
23
+
24
+ const toPosix = (p: string): string => p.split(path.sep).join("/");
25
+ const isUnder = (rel: string): boolean => rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
26
+
27
+ /** Any `AGENTS.md` / `*.AGENTS.md` except the root one is a DOX row file, never harness. */
28
+ function isDoxFile(rel: string): boolean {
29
+ const base = rel.split("/").pop() ?? rel;
30
+ return (base === "AGENTS.md" || base.endsWith(".AGENTS.md")) && rel !== "AGENTS.md";
31
+ }
32
+
33
+ /** Global-scope rel path → skill key when it is a skill file, else the rel path. */
34
+ function globalKey(rel: string): string {
35
+ let m = rel.match(/^(?:pi-hermes-memory\/)?skills\/([^/]+)\//);
36
+ if (m) return `skill:${m[1]}@global`;
37
+ m = rel.match(/^projects-memory\/[^/]+\/skills\/([^/]+)\//);
38
+ if (m) return `skill:${m[1]}@project`;
39
+ return rel;
40
+ }
41
+
42
+ /** Classify one file path (or skill key) for an attempt / draft. Null = not harness. */
43
+ export function classifyFile(file: string, cwd: string, agent: string): Classified | null {
44
+ const skill = file.match(SKILL_KEY_RE);
45
+ if (skill) return { scope: "global", key: file, scopeRoot: globalScopeRoot(agent) };
46
+ const real = realpathOr(path.resolve(cwd, file));
47
+ const agentReal = realpathOr(agent);
48
+ const relAgent = toPosix(path.relative(agentReal, real));
49
+ if (isUnder(relAgent)) {
50
+ if (isDoxFile(relAgent)) return null;
51
+ if (relAgent.startsWith("sim/")) return null; // SIM's own store is never harness
52
+ const cfg = loadGlobalConfig(agent);
53
+ if (!cfg.harnessGlobs.some((g) => matchesGlob(relAgent, g))) return null;
54
+ return { scope: "global", key: globalKey(relAgent), scopeRoot: globalScopeRoot(agent) };
55
+ }
56
+ const git = gitInfo(nearestDir(real)) ?? gitInfo(cwd);
57
+ if (!git) {
58
+ const rel = toPosix(path.relative(realpathOr(cwd), real));
59
+ if (!isUnder(rel) || isDoxFile(rel)) return null;
60
+ // No repository: default globs only (no project config to read).
61
+ const globs = loadProjectConfig(realpathOr(cwd)).harnessGlobs;
62
+ return globs.some((g) => matchesGlob(rel, g)) ? { scope: "project", key: rel, scopeRoot: null, toplevel: null } : null;
63
+ }
64
+ const rel = toPosix(path.relative(git.toplevel, real));
65
+ if (!isUnder(rel) || isDoxFile(rel)) return null;
66
+ if (rel.startsWith(".pi/sim/")) return null;
67
+ const cfg = loadProjectConfig(git.toplevel);
68
+ if (!cfg.harnessGlobs.some((g) => matchesGlob(rel, g))) return null;
69
+ return { scope: "project", key: rel, scopeRoot: projectScopeRoot(git.toplevel), toplevel: git.toplevel };
70
+ }
71
+
72
+ function nearestDir(p: string): string {
73
+ // The edited file exists after a successful edit; its parent dir is the anchor.
74
+ return path.dirname(p);
75
+ }
76
+
77
+ /** Skill key for a successful `skill_manage` write (`name` or `skill_id`). */
78
+ export function skillManageKey(input: Record<string, unknown>): string | null {
79
+ const action = String(input.action ?? "");
80
+ if (!SKILL_MANAGE_WRITES.has(action)) return null;
81
+ let name = typeof input.name === "string" ? input.name : undefined;
82
+ let scope = typeof input.scope === "string" ? input.scope : undefined;
83
+ const sid = typeof input.skill_id === "string" ? input.skill_id : undefined;
84
+ if (sid) {
85
+ const parts = sid.split(":");
86
+ scope ??= parts[0];
87
+ name ??= parts[parts.length - 1];
88
+ }
89
+ if (!name || !/^[A-Za-z0-9._-]+$/.test(name)) return null;
90
+ return `skill:${name}@${scope === "project" ? "project" : "global"}`;
91
+ }
92
+
93
+ export interface ToolEdit {
94
+ toolName: string;
95
+ input: Record<string, unknown>;
96
+ isError: boolean;
97
+ cwd: string;
98
+ }
99
+
100
+ /**
101
+ * Classify a tool result as a harness edit. Triggers: successful `edit` /
102
+ * `write` with a `path`, and successful `skill_manage` writes (always global
103
+ * scope: every write lands under the agent dir). Bash is not parsed.
104
+ */
105
+ export function classifyHarnessEdit(e: ToolEdit, agent: string): Classified | null {
106
+ if (e.isError) return null;
107
+ if (e.toolName === "skill_manage") {
108
+ const key = skillManageKey(e.input);
109
+ return key ? { scope: "global", key, scopeRoot: globalScopeRoot(agent) } : null;
110
+ }
111
+ if (e.toolName !== "edit" && e.toolName !== "write") return null;
112
+ const p = e.input.path ?? e.input.file_path;
113
+ if (typeof p !== "string" || !p) return null;
114
+ const c = classifyFile(p, e.cwd, agent);
115
+ return c && c.scopeRoot ? c : null;
116
+ }