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.
Files changed (135) hide show
  1. package/README.md +46 -28
  2. package/dist/resources/.managed-resources-content-hash +1 -1
  3. package/dist/resources/extensions/browser-tools/tools/screenshot.js +1 -0
  4. package/dist/resources/extensions/browser-tools/tools/zoom.js +1 -0
  5. package/dist/resources/extensions/gsd/auto/phases.js +9 -0
  6. package/dist/resources/extensions/gsd/auto-prompts.js +11 -3
  7. package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +5 -0
  8. package/dist/resources/extensions/gsd/bootstrap/system-context.js +55 -12
  9. package/dist/resources/extensions/gsd/commands/handlers/core.js +1 -1
  10. package/dist/resources/extensions/gsd/commands-handlers.js +15 -2
  11. package/dist/resources/extensions/gsd/context-store.js +112 -0
  12. package/dist/resources/extensions/gsd/db-writer.js +150 -84
  13. package/dist/resources/extensions/gsd/docs/preferences-reference.md +1 -1
  14. package/dist/resources/extensions/gsd/doctor-git-checks.js +41 -6
  15. package/dist/resources/extensions/gsd/knowledge-backfill.js +144 -0
  16. package/dist/resources/extensions/gsd/knowledge-capture.js +136 -0
  17. package/dist/resources/extensions/gsd/knowledge-parser.js +154 -0
  18. package/dist/resources/extensions/gsd/knowledge-projection.js +210 -0
  19. package/dist/resources/extensions/gsd/markdown-renderer.js +6 -1
  20. package/dist/resources/extensions/gsd/memory-backfill.js +73 -17
  21. package/dist/resources/extensions/gsd/memory-consolidation-scanner.js +222 -0
  22. package/dist/resources/extensions/gsd/prompts/system.md +2 -2
  23. package/dist/resources/extensions/gsd/provider-switch-observer.js +146 -0
  24. package/dist/resources/extensions/gsd/templates/knowledge.md +2 -2
  25. package/dist/tsconfig.extensions.tsbuildinfo +1 -1
  26. package/dist/web/standalone/.next/BUILD_ID +1 -1
  27. package/dist/web/standalone/.next/app-path-routes-manifest.json +11 -11
  28. package/dist/web/standalone/.next/build-manifest.json +2 -2
  29. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  30. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  31. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  32. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  33. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  34. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  35. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  36. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  37. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  38. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  39. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  40. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  41. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  42. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  43. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  44. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  45. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  46. package/dist/web/standalone/.next/server/app/index.html +1 -1
  47. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  48. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  49. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  50. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  51. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  52. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  53. package/dist/web/standalone/.next/server/app-paths-manifest.json +11 -11
  54. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  55. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  56. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  57. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  58. package/package.json +3 -2
  59. package/packages/daemon/package.json +2 -2
  60. package/packages/mcp-server/README.md +2 -0
  61. package/packages/mcp-server/package.json +2 -2
  62. package/packages/mcp-server/src/workflow-tools-parity.test.ts +244 -0
  63. package/packages/native/package.json +1 -1
  64. package/packages/pi-agent-core/package.json +1 -1
  65. package/packages/pi-agent-core/tsconfig.tsbuildinfo +1 -1
  66. package/packages/pi-ai/dist/index.d.ts +2 -2
  67. package/packages/pi-ai/dist/index.d.ts.map +1 -1
  68. package/packages/pi-ai/dist/index.js +1 -1
  69. package/packages/pi-ai/dist/index.js.map +1 -1
  70. package/packages/pi-ai/dist/providers/transform-messages.d.ts +11 -0
  71. package/packages/pi-ai/dist/providers/transform-messages.d.ts.map +1 -1
  72. package/packages/pi-ai/dist/providers/transform-messages.js +20 -0
  73. package/packages/pi-ai/dist/providers/transform-messages.js.map +1 -1
  74. package/packages/pi-ai/package.json +1 -1
  75. package/packages/pi-ai/src/index.ts +7 -2
  76. package/packages/pi-ai/src/providers/transform-messages.ts +24 -0
  77. package/packages/pi-ai/tsconfig.tsbuildinfo +1 -1
  78. package/packages/pi-coding-agent/dist/core/system-prompt.js +4 -4
  79. package/packages/pi-coding-agent/dist/core/system-prompt.js.map +1 -1
  80. package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.d.ts +2 -0
  81. package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.d.ts.map +1 -0
  82. package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.js +17 -0
  83. package/packages/pi-coding-agent/dist/tests/system-prompt-file-safety.test.js.map +1 -0
  84. package/packages/pi-coding-agent/package.json +1 -1
  85. package/packages/pi-coding-agent/src/core/system-prompt.ts +4 -4
  86. package/packages/pi-coding-agent/src/tests/system-prompt-file-safety.test.ts +22 -0
  87. package/packages/pi-coding-agent/tsconfig.tsbuildinfo +1 -1
  88. package/packages/pi-tui/package.json +1 -1
  89. package/packages/rpc-client/package.json +1 -1
  90. package/pkg/package.json +1 -1
  91. package/src/resources/extensions/browser-tools/tools/screenshot.ts +1 -0
  92. package/src/resources/extensions/browser-tools/tools/zoom.ts +1 -0
  93. package/src/resources/extensions/gsd/auto/phases.ts +14 -0
  94. package/src/resources/extensions/gsd/auto-prompts.ts +11 -3
  95. package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +6 -0
  96. package/src/resources/extensions/gsd/bootstrap/system-context.ts +58 -15
  97. package/src/resources/extensions/gsd/commands/handlers/core.ts +1 -1
  98. package/src/resources/extensions/gsd/commands-handlers.ts +19 -2
  99. package/src/resources/extensions/gsd/context-store.ts +120 -1
  100. package/src/resources/extensions/gsd/db-writer.ts +167 -84
  101. package/src/resources/extensions/gsd/docs/preferences-reference.md +1 -1
  102. package/src/resources/extensions/gsd/doctor-git-checks.ts +44 -6
  103. package/src/resources/extensions/gsd/doctor-types.ts +2 -0
  104. package/src/resources/extensions/gsd/knowledge-backfill.ts +164 -0
  105. package/src/resources/extensions/gsd/knowledge-capture.ts +160 -0
  106. package/src/resources/extensions/gsd/knowledge-parser.ts +174 -0
  107. package/src/resources/extensions/gsd/knowledge-projection.ts +241 -0
  108. package/src/resources/extensions/gsd/markdown-renderer.ts +6 -1
  109. package/src/resources/extensions/gsd/memory-backfill.ts +89 -17
  110. package/src/resources/extensions/gsd/memory-consolidation-scanner.ts +277 -0
  111. package/src/resources/extensions/gsd/prompts/system.md +2 -2
  112. package/src/resources/extensions/gsd/provider-switch-observer.ts +185 -0
  113. package/src/resources/extensions/gsd/templates/knowledge.md +2 -2
  114. package/src/resources/extensions/gsd/tests/auto-loop.test.ts +75 -0
  115. package/src/resources/extensions/gsd/tests/browser-tools-compatibility-declarations.test.ts +62 -0
  116. package/src/resources/extensions/gsd/tests/context-store-decisions-from-memories.test.ts +312 -0
  117. package/src/resources/extensions/gsd/tests/db-writer.test.ts +13 -8
  118. package/src/resources/extensions/gsd/tests/decisions-projection-from-memories.test.ts +453 -0
  119. package/src/resources/extensions/gsd/tests/decisions-stop-table-writes.test.ts +348 -0
  120. package/src/resources/extensions/gsd/tests/freeform-decisions.test.ts +8 -4
  121. package/src/resources/extensions/gsd/tests/gsd-tools.test.ts +11 -7
  122. package/src/resources/extensions/gsd/tests/integration/doctor-git.test.ts +44 -0
  123. package/src/resources/extensions/gsd/tests/integration/integration-lifecycle.test.ts +13 -5
  124. package/src/resources/extensions/gsd/tests/knowledge-backfill-projection.test.ts +323 -0
  125. package/src/resources/extensions/gsd/tests/knowledge-capture.test.ts +242 -0
  126. package/src/resources/extensions/gsd/tests/knowledge.test.ts +47 -2
  127. package/src/resources/extensions/gsd/tests/load-knowledge-block-rules-only.test.ts +209 -0
  128. package/src/resources/extensions/gsd/tests/memory-consolidation-scanner.test.ts +316 -0
  129. package/src/resources/extensions/gsd/tests/plan-milestone-sketch-render.test.ts +157 -0
  130. package/src/resources/extensions/gsd/tests/prompt-contracts.test.ts +8 -0
  131. package/src/resources/extensions/gsd/tests/provider-switch-observer.test.ts +252 -0
  132. package/src/resources/extensions/gsd/tests/session-start-footer.test.ts +16 -4
  133. package/src/resources/extensions/gsd/workflow-logger.ts +4 -0
  134. /package/dist/web/standalone/.next/static/{rIkMv4YSNlfSeqmGqWVns → KDRTXR-22LPCsa80X9dey}/_buildManifest.js +0 -0
  135. /package/dist/web/standalone/.next/static/{rIkMv4YSNlfSeqmGqWVns → KDRTXR-22LPCsa80X9dey}/_ssgManifest.js +0 -0
@@ -210,16 +210,62 @@ export async function nextDecisionId() {
210
210
  return 'D001';
211
211
  }
212
212
  }
213
- /** Synchronous variant for use inside db.transaction(). */
214
- function nextDecisionIdSync(adapter) {
213
+ /**
214
+ * ADR-013 Stage 3: compute the next `D###` identifier across both the legacy
215
+ * `decisions` table AND the `memories.structured_fields.sourceDecisionId`
216
+ * surface. Returns the max numeric suffix from either side + 1, three-digit
217
+ * padded.
218
+ *
219
+ * Used by `saveDecisionToDb` once writes to the `decisions` table stop —
220
+ * new decisions live only in memories, but historical IDs sit in both
221
+ * places during the cutover bake. The cross-surface max keeps IDs
222
+ * monotonic and avoids collisions on the next save.
223
+ */
224
+ function nextDecisionIdAcrossSurfaces(adapter) {
215
225
  if (!adapter)
216
226
  return 'D001';
217
- const row = adapter
218
- .prepare('SELECT MAX(CAST(SUBSTR(id, 2) AS INTEGER)) as max_num FROM decisions')
219
- .get();
220
- const maxNum = row ? row['max_num'] : null;
221
- if (maxNum == null || isNaN(maxNum))
222
- return 'D001';
227
+ let maxNum = 0;
228
+ // Legacy table best-effort.
229
+ try {
230
+ const row = adapter
231
+ .prepare('SELECT MAX(CAST(SUBSTR(id, 2) AS INTEGER)) as max_num FROM decisions')
232
+ .get();
233
+ const candidate = row ? row['max_num'] : null;
234
+ if (typeof candidate === 'number' && Number.isFinite(candidate)) {
235
+ maxNum = Math.max(maxNum, candidate);
236
+ }
237
+ }
238
+ catch {
239
+ // fall through to memory-only
240
+ }
241
+ // Memory surface: scan structuredFields.sourceDecisionId for D### values.
242
+ // SQLite LIKE on the JSON-stringified field is sufficient — rows tagged
243
+ // with sourceDecisionId are bounded by the decisions count.
244
+ try {
245
+ const rows = adapter
246
+ .prepare("SELECT structured_fields FROM memories WHERE structured_fields LIKE '%\"sourceDecisionId\":\"D%'")
247
+ .all();
248
+ for (const row of rows) {
249
+ if (!row.structured_fields)
250
+ continue;
251
+ let sf;
252
+ try {
253
+ sf = JSON.parse(row.structured_fields);
254
+ }
255
+ catch {
256
+ continue;
257
+ }
258
+ const sourceId = sf['sourceDecisionId'];
259
+ if (typeof sourceId !== 'string' || !sourceId.startsWith('D'))
260
+ continue;
261
+ const num = parseInt(sourceId.slice(1), 10);
262
+ if (Number.isFinite(num) && num > maxNum)
263
+ maxNum = num;
264
+ }
265
+ }
266
+ catch {
267
+ // best-effort
268
+ }
223
269
  const next = maxNum + 1;
224
270
  return `D${String(next).padStart(3, '0')}`;
225
271
  }
@@ -376,38 +422,55 @@ export async function saveDecisionToDb(fields, basePath) {
376
422
  try {
377
423
  const db = await import('./gsd-db.js');
378
424
  const adapter = db._getAdapter();
379
- const id = db.transaction(() => {
380
- const nextId = nextDecisionIdSync(adapter);
381
- db.upsertDecision({
382
- id: nextId,
383
- when_context: fields.when_context ?? '',
384
- scope: fields.scope,
385
- decision: fields.decision,
386
- choice: fields.choice,
387
- rationale: fields.rationale,
388
- revisable: fields.revisable ?? 'Yes',
389
- made_by: fields.made_by ?? 'agent',
390
- source: fields.source ?? 'discussion',
391
- superseded_by: null,
425
+ const normalized = {
426
+ ...fields,
427
+ when_context: fields.when_context ?? '',
428
+ revisable: fields.revisable ?? 'Yes',
429
+ made_by: fields.made_by ?? 'agent',
430
+ source: fields.source ?? 'discussion',
431
+ };
432
+ // ADR-013 Stage 3 (destructive): writes to the `decisions` table stop
433
+ // here. New decisions live only in the `memories` table; the projection
434
+ // regen below sources from memories (Stage 2a). The decisions table
435
+ // remains for backwards-compat reads (queryDecisions, md-importer,
436
+ // commands-inspect, workflow-manifest) until #5756 drops it.
437
+ //
438
+ // Reversal: a code revert of this change restores the upsertDecision
439
+ // call. Memory rows written between merge and revert stay durable; the
440
+ // legacy table simply doesn't grow during the cutover window.
441
+ const id = nextDecisionIdAcrossSurfaces(adapter);
442
+ // The mirror-to-memories write is what persists the new decision. Must
443
+ // run before the projection regen — the regen sources from memories
444
+ // (Stage 2a) and would otherwise miss the just-saved decision. Pass
445
+ // the normalized field set so defaults (revisable, made_by, source)
446
+ // are recorded on the memory row.
447
+ await mirrorDecisionToMemory(id, normalized);
448
+ // Fetch all decisions (including superseded for the full register).
449
+ // ADR-013 Stage 2a: source from the `memories` table. The Phase 5
450
+ // dual-write keeps memories in sync with each decision save; the backfill
451
+ // (memory-backfill.ts) absorbs the historical chain and drift-heals
452
+ // superseded_by on every session start.
453
+ const { getAllDecisionsFromMemories } = await import('./context-store.js');
454
+ let allDecisions = getAllDecisionsFromMemories();
455
+ if (!allDecisions.some(d => d.id === id)) {
456
+ logWarning('projection', 'just-saved decision missing from memories after mirror; injecting fallback for projection', {
457
+ fn: 'saveDecisionToDb',
458
+ decisionId: id,
392
459
  });
393
- return nextId;
394
- });
395
- // Fetch all decisions (including superseded for the full register)
396
- let allDecisions = [];
397
- if (adapter) {
398
- const rows = adapter.prepare('SELECT * FROM decisions ORDER BY seq').all();
399
- allDecisions = rows.map(row => ({
400
- seq: row['seq'],
401
- id: row['id'],
402
- when_context: row['when_context'],
403
- scope: row['scope'],
404
- decision: row['decision'],
405
- choice: row['choice'],
406
- rationale: row['rationale'],
407
- revisable: row['revisable'],
408
- made_by: row['made_by'] ?? 'agent',
409
- superseded_by: row['superseded_by'] ?? null,
410
- }));
460
+ const nextSeq = allDecisions.reduce((max, d) => Math.max(max, d.seq ?? 0), 0) + 1;
461
+ const fallback = {
462
+ seq: nextSeq,
463
+ id,
464
+ when_context: normalized.when_context,
465
+ scope: normalized.scope,
466
+ decision: normalized.decision,
467
+ choice: normalized.choice,
468
+ rationale: normalized.rationale,
469
+ revisable: normalized.revisable,
470
+ made_by: normalized.made_by,
471
+ superseded_by: null,
472
+ };
473
+ allDecisions = [...allDecisions, fallback];
411
474
  }
412
475
  const filePath = resolveGsdRootFile(basePath, 'DECISIONS');
413
476
  // Check if existing DECISIONS.md has freeform (non-table) content.
@@ -460,51 +523,6 @@ export async function saveDecisionToDb(fields, basePath) {
460
523
  invalidateStateCache();
461
524
  clearPathCache();
462
525
  clearParseCache();
463
- // ADR-013 dual-write: keep the memory store in sync with every decision
464
- // persisted via the legacy gsd_save_decision path. Without this, prompts
465
- // that still call gsd_save_decision (discuss.md, plan-milestone.md,
466
- // plan-slice.md, et al.) would create decisions rows invisible to
467
- // memory_query and loadMemoryBlock.
468
- // Best-effort — never throw, never roll back the decision on failure.
469
- try {
470
- const { createMemory } = await import('./memory-store.js');
471
- const decisionText = (fields.decision ?? '').trim();
472
- const choiceText = (fields.choice ?? '').trim();
473
- const rationaleText = (fields.rationale ?? '').trim();
474
- const contentParts = [];
475
- if (decisionText)
476
- contentParts.push(decisionText);
477
- if (choiceText)
478
- contentParts.push(`Chose: ${choiceText}.`);
479
- if (rationaleText)
480
- contentParts.push(`Rationale: ${rationaleText}.`);
481
- const content = contentParts.join(' ').slice(0, 600);
482
- if (content) {
483
- createMemory({
484
- category: 'architecture',
485
- content,
486
- scope: fields.scope || 'project',
487
- confidence: 0.85,
488
- structuredFields: {
489
- sourceDecisionId: id,
490
- when_context: fields.when_context ?? '',
491
- scope: fields.scope,
492
- decision: fields.decision,
493
- choice: fields.choice,
494
- rationale: fields.rationale,
495
- made_by: fields.made_by ?? 'agent',
496
- revisable: fields.revisable ?? '',
497
- },
498
- });
499
- }
500
- }
501
- catch (mirrorErr) {
502
- logError('manifest', 'memory-store mirror write failed (non-fatal)', {
503
- fn: 'saveDecisionToDb',
504
- decisionId: id,
505
- error: String(mirrorErr.message),
506
- });
507
- }
508
526
  return { id };
509
527
  }
510
528
  catch (err) {
@@ -515,6 +533,54 @@ export async function saveDecisionToDb(fields, basePath) {
515
533
  release();
516
534
  }
517
535
  }
536
+ /**
537
+ * ADR-013 dual-write — mirror a freshly-saved decision into the `memories`
538
+ * table so the memory store remains the single source of truth for the
539
+ * DECISIONS.md projection (Stage 2a) and for prompt-inline reads (Stage 1).
540
+ *
541
+ * Best-effort mirror: logs failures without throwing to avoid blocking saves.
542
+ * Caller invokes this AFTER the decisions-table write completes and
543
+ * BEFORE the projection regen — the regen sources from memories and would
544
+ * otherwise miss the just-saved decision.
545
+ */
546
+ async function mirrorDecisionToMemory(id, normalizedFields) {
547
+ try {
548
+ const { createMemory } = await import('./memory-store.js');
549
+ const { synthesizeDecisionMemoryContent } = await import('./memory-backfill.js');
550
+ const content = synthesizeDecisionMemoryContent(normalizedFields);
551
+ if (!content)
552
+ return false;
553
+ createMemory({
554
+ category: 'architecture',
555
+ content,
556
+ scope: normalizedFields.scope || 'project',
557
+ confidence: 0.85,
558
+ structuredFields: {
559
+ sourceDecisionId: id,
560
+ when_context: normalizedFields.when_context,
561
+ scope: normalizedFields.scope,
562
+ decision: normalizedFields.decision,
563
+ choice: normalizedFields.choice,
564
+ rationale: normalizedFields.rationale,
565
+ made_by: normalizedFields.made_by,
566
+ revisable: normalizedFields.revisable,
567
+ // New decisions are always written as active; md-importer can later
568
+ // set superseded_by on the source decision row, and the backfill's
569
+ // drift auto-heal pass propagates that update to this memory.
570
+ superseded_by: null,
571
+ },
572
+ });
573
+ return true;
574
+ }
575
+ catch (mirrorErr) {
576
+ logError('manifest', 'memory-store mirror write failed', {
577
+ fn: 'saveDecisionToDb',
578
+ decisionId: id,
579
+ error: String(mirrorErr.message),
580
+ });
581
+ return false;
582
+ }
583
+ }
518
584
  /**
519
585
  * Extract a milestone/slice reference from a deferral decision.
520
586
  *
@@ -100,7 +100,7 @@ Setting `prefer_skills: []` does **not** disable skill discovery — it just mea
100
100
 
101
101
  - `skill_rules`: situational rules with a human-readable `when` trigger and one or more of `use`, `prefer`, or `avoid`.
102
102
 
103
- - `custom_instructions`: extra durable instructions related to skill use. For operational project knowledge (recurring rules, gotchas, patterns), use `.gsd/KNOWLEDGE.md` instead it's injected into every agent prompt automatically and agents can append to it during execution.
103
+ - `custom_instructions`: extra durable instructions related to skill use. For operational project knowledge, use `.gsd/KNOWLEDGE.md` instead. Rules are file-canonical; patterns and lessons are persisted to the `memories` table and projected back into `KNOWLEDGE.md` on the next session start.
104
104
 
105
105
  - `language`: preferred response language for all GSD interactions. Accepts any language name or code — `"Chinese"`, `"zh"`, `"German"`, `"de"`, `"日本語"`, etc. When set, GSD injects "Always respond in \<language\>" into every agent's system prompt, including after `/clear`. Quickest way to set it: `/gsd language <name>`. To clear: `/gsd language off`.
106
106
 
@@ -1,3 +1,5 @@
1
+ // GSD-2 doctor git health checks
2
+ import { spawnSync } from "node:child_process";
1
3
  import { existsSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
2
4
  import { join, sep } from "node:path";
3
5
  import { loadFile } from "./files.js";
@@ -48,6 +50,23 @@ function isSameOrNestedPath(candidate, container) {
48
50
  return normalizedCandidate === normalizedContainer ||
49
51
  normalizedCandidate.startsWith(`${normalizedContainer}/`);
50
52
  }
53
+ function getSnapshotDiffCheckFailure(basePath) {
54
+ const failures = [];
55
+ for (const args of [["--cached"], []]) {
56
+ const result = spawnSync("git", ["diff", "--check", ...args], {
57
+ cwd: basePath,
58
+ encoding: "utf-8",
59
+ });
60
+ if (result.status === 0)
61
+ continue;
62
+ const output = [result.stdout, result.stderr, result.error?.message]
63
+ .filter(Boolean)
64
+ .join("\n")
65
+ .trim();
66
+ failures.push(output || `git diff --check ${args.join(" ")} failed`);
67
+ }
68
+ return failures.length > 0 ? failures.join("\n") : null;
69
+ }
51
70
  async function isCompletedMilestoneTerminal(basePath, milestoneId) {
52
71
  const summaryPath = resolveMilestoneFile(basePath, milestoneId, "SUMMARY");
53
72
  if (!summaryPath)
@@ -401,16 +420,32 @@ export async function checkGitHealth(basePath, issues, fixesApplied, shouldFix,
401
420
  message: `Uncommitted changes detected with no commit in ${mins} minute${mins === 1 ? "" : "s"} (threshold: ${thresholdMinutes}m). Snapshotting tracked files.`,
402
421
  fixable: true,
403
422
  });
423
+ const diffCheckFailure = getSnapshotDiffCheckFailure(basePath);
424
+ if (diffCheckFailure) {
425
+ issues.push({
426
+ severity: "error",
427
+ code: "conflict_markers_in_tracked_files",
428
+ scope: "project",
429
+ unitId: "project",
430
+ message: `Cannot create gsd snapshot: tracked changes contain conflict markers or whitespace errors. Resolve conflicts manually before auto-mode can proceed.\n${diffCheckFailure}`,
431
+ fixable: false,
432
+ });
433
+ }
404
434
  if (shouldFix("stale_uncommitted_changes")) {
405
435
  try {
406
- nativeAddTracked(basePath);
407
- const commitMsg = `gsd snapshot: uncommitted changes after ${mins}m inactivity`;
408
- const result = nativeCommit(basePath, commitMsg);
409
- if (result) {
410
- fixesApplied.push(`created gsd snapshot after ${mins}m of uncommitted changes`);
436
+ if (diffCheckFailure) {
437
+ fixesApplied.push("gsd snapshot skipped - conflict markers detected in tracked files");
411
438
  }
412
439
  else {
413
- fixesApplied.push("gsd snapshot skipped — nothing to commit after staging tracked files");
440
+ nativeAddTracked(basePath);
441
+ const commitMsg = `gsd snapshot: uncommitted changes after ${mins}m inactivity`;
442
+ const result = nativeCommit(basePath, commitMsg);
443
+ if (result) {
444
+ fixesApplied.push(`created gsd snapshot after ${mins}m of uncommitted changes`);
445
+ }
446
+ else {
447
+ fixesApplied.push("gsd snapshot skipped — nothing to commit after staging tracked files");
448
+ }
414
449
  }
415
450
  }
416
451
  catch {
@@ -0,0 +1,144 @@
1
+ // GSD2 — KNOWLEDGE.md -> memories backfill (ADR-013 Stage 2b).
2
+ //
3
+ // Idempotent migration of `.gsd/KNOWLEDGE.md` Patterns and Lessons rows into
4
+ // the `memories` table. Patterns become memories with `category: "pattern"`;
5
+ // Lessons become memories with `category: "gotcha"` (mirroring the ADR-013
6
+ // line 38 contract). Rules (K###) are NOT migrated — they remain manually
7
+ // maintained in `KNOWLEDGE.md` per ADR-013 line 39.
8
+ //
9
+ // Idempotency is enforced by tagging each backfilled memory with
10
+ // `structured_fields.sourceKnowledgeId = "<P|L>NNN"`. The
11
+ // memory-consolidation-scanner (PR #5765) checks for the same marker.
12
+ //
13
+ // Triggered opportunistically by `buildBeforeAgentStartResult` so the cost
14
+ // only ever fires once per project. Costs O(N) inserts on first run where N
15
+ // is the row count; subsequent runs are an O(N) lookup that finds existing
16
+ // markers and exits.
17
+ import { _getAdapter, isDbAvailable } from "./gsd-db.js";
18
+ import { createMemory } from "./memory-store.js";
19
+ import { parseKnowledgeRows, readKnowledgeMd } from "./knowledge-parser.js";
20
+ import { logWarning } from "./workflow-logger.js";
21
+ /**
22
+ * Backfill KNOWLEDGE.md Patterns + Lessons rows into the memories table.
23
+ *
24
+ * - Idempotent (per-row): each migrated memory carries
25
+ * `structured_fields.sourceKnowledgeId = "<P|L>NNN"`. Rows whose ID is
26
+ * already present in the memory store are skipped.
27
+ * - Best-effort: never throws. Logs and returns 0 on failure so a broken
28
+ * backfill cannot block agent startup.
29
+ * - Rules (K###) are intentionally skipped — they remain manually maintained
30
+ * in `KNOWLEDGE.md` per ADR-013.
31
+ *
32
+ * Returns the number of memories written (0 when there's nothing to migrate
33
+ * or when the file is absent).
34
+ */
35
+ export function backfillKnowledgeToMemories(basePath) {
36
+ if (!isDbAvailable())
37
+ return 0;
38
+ const adapter = _getAdapter();
39
+ if (!adapter)
40
+ return 0;
41
+ try {
42
+ const content = readKnowledgeMd(basePath);
43
+ if (!content.trim())
44
+ return 0;
45
+ const rows = parseKnowledgeRows(content);
46
+ if (rows.length === 0)
47
+ return 0;
48
+ const checkExisting = adapter.prepare("SELECT 1 FROM memories WHERE structured_fields LIKE :pattern LIMIT 1");
49
+ let written = 0;
50
+ for (const row of rows) {
51
+ const synth = synthesize(row);
52
+ if (!synth)
53
+ continue;
54
+ // Pattern is anchored on both sides of the value to avoid prefix
55
+ // collisions (e.g. P1 vs P10).
56
+ const matchPattern = `%"sourceKnowledgeId":"${synth.id}"%`;
57
+ if (checkExisting.get({ ":pattern": matchPattern }))
58
+ continue;
59
+ const id = createMemory({
60
+ category: synth.category,
61
+ content: synth.content,
62
+ scope: synth.scope,
63
+ confidence: 0.85,
64
+ structuredFields: synth.structuredFields,
65
+ });
66
+ if (id)
67
+ written += 1;
68
+ }
69
+ return written;
70
+ }
71
+ catch (e) {
72
+ logWarning("memory-backfill", `KNOWLEDGE.md -> memories backfill failed: ${e.message}`);
73
+ return 0;
74
+ }
75
+ }
76
+ /**
77
+ * Convert a parsed KNOWLEDGE.md row into the memory payload we insert.
78
+ * Returns `null` for Rules (K###) which are not migrated, or for rows whose
79
+ * primary content cell is empty (defensive against malformed manual edits).
80
+ */
81
+ function synthesize(row) {
82
+ if (row.table === "rules")
83
+ return null;
84
+ if (row.table === "patterns") {
85
+ // Cells: [P###, Pattern, Where, Notes]
86
+ const [, pattern, where, notes] = row.cells;
87
+ const cleaned = (pattern ?? "").trim();
88
+ if (!cleaned)
89
+ return null;
90
+ const contentParts = [cleaned];
91
+ if (where && where.trim() && where.trim() !== "—") {
92
+ contentParts.push(`Where: ${where.trim()}.`);
93
+ }
94
+ if (notes && notes.trim() && notes.trim() !== "—") {
95
+ contentParts.push(`Notes: ${notes.trim()}.`);
96
+ }
97
+ return {
98
+ table: "patterns",
99
+ id: row.id,
100
+ category: "pattern",
101
+ content: trim(contentParts.join(" "), 600),
102
+ scope: (where ?? "").trim() || "project",
103
+ structuredFields: {
104
+ sourceKnowledgeId: row.id,
105
+ sourceKnowledgeTable: "patterns",
106
+ pattern: cleaned,
107
+ where: (where ?? "").trim(),
108
+ notes: (notes ?? "").trim(),
109
+ },
110
+ };
111
+ }
112
+ // table === "lessons"
113
+ // Cells: [L###, What Happened, Root Cause, Fix, Scope]
114
+ const [, whatHappened, rootCause, fix, scope] = row.cells;
115
+ const cleanedWhat = (whatHappened ?? "").trim();
116
+ if (!cleanedWhat)
117
+ return null;
118
+ const contentParts = [cleanedWhat];
119
+ if (rootCause && rootCause.trim() && rootCause.trim() !== "—") {
120
+ contentParts.push(`Root cause: ${rootCause.trim()}.`);
121
+ }
122
+ if (fix && fix.trim() && fix.trim() !== "—") {
123
+ contentParts.push(`Fix: ${fix.trim()}.`);
124
+ }
125
+ return {
126
+ table: "lessons",
127
+ id: row.id,
128
+ category: "gotcha",
129
+ content: trim(contentParts.join(" "), 600),
130
+ scope: (scope ?? "").trim() || "project",
131
+ structuredFields: {
132
+ sourceKnowledgeId: row.id,
133
+ sourceKnowledgeTable: "lessons",
134
+ whatHappened: cleanedWhat,
135
+ rootCause: (rootCause ?? "").trim(),
136
+ fix: (fix ?? "").trim(),
137
+ scopeText: (scope ?? "").trim(),
138
+ },
139
+ };
140
+ }
141
+ function trim(value, max) {
142
+ const cleaned = value.replace(/\s+/g, " ").trim();
143
+ return cleaned.length > max ? cleaned.slice(0, max - 1) + "…" : cleaned;
144
+ }
@@ -0,0 +1,136 @@
1
+ // GSD2 — KNOWLEDGE.md write-side cutover (ADR-013 Stage 2c).
2
+ //
3
+ // Replaces the legacy `appendKnowledge` file-append path for Patterns and
4
+ // Lessons with `createMemory` calls. Rules (K###) continue to flow through
5
+ // the legacy file-append because they are intentionally not migrated to
6
+ // memories per ADR-013 line 39.
7
+ //
8
+ // Next-ID assignment is the cross-surface stable rule: read the existing
9
+ // `.gsd/KNOWLEDGE.md` for the highest <prefix>### in that section, AND read
10
+ // the memories table for the highest `sourceKnowledgeId` with the matching
11
+ // prefix, take the max, and increment. This stays stable across the
12
+ // knowledge backfill mid-run (when some rows exist only in the file and
13
+ // others only in memories) and on a fresh project where neither has any
14
+ // entries yet.
15
+ import { _getAdapter, isDbAvailable } from "./gsd-db.js";
16
+ import { createMemory } from "./memory-store.js";
17
+ import { parseKnowledgeRows, readKnowledgeMd } from "./knowledge-parser.js";
18
+ import { logWarning } from "./workflow-logger.js";
19
+ /**
20
+ * Append a new Pattern or Lesson by writing it as a memory row carrying a
21
+ * `sourceKnowledgeId` marker. The next session's KNOWLEDGE.md projection
22
+ * render (`knowledge-projection.ts`) picks it up and emits the row into the
23
+ * appropriate section.
24
+ *
25
+ * `entryText` is treated as the row's primary description cell (Pattern for
26
+ * patterns, "What Happened" for lessons). Auxiliary cells (Where/Notes for
27
+ * patterns; Root Cause/Fix/Scope for lessons) are left empty — the projection
28
+ * renders `—` for empty cells. Users who need richer structure can call
29
+ * `capture_thought` directly with a fuller `structuredFields` payload.
30
+ */
31
+ export function captureKnowledgeEntry(basePath, type, entryText, scope) {
32
+ const cleaned = entryText.trim();
33
+ const idPrefix = type === "pattern" ? "P" : "L";
34
+ const id = nextKnowledgeId(basePath, idPrefix);
35
+ if (!cleaned) {
36
+ return { id, written: false };
37
+ }
38
+ if (!isDbAvailable()) {
39
+ logWarning("knowledge-capture", "DB unavailable; cannot persist knowledge entry");
40
+ return { id, written: false };
41
+ }
42
+ try {
43
+ const category = type === "pattern" ? "pattern" : "gotcha";
44
+ const structuredFields = type === "pattern"
45
+ ? {
46
+ sourceKnowledgeId: id,
47
+ sourceKnowledgeTable: "patterns",
48
+ pattern: cleaned,
49
+ where: "",
50
+ notes: "",
51
+ }
52
+ : {
53
+ sourceKnowledgeId: id,
54
+ sourceKnowledgeTable: "lessons",
55
+ whatHappened: cleaned,
56
+ rootCause: "",
57
+ fix: "",
58
+ scopeText: scope,
59
+ };
60
+ const memoryId = createMemory({
61
+ category,
62
+ content: cleaned,
63
+ scope: scope || "project",
64
+ confidence: 0.85,
65
+ structuredFields,
66
+ });
67
+ return { id, written: !!memoryId };
68
+ }
69
+ catch (e) {
70
+ logWarning("knowledge-capture", `failed to persist ${type} entry as memory: ${e.message}`);
71
+ return { id, written: false };
72
+ }
73
+ }
74
+ /**
75
+ * Compute the next <prefix>### identifier across both the legacy
76
+ * `.gsd/KNOWLEDGE.md` and the `memories.structured_fields.sourceKnowledgeId`
77
+ * surface. Takes the max numeric suffix from either side and increments.
78
+ *
79
+ * Padded to three digits to match the existing `appendKnowledge` convention.
80
+ * Exported for tests; production callers go through `captureKnowledgeEntry`.
81
+ */
82
+ export function nextKnowledgeId(basePath, prefix) {
83
+ const fromFile = maxIdInFile(basePath, prefix);
84
+ const fromMemories = maxIdInMemories(prefix);
85
+ const next = Math.max(fromFile, fromMemories) + 1;
86
+ return `${prefix}${String(next).padStart(3, "0")}`;
87
+ }
88
+ function maxIdInFile(basePath, prefix) {
89
+ const content = readKnowledgeMd(basePath);
90
+ if (!content.trim())
91
+ return 0;
92
+ const expectedTable = prefix === "K" ? "rules" : prefix === "P" ? "patterns" : "lessons";
93
+ let max = 0;
94
+ for (const row of parseKnowledgeRows(content)) {
95
+ if (row.table !== expectedTable)
96
+ continue;
97
+ const num = parseInt(row.id.slice(1), 10);
98
+ if (Number.isFinite(num) && num > max)
99
+ max = num;
100
+ }
101
+ return max;
102
+ }
103
+ function maxIdInMemories(prefix) {
104
+ if (!isDbAvailable())
105
+ return 0;
106
+ const adapter = _getAdapter();
107
+ if (!adapter)
108
+ return 0;
109
+ try {
110
+ const rows = adapter
111
+ .prepare("SELECT structured_fields FROM memories WHERE structured_fields LIKE :pattern")
112
+ .all({ ":pattern": `%"sourceKnowledgeId":"${prefix}%` });
113
+ let max = 0;
114
+ for (const row of rows) {
115
+ if (!row.structured_fields)
116
+ continue;
117
+ let sf;
118
+ try {
119
+ sf = JSON.parse(row.structured_fields);
120
+ }
121
+ catch {
122
+ continue;
123
+ }
124
+ const sourceId = sf["sourceKnowledgeId"];
125
+ if (typeof sourceId !== "string" || !sourceId.startsWith(prefix))
126
+ continue;
127
+ const num = parseInt(sourceId.slice(1), 10);
128
+ if (Number.isFinite(num) && num > max)
129
+ max = num;
130
+ }
131
+ return max;
132
+ }
133
+ catch {
134
+ return 0;
135
+ }
136
+ }