@sanqianx/project-knowledge 5.0.31 → 5.0.33

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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +5 -2
  4. package/_site/_test/automatic-context-test.js +19 -0
  5. package/_site/_test/context-session-index-test.js +244 -0
  6. package/_site/_test/fixtures/retrieval-gold-queries.json +4 -0
  7. package/_site/_test/helpers/parallel-capture-safety-r5-cap-shell.js +1 -1
  8. package/_site/_test/helpers/parallel-capture-safety-r5-memory-shell.js +1 -1
  9. package/_site/_test/helpers/parallel-engine-advanced-engine-child.js +1 -1
  10. package/_site/_test/helpers/parallel-engine-advanced-fault-writer.js +3 -3
  11. package/_site/_test/helpers/parallel-engine-advanced-harness.js +1 -1
  12. package/_site/_test/helpers/parallel-engine-advanced-standin-analyzer.js +1 -1
  13. package/_site/_test/helpers/parallel-engine-final-harness.js +2 -2
  14. package/_site/_test/helpers/parallel-engine-final-standin-analyzer.js +1 -1
  15. package/_site/_test/helpers/parallel-engine-reconcile-r4-harness.js +1 -1
  16. package/_site/_test/helpers/parallel-engine-reconcile-r4-standin-analyzer.js +1 -1
  17. package/_site/_test/helpers/parallel-memory-analyzer.js +1 -1
  18. package/_site/_test/helpers/parallel-memory-capture-r4-cap-shell.js +1 -1
  19. package/_site/_test/helpers/parallel-memory-injection-shell.js +1 -1
  20. package/_site/_test/helpers/parallel-nav-shell.js +1 -1
  21. package/_site/_test/helpers/parallel-qa-engine-endpoint-guard.js +1 -1
  22. package/_site/_test/helpers/parallel-retrieval-followup-r2-shell.js +1 -1
  23. package/_site/_test/helpers/qa-r91-harness.cjs +4 -1
  24. package/_site/_test/package-boundary-test.js +5 -0
  25. package/_site/_test/parallel-capture-safety-r5-cap008e-probe.js +1 -1
  26. package/_site/_test/parallel-engine-advanced-eng011-ui-probe.js +1 -1
  27. package/_site/_test/parallel-knowledge-engine-test.js +3 -3
  28. package/_site/_test/parallel-knowledge-retrieval-test.js +2 -2
  29. package/_site/_test/parallel-memory-capture-r4-cap008e-probe.js +1 -1
  30. package/_site/_test/parallel-memory-injection-origin-probe.js +1 -1
  31. package/_site/_test/parallel-nav-isolation-test.js +1 -1
  32. package/_site/_test/parallel-qa-engine-endpoint-guard-test.js +1 -1
  33. package/_site/_test/parallel-retrieval-followup-citation-test.js +2 -2
  34. package/_site/_test/parallel-retrieval-followup-corpus-test.js +1 -1
  35. package/_site/_test/qa-r45-offline-backfill-test.js +2 -2
  36. package/_site/_test/t07d-git-rel-coverage-test.js +5 -3
  37. package/_site/_test/t07f-mem-008-coverage-test.js +1 -1
  38. package/_site/lib/module-bridge.js +2 -11
  39. package/_site/scripts/ab-rank-v2-v3.js +142 -0
  40. package/_site/scripts/install-module-candidates.js +1 -1
  41. package/_site/scripts/pack-module-candidates.js +2 -1
  42. package/_site/scripts/run-retrieval-gold-isolated.js +221 -0
  43. package/_site/scripts/verify-module-runtime.js +17 -32
  44. package/_site/scripts/verify-product-runtime.js +7 -3
  45. package/_site/scripts/verify-retrieval-gold.js +57 -10
  46. package/docs/README.zh-CN.md +3 -1
  47. package/module-runtime-manifest.json +54 -4
  48. package/package.json +2 -4
  49. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  50. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  51. package/plugins/project-knowledge/.mcp.json +1 -1
  52. package/plugins/project-knowledge/scripts/context-hook.cjs +9 -5
  53. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +39 -28
  54. package/_modules/knowledge-engine/README.md +0 -133
  55. package/_modules/knowledge-engine/package.json +0 -38
  56. package/_modules/knowledge-engine/src/analysis-contract.js +0 -35
  57. package/_modules/knowledge-engine/src/analysis-failures.js +0 -39
  58. package/_modules/knowledge-engine/src/analysis-output.js +0 -52
  59. package/_modules/knowledge-engine/src/analysis-worker.js +0 -58
  60. package/_modules/knowledge-engine/src/bin.js +0 -52
  61. package/_modules/knowledge-engine/src/bridge-client.js +0 -24
  62. package/_modules/knowledge-engine/src/context.js +0 -140
  63. package/_modules/knowledge-engine/src/coordinator.js +0 -376
  64. package/_modules/knowledge-engine/src/diagnostics.js +0 -37
  65. package/_modules/knowledge-engine/src/headless-analyzer.js +0 -66
  66. package/_modules/knowledge-engine/src/index-request.js +0 -49
  67. package/_modules/knowledge-engine/src/knowledge-targets.js +0 -46
  68. package/_modules/knowledge-engine/src/memories.js +0 -281
  69. package/_modules/knowledge-engine/src/memory-eligibility.js +0 -74
  70. package/_modules/knowledge-engine/src/retrieval-policy.json +0 -14
  71. package/_modules/knowledge-engine/src/retrieval-ranking.js +0 -153
  72. package/_modules/knowledge-engine/src/retrieval.js +0 -367
  73. package/_modules/knowledge-engine/src/runtime/README.md +0 -7
  74. package/_modules/knowledge-engine/src/runtime/atomic-file.js +0 -204
  75. package/_modules/knowledge-engine/src/runtime/automation-config.js +0 -140
  76. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +0 -250
  77. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +0 -26
  78. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +0 -205
  79. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +0 -432
  80. package/_modules/knowledge-engine/src/runtime/content-hash.js +0 -4
  81. package/_modules/knowledge-engine/src/runtime/contracts.js +0 -282
  82. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +0 -204
  83. package/_modules/knowledge-engine/src/runtime/conversation-store.js +0 -389
  84. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +0 -228
  85. package/_modules/knowledge-engine/src/runtime/git-runner.js +0 -62
  86. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +0 -559
  87. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +0 -408
  88. package/_modules/knowledge-engine/src/runtime/layout.js +0 -46
  89. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +0 -276
  90. package/_modules/knowledge-engine/src/runtime/scanner.js +0 -298
  91. package/_modules/knowledge-engine/src/server.js +0 -166
  92. package/_modules/knowledge-engine/src/store.js +0 -267
  93. package/_modules/knowledge-engine/ui/app.css +0 -172
  94. package/_modules/knowledge-engine/ui/app.js +0 -318
  95. package/_modules/knowledge-engine/ui/index.html +0 -95
  96. package/_site/scripts/vendor-modules.js +0 -49
  97. package/vendor-manifest.json +0 -55
