Files
opencode-working-memory/src/extractors.ts
T
Ralph Chang a154139b27 fix: P0c/P0d architect review corrections
P0c fixes:
- Chinese file count regex now accepts 個/个 between number and 文件
- Admin PIN short reference (<20 chars) passes via config value allowlist
- Phase snapshot uses semantic window (.{0,20}) instead of absolute position

P0d fixes:
- Feedback key split: 500 error and port issue remain separate entries
- extractEntityKey avoids over-merging unrelated plugin configs
- chooseBetterMemory supports supersession mode (newer beats longer)
- Sort comparator now includes source priority as secondary tie-breaker

New regression tests (11 total):
- Real Admin PIN short reference passes
- Real Chinese 37 個文件 snapshot rejected
- Real pathology Phase 1-4 snapshot rejected
- Feedback 500 vs port entries not collapsed
- Unrelated plugin configs not collapsed
- Supersession prefers newer shorter over older longer

67/67 tests pass.
2026-04-26 16:50:58 +08:00

299 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createHash } from "crypto";
import type { ActiveFile, LongTermMemoryEntry, LongTermType, OpenError } from "./types.ts";
import { LONG_TERM_LIMITS } from "./types.ts";
function id(prefix: string): string {
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}
function hash(value: string): string {
return createHash("sha1").update(value).digest("hex").slice(0, 12);
}
/**
* Check if a memory request is negated (e.g., "不要記住", "don't remember").
* Uses structured adjacency detection to avoid false positives.
*/
function isNegatedMemoryRequest(text: string, matchIndex: number): boolean {
const prefix = text.slice(Math.max(0, matchIndex - 30), matchIndex);
// Chinese negative: 不要/別/不用 + optional 幫我, must be adjacent to trigger
if (/(?:|||||)\s*(?:|)?\s*$/u.test(prefix)) {
return true;
}
// English negative: do not / don't / never / not + optional please, must be adjacent to trigger
if (/(?:do\s+not|don't|dont|never|not)\s+(?:please\s+)?$/i.test(prefix)) {
return true;
}
return false;
}
export function extractExplicitMemories(text: string): LongTermMemoryEntry[] {
// 注意:所有pattern必須有 g flag,因為使用 matchAll()
// Pattern 必須在行首匹配,避免匹配到句子中間的非指令式用法
const patterns = [
// 中文:請/幫我 + 記住 + 可選後綴
/(?:^|\n)\s*(?:请|請)?(?:帮我|幫我)?(?:记住|記住)(?:这一点|這一點|这点|這點|这个|這個)?[:,]?\s*(.+)$/gim,
// 英文:remember this/that - 必須在行首,避免 "to remember" 非指令匹配
/(?:^|\n)\s*(?:please\s+)?remember\s+(?:this|that)?[:,]?\s*(.+)$/gim,
// save/add to memory
/(?:^|\n)\s*(?:please\s+)?(?:save|add)\s+(?:this|that)?\s*(?:to|in)\s+memory[:,]?\s*(.+)$/gim,
// commit to memory
/(?:^|\n)\s*(?:please\s+)?commit\s+(?:this|that)?\s*to memory[:,]?\s*(.+)$/gim,
// going forward / from now on
/(?:从现在开始|從現在開始|从今以后|從今以後|from now on|going forward)[:,]?\s*(.+)$/gim,
// 偏好
/(?:我的偏好是|我偏好|以后请|以後請|以后都|以後都)[:,]?\s*(.+)$/gim,
/(?:^|\n)\s*(?:my preference is|i prefer)[:,]?\s*(.+)$/gim,
];
const now = new Date().toISOString();
const entries: LongTermMemoryEntry[] = [];
const seen = new Set<string>();
for (const pattern of patterns) {
for (const match of text.matchAll(pattern)) {
const body = match[1]?.trim();
if (!body || body.length < 8) continue;
// Calculate actual trigger position (after possible newline)
const triggerIndex = match.index! + (match[0].match(/^[\s\n]*/)?.[0]?.length || 0);
// Check if this is a negated request (e.g., "不要記住")
if (isNegatedMemoryRequest(text, triggerIndex)) continue;
// Check if it's a deferral (e.g., "later", "next time")
if (/^(再说|再說|later|next time)$/i.test(body)) continue;
// Dedupe by canonical body
const key = body.toLowerCase().replace(/\s+/g, " ").trim();
if (seen.has(key)) continue;
seen.add(key);
const type = classifyExplicitMemory(body);
entries.push({
id: id("mem"),
type,
text: body.slice(0, LONG_TERM_LIMITS.maxEntryTextChars),
source: "explicit",
confidence: 1,
status: "active",
createdAt: now,
updatedAt: now,
staleAfterDays: staleAfterDaysFor(type),
});
}
}
return entries;
}
function classifyExplicitMemory(text: string): LongTermType {
const lower = text.toLowerCase();
if (/https?:\/\/|linear|slack|notion|dashboard|grafana/.test(lower)) return "reference";
if (/decide|decision|choose|chosen|决定|決定|选择|選擇/.test(lower)) return "decision";
if (/project|repo|项目|專案/.test(lower)) return "project";
return "feedback";
}
export function staleAfterDaysFor(type: LongTermType): number | undefined {
if (type === "feedback") return undefined;
if (type === "decision") return 45;
if (type === "project") return 60;
return 90;
}
export function extractActiveFiles(
toolName: string,
args: Record<string, unknown>,
output: string,
): Array<{ path: string; action: ActiveFile["action"] }> {
if (toolName === "read" && typeof args.filePath === "string") return [{ path: args.filePath, action: "read" }];
if (toolName === "edit" && typeof args.filePath === "string") return [{ path: args.filePath, action: "edit" }];
if (toolName === "write" && typeof args.filePath === "string") return [{ path: args.filePath, action: "write" }];
if (toolName === "grep") return extractGrepPaths(output).map(path => ({ path, action: "grep" as const }));
return [];
}
function extractGrepPaths(output: string): string[] {
const matches = output.match(/^(\/[^\n]+\.(ts|tsx|js|jsx|json|md|py|go|rs|toml|yml|yaml)):/gm) ?? [];
return [...new Set(matches.map(match => match.replace(/:$/, "")))].slice(0, 10);
}
function isErrorLine(line: string, knownValidationCommand: boolean): boolean {
// 無條件捕捉的強訊號
if (/TS\d{4}|ERR!|Traceback \(most recent call last\):|panic:/i.test(line)) return true;
// Error 類型前綴(獨立行)
if (/^\s*(Error|TypeError|ReferenceError|SyntaxError|Exception):/i.test(line)) {
return true;
}
// 已知 validation command 才用寬鬆匹配
if (knownValidationCommand) {
return /\b(error|failed|failure|exception)\b/i.test(line);
}
return false;
}
export function extractErrorsFromBash(command: string, output: string): OpenError[] {
const classifiedCategory = classifyCommand(command);
const knownValidationCommand = classifiedCategory !== null;
const lines = output
.split("\n")
.filter(line => isErrorLine(line, knownValidationCommand))
.slice(0, 5);
if (lines.length === 0) return [];
const category = classifiedCategory ?? "runtime";
const summary = lines.join(" ").slice(0, 280);
const fingerprint = hash(`${category}:${summary.toLowerCase().replace(/\s+/g, " ")}`);
const now = Date.now();
return [
{
id: `err_${fingerprint}`,
category,
summary,
command,
file: extractFirstPath(summary),
fingerprint,
status: "open",
firstSeen: now,
lastSeen: now,
seenCount: 1,
},
];
}
export function classifyCommand(command: string): OpenError["category"] | null {
const c = command.toLowerCase();
if (/\b(tsc|typecheck)\b/.test(c)) return "typecheck";
if (/\b(test|vitest|jest|mocha|pytest|go test|cargo test)\b/.test(c)) return "test";
if (/\b(lint|eslint|biome)\b/.test(c)) return "lint";
if (/\b(build|vite build|webpack|tsup)\b/.test(c)) return "build";
return null;
}
function extractFirstPath(text: string): string | undefined {
return text.match(/[\w./-]+\.(ts|tsx|js|jsx|json|md|py|go|rs)/)?.[0];
}
/**
* Quality gate for workspace memory candidates.
* Rejects low-quality entries like git hashes, error messages, etc.
*/
function shouldAcceptWorkspaceMemoryCandidate(entry: {
type: LongTermType;
text: string;
}): boolean {
const text = entry.text.trim();
// Too short (with type-specific allowlist for stable config values)
if (entry.type === "reference" && /\b(?:admin\s+)?pin\s|scrypt|n=\d+|r=\d+|p=\d+/i.test(text)) {
// Stable config values can be short — allow below generic min length
} else if (text.length < 20) {
return false;
}
// Git history / commit hash
if (/\b[0-9a-f]{7,40}\b/.test(text)) return false;
if (/^(fix|feat|chore|docs|refactor|test):/i.test(text)) return false;
// Raw error / stack trace
if (/^\s*(Error|TypeError|ReferenceError|SyntaxError):/i.test(text)) return false;
if (/at \S+ \([^)]+:\d+:\d+\)/.test(text)) return false;
// Active file list
if (/^(modified|created|deleted|renamed)\s+\S+\.\S+$/i.test(text)) return false;
// Temporary progress
if (/^(currently|now|pending|in progress|todo|wip):/i.test(text)) return false;
// Code signature / API doc
if (/^(function|class|interface|type|const|let|var)\s+\w+/.test(text)) return false;
if (/^(GET|POST|PUT|DELETE|PATCH)\s+\//.test(text)) return false;
// Path-heavy facts (rediscoverable from repo)
const pathCount = (text.match(/\/[\w.-]+(\/[\w.-]+)+/g) || []).length;
if (pathCount > 2) return false;
// Session-specific progress snapshots for project type
if (entry.type === "project") {
if (/\b\d+\s+tests?\s+pass(?:ed)?\b/i.test(text)) return false;
if (/\b\d+\s+suites?\b/i.test(text)) return false;
if (/\b\d+\s*(?:個|个)?\s*(?:files?|文件)/i.test(text)) return false;
// Reject "Phase N completed" using semantic window (within 20 chars either direction)
if (/\bphase\s*\d+(?:\s*[-]\s*\d+)?\b.{0,20}\b(?:completed|done|finished)\b/i.test(text)) return false;
if (/\b(?:completed|done|finished)\b.{0,20}\bphase\s*\d+(?:\s*[-]\s*\d+)?\b/i.test(text)) return false;
if (/已完成.{0,20}Phase\s*\d+(?:\s*[-]\s*\d+)?/i.test(text)) return false;
if (/Phase\s*\d+(?:\s*[-]\s*\d+)?.{0,20}已完成/i.test(text)) return false;
}
return true;
}
/**
* Extract candidate block from summary using multiple formats.
* Supports: Plain text label, Markdown section, legacy XML.
*/
function extractCandidateBlock(summary: string): string | null {
// 1. Plain text label (primary format, no Markdown header)
const plainMatch = summary.match(/Memory candidates:\s*\n([\s\S]*?)(?:\n[A-Z][a-z]+ [a-z]+:|\n##\s|$)/i);
if (plainMatch) return plainMatch[1];
// 2. Markdown section (legacy)
const markdownMatch = summary.match(/##\s*Memory Candidates\s*\n([\s\S]*?)(?:\n##\s|$)/i);
if (markdownMatch) return markdownMatch[1];
// 3. Legacy "Workspace Memory Candidates" section
const legacyMatch = summary.match(/##\s*Workspace Memory Candidates\s*\n([\s\S]*?)(?:\n##\s|$)/i);
if (legacyMatch) return legacyMatch[1];
// 4. Legacy XML block (backward compatible)
const xmlMatch = summary.match(/<workspace_memory_candidates>([\s\S]*?)<\/workspace_memory_candidates>/i);
if (xmlMatch) return xmlMatch[1];
return null;
}
export function parseWorkspaceMemoryCandidates(summary: string): LongTermMemoryEntry[] {
const block = extractCandidateBlock(summary);
if (!block) return [];
const now = new Date().toISOString();
const entries: LongTermMemoryEntry[] = [];
for (const line of block.split("\n")) {
// Accept both "- [type] text" (bracketed) and "- type text" (bracketless)
const item = line.trim().match(
/^-\s*(?:\[(feedback|project|decision|reference)\]|(feedback|project|decision|reference)\b)\s+(.+)$/i,
);
if (!item) continue;
const type = (item[1] ?? item[2]).toLowerCase() as LongTermType;
const body = item[3].trim();
if (body.length < 12) continue;
// Apply quality gate
if (!shouldAcceptWorkspaceMemoryCandidate({ type, text: body })) continue;
entries.push({
id: id("mem"),
type,
text: body.slice(0, LONG_TERM_LIMITS.maxEntryTextChars),
source: "compaction",
confidence: 0.75,
status: "active",
createdAt: now,
updatedAt: now,
staleAfterDays: staleAfterDaysFor(type),
});
}
return entries;
}