gsd-pi 2.81.0-dev.72a81bdf3 → 2.82.0-dev.725028083
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 +46 -28
- package/dist/resources/.managed-resources-content-hash +1 -1
- package/dist/resources/extensions/browser-tools/tools/screenshot.js +1 -0
- package/dist/resources/extensions/browser-tools/tools/zoom.js +1 -0
- package/dist/resources/extensions/gsd/auto/phases.js +9 -0
- package/dist/resources/extensions/gsd/auto-prompts.js +11 -3
- package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +5 -0
- package/dist/resources/extensions/gsd/bootstrap/system-context.js +55 -12
- package/dist/resources/extensions/gsd/commands/handlers/core.js +1 -1
- package/dist/resources/extensions/gsd/commands-handlers.js +15 -2
- package/dist/resources/extensions/gsd/context-store.js +112 -0
- package/dist/resources/extensions/gsd/db-writer.js +150 -84
- package/dist/resources/extensions/gsd/docs/preferences-reference.md +1 -1
- package/dist/resources/extensions/gsd/doctor-git-checks.js +41 -6
- package/dist/resources/extensions/gsd/knowledge-backfill.js +144 -0
- package/dist/resources/extensions/gsd/knowledge-capture.js +136 -0
- package/dist/resources/extensions/gsd/knowledge-parser.js +154 -0
- package/dist/resources/extensions/gsd/knowledge-projection.js +210 -0
- package/dist/resources/extensions/gsd/markdown-renderer.js +6 -1
- package/dist/resources/extensions/gsd/memory-backfill.js +73 -17
- package/dist/resources/extensions/gsd/memory-consolidation-scanner.js +222 -0
- package/dist/resources/extensions/gsd/prompts/system.md +2 -2
- package/dist/resources/extensions/gsd/provider-switch-observer.js +146 -0
- package/dist/resources/extensions/gsd/templates/knowledge.md +2 -2
- package/dist/tsconfig.extensions.tsbuildinfo +1 -1
- package/dist/web/standalone/.next/BUILD_ID +1 -1
- package/dist/web/standalone/.next/app-path-routes-manifest.json +11 -11
- package/dist/web/standalone/.next/build-manifest.json +2 -2
- package/dist/web/standalone/.next/prerender-manifest.json +3 -3
- package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.html +1 -1
- package/dist/web/standalone/.next/server/app/index.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app-paths-manifest.json +11 -11
- package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
- package/dist/web/standalone/.next/server/pages/404.html +1 -1
- package/dist/web/standalone/.next/server/pages/500.html +1 -1
- package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
- package/package.json +3 -2
- package/packages/daemon/package.json +2 -2
- package/packages/mcp-server/README.md +2 -0
- package/packages/mcp-server/package.json +2 -2
- package/packages/mcp-server/src/workflow-tools-parity.test.ts +244 -0
- package/packages/native/package.json +1 -1
- package/packages/pi-agent-core/package.json +1 -1
- package/packages/pi-agent-core/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-ai/dist/index.d.ts +2 -2
- package/packages/pi-ai/dist/index.d.ts.map +1 -1
- package/packages/pi-ai/dist/index.js +1 -1
- package/packages/pi-ai/dist/index.js.map +1 -1
- package/packages/pi-ai/dist/providers/transform-messages.d.ts +11 -0
- package/packages/pi-ai/dist/providers/transform-messages.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/transform-messages.js +20 -0
- package/packages/pi-ai/dist/providers/transform-messages.js.map +1 -1
- package/packages/pi-ai/package.json +1 -1
- package/packages/pi-ai/src/index.ts +7 -2
- package/packages/pi-ai/src/providers/transform-messages.ts +24 -0
- package/packages/pi-ai/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-coding-agent/dist/core/system-prompt.js +4 -4
- package/packages/pi-coding-agent/dist/core/system-prompt.js.map +1 -1
- package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.d.ts +2 -0
- package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.js +17 -0
- package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.js.map +1 -0
- package/packages/pi-coding-agent/package.json +1 -1
- package/packages/pi-coding-agent/src/core/system-prompt.ts +4 -4
- package/packages/pi-coding-agent/src/tests/system-prompt-file-safety.test.ts +22 -0
- package/packages/pi-coding-agent/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-tui/package.json +1 -1
- package/packages/rpc-client/package.json +1 -1
- package/pkg/package.json +1 -1
- package/src/resources/extensions/browser-tools/tools/screenshot.ts +1 -0
- package/src/resources/extensions/browser-tools/tools/zoom.ts +1 -0
- package/src/resources/extensions/gsd/auto/phases.ts +14 -0
- package/src/resources/extensions/gsd/auto-prompts.ts +11 -3
- package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +6 -0
- package/src/resources/extensions/gsd/bootstrap/system-context.ts +58 -15
- package/src/resources/extensions/gsd/commands/handlers/core.ts +1 -1
- package/src/resources/extensions/gsd/commands-handlers.ts +19 -2
- package/src/resources/extensions/gsd/context-store.ts +120 -1
- package/src/resources/extensions/gsd/db-writer.ts +167 -84
- package/src/resources/extensions/gsd/docs/preferences-reference.md +1 -1
- package/src/resources/extensions/gsd/doctor-git-checks.ts +44 -6
- package/src/resources/extensions/gsd/doctor-types.ts +2 -0
- package/src/resources/extensions/gsd/knowledge-backfill.ts +164 -0
- package/src/resources/extensions/gsd/knowledge-capture.ts +160 -0
- package/src/resources/extensions/gsd/knowledge-parser.ts +174 -0
- package/src/resources/extensions/gsd/knowledge-projection.ts +241 -0
- package/src/resources/extensions/gsd/markdown-renderer.ts +6 -1
- package/src/resources/extensions/gsd/memory-backfill.ts +89 -17
- package/src/resources/extensions/gsd/memory-consolidation-scanner.ts +277 -0
- package/src/resources/extensions/gsd/prompts/system.md +2 -2
- package/src/resources/extensions/gsd/provider-switch-observer.ts +185 -0
- package/src/resources/extensions/gsd/templates/knowledge.md +2 -2
- package/src/resources/extensions/gsd/tests/auto-loop.test.ts +75 -0
- package/src/resources/extensions/gsd/tests/browser-tools-compatibility-declarations.test.ts +62 -0
- package/src/resources/extensions/gsd/tests/context-store-decisions-from-memories.test.ts +312 -0
- package/src/resources/extensions/gsd/tests/db-writer.test.ts +13 -8
- package/src/resources/extensions/gsd/tests/decisions-projection-from-memories.test.ts +453 -0
- package/src/resources/extensions/gsd/tests/decisions-stop-table-writes.test.ts +348 -0
- package/src/resources/extensions/gsd/tests/freeform-decisions.test.ts +8 -4
- package/src/resources/extensions/gsd/tests/gsd-tools.test.ts +11 -7
- package/src/resources/extensions/gsd/tests/integration/doctor-git.test.ts +44 -0
- package/src/resources/extensions/gsd/tests/integration/integration-lifecycle.test.ts +13 -5
- package/src/resources/extensions/gsd/tests/knowledge-backfill-projection.test.ts +323 -0
- package/src/resources/extensions/gsd/tests/knowledge-capture.test.ts +242 -0
- package/src/resources/extensions/gsd/tests/knowledge.test.ts +47 -2
- package/src/resources/extensions/gsd/tests/load-knowledge-block-rules-only.test.ts +209 -0
- package/src/resources/extensions/gsd/tests/memory-consolidation-scanner.test.ts +316 -0
- package/src/resources/extensions/gsd/tests/plan-milestone-sketch-render.test.ts +157 -0
- package/src/resources/extensions/gsd/tests/prompt-contracts.test.ts +8 -0
- package/src/resources/extensions/gsd/tests/provider-switch-observer.test.ts +252 -0
- package/src/resources/extensions/gsd/tests/session-start-footer.test.ts +16 -4
- package/src/resources/extensions/gsd/workflow-logger.ts +4 -0
- /package/dist/web/standalone/.next/static/{rIkMv4YSNlfSeqmGqWVns → KDRTXR-22LPCsa80X9dey}/_buildManifest.js +0 -0
- /package/dist/web/standalone/.next/static/{rIkMv4YSNlfSeqmGqWVns → KDRTXR-22LPCsa80X9dey}/_ssgManifest.js +0 -0
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// GSD2 — Decisions -> memories backfill (ADR-013 step 5)
|
|
2
2
|
//
|
|
3
|
-
// Idempotent
|
|
4
|
-
// the memories table with
|
|
5
|
-
//
|
|
6
|
-
//
|
|
3
|
+
// Idempotent migration that copies every decisions row (active and
|
|
4
|
+
// superseded — see Stage 2a note below) into the memories table with
|
|
5
|
+
// category="architecture" and a structured_fields payload preserving the
|
|
6
|
+
// original gsd_save_decision schema (when_context, scope, decision, choice,
|
|
7
|
+
// rationale, made_by, revisable, superseded_by, sourceDecisionId).
|
|
7
8
|
//
|
|
8
9
|
// The backfill exists so the cutover in ADR-013 step 6 can drop the
|
|
9
10
|
// decisions table without losing schema fidelity. Idempotency is enforced
|
|
@@ -14,6 +15,13 @@
|
|
|
14
15
|
// only ever fires once per project. Costs O(N) inserts on first run where
|
|
15
16
|
// N is the active-decisions count; subsequent runs are an O(N) lookup that
|
|
16
17
|
// finds existing markers and exits.
|
|
18
|
+
//
|
|
19
|
+
// ADR-013 Stage 2a (PR #5755): backfill now includes superseded rows so the
|
|
20
|
+
// DECISIONS.md projection regen can source from memories without losing
|
|
21
|
+
// historical entries. An auto-heal pass runs after the initial migration to
|
|
22
|
+
// pick up superseded_by changes that occurred after the source decision was
|
|
23
|
+
// already migrated (e.g. a fresh md-importer run that introduced a new
|
|
24
|
+
// supersedes-chain).
|
|
17
25
|
|
|
18
26
|
import { isDbAvailable, _getAdapter } from "./gsd-db.js";
|
|
19
27
|
import { createMemory } from "./memory-store.js";
|
|
@@ -31,8 +39,10 @@ interface DecisionRow {
|
|
|
31
39
|
superseded_by: string | null;
|
|
32
40
|
}
|
|
33
41
|
|
|
42
|
+
type DecisionContentFields = Pick<DecisionRow, "decision" | "choice" | "rationale">;
|
|
43
|
+
|
|
34
44
|
/**
|
|
35
|
-
* Backfill
|
|
45
|
+
* Backfill decisions rows into the memories table.
|
|
36
46
|
*
|
|
37
47
|
* - Idempotent (per-row): every row written carries
|
|
38
48
|
* `structured_fields.sourceDecisionId = "<decisionId>"`. Each candidate
|
|
@@ -41,13 +51,18 @@ interface DecisionRow {
|
|
|
41
51
|
* their own `sourceDecisionId` does NOT abort the backfill.
|
|
42
52
|
* - Best-effort: never throws. Logs and returns 0 on failure so a broken
|
|
43
53
|
* backfill cannot block agent startup.
|
|
44
|
-
* -
|
|
45
|
-
*
|
|
46
|
-
*
|
|
54
|
+
* - Full migration (ADR-013 Stage 2a): both active and superseded rows are
|
|
55
|
+
* migrated. `structured_fields.superseded_by` preserves the supersedes
|
|
56
|
+
* chain so the DECISIONS.md projection regen can source from memories
|
|
57
|
+
* without losing historical entries.
|
|
58
|
+
* - Drift auto-heal: after the initial insert pass, the function updates
|
|
59
|
+
* any pre-existing memory whose `structured_fields.superseded_by` drifted
|
|
60
|
+
* from the source decision (e.g. a fresh md-importer run introduced a
|
|
61
|
+
* new supersedes annotation after the initial migration).
|
|
47
62
|
*
|
|
48
63
|
* Returns the number of memories written (0 when already backfilled or
|
|
49
|
-
* when the DB has no decisions).
|
|
50
|
-
*
|
|
64
|
+
* when the DB has no decisions). Drift-heal updates are not counted in
|
|
65
|
+
* this return — they are logged separately.
|
|
51
66
|
*/
|
|
52
67
|
export function backfillDecisionsToMemories(): number {
|
|
53
68
|
if (!isDbAvailable()) return 0;
|
|
@@ -56,7 +71,7 @@ export function backfillDecisionsToMemories(): number {
|
|
|
56
71
|
|
|
57
72
|
try {
|
|
58
73
|
const decisions = adapter
|
|
59
|
-
.prepare("SELECT id, when_context, scope, decision, choice, rationale, made_by, revisable, superseded_by FROM decisions
|
|
74
|
+
.prepare("SELECT id, when_context, scope, decision, choice, rationale, made_by, revisable, superseded_by FROM decisions ORDER BY seq")
|
|
60
75
|
.all() as Array<Record<string, unknown>>;
|
|
61
76
|
|
|
62
77
|
if (decisions.length === 0) return 0;
|
|
@@ -67,10 +82,14 @@ export function backfillDecisionsToMemories(): number {
|
|
|
67
82
|
// sentinel would silently abort the backfill if a user manually called
|
|
68
83
|
// capture_thought with their own structuredFields.sourceDecisionId.
|
|
69
84
|
const checkExisting = adapter.prepare(
|
|
70
|
-
"SELECT
|
|
85
|
+
"SELECT id, structured_fields FROM memories WHERE structured_fields LIKE :pattern LIMIT 1",
|
|
86
|
+
);
|
|
87
|
+
const updateStructuredFields = adapter.prepare(
|
|
88
|
+
"UPDATE memories SET structured_fields = :sf, updated_at = :ts WHERE id = :id",
|
|
71
89
|
);
|
|
72
90
|
|
|
73
91
|
let written = 0;
|
|
92
|
+
let healed = 0;
|
|
74
93
|
for (const raw of decisions) {
|
|
75
94
|
const row: DecisionRow = {
|
|
76
95
|
id: String(raw["id"] ?? ""),
|
|
@@ -85,11 +104,48 @@ export function backfillDecisionsToMemories(): number {
|
|
|
85
104
|
};
|
|
86
105
|
if (!row.id) continue;
|
|
87
106
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
107
|
+
const pattern = `%"sourceDecisionId":"${row.id}"%`;
|
|
108
|
+
const existing = checkExisting.get({ ":pattern": pattern }) as
|
|
109
|
+
| { id: string; structured_fields: string | null }
|
|
110
|
+
| undefined;
|
|
91
111
|
|
|
92
|
-
|
|
112
|
+
if (existing) {
|
|
113
|
+
// Drift auto-heal: if the source decision's superseded_by has changed
|
|
114
|
+
// since the original migration, update the memory in place. Read-side
|
|
115
|
+
// queries reconstruct Decision.superseded_by from this field, so the
|
|
116
|
+
// DECISIONS.md projection stays accurate without us having to track
|
|
117
|
+
// supersedes events at the write site.
|
|
118
|
+
const parsedSf = existing.structured_fields
|
|
119
|
+
? safeParse(existing.structured_fields)
|
|
120
|
+
: {};
|
|
121
|
+
if (existing.structured_fields && !parsedSf) {
|
|
122
|
+
logWarning(
|
|
123
|
+
"memory-backfill",
|
|
124
|
+
`decisions->memories drift heal skipped for ${row.id}: invalid structured_fields JSON`,
|
|
125
|
+
);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const currentSf = parsedSf ?? {};
|
|
129
|
+
const memorySuperseded =
|
|
130
|
+
typeof currentSf["superseded_by"] === "string" || currentSf["superseded_by"] === null
|
|
131
|
+
? (currentSf["superseded_by"] as string | null | undefined)
|
|
132
|
+
: null;
|
|
133
|
+
if (memorySuperseded !== row.superseded_by) {
|
|
134
|
+
const merged = {
|
|
135
|
+
...currentSf,
|
|
136
|
+
superseded_by: row.superseded_by,
|
|
137
|
+
};
|
|
138
|
+
updateStructuredFields.run({
|
|
139
|
+
":id": existing.id,
|
|
140
|
+
":sf": JSON.stringify(merged),
|
|
141
|
+
":ts": new Date().toISOString(),
|
|
142
|
+
});
|
|
143
|
+
healed += 1;
|
|
144
|
+
}
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const content = synthesizeDecisionMemoryContent(row);
|
|
93
149
|
const id = createMemory({
|
|
94
150
|
category: "architecture",
|
|
95
151
|
content,
|
|
@@ -104,11 +160,19 @@ export function backfillDecisionsToMemories(): number {
|
|
|
104
160
|
rationale: row.rationale,
|
|
105
161
|
made_by: row.made_by,
|
|
106
162
|
revisable: row.revisable,
|
|
163
|
+
superseded_by: row.superseded_by,
|
|
107
164
|
},
|
|
108
165
|
});
|
|
109
166
|
if (id) written += 1;
|
|
110
167
|
}
|
|
111
168
|
|
|
169
|
+
if (healed > 0) {
|
|
170
|
+
logWarning(
|
|
171
|
+
"memory-backfill",
|
|
172
|
+
`decisions->memories drift healed: ${healed} row${healed === 1 ? "" : "s"} updated superseded_by`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
112
176
|
return written;
|
|
113
177
|
} catch (e) {
|
|
114
178
|
logWarning("memory-backfill", `decisions->memories backfill failed: ${(e as Error).message}`);
|
|
@@ -116,6 +180,14 @@ export function backfillDecisionsToMemories(): number {
|
|
|
116
180
|
}
|
|
117
181
|
}
|
|
118
182
|
|
|
183
|
+
function safeParse(raw: string): Record<string, unknown> | null {
|
|
184
|
+
try {
|
|
185
|
+
return JSON.parse(raw) as Record<string, unknown>;
|
|
186
|
+
} catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
119
191
|
/**
|
|
120
192
|
* Combine the decision's structured fields into a 1-3 sentence content
|
|
121
193
|
* string suitable for keyword retrieval and human review.
|
|
@@ -124,7 +196,7 @@ export function backfillDecisionsToMemories(): number {
|
|
|
124
196
|
* Truncates each field to keep the synthesized line under ~600 chars so
|
|
125
197
|
* memory_query rendering stays readable.
|
|
126
198
|
*/
|
|
127
|
-
function
|
|
199
|
+
export function synthesizeDecisionMemoryContent(row: DecisionContentFields): string {
|
|
128
200
|
const trim = (value: string, max: number): string => {
|
|
129
201
|
const cleaned = value.replace(/\s+/g, " ").trim();
|
|
130
202
|
return cleaned.length > max ? cleaned.slice(0, max - 1) + "\u2026" : cleaned;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// GSD-2 — ADR-013 Phase 6 preflight scanner.
|
|
2
|
+
//
|
|
3
|
+
// Read-only detection of rows in the legacy knowledge surfaces (decisions
|
|
4
|
+
// table, `.gsd/KNOWLEDGE.md`) that lack a corresponding `memories` row.
|
|
5
|
+
// Runs on session start (and on demand via doctor); never mutates state.
|
|
6
|
+
//
|
|
7
|
+
// The scanner exists so the destructive Phase 6 cutover (#5755) can prove
|
|
8
|
+
// the migration is complete before any tables are dropped. Today's
|
|
9
|
+
// `backfillDecisionsToMemories` writes a `structured_fields.sourceDecisionId`
|
|
10
|
+
// marker on each migrated row; the scanner uses that marker for decisions
|
|
11
|
+
// detection. A `sourceKnowledgeId` marker is reserved for the parallel
|
|
12
|
+
// KNOWLEDGE.md backfill that Phase 6 will introduce — until that ships,
|
|
13
|
+
// every KNOWLEDGE.md row is reported as unmigrated, which is the honest
|
|
14
|
+
// state of the consolidation.
|
|
15
|
+
|
|
16
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
17
|
+
|
|
18
|
+
import { _getAdapter, isDbAvailable } from "./gsd-db.js";
|
|
19
|
+
import { appendNotification } from "./notification-store.js";
|
|
20
|
+
import { resolveGsdRootFile } from "./paths.js";
|
|
21
|
+
import { logWarning } from "./workflow-logger.js";
|
|
22
|
+
|
|
23
|
+
// ─── Types ──────────────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
export interface KnowledgeSurfaceReport {
|
|
26
|
+
total: number;
|
|
27
|
+
migrated: number;
|
|
28
|
+
unmigrated: number;
|
|
29
|
+
byTable: { rules: number; patterns: number; lessons: number };
|
|
30
|
+
/** Up to 5 sample row IDs/content for diagnosing what's unmigrated. */
|
|
31
|
+
samples: Array<{ table: "rules" | "patterns" | "lessons"; id: string; row: string }>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface DecisionsSurfaceReport {
|
|
35
|
+
total: number;
|
|
36
|
+
migrated: number;
|
|
37
|
+
unmigrated: number;
|
|
38
|
+
/** Up to 5 sample decision IDs with a short content excerpt. */
|
|
39
|
+
samples: Array<{ id: string; decision: string }>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ConsolidationGapReport {
|
|
43
|
+
decisions: DecisionsSurfaceReport;
|
|
44
|
+
knowledge: KnowledgeSurfaceReport;
|
|
45
|
+
/** Sum of unmigrated rows across both surfaces. Zero ⇒ clean preflight. */
|
|
46
|
+
totalGaps: number;
|
|
47
|
+
/** Human-readable single-line summary suitable for notifications + logs. */
|
|
48
|
+
summary: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ─── KNOWLEDGE.md parsing ────────────────────────────────────────────────────
|
|
52
|
+
|
|
53
|
+
const KNOWLEDGE_SECTIONS = [
|
|
54
|
+
{ table: "rules" as const, heading: "## Rules", idPrefix: "K" },
|
|
55
|
+
{ table: "patterns" as const, heading: "## Patterns", idPrefix: "P" },
|
|
56
|
+
{ table: "lessons" as const, heading: "## Lessons Learned", idPrefix: "L" },
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
interface KnowledgeRow {
|
|
60
|
+
table: "rules" | "patterns" | "lessons";
|
|
61
|
+
id: string;
|
|
62
|
+
row: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Parse `.gsd/KNOWLEDGE.md` into rows, one per table entry. Skips the table
|
|
67
|
+
* header and separator lines; ignores rows from unrecognized sections.
|
|
68
|
+
*
|
|
69
|
+
* The format is locked in `files.ts:appendKnowledge` — three `## ` sections
|
|
70
|
+
* (Rules, Patterns, Lessons Learned), each a Markdown table. Row IDs are
|
|
71
|
+
* `K###` / `P###` / `L###`.
|
|
72
|
+
*/
|
|
73
|
+
export function parseKnowledgeRows(content: string): KnowledgeRow[] {
|
|
74
|
+
const rows: KnowledgeRow[] = [];
|
|
75
|
+
if (!content.trim()) return rows;
|
|
76
|
+
|
|
77
|
+
// Slice the content into sections by heading. The leading text before the
|
|
78
|
+
// first ## heading is intro prose — ignored.
|
|
79
|
+
const lines = content.split("\n");
|
|
80
|
+
let activeSection: typeof KNOWLEDGE_SECTIONS[number] | undefined;
|
|
81
|
+
|
|
82
|
+
for (const line of lines) {
|
|
83
|
+
const trimmed = line.trim();
|
|
84
|
+
if (trimmed.startsWith("## ")) {
|
|
85
|
+
activeSection = KNOWLEDGE_SECTIONS.find((s) => s.heading === trimmed);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (!activeSection) continue;
|
|
89
|
+
if (!trimmed.startsWith("|")) continue;
|
|
90
|
+
|
|
91
|
+
// Skip the table header rows: the column-titles line and the |---|---| separator.
|
|
92
|
+
// Real data rows start with `| <prefix>### |`.
|
|
93
|
+
const idMatch = new RegExp(`^\\|\\s*(${activeSection.idPrefix}\\d+)\\s*\\|`).exec(trimmed);
|
|
94
|
+
if (!idMatch) continue;
|
|
95
|
+
|
|
96
|
+
rows.push({
|
|
97
|
+
table: activeSection.table,
|
|
98
|
+
id: idMatch[1] ?? "",
|
|
99
|
+
row: trimmed,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return rows;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function knowledgeMdContent(basePath: string): string {
|
|
107
|
+
const path = resolveGsdRootFile(basePath, "KNOWLEDGE");
|
|
108
|
+
if (!existsSync(path)) return "";
|
|
109
|
+
try {
|
|
110
|
+
return readFileSync(path, "utf-8");
|
|
111
|
+
} catch {
|
|
112
|
+
return "";
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ─── DB queries ──────────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
interface DecisionRow {
|
|
119
|
+
id: string;
|
|
120
|
+
decision: string;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function getActiveDecisions(): DecisionRow[] {
|
|
124
|
+
if (!isDbAvailable()) return [];
|
|
125
|
+
const adapter = _getAdapter();
|
|
126
|
+
if (!adapter) return [];
|
|
127
|
+
try {
|
|
128
|
+
const rows = adapter
|
|
129
|
+
.prepare(
|
|
130
|
+
"SELECT id, decision FROM decisions WHERE superseded_by IS NULL",
|
|
131
|
+
)
|
|
132
|
+
.all() as Array<Record<string, unknown>>;
|
|
133
|
+
return rows
|
|
134
|
+
.map((row): DecisionRow => ({
|
|
135
|
+
id: String(row["id"] ?? ""),
|
|
136
|
+
decision: String(row["decision"] ?? ""),
|
|
137
|
+
}))
|
|
138
|
+
.filter((row) => row.id.length > 0);
|
|
139
|
+
} catch {
|
|
140
|
+
return [];
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* True when a memory row has a `structured_fields` JSON payload containing
|
|
146
|
+
* the given `markerKey: "value"` pair. Matches the LIKE pattern used by
|
|
147
|
+
* `backfillDecisionsToMemories` so the scanner is consistent with the
|
|
148
|
+
* backfill's idempotency check.
|
|
149
|
+
*/
|
|
150
|
+
function memoryHasSourceMarker(markerKey: string, value: string): boolean {
|
|
151
|
+
if (!isDbAvailable()) return false;
|
|
152
|
+
const adapter = _getAdapter();
|
|
153
|
+
if (!adapter) return false;
|
|
154
|
+
try {
|
|
155
|
+
const pattern = `%"${markerKey}":"${value}"%`;
|
|
156
|
+
const row = adapter
|
|
157
|
+
.prepare("SELECT 1 FROM memories WHERE structured_fields LIKE :pattern LIMIT 1")
|
|
158
|
+
.get({ ":pattern": pattern });
|
|
159
|
+
return row !== undefined;
|
|
160
|
+
} catch {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ─── Public API ──────────────────────────────────────────────────────────────
|
|
166
|
+
|
|
167
|
+
const SAMPLE_LIMIT = 5;
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Scan the legacy knowledge surfaces and return a structured report of what's
|
|
171
|
+
* already in the `memories` table vs what's still unmigrated. Pure detection
|
|
172
|
+
* — no DB writes, no file writes, no notifications.
|
|
173
|
+
*/
|
|
174
|
+
export function scanConsolidationGaps(basePath: string): ConsolidationGapReport {
|
|
175
|
+
// ── Decisions ────────────────────────────────────────────────────────
|
|
176
|
+
const decisions = getActiveDecisions();
|
|
177
|
+
const decisionSamples: DecisionsSurfaceReport["samples"] = [];
|
|
178
|
+
let decisionMigrated = 0;
|
|
179
|
+
for (const decision of decisions) {
|
|
180
|
+
if (memoryHasSourceMarker("sourceDecisionId", decision.id)) {
|
|
181
|
+
decisionMigrated += 1;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (decisionSamples.length < SAMPLE_LIMIT) {
|
|
185
|
+
decisionSamples.push({
|
|
186
|
+
id: decision.id,
|
|
187
|
+
decision: decision.decision.length > 80 ? decision.decision.slice(0, 79) + "…" : decision.decision,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ── KNOWLEDGE.md ─────────────────────────────────────────────────────
|
|
193
|
+
const knowledgeRows = parseKnowledgeRows(knowledgeMdContent(basePath));
|
|
194
|
+
const knowledgeByTable = { rules: 0, patterns: 0, lessons: 0 };
|
|
195
|
+
const knowledgeSamples: KnowledgeSurfaceReport["samples"] = [];
|
|
196
|
+
let knowledgeMigrated = 0;
|
|
197
|
+
for (const row of knowledgeRows) {
|
|
198
|
+
knowledgeByTable[row.table] += 1;
|
|
199
|
+
// Phase 6 will introduce a `sourceKnowledgeId` marker as part of the
|
|
200
|
+
// KNOWLEDGE.md backfill. Until that path ships, this check returns
|
|
201
|
+
// false for every row, which is the honest state of the consolidation.
|
|
202
|
+
if (memoryHasSourceMarker("sourceKnowledgeId", row.id)) {
|
|
203
|
+
knowledgeMigrated += 1;
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (knowledgeSamples.length < SAMPLE_LIMIT) {
|
|
207
|
+
knowledgeSamples.push({
|
|
208
|
+
table: row.table,
|
|
209
|
+
id: row.id,
|
|
210
|
+
row: row.row.length > 100 ? row.row.slice(0, 99) + "…" : row.row,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const decisionsReport: DecisionsSurfaceReport = {
|
|
216
|
+
total: decisions.length,
|
|
217
|
+
migrated: decisionMigrated,
|
|
218
|
+
unmigrated: decisions.length - decisionMigrated,
|
|
219
|
+
samples: decisionSamples,
|
|
220
|
+
};
|
|
221
|
+
const knowledgeReport: KnowledgeSurfaceReport = {
|
|
222
|
+
total: knowledgeRows.length,
|
|
223
|
+
migrated: knowledgeMigrated,
|
|
224
|
+
unmigrated: knowledgeRows.length - knowledgeMigrated,
|
|
225
|
+
byTable: knowledgeByTable,
|
|
226
|
+
samples: knowledgeSamples,
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
const totalGaps = decisionsReport.unmigrated + knowledgeReport.unmigrated;
|
|
230
|
+
|
|
231
|
+
// Summary line is intentionally short so it fits in a single notification
|
|
232
|
+
// (notification-store truncates messages over 500 chars). Detail is
|
|
233
|
+
// accessible via getProviderSwitchStats-style callers, not embedded here.
|
|
234
|
+
const parts: string[] = [];
|
|
235
|
+
if (decisionsReport.unmigrated > 0) {
|
|
236
|
+
parts.push(`${decisionsReport.unmigrated} of ${decisionsReport.total} active decisions`);
|
|
237
|
+
}
|
|
238
|
+
if (knowledgeReport.unmigrated > 0) {
|
|
239
|
+
parts.push(`${knowledgeReport.unmigrated} of ${knowledgeReport.total} KNOWLEDGE.md rows`);
|
|
240
|
+
}
|
|
241
|
+
const summary =
|
|
242
|
+
parts.length === 0
|
|
243
|
+
? "Memory consolidation: all decisions and KNOWLEDGE.md rows are in memories."
|
|
244
|
+
: `Memory consolidation: ${parts.join(" and ")} not yet in memories table. Run /doctor for details.`;
|
|
245
|
+
|
|
246
|
+
return { decisions: decisionsReport, knowledge: knowledgeReport, totalGaps, summary };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Run the scanner and emit a persistent notification + workflow-logger
|
|
251
|
+
* warning when gaps exist. Best-effort: never throws; a broken scanner
|
|
252
|
+
* cannot block agent startup.
|
|
253
|
+
*
|
|
254
|
+
* Returns the full {@link ConsolidationGapReport} regardless of whether gaps
|
|
255
|
+
* exist (including when `totalGaps === 0`). Returns `null` only when
|
|
256
|
+
* `scanConsolidationGaps` itself throws. `appendNotification` and
|
|
257
|
+
* `logWarning` are called only when `report.totalGaps > 0`.
|
|
258
|
+
*
|
|
259
|
+
* Idempotent at the surface: the notification store applies its own
|
|
260
|
+
* 30-second dedup window keyed on (severity, source, message), so repeated
|
|
261
|
+
* boots with identical gaps produce one notification, not a flood.
|
|
262
|
+
*/
|
|
263
|
+
export function reportConsolidationGaps(basePath: string): ConsolidationGapReport | null {
|
|
264
|
+
try {
|
|
265
|
+
const report = scanConsolidationGaps(basePath);
|
|
266
|
+
if (report.totalGaps === 0) return report;
|
|
267
|
+
appendNotification(report.summary, "warning", "workflow-logger");
|
|
268
|
+
logWarning("memory-consolidation", report.summary);
|
|
269
|
+
return report;
|
|
270
|
+
} catch (e) {
|
|
271
|
+
logWarning(
|
|
272
|
+
"memory-consolidation",
|
|
273
|
+
`scanner failed: ${(e as Error).message}`,
|
|
274
|
+
);
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
@@ -27,7 +27,7 @@ GSD ships with bundled skills. When the task matches, load the relevant skill fi
|
|
|
27
27
|
|
|
28
28
|
- Never ask the user to do work the agent can execute or verify itself.
|
|
29
29
|
- Use the lightest sufficient tool first.
|
|
30
|
-
- Read before edit.
|
|
30
|
+
- Read before edit or overwrite. Before any write that creates or replaces a file, verify the target path and read relevant existing files, templates, callers, or surrounding code. For truly new files, confirm the path does not already exist.
|
|
31
31
|
- Reproduce before fix when possible.
|
|
32
32
|
- Work is not done until the relevant verification has passed.
|
|
33
33
|
- **Never fabricate, simulate, or role-play user responses.** Never generate markers like `[User]`, `[Human]`, `User:`, or similar; never emit `<user_message>`, `<assistant_message>`, or similar as user input. Treat `<conversation_history>` as read-only context. Ask one question round (1-3 questions), then stop and wait for the user's actual response. If `ask_user_questions` is available, its result is the only valid structured user input for that round. If it cancels, fails, or returns nothing, never use earlier chat as confirmation for the current gate; ask in plain chat and stop.
|
|
@@ -102,7 +102,7 @@ Templates are in `{{templatesDir}}`.
|
|
|
102
102
|
|
|
103
103
|
**File reading:** Use `read` for file inspection. Never use `cat`, `head`, `tail`, or `sed -n` to view contents. Use `read` with `offset`/`limit` for slicing. `bash` is for searching (`rg`, `grep`, `find`) and commands, not displaying files.
|
|
104
104
|
|
|
105
|
-
**File editing:** Always `read` before `edit
|
|
105
|
+
**File editing:** Always `read` before `edit` or overwrite. Before `write`, confirm whether the path exists; if it does, `read` it first and preserve intentional existing content. Use `write` only for new files or complete rewrites.
|
|
106
106
|
|
|
107
107
|
**Code navigation:** Use `lsp` for definition, type_definition, implementation, references, calls, hover, signature, symbols, rename, code_actions, format, and diagnostics. Do not `grep` symbol definitions or shell out to formatters when `lsp` can do it. After code edits, run `lsp diagnostics`.
|
|
108
108
|
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// GSD-2 — ADR-005 Phase 3b: surface ProviderSwitchReport from pi-ai.
|
|
2
|
+
//
|
|
3
|
+
// pi-ai builds a ProviderSwitchReport on every cross-provider transform but
|
|
4
|
+
// only logs it to stderr when GSD_VERBOSE=1. This module installs a
|
|
5
|
+
// single-subscriber observer that surfaces non-empty reports through GSD's
|
|
6
|
+
// three usual telemetry surfaces:
|
|
7
|
+
//
|
|
8
|
+
// 1. UOK audit event (category model-policy, type provider-switch) — only
|
|
9
|
+
// when an auto trace is active.
|
|
10
|
+
// 2. Persistent notification (.gsd/notifications.jsonl, severity warning) —
|
|
11
|
+
// whenever the GSD basePath is known, so users see the loss in the
|
|
12
|
+
// dashboard / status surface without GSD_VERBOSE.
|
|
13
|
+
// 3. In-memory counter, exposed via getProviderSwitchStats() so any
|
|
14
|
+
// caller (dashboard, doctor, tests) can read the rollup.
|
|
15
|
+
|
|
16
|
+
import { setProviderSwitchObserver, type ProviderSwitchReport } from "@gsd/pi-ai";
|
|
17
|
+
|
|
18
|
+
import { autoSession } from "./auto-runtime-state.js";
|
|
19
|
+
import { appendNotification } from "./notification-store.js";
|
|
20
|
+
import { buildAuditEnvelope, emitUokAuditEvent } from "./uok/audit.js";
|
|
21
|
+
|
|
22
|
+
/** Rollup of cross-provider context transformations, grouped by trace. */
|
|
23
|
+
export interface ProviderSwitchStats {
|
|
24
|
+
/** Total non-empty reports observed since process start (or last reset). */
|
|
25
|
+
totalSwitches: number;
|
|
26
|
+
/** Sum of every counted transformation across all reports. */
|
|
27
|
+
totals: {
|
|
28
|
+
thinkingBlocksDropped: number;
|
|
29
|
+
thinkingBlocksDowngraded: number;
|
|
30
|
+
toolCallIdsRemapped: number;
|
|
31
|
+
syntheticToolResultsInserted: number;
|
|
32
|
+
thoughtSignaturesDropped: number;
|
|
33
|
+
};
|
|
34
|
+
/** Per-trace breakdown. Key "interactive" covers reports outside auto-mode. */
|
|
35
|
+
byTrace: Record<string, TraceSwitchStats>;
|
|
36
|
+
/** The most recent non-empty report, if any. */
|
|
37
|
+
lastReport: ProviderSwitchReport | null;
|
|
38
|
+
/** ISO timestamp of the most recent non-empty report, if any. */
|
|
39
|
+
lastAt: string | null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface TraceSwitchStats {
|
|
43
|
+
switches: number;
|
|
44
|
+
lastReport: ProviderSwitchReport;
|
|
45
|
+
lastAt: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const INTERACTIVE_TRACE_KEY = "interactive";
|
|
49
|
+
|
|
50
|
+
interface MutableTraceStats {
|
|
51
|
+
switches: number;
|
|
52
|
+
lastReport: ProviderSwitchReport;
|
|
53
|
+
lastAt: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let installed = false;
|
|
57
|
+
let totalSwitches = 0;
|
|
58
|
+
const totals = {
|
|
59
|
+
thinkingBlocksDropped: 0,
|
|
60
|
+
thinkingBlocksDowngraded: 0,
|
|
61
|
+
toolCallIdsRemapped: 0,
|
|
62
|
+
syntheticToolResultsInserted: 0,
|
|
63
|
+
thoughtSignaturesDropped: 0,
|
|
64
|
+
};
|
|
65
|
+
const byTrace = new Map<string, MutableTraceStats>();
|
|
66
|
+
let lastReport: ProviderSwitchReport | null = null;
|
|
67
|
+
let lastAt: string | null = null;
|
|
68
|
+
|
|
69
|
+
/** Format a one-line summary suitable for a notification message. */
|
|
70
|
+
function summarize(report: ProviderSwitchReport): string {
|
|
71
|
+
const parts: string[] = [];
|
|
72
|
+
if (report.thinkingBlocksDropped > 0) parts.push(`${report.thinkingBlocksDropped} thinking dropped`);
|
|
73
|
+
if (report.thinkingBlocksDowngraded > 0) parts.push(`${report.thinkingBlocksDowngraded} thinking downgraded`);
|
|
74
|
+
if (report.toolCallIdsRemapped > 0) parts.push(`${report.toolCallIdsRemapped} tool ids remapped`);
|
|
75
|
+
if (report.syntheticToolResultsInserted > 0) parts.push(`${report.syntheticToolResultsInserted} synthetic tool results`);
|
|
76
|
+
if (report.thoughtSignaturesDropped > 0) parts.push(`${report.thoughtSignaturesDropped} thought signatures dropped`);
|
|
77
|
+
return `Provider switch ${report.fromApi} → ${report.toApi}: ${parts.join(", ")}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function recordReport(report: ProviderSwitchReport): void {
|
|
81
|
+
const now = new Date().toISOString();
|
|
82
|
+
totalSwitches += 1;
|
|
83
|
+
totals.thinkingBlocksDropped += report.thinkingBlocksDropped;
|
|
84
|
+
totals.thinkingBlocksDowngraded += report.thinkingBlocksDowngraded;
|
|
85
|
+
totals.toolCallIdsRemapped += report.toolCallIdsRemapped;
|
|
86
|
+
totals.syntheticToolResultsInserted += report.syntheticToolResultsInserted;
|
|
87
|
+
totals.thoughtSignaturesDropped += report.thoughtSignaturesDropped;
|
|
88
|
+
lastReport = report;
|
|
89
|
+
lastAt = now;
|
|
90
|
+
|
|
91
|
+
const traceKey = autoSession.currentTraceId ?? INTERACTIVE_TRACE_KEY;
|
|
92
|
+
const existing = byTrace.get(traceKey);
|
|
93
|
+
if (existing) {
|
|
94
|
+
existing.switches += 1;
|
|
95
|
+
existing.lastReport = report;
|
|
96
|
+
existing.lastAt = now;
|
|
97
|
+
} else {
|
|
98
|
+
byTrace.set(traceKey, { switches: 1, lastReport: report, lastAt: now });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function emitAudit(report: ProviderSwitchReport): void {
|
|
103
|
+
const traceId = autoSession.currentTraceId;
|
|
104
|
+
const basePath = autoSession.basePath;
|
|
105
|
+
if (!traceId || !basePath) return;
|
|
106
|
+
try {
|
|
107
|
+
emitUokAuditEvent(
|
|
108
|
+
basePath,
|
|
109
|
+
buildAuditEnvelope({
|
|
110
|
+
traceId,
|
|
111
|
+
category: "model-policy",
|
|
112
|
+
type: "provider-switch",
|
|
113
|
+
payload: {
|
|
114
|
+
fromApi: report.fromApi,
|
|
115
|
+
toApi: report.toApi,
|
|
116
|
+
thinkingBlocksDropped: report.thinkingBlocksDropped,
|
|
117
|
+
thinkingBlocksDowngraded: report.thinkingBlocksDowngraded,
|
|
118
|
+
toolCallIdsRemapped: report.toolCallIdsRemapped,
|
|
119
|
+
syntheticToolResultsInserted: report.syntheticToolResultsInserted,
|
|
120
|
+
thoughtSignaturesDropped: report.thoughtSignaturesDropped,
|
|
121
|
+
},
|
|
122
|
+
}),
|
|
123
|
+
);
|
|
124
|
+
} catch {
|
|
125
|
+
// Audit emission is best-effort. Counter + notification still fire.
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function emitNotification(report: ProviderSwitchReport): void {
|
|
130
|
+
try {
|
|
131
|
+
appendNotification(summarize(report), "warning", "workflow-logger");
|
|
132
|
+
} catch {
|
|
133
|
+
// Notification persistence is best-effort.
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function handleReport(report: ProviderSwitchReport): void {
|
|
138
|
+
recordReport(report);
|
|
139
|
+
emitAudit(report);
|
|
140
|
+
emitNotification(report);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Install the pi-ai observer. Idempotent — calling more than once is a no-op
|
|
145
|
+
* after the first install.
|
|
146
|
+
*/
|
|
147
|
+
export function installProviderSwitchObserver(): void {
|
|
148
|
+
if (installed) return;
|
|
149
|
+
setProviderSwitchObserver(handleReport);
|
|
150
|
+
installed = true;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Uninstall the observer. Intended for tests. */
|
|
154
|
+
export function uninstallProviderSwitchObserver(): void {
|
|
155
|
+
setProviderSwitchObserver(undefined);
|
|
156
|
+
installed = false;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Read-only snapshot of the in-memory rollup. */
|
|
160
|
+
export function getProviderSwitchStats(): ProviderSwitchStats {
|
|
161
|
+
const trace: Record<string, TraceSwitchStats> = {};
|
|
162
|
+
for (const [key, value] of byTrace) {
|
|
163
|
+
trace[key] = { switches: value.switches, lastReport: { ...value.lastReport }, lastAt: value.lastAt };
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
totalSwitches,
|
|
167
|
+
totals: { ...totals },
|
|
168
|
+
byTrace: trace,
|
|
169
|
+
lastReport: lastReport ? { ...lastReport } : null,
|
|
170
|
+
lastAt,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Reset the in-memory rollup. Intended for tests. */
|
|
175
|
+
export function _resetProviderSwitchStats(): void {
|
|
176
|
+
totalSwitches = 0;
|
|
177
|
+
totals.thinkingBlocksDropped = 0;
|
|
178
|
+
totals.thinkingBlocksDowngraded = 0;
|
|
179
|
+
totals.toolCallIdsRemapped = 0;
|
|
180
|
+
totals.syntheticToolResultsInserted = 0;
|
|
181
|
+
totals.thoughtSignaturesDropped = 0;
|
|
182
|
+
byTrace.clear();
|
|
183
|
+
lastReport = null;
|
|
184
|
+
lastAt = null;
|
|
185
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Project Knowledge
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
Project-specific rules plus projected patterns and lessons learned.
|
|
4
|
+
Rules are maintained in this file. Patterns and lessons are persisted to the memories table and rendered here on the next session-start projection.
|
|
5
5
|
|
|
6
6
|
## Rules
|
|
7
7
|
|