@@ -1,140 +0,0 @@
1
- const path = require('path');
2
-
3
- const PERMISSION_MODES = new Set(['plan', 'default', 'acceptEdits', 'auto', 'bypassPermissions']);
4
- const PROMPT_TEMPLATE_VERSION = 2;
5
-
6
- const DEFAULT_COMMIT_PROMPT_TEMPLATE = `你正在根据一个 Git Commit 的冻结证据维护项目知识库。
7
-
8
- 用户需求:
9
- {{userRequirement}}
10
-
11
- Commit 信息:
12
- {{commitMetadata}}
13
-
14
- Commit 实际变更文件:
15
- {{actualChanges}}
16
-
17
- Commit 实际 Patch:
18
- {{actualPatch}}
19
-
20
- 现有相关知识:
21
- {{existingKnowledge}}
22
-
23
- 请完成以下判断,并只输出符合 staging manifest 合同的知识变更:
24
- 1. 比较用户需求与实际实现是否一致;没有可靠需求时不得猜测业务目的。
25
- 2. 只记录 Commit、Patch 和现有知识能够证明的事实。
26
- 3. 明确需要新增、更新或删除哪些知识;删除必须有实际变更证据。
27
- 4. 不得修改源码、最终知识目录、其他项目或派生索引。
28
- 5. Patch 使用 chunk evidence 时,必须从只读 manifest 按序读取所需 chunk;不得从源码工作树补读或猜测。`;
29
-
30
- const READ_TOOLS = ['Read'];
31
- const WRITE_TOOLS = ['Edit', 'Write', 'MultiEdit'];
32
-
33
- function normalizePermissionMode(value) {
34
- return PERMISSION_MODES.has(value) ? value : 'default';
35
- }
36
-
37
- function normalizeAutomationConfig(input) {
38
- const source = input && typeof input === 'object' ? input : {};
39
- const explicit = typeof source.commitPromptTemplate === 'string' && source.commitPromptTemplate.trim();
40
- const legacy = typeof source.hookPromptTemplate === 'string' && source.hookPromptTemplate.trim();
41
- return {
42
- enabled: source.enabled !== false,
43
- commitPromptTemplate: explicit || legacy || DEFAULT_COMMIT_PROMPT_TEMPLATE,
44
- promptTemplateVersion: PROMPT_TEMPLATE_VERSION,
45
- legacyPromptOverride: !explicit && Boolean(legacy),
46
- };
47
- }
48
-
49
- function normalizeClaudeWorkbenchConfig(input) {
50
- const source = input && typeof input === 'object' ? input : {};
51
- return { permissionMode: normalizePermissionMode(source.permissionMode) };
52
- }
53
-
54
- function renderTemplate(template, vars) {
55
- const source = typeof template === 'string' && template.trim() ? template : DEFAULT_COMMIT_PROMPT_TEMPLATE;
56
- const safeVars = vars && typeof vars === 'object' ? vars : {};
57
- return source.replace(/\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g, (match, name) => {
58
- if (!Object.prototype.hasOwnProperty.call(safeVars, name)) return match;
59
- const value = safeVars[name];
60
- return value == null ? '' : String(value);
61
- });
62
- }
63
-
64
- function normalizePathForCompare(value) {
65
- if (!value || typeof value !== 'string') return '';
66
- const normalized = path.resolve(value).replace(/[\\/]+$/, '');
67
- return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
68
- }
69
-
70
- function pathsReferToSameLocation(leftValue, rightValue) {
71
- const left = normalizePathForCompare(leftValue);
72
- const right = normalizePathForCompare(rightValue);
73
- return Boolean(left && right && left === right);
74
- }
75
-
76
- function isInsidePath(root, target) {
77
- if (!root || !target) return false;
78
- const rootAbs = path.resolve(root);
79
- const targetAbs = path.resolve(rootAbs, target);
80
- const relative = path.relative(rootAbs, targetAbs);
81
- return relative === '' || Boolean(relative && !relative.startsWith('..') && !path.isAbsolute(relative));
82
- }
83
-
84
- function extractToolPaths(toolName, input) {
85
- if (!input || typeof input !== 'object') return [];
86
- const candidates = [];
87
- for (const key of ['file_path', 'path', 'notebook_path']) {
88
- if (typeof input[key] === 'string') candidates.push(input[key]);
89
- }
90
- if (toolName === 'MultiEdit' && typeof input.file_path === 'string') candidates.push(input.file_path);
91
- return [...new Set(candidates)];
92
- }
93
-
94
- function buildAutomationToolPolicy(options = {}) {
95
- const stagingPath = options.stagingPath || options.kbPath || '';
96
- const evidenceRoot = options.evidenceRoot || '';
97
- return {
98
- kind: 'knowledge-staging',
99
- stagingPath,
100
- evidenceRoot,
101
- readRoots: [evidenceRoot, stagingPath].filter(Boolean),
102
- writeRoot: stagingPath,
103
- allowedTools: [...READ_TOOLS, ...WRITE_TOOLS],
104
- canWriteKb: false,
105
- canWriteStaging: true,
106
- allowReadOnlyBash: false,
107
- };
108
- }
109
-
110
- function evaluateAutomationToolUse(policy, toolName, input) {
111
- if (!policy || policy.kind !== 'knowledge-staging') return { behavior: 'ask', reason: 'no staging policy' };
112
- if (!policy.allowedTools.includes(toolName)) return { behavior: 'deny', reason: `tool is not allowed: ${toolName}` };
113
- const paths = extractToolPaths(toolName, input);
114
- if (!paths.length) return { behavior: 'deny', reason: `${toolName} has no explicit file path` };
115
- for (const filePath of paths) {
116
- if (toolName === 'Read') {
117
- if (!(policy.readRoots || []).some(root => isInsidePath(root, filePath))) {
118
- return { behavior: 'deny', reason: `path outside read-only evidence/output roots: ${filePath}` };
119
- }
120
- } else if (!isInsidePath(policy.writeRoot || policy.stagingPath, filePath)) {
121
- return { behavior: 'deny', reason: `path outside writable run output: ${filePath}` };
122
- }
123
- }
124
- return { behavior: 'allow', reason: toolName === 'Read' ? 'path is inside an isolated read root' : 'path is inside the isolated writable output root' };
125
- }
126
-
127
- module.exports = {
128
- PERMISSION_MODES,
129
- PROMPT_TEMPLATE_VERSION,
130
- DEFAULT_COMMIT_PROMPT_TEMPLATE,
131
- normalizePermissionMode,
132
- normalizeAutomationConfig,
133
- normalizeClaudeWorkbenchConfig,
134
- renderTemplate,
135
- normalizePathForCompare,
136
- pathsReferToSameLocation,
137
- isInsidePath,
138
- buildAutomationToolPolicy,
139
- evaluateAutomationToolUse,
140
- };
@@ -1,250 +0,0 @@
1
- const fs = require('fs');
2
- const { DomainError, validateProjectId } = require('./contracts');
3
- const { ConversationStore, sha256 } = require('./conversation-store');
4
- const { readDevelopmentEvents } = require('./conversation-exclusions');
5
-
6
- function projectEvent(event) {
7
- return {
8
- eventId: event.eventId,
9
- sequence: event.sequence,
10
- content: event.content,
11
- contentHash: event.contentHash,
12
- inputOrigin: event.inputOrigin || 'unknown',
13
- capturedAt: event.capturedAt,
14
- };
15
- }
16
-
17
- class CommitConversationBinder {
18
- constructor(options = {}) {
19
- this.layout = options.layout;
20
- this.projectStore = options.projectStore;
21
- this.conversationStore = options.conversationStore || new ConversationStore({
22
- layout: this.layout,
23
- projectStore: this.projectStore,
24
- logger: options.logger,
25
- });
26
- this.logger = options.logger || null;
27
- }
28
-
29
- async log(level, event, message, context) {
30
- if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
31
- }
32
-
33
- repoMatches(left, right) {
34
- if (!left || !right) return false;
35
- // workspaceId is the canonical primary key (I-06). commonDir/repoId are
36
- // read-compat fallbacks for records stored before repo-identity/v1.
37
- if (left.workspaceId && right.workspaceId) return String(left.workspaceId) === String(right.workspaceId);
38
- if (left.commonDir && right.commonDir) return this.layout.pathsEqual(left.commonDir, right.commonDir);
39
- if (left.repoId && right.repoId) return String(left.repoId) === String(right.repoId);
40
- return false;
41
- }
42
-
43
- boundaryOrder(boundary) {
44
- return Number.isInteger(boundary.journalSequence) ? boundary.journalSequence : boundary.bridgeCursorAtCommit;
45
- }
46
-
47
- previousBoundary(projectId, boundary) {
48
- const order = this.boundaryOrder(boundary);
49
- return this.conversationStore.listBoundaries(projectId)
50
- .filter(candidate => candidate.commitSha !== boundary.commitSha
51
- && (candidate.journalId || 'global') === (boundary.journalId || 'global')
52
- && this.repoMatches(candidate.repoIdentity, boundary.repoIdentity)
53
- && this.boundaryOrder(candidate) < order)
54
- .sort((left, right) => this.boundaryOrder(right) - this.boundaryOrder(left))[0] || null;
55
- }
56
-
57
- snapshotExists(projectId, commitSha) {
58
- return fs.existsSync(this.layout.getProjectCommitConversationPath(projectId, commitSha));
59
- }
60
-
61
- async bind(input = {}) {
62
- const projectId = validateProjectId(input.projectId);
63
- const commitSha = this.layout.validateCommitSha(input.commitSha);
64
- if (this.snapshotExists(projectId, commitSha)) return this.conversationStore.readSnapshot(projectId, commitSha);
65
-
66
- if (this.projectStore) await this.conversationStore.importLegacyRequirements(projectId);
67
- // Development Conversation reads are centralized: exclusions and Codex
68
- // turn repair are identical here and in the query service.
69
- let events = readDevelopmentEvents(this.conversationStore, projectId);
70
- let boundary = null;
71
- try { boundary = this.conversationStore.readBoundary(projectId, commitSha); }
72
- catch (error) {
73
- if (!error || error.code !== 'ENOENT') throw error;
74
- }
75
-
76
- if (boundary) events = events.filter(event => (event.journalId || 'global') === (boundary.journalId || 'global'));
77
- const explicitEvents = events.filter(event => event.role === 'user' && event.explicitCommitSha === commitSha);
78
- if (!boundary) {
79
- const turns = this.buildExplicitTurns(explicitEvents);
80
- return this.finalize(projectId, commitSha, {
81
- repoIdentity: null,
82
- parentSha: null,
83
- boundaryStartCursor: null,
84
- boundaryEndCursor: null,
85
- status: turns.length ? 'available' : 'unavailable',
86
- turns,
87
- excludedFuturePromptCount: 0,
88
- }, { reason: 'missing-commit-boundary' });
89
- }
90
-
91
- const previous = this.previousBoundary(projectId, boundary);
92
- const state = this.projectStore ? this.projectStore.readState(projectId) : { conversationBaselineCursor: null };
93
- const journalId = boundary.journalId || 'global';
94
- const baseline = state.conversationBaselineCursors?.[journalId] ?? (journalId === 'global' ? state.conversationBaselineCursor : 0);
95
- const startCursor = previous ? previous.bridgeCursorAtCommit : baseline;
96
- const endCursor = boundary.bridgeCursorAtCommit;
97
- const selected = new Map();
98
- let ambiguousCount = 0;
99
- let excludedFuturePromptCount = 0;
100
-
101
- for (const event of explicitEvents) {
102
- if (event.repoIdentity && boundary.repoIdentity && !this.repoMatches(event.repoIdentity, boundary.repoIdentity)) {
103
- ambiguousCount += 1;
104
- continue;
105
- }
106
- if (!event.turnId) { ambiguousCount += 1; continue; }
107
- selected.set(event.turnId, 'explicit');
108
- }
109
-
110
- if (Number.isInteger(startCursor)) {
111
- for (const event of events) {
112
- if (event.role !== 'user' || event.sequence == null || event.explicitCommitSha) continue;
113
- if (!this.repoMatches(event.repoIdentity, boundary.repoIdentity)) {
114
- if (event.sequence > startCursor && event.sequence <= endCursor && !event.repoIdentity) ambiguousCount += 1;
115
- continue;
116
- }
117
- if (event.sequence > endCursor) {
118
- excludedFuturePromptCount += 1;
119
- continue;
120
- }
121
- if (event.sequence <= startCursor) continue;
122
- // Automatic direct evidence requires exact identity. Legacy stored
123
- // 'high'/'trusted' translate to exact for old known data only;
124
- // 'explicit' is the explicit-fallback tier (I-18: no synthetic).
125
- const rawConfidence = String(event.identityConfidence || '');
126
- const effectiveConfidence = rawConfidence === 'high' || rawConfidence === 'trusted' ? 'exact' : rawConfidence;
127
- if (!event.turnId || !['exact', 'explicit'].includes(effectiveConfidence)) {
128
- ambiguousCount += 1;
129
- continue;
130
- }
131
- selected.set(event.turnId, 'direct');
132
- }
133
-
134
- for (const turnId of boundary.openTurnIdsAtCommit) {
135
- if (selected.has(turnId)) continue;
136
- const user = events.find(event => event.role === 'user'
137
- && event.turnId === turnId
138
- && event.sequence != null
139
- && event.sequence <= startCursor
140
- && this.repoMatches(event.repoIdentity, boundary.repoIdentity));
141
- const closedAt = user && user.developmentTurnClosedAtSequence;
142
- if (user && !(Number.isInteger(closedAt) && closedAt <= startCursor)) {
143
- selected.set(turnId, 'shared-spanning');
144
- }
145
- }
146
- }
147
-
148
- const turns = [];
149
- for (const [turnId, bindingKind] of selected) {
150
- const turnEvents = events.filter(event => event.turnId === turnId).sort((left, right) => {
151
- if (left.sequence == null) return 1;
152
- if (right.sequence == null) return -1;
153
- return left.sequence - right.sequence;
154
- });
155
- const userEvents = turnEvents.filter(event => event.role === 'user'
156
- && (bindingKind === 'explicit' || (event.sequence != null && event.sequence <= endCursor)));
157
- if (!userEvents.length) continue;
158
- const first = userEvents[0];
159
- // I-13: no event beyond the commit boundary may enter a frozen
160
- // snapshot — including assistant replies that arrived after the
161
- // boundary but before a delayed binder run.
162
- const assistantEvents = turnEvents.filter(event => event.role === 'assistant'
163
- && (bindingKind === 'explicit' || (event.sequence != null && event.sequence <= endCursor)));
164
- turns.push({
165
- turnId,
166
- source: first.source,
167
- sessionId: first.sessionId,
168
- bindingKind,
169
- userEvents: userEvents.map(projectEvent),
170
- assistantEvents: assistantEvents.map(projectEvent),
171
- });
172
- }
173
- turns.sort((left, right) => {
174
- const a = left.userEvents[0].sequence;
175
- const b = right.userEvents[0].sequence;
176
- if (a == null) return 1;
177
- if (b == null) return -1;
178
- return a - b;
179
- });
180
-
181
- let status = turns.length ? 'available' : 'no-new-user-prompt';
182
- let reason = turns.length ? 'sequence-window' : 'no-new-user-prompt';
183
- if (!Number.isInteger(startCursor)) {
184
- status = explicitEvents.length && turns.length ? 'available' : 'unavailable';
185
- reason = 'conversation-baseline-unavailable';
186
- } else if (ambiguousCount > 0 && !turns.length) {
187
- status = 'ambiguous';
188
- reason = 'turn-or-repo-identity-ambiguous';
189
- }
190
-
191
- return this.finalize(projectId, commitSha, {
192
- repoIdentity: boundary.repoIdentity,
193
- parentSha: boundary.parentShas[0] || null,
194
- boundaryStartCursor: startCursor,
195
- boundaryEndCursor: endCursor,
196
- status,
197
- turns,
198
- excludedFuturePromptCount,
199
- }, { reason, ambiguousCount, previousBoundaryCommit: previous && previous.commitSha || null });
200
- }
201
-
202
- buildExplicitTurns(events) {
203
- return events.filter(event => event.turnId).map(event => ({
204
- turnId: event.turnId,
205
- source: event.source,
206
- sessionId: event.sessionId,
207
- bindingKind: 'explicit',
208
- userEvents: [projectEvent(event)],
209
- assistantEvents: [],
210
- }));
211
- }
212
-
213
- async finalize(projectId, commitSha, snapshotInput, decision) {
214
- const snapshot = this.conversationStore.writeSnapshot(projectId, {
215
- commitSha,
216
- ...snapshotInput,
217
- finalizedAt: new Date().toISOString(),
218
- });
219
- await this.log(snapshot.status === 'ambiguous' || snapshot.status === 'unavailable' ? 'warn' : 'info', 'conversation.commit_snapshot_frozen', 'Commit conversation snapshot was frozen.', {
220
- projectId,
221
- commitSha,
222
- component: 'commit-conversation-binder',
223
- phase: 'snapshot-frozen',
224
- context: {
225
- snapshotHash: snapshot.snapshotHash,
226
- status: snapshot.status,
227
- turnCount: snapshot.turns.length,
228
- userEventCount: snapshot.turns.reduce((total, turn) => total + turn.userEvents.length, 0),
229
- assistantEventCount: snapshot.turns.reduce((total, turn) => total + turn.assistantEvents.length, 0),
230
- decision,
231
- },
232
- });
233
- return snapshot;
234
- }
235
- }
236
-
237
- function snapshotRequirementRecords(snapshot) {
238
- return snapshot.turns.flatMap(turn => turn.userEvents.map(event => ({
239
- id: event.eventId,
240
- client: turn.source,
241
- sessionId: turn.sessionId,
242
- ts: event.capturedAt,
243
- requirement: event.content,
244
- requirementHash: event.contentHash,
245
- turnId: turn.turnId,
246
- bindingKind: turn.bindingKind,
247
- })));
248
- }
249
-
250
- module.exports = { CommitConversationBinder, snapshotRequirementRecords, projectEvent, sha256 };
@@ -1,26 +0,0 @@
1
- const fs = require('fs');
2
- const { DomainError, validateProjectId } = require('./contracts');
3
- const { validateSha } = require('./scanner');
4
- const AtomicFile = require('./atomic-file');
5
-
6
- class CommitProcessingLedger {
7
- constructor(options = {}) { this.layout = options.layout; this.atomic = options.atomic || AtomicFile; }
8
- filePath(projectId, commitSha) { return this.layout.getRuntimePath('processed-commits', validateProjectId(projectId), `${validateSha(commitSha)}.json`); }
9
- read(projectId, commitSha) {
10
- const file = this.filePath(projectId, commitSha);
11
- if (!fs.existsSync(file)) return null;
12
- return this.atomic.readJsonStrict(file, { category: 'commit-processing-record', validate: value => {
13
- if (!value || value.schema !== 'commit-processing-record/v1' || value.projectId !== projectId || value.commitSha !== commitSha || value.status !== 'completed') {
14
- throw new DomainError('DATA_CORRUPT', 'Commit processing ledger record is corrupt.', { status: 500 });
15
- }
16
- return value;
17
- } });
18
- }
19
- complete(projectId, commitSha, fields = {}) {
20
- const record = { schema: 'commit-processing-record/v1', projectId: validateProjectId(projectId), commitSha: validateSha(commitSha), status: 'completed', ...fields, completedAt: new Date().toISOString() };
21
- this.atomic.writeJsonAtomic(this.filePath(projectId, commitSha), record);
22
- return record;
23
- }
24
- }
25
-
26
- module.exports = { CommitProcessingLedger };
@@ -1,205 +0,0 @@
1
- const crypto = require('crypto');
2
- const fs = require('fs');
3
- const path = require('path');
4
- const {
5
- DEFAULT_COMMIT_PROMPT_TEMPLATE,
6
- PROMPT_TEMPLATE_VERSION,
7
- normalizeAutomationConfig,
8
- renderTemplate,
9
- } = require('./automation-config');
10
-
11
- const REQUIREMENT_UNAVAILABLE = '需求上下文未记录。只能记录代码可以证明的变化,不得猜测业务目的。';
12
- const REQUIRED_SECTIONS = Object.freeze([
13
- ['userRequirement', '用户需求'],
14
- ['aiConversationEvidence', 'AI 对话证据'],
15
- ['commitMetadata', 'Commit 信息'],
16
- ['actualChanges', 'Commit 实际变更文件'],
17
- ['actualPatch', 'Commit 实际 Patch'],
18
- ['existingKnowledge', '现有相关知识'],
19
- ]);
20
-
21
- function sha256(value) {
22
- return `sha256:${crypto.createHash('sha256').update(value, 'utf8').digest('hex')}`;
23
- }
24
-
25
- function formatRequirements(records) {
26
- if (!Array.isArray(records) || records.length === 0) return REQUIREMENT_UNAVAILABLE;
27
- return records.map(record => [
28
- `- requirementId: ${record.id}`,
29
- ` client/session: ${record.client}/${record.sessionId}`,
30
- ` recordedAt: ${record.ts}`,
31
- ' requirement: |',
32
- ...String(record.requirement || '').split(/\r?\n/).map(line => ` ${line}`),
33
- ].join('\n')).join('\n');
34
- }
35
-
36
- function formatConversationUserTruth(snapshot) {
37
- if (!snapshot || !Array.isArray(snapshot.turns) || snapshot.turns.length === 0) return REQUIREMENT_UNAVAILABLE;
38
- const rendered = snapshot.turns.flatMap(turn => turn.userEvents.map(event => [
39
- `- turnId: ${turn.turnId}`,
40
- ` eventId: ${event.eventId}`,
41
- ` inputOrigin: ${event.inputOrigin || 'unknown'}`,
42
- ` contentHash: ${event.contentHash}`,
43
- ` source/session: ${turn.source}/${turn.sessionId || '(unavailable)'}`,
44
- ` binding: ${turn.bindingKind}`,
45
- ` capturedAt: ${event.capturedAt}`,
46
- ' userPrompt: |',
47
- ...String(event.content || '').split(/\r?\n/).map(line => ` ${line}`),
48
- ].join('\n'))).join('\n');
49
- return `inputOrigin marks who typed each frozen user event: only "human" is the owner speaking; "agent-delegation" is a delegated task order from another agent; "unknown" cannot be verified. Memory candidates may rely on "human" events only.\n${rendered}`;
50
- }
51
-
52
- function formatAssistantEvidence(snapshot) {
53
- if (!snapshot || !Array.isArray(snapshot.turns)) return '(no assistant conversation evidence was frozen)';
54
- const entries = snapshot.turns.flatMap(turn => turn.assistantEvents.map(event => [
55
- `- turnId: ${turn.turnId}`,
56
- ` eventId: ${event.eventId}`,
57
- ` capturedAt: ${event.capturedAt}`,
58
- ' assistantResponse: |',
59
- ...String(event.content || '').split(/\r?\n/).map(line => ` ${line}`),
60
- ].join('\n')));
61
- return entries.length ? entries.join('\n') : '(no assistant conversation evidence was frozen)';
62
- }
63
-
64
- function formatCommitMetadata(evidence) {
65
- return [
66
- `fullSha: ${evidence.commitSha}`,
67
- `parents: ${(evidence.parents || []).join(', ') || '(root commit)'}`,
68
- `author: ${evidence.author || ''}`,
69
- `date: ${evidence.date || ''}`,
70
- `subject: ${evidence.subject || ''}`,
71
- `branchAtScan: ${evidence.branch || '(detached/unavailable)'}`,
72
- `patchMode: ${evidence.patchMode}`,
73
- `patchHash: ${evidence.patchHash}`,
74
- `patchBytes: ${evidence.patchBytes}`,
75
- ].join('\n');
76
- }
77
-
78
- function formatChanges(evidence) {
79
- if (!evidence.files || evidence.files.length === 0) return '(no changed paths reported by Git)';
80
- return evidence.files.map(file => {
81
- const rename = file.oldPath ? ` ${file.oldPath} -> ${file.path}` : ` ${file.path}`;
82
- const stats = file.binary ? ' binary' : ` +${file.added == null ? '?' : file.added}/-${file.deleted == null ? '?' : file.deleted}`;
83
- return `- ${file.status}${rename}${stats}`;
84
- }).join('\n');
85
- }
86
-
87
- function formatPatch(evidence) {
88
- if (!evidence.patchChunked) return evidence.patch || '(empty patch)';
89
- const bundle = evidence.evidenceBundle || {};
90
- return [
91
- '[EXACT PATCH AVAILABLE AS READ-ONLY CHUNKS]',
92
- `fullPatchHash: ${evidence.patchHash}`,
93
- `fullPatchBytes: ${evidence.patchBytes}`,
94
- `patchManifestHash: ${bundle.manifestHash || '(unavailable)'}`,
95
- `patchManifestPath: ${bundle.manifestPath || '(unavailable)'}`,
96
- `chunkCount: ${bundle.chunkCount == null ? '(unavailable)' : bundle.chunkCount}`,
97
- 'Read patch-manifest.json, then Read exact patch chunks in manifest sequence. The chunks cover the full Git diff.',
98
- 'Do not read the source worktree and do not infer unread evidence.',
99
- ].join('\n');
100
- }
101
-
102
- function formatExistingKnowledge(existing) {
103
- if (!existing || !Array.isArray(existing.entries) || existing.entries.length === 0) {
104
- return '(no existing project knowledge was available)';
105
- }
106
- const sections = existing.entries.map(entry => `--- ${entry.path} (${entry.hash}) ---\n${entry.content}`);
107
- if (existing.omitted && existing.omitted.length) {
108
- sections.push(`[EXISTING KNOWLEDGE OMITTED: ${existing.omitted.join(', ')}]`);
109
- }
110
- return sections.join('\n\n');
111
- }
112
-
113
- function ensureRequiredSections(template, rendered, vars) {
114
- const missing = REQUIRED_SECTIONS.filter(([name]) => !new RegExp(`\\{\\{\\s*${name}\\s*\\}\\}`, 'i').test(template));
115
- if (!missing.length) return rendered;
116
- const footer = missing.map(([name, label]) => `${label}:\n${vars[name]}`).join('\n\n');
117
- return `${rendered.trimEnd()}\n\n${footer}`;
118
- }
119
-
120
- function renderCommitPrompt(input = {}) {
121
- const config = input.config || {};
122
- const evidence = input.evidence || {};
123
- const automation = normalizeAutomationConfig(config.automation);
124
- const template = automation.commitPromptTemplate || DEFAULT_COMMIT_PROMPT_TEMPLATE;
125
- const vars = {
126
- userRequirement: input.conversationSnapshot
127
- ? formatConversationUserTruth(input.conversationSnapshot)
128
- : formatRequirements(input.requirements),
129
- aiConversationEvidence: formatAssistantEvidence(input.conversationSnapshot),
130
- commitMetadata: formatCommitMetadata(evidence),
131
- actualChanges: formatChanges(evidence),
132
- actualPatch: formatPatch(evidence),
133
- existingKnowledge: formatExistingKnowledge(input.existingKnowledge),
134
- projectId: config.projectId || input.projectId || '',
135
- displayName: config.displayName || config.projectId || '',
136
- knowledgePath: config.knowledgePath || '',
137
- repoPath: config.repoPath || '',
138
- commitHash: evidence.commitSha || '',
139
- commitSubject: evidence.subject || '',
140
- commitAuthor: evidence.author || '',
141
- commitDate: evidence.date || '',
142
- branch: evidence.branch || '',
143
- changedFiles: formatChanges(evidence),
144
- diffSummary: formatPatch(evidence),
145
- };
146
- const rendered = ensureRequiredSections(template, renderTemplate(template, vars), vars).trimEnd() + '\n';
147
- return {
148
- prompt: rendered,
149
- promptHash: sha256(rendered),
150
- promptTemplateVersion: PROMPT_TEMPLATE_VERSION,
151
- promptLength: rendered.length,
152
- vars,
153
- };
154
- }
155
-
156
- class KnowledgeEvidenceReader {
157
- constructor(options = {}) {
158
- this.maxBytes = Number(options.maxBytes || 256 * 1024);
159
- this.maxFiles = Number(options.maxFiles || 24);
160
- }
161
-
162
- read(config) {
163
- const root = config && config.knowledgePath ? path.resolve(config.knowledgePath) : '';
164
- if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) return { entries: [], omitted: [] };
165
- const realRoot = fs.realpathSync(root);
166
- const files = [];
167
- const walk = current => {
168
- for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
169
- if (entry.isSymbolicLink()) continue;
170
- const absolute = path.join(current, entry.name);
171
- if (entry.isDirectory()) walk(absolute);
172
- else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) files.push(absolute);
173
- }
174
- };
175
- walk(root);
176
- let used = 0;
177
- const entries = [];
178
- const omitted = [];
179
- for (const file of files) {
180
- const realFile = fs.realpathSync(file);
181
- const relativeBoundary = path.relative(realRoot, realFile);
182
- if (relativeBoundary.startsWith('..') || path.isAbsolute(relativeBoundary)) continue;
183
- const relativePath = path.relative(root, file).replace(/\\/g, '/');
184
- const content = fs.readFileSync(file, 'utf8');
185
- const bytes = Buffer.byteLength(content, 'utf8');
186
- if (entries.length >= this.maxFiles || used + bytes > this.maxBytes) {
187
- omitted.push(relativePath);
188
- continue;
189
- }
190
- used += bytes;
191
- entries.push({ path: relativePath, hash: sha256(content), content });
192
- }
193
- return { entries, omitted, totalBytes: used, limitBytes: this.maxBytes, limitFiles: this.maxFiles };
194
- }
195
- }
196
-
197
- module.exports = {
198
- REQUIREMENT_UNAVAILABLE,
199
- KnowledgeEvidenceReader,
200
- formatRequirements,
201
- formatConversationUserTruth,
202
- formatAssistantEvidence,
203
- renderCommitPrompt,
204
- sha256,
205
- };