@winspan/claude-forge 8.28.2 → 8.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -215
- package/dist/capability/execution-manager.d.ts +96 -0
- package/dist/capability/execution-manager.d.ts.map +1 -0
- package/dist/capability/execution-manager.js +260 -0
- package/dist/capability/execution-manager.js.map +1 -0
- package/dist/capability/executor/background-executor.d.ts +58 -0
- package/dist/capability/executor/background-executor.d.ts.map +1 -0
- package/dist/capability/executor/background-executor.js +322 -0
- package/dist/capability/executor/background-executor.js.map +1 -0
- package/dist/capability/executor/foreground-executor.d.ts +26 -0
- package/dist/capability/executor/foreground-executor.d.ts.map +1 -0
- package/dist/capability/executor/foreground-executor.js +82 -0
- package/dist/capability/executor/foreground-executor.js.map +1 -0
- package/dist/capability/executor/orchestrator.d.ts +38 -0
- package/dist/capability/executor/orchestrator.d.ts.map +1 -0
- package/dist/capability/executor/orchestrator.js +158 -0
- package/dist/capability/executor/orchestrator.js.map +1 -0
- package/dist/capability/executor/stream-parser.d.ts +73 -0
- package/dist/capability/executor/stream-parser.d.ts.map +1 -0
- package/dist/capability/executor/stream-parser.js +56 -0
- package/dist/capability/executor/stream-parser.js.map +1 -0
- package/dist/capability/executor/types.d.ts +44 -0
- package/dist/capability/executor/types.d.ts.map +1 -0
- package/dist/capability/executor/types.js +9 -0
- package/dist/capability/executor/types.js.map +1 -0
- package/dist/capability/executor/worker-auth-probe.d.ts +30 -0
- package/dist/capability/executor/worker-auth-probe.d.ts.map +1 -0
- package/dist/capability/executor/worker-auth-probe.js +108 -0
- package/dist/capability/executor/worker-auth-probe.js.map +1 -0
- package/dist/capability/methodologies/bmad.yaml +17 -5
- package/dist/capability/methodologies/code-quality-audit.yaml +26 -0
- package/dist/capability/methodologies/harness-engineering.yaml +12 -6
- package/dist/capability/methodologies/test-coverage-scan.yaml +26 -0
- package/dist/capability/methodology-planner.d.ts +17 -1
- package/dist/capability/methodology-planner.d.ts.map +1 -1
- package/dist/capability/methodology-planner.js +125 -0
- package/dist/capability/methodology-planner.js.map +1 -1
- package/dist/capability/methodology-registry.d.ts.map +1 -1
- package/dist/capability/methodology-registry.js +21 -5
- package/dist/capability/methodology-registry.js.map +1 -1
- package/dist/capability/types.d.ts +12 -1
- package/dist/capability/types.d.ts.map +1 -1
- package/dist/core/ai/provider.d.ts +17 -9
- package/dist/core/ai/provider.d.ts.map +1 -1
- package/dist/core/ai/provider.js +130 -23
- package/dist/core/ai/provider.js.map +1 -1
- package/dist/core/ai/types.d.ts +26 -5
- package/dist/core/ai/types.d.ts.map +1 -1
- package/dist/core/storage/rows.d.ts +153 -0
- package/dist/core/storage/rows.d.ts.map +1 -0
- package/dist/core/storage/rows.js +14 -0
- package/dist/core/storage/rows.js.map +1 -0
- package/dist/core/storage/schema.sql +26 -2
- package/dist/core/storage/sqlite.d.ts +112 -6
- package/dist/core/storage/sqlite.d.ts.map +1 -1
- package/dist/core/storage/sqlite.js +480 -22
- package/dist/core/storage/sqlite.js.map +1 -1
- package/dist/core/utils/token-tracker.d.ts +40 -0
- package/dist/core/utils/token-tracker.d.ts.map +1 -0
- package/dist/core/utils/token-tracker.js +70 -0
- package/dist/core/utils/token-tracker.js.map +1 -0
- package/dist/daemon/handlers/methodology-formatter.d.ts +7 -0
- package/dist/daemon/handlers/methodology-formatter.d.ts.map +1 -1
- package/dist/daemon/handlers/methodology-formatter.js +46 -0
- package/dist/daemon/handlers/methodology-formatter.js.map +1 -1
- package/dist/daemon/handlers/post-tool-use.d.ts +1 -0
- package/dist/daemon/handlers/post-tool-use.d.ts.map +1 -1
- package/dist/daemon/handlers/post-tool-use.js +7 -0
- package/dist/daemon/handlers/post-tool-use.js.map +1 -1
- package/dist/daemon/handlers/stop.d.ts +17 -1
- package/dist/daemon/handlers/stop.d.ts.map +1 -1
- package/dist/daemon/handlers/stop.js +97 -1
- package/dist/daemon/handlers/stop.js.map +1 -1
- package/dist/daemon/handlers/user-prompt.d.ts.map +1 -1
- package/dist/daemon/handlers/user-prompt.js +97 -5
- package/dist/daemon/handlers/user-prompt.js.map +1 -1
- package/dist/daemon/idle-detector.d.ts +35 -0
- package/dist/daemon/idle-detector.d.ts.map +1 -0
- package/dist/daemon/idle-detector.js +56 -0
- package/dist/daemon/idle-detector.js.map +1 -0
- package/dist/daemon/idle-trigger.d.ts +53 -0
- package/dist/daemon/idle-trigger.d.ts.map +1 -0
- package/dist/daemon/idle-trigger.js +153 -0
- package/dist/daemon/idle-trigger.js.map +1 -0
- package/dist/daemon/index.d.ts.map +1 -1
- package/dist/daemon/index.js +49 -2
- package/dist/daemon/index.js.map +1 -1
- package/dist/daemon/methodology-pending-queue.d.ts +33 -0
- package/dist/daemon/methodology-pending-queue.d.ts.map +1 -0
- package/dist/daemon/methodology-pending-queue.js +120 -0
- package/dist/daemon/methodology-pending-queue.js.map +1 -0
- package/dist/daemon/routing-observer.d.ts +2 -1
- package/dist/daemon/routing-observer.d.ts.map +1 -1
- package/dist/daemon/routing-observer.js +117 -39
- package/dist/daemon/routing-observer.js.map +1 -1
- package/dist/engine/agent-router.d.ts +6 -0
- package/dist/engine/agent-router.d.ts.map +1 -1
- package/dist/engine/agent-router.js +13 -1
- package/dist/engine/agent-router.js.map +1 -1
- package/dist/engine/conventions/routing.yaml +15 -0
- package/dist/engine/dsl/compiler.d.ts.map +1 -1
- package/dist/engine/dsl/compiler.js +85 -3
- package/dist/engine/dsl/compiler.js.map +1 -1
- package/dist/engine/recommender.d.ts.map +1 -1
- package/dist/engine/recommender.js +10 -1
- package/dist/engine/recommender.js.map +1 -1
- package/dist/intelligence/classifier.d.ts +6 -0
- package/dist/intelligence/classifier.d.ts.map +1 -1
- package/dist/intelligence/classifier.js +57 -0
- package/dist/intelligence/classifier.js.map +1 -1
- package/dist/skills/registry.d.ts +6 -0
- package/dist/skills/registry.d.ts.map +1 -1
- package/dist/skills/registry.js +49 -14
- package/dist/skills/registry.js.map +1 -1
- package/dist/skills/semantic-matcher.d.ts +1 -0
- package/dist/skills/semantic-matcher.d.ts.map +1 -1
- package/dist/skills/semantic-matcher.js +6 -1
- package/dist/skills/semantic-matcher.js.map +1 -1
- package/dist/web/auth-middleware.d.ts +22 -0
- package/dist/web/auth-middleware.d.ts.map +1 -0
- package/dist/web/auth-middleware.js +51 -0
- package/dist/web/auth-middleware.js.map +1 -0
- package/dist/web/routes/agents.d.ts +7 -0
- package/dist/web/routes/agents.d.ts.map +1 -0
- package/dist/web/routes/agents.js +192 -0
- package/dist/web/routes/agents.js.map +1 -0
- package/dist/web/routes/ai.d.ts +10 -0
- package/dist/web/routes/ai.d.ts.map +1 -0
- package/dist/web/routes/ai.js +197 -0
- package/dist/web/routes/ai.js.map +1 -0
- package/dist/web/routes/auth.d.ts +12 -0
- package/dist/web/routes/auth.d.ts.map +1 -0
- package/dist/web/routes/auth.js +20 -0
- package/dist/web/routes/auth.js.map +1 -0
- package/dist/web/routes/events.d.ts +11 -0
- package/dist/web/routes/events.d.ts.map +1 -0
- package/dist/web/routes/events.js +43 -0
- package/dist/web/routes/events.js.map +1 -0
- package/dist/web/routes/execution-trace.d.ts +13 -0
- package/dist/web/routes/execution-trace.d.ts.map +1 -0
- package/dist/web/routes/execution-trace.js +308 -0
- package/dist/web/routes/execution-trace.js.map +1 -0
- package/dist/web/routes/experiments.d.ts +15 -0
- package/dist/web/routes/experiments.d.ts.map +1 -0
- package/dist/web/routes/experiments.js +187 -0
- package/dist/web/routes/experiments.js.map +1 -0
- package/dist/web/routes/methodology.d.ts +12 -0
- package/dist/web/routes/methodology.d.ts.map +1 -0
- package/dist/web/routes/methodology.js +228 -0
- package/dist/web/routes/methodology.js.map +1 -0
- package/dist/web/routes/patch.d.ts +7 -0
- package/dist/web/routes/patch.d.ts.map +1 -0
- package/dist/web/routes/patch.js +106 -0
- package/dist/web/routes/patch.js.map +1 -0
- package/dist/web/routes/routing.d.ts +17 -0
- package/dist/web/routes/routing.d.ts.map +1 -0
- package/dist/web/routes/routing.js +582 -0
- package/dist/web/routes/routing.js.map +1 -0
- package/dist/web/routes/rules.d.ts +7 -0
- package/dist/web/routes/rules.d.ts.map +1 -0
- package/dist/web/routes/rules.js +105 -0
- package/dist/web/routes/rules.js.map +1 -0
- package/dist/web/routes/sessions.d.ts +10 -0
- package/dist/web/routes/sessions.d.ts.map +1 -0
- package/dist/web/routes/sessions.js +234 -0
- package/dist/web/routes/sessions.js.map +1 -0
- package/dist/web/routes/skills.d.ts +10 -0
- package/dist/web/routes/skills.d.ts.map +1 -0
- package/dist/web/routes/skills.js +272 -0
- package/dist/web/routes/skills.js.map +1 -0
- package/dist/web/routes/static.d.ts +19 -0
- package/dist/web/routes/static.d.ts.map +1 -0
- package/dist/web/routes/static.js +61 -0
- package/dist/web/routes/static.js.map +1 -0
- package/dist/web/routes/status.d.ts +7 -0
- package/dist/web/routes/status.d.ts.map +1 -0
- package/dist/web/routes/status.js +28 -0
- package/dist/web/routes/status.js.map +1 -0
- package/dist/web/routes/token-usage.d.ts +7 -0
- package/dist/web/routes/token-usage.d.ts.map +1 -0
- package/dist/web/routes/token-usage.js +33 -0
- package/dist/web/routes/token-usage.js.map +1 -0
- package/dist/web/routes/types.d.ts +40 -0
- package/dist/web/routes/types.d.ts.map +1 -0
- package/dist/web/routes/types.js +52 -0
- package/dist/web/routes/types.js.map +1 -0
- package/dist/web/server.d.ts +13 -4
- package/dist/web/server.d.ts.map +1 -1
- package/dist/web/server.js +60 -2210
- package/dist/web/server.js.map +1 -1
- package/dist/web/ssrf-guard.d.ts +35 -0
- package/dist/web/ssrf-guard.d.ts.map +1 -0
- package/dist/web/ssrf-guard.js +93 -0
- package/dist/web/ssrf-guard.js.map +1 -0
- package/dist/web/static/assets/AIConfig-D-vrYoJ3.js +2 -0
- package/dist/web/static/assets/AIConfig-D-vrYoJ3.js.map +1 -0
- package/dist/web/static/assets/Agents-DAGWYsJj.js +2 -0
- package/dist/web/static/assets/Agents-DAGWYsJj.js.map +1 -0
- package/dist/web/static/assets/CodeBlock--H53gk46.js +2 -0
- package/dist/web/static/assets/CodeBlock--H53gk46.js.map +1 -0
- package/dist/web/static/assets/Dashboard-qUCxXFSI.js +2 -0
- package/dist/web/static/assets/Dashboard-qUCxXFSI.js.map +1 -0
- package/dist/web/static/assets/Drawer-DeKukfwJ.js +2 -0
- package/dist/web/static/assets/Drawer-DeKukfwJ.js.map +1 -0
- package/dist/web/static/assets/Events-BoQ8Fo5k.js +2 -0
- package/dist/web/static/assets/Events-BoQ8Fo5k.js.map +1 -0
- package/dist/web/static/assets/ExecutionTrace-sFZ_vHNf.js +2 -0
- package/dist/web/static/assets/ExecutionTrace-sFZ_vHNf.js.map +1 -0
- package/dist/web/static/assets/MarkdownRenderer-CCIz1MOz.js +2 -0
- package/dist/web/static/assets/MarkdownRenderer-CCIz1MOz.js.map +1 -0
- package/dist/web/static/assets/Methodologies-C0-Keokj.js +5 -0
- package/dist/web/static/assets/Methodologies-C0-Keokj.js.map +1 -0
- package/dist/web/static/assets/MethodologyDetail-Do1taSKM.js +2 -0
- package/dist/web/static/assets/MethodologyDetail-Do1taSKM.js.map +1 -0
- package/dist/web/static/assets/Routing-CFmM7JuB.js +2 -0
- package/dist/web/static/assets/Routing-CFmM7JuB.js.map +1 -0
- package/dist/web/static/assets/SessionDetail-DzTue2xK.js +2 -0
- package/dist/web/static/assets/SessionDetail-DzTue2xK.js.map +1 -0
- package/dist/web/static/assets/Sessions-Bjf-Mvwb.js +2 -0
- package/dist/web/static/assets/Sessions-Bjf-Mvwb.js.map +1 -0
- package/dist/web/static/assets/Skills-CrLshkrJ.js +2 -0
- package/dist/web/static/assets/Skills-CrLshkrJ.js.map +1 -0
- package/dist/web/static/assets/charts-CLrM0_uM.js +37 -0
- package/dist/web/static/assets/charts-CLrM0_uM.js.map +1 -0
- package/dist/web/static/assets/date-fns-CZ_bHujz.js +2 -0
- package/dist/web/static/assets/date-fns-CZ_bHujz.js.map +1 -0
- package/dist/web/static/assets/export-CEzDNM66.js +4 -0
- package/dist/web/static/assets/export-CEzDNM66.js.map +1 -0
- package/dist/web/static/assets/index-D23sAOAt.js +3 -0
- package/dist/web/static/assets/index-D23sAOAt.js.map +1 -0
- package/dist/web/static/assets/index-Drpf7sLl.css +1 -0
- package/dist/web/static/assets/lucide-DjB4fWNj.js +227 -0
- package/dist/web/static/assets/lucide-DjB4fWNj.js.map +1 -0
- package/dist/web/static/assets/query-C99w429o.js +2 -0
- package/dist/web/static/assets/query-C99w429o.js.map +1 -0
- package/dist/web/static/assets/react-router-I-HqunH7.js +20 -0
- package/dist/web/static/assets/react-router-I-HqunH7.js.map +1 -0
- package/dist/web/static/assets/react-vendor-CSp-GLFF.js +49 -0
- package/dist/web/static/assets/react-vendor-CSp-GLFF.js.map +1 -0
- package/dist/web/static/assets/syntax-highlighter-44FakypI.js +9 -0
- package/dist/web/static/assets/syntax-highlighter-44FakypI.js.map +1 -0
- package/dist/web/static/assets/vendor-CMMjVdZs.js +64 -0
- package/dist/web/static/assets/vendor-CMMjVdZs.js.map +1 -0
- package/dist/web/static/index.html +8 -2
- package/package.json +3 -2
- package/dist/web/static/assets/index-CtylfoaN.css +0 -1
- package/dist/web/static/assets/index-DnaQt27h.js +0 -388
- package/dist/web/static/assets/index-DnaQt27h.js.map +0 -1
|
@@ -27,6 +27,7 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
27
27
|
this.db.pragma(`cache_size = ${DATABASE.CACHE_SIZE}`);
|
|
28
28
|
this.db.pragma(`busy_timeout = ${DATABASE.BUSY_TIMEOUT}`);
|
|
29
29
|
this.initSchema();
|
|
30
|
+
this.runMigrations();
|
|
30
31
|
}
|
|
31
32
|
initSchema() {
|
|
32
33
|
const thisDir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -52,6 +53,284 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
52
53
|
`);
|
|
53
54
|
}
|
|
54
55
|
}
|
|
56
|
+
hasColumn(table, column) {
|
|
57
|
+
try {
|
|
58
|
+
const rows = this.db.prepare(`PRAGMA table_info(${table})`).all();
|
|
59
|
+
return rows.some(r => r.name === column);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
addColumnIfMissing(table, column, definition) {
|
|
66
|
+
if (!this.hasColumn(table, column)) {
|
|
67
|
+
try {
|
|
68
|
+
this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
|
|
69
|
+
logger.info(`[SQLiteStorage] migration: added ${table}.${column}`);
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
logger.warn(`[SQLiteStorage] migration: ALTER ${table} ADD ${column} failed: ${err}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Incremental schema migrations. Kept idempotent so daemon restarts are safe.
|
|
78
|
+
* New columns since the base schema.sql go here.
|
|
79
|
+
*/
|
|
80
|
+
runMigrations() {
|
|
81
|
+
// methodology_executions: mode / worker_pid / worker_session_id / last_progress_at
|
|
82
|
+
this.addColumnIfMissing('methodology_executions', 'mode', "TEXT NOT NULL DEFAULT 'foreground'");
|
|
83
|
+
this.addColumnIfMissing('methodology_executions', 'worker_pid', 'INTEGER');
|
|
84
|
+
this.addColumnIfMissing('methodology_executions', 'worker_session_id', 'TEXT');
|
|
85
|
+
this.addColumnIfMissing('methodology_executions', 'last_progress_at', 'INTEGER');
|
|
86
|
+
// methodology_executions: retry_count / original_plan_json (failure feedback loop)
|
|
87
|
+
this.addColumnIfMissing('methodology_executions', 'retry_count', 'INTEGER DEFAULT 0');
|
|
88
|
+
this.addColumnIfMissing('methodology_executions', 'original_plan_json', 'TEXT');
|
|
89
|
+
// methodology_executions: trigger_type (idle trigger support)
|
|
90
|
+
this.addColumnIfMissing('methodology_executions', 'trigger_type', "TEXT DEFAULT 'manual'");
|
|
91
|
+
// sessions: first_prompt — 避免 querySessions 再对 events 表做 O(sessions × events)
|
|
92
|
+
// 的相关子查询;新增列后若库里已有 sessions 但无 first_prompt,后续 backfill 会补齐。
|
|
93
|
+
this.addColumnIfMissing('sessions', 'first_prompt', 'TEXT');
|
|
94
|
+
// phase_executions: output_text / error_message / stream_log_path
|
|
95
|
+
this.addColumnIfMissing('phase_executions', 'output_text', 'TEXT');
|
|
96
|
+
this.addColumnIfMissing('phase_executions', 'error_message', 'TEXT');
|
|
97
|
+
this.addColumnIfMissing('phase_executions', 'stream_log_path', 'TEXT');
|
|
98
|
+
// phase_executions.status: 升级 CHECK 约束以支持 'cancelled'
|
|
99
|
+
this.rebuildPhaseExecutionsIfNeeded();
|
|
100
|
+
// methodology_executions.status: 升级 CHECK 约束以支持 'stale'
|
|
101
|
+
this.rebuildMethodologyExecutionsIfNeeded();
|
|
102
|
+
// sessions 聚合表性能索引(幂等):start_time 用于 querySessions 的 ORDER BY
|
|
103
|
+
try {
|
|
104
|
+
this.db.exec('CREATE INDEX IF NOT EXISTS idx_sessions_start_time ON sessions(start_time DESC)');
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
logger.warn(`[SQLiteStorage] migration: create idx_sessions_start_time failed: ${err}`);
|
|
108
|
+
}
|
|
109
|
+
// 一次性回填 sessions 聚合表(仅在 sessions 尚未对齐时触发)
|
|
110
|
+
this.backfillSessionsIfNeeded();
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 将 events 表按 session_id 聚合回填到 sessions 表,仅在 sessions 尚未对齐
|
|
114
|
+
* (没有任何一行带 first_prompt)时触发。旧库升级场景:引入 sessions 聚合表 +
|
|
115
|
+
* upsert 写入路径后,历史 events 不会自动同步到 sessions,必须通过一次性回填补齐。
|
|
116
|
+
*
|
|
117
|
+
* 幂等策略:检测到已有 first_prompt 非空的聚合行就跳过;避免覆盖已被新写路径
|
|
118
|
+
* upsert 过的数据。
|
|
119
|
+
*/
|
|
120
|
+
backfillSessionsIfNeeded() {
|
|
121
|
+
const eventsExists = this.db
|
|
122
|
+
.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='events'`)
|
|
123
|
+
.get();
|
|
124
|
+
if (!eventsExists)
|
|
125
|
+
return;
|
|
126
|
+
const aggRow = this.db
|
|
127
|
+
.prepare(`SELECT COUNT(*) AS total, COUNT(first_prompt) AS with_prompt FROM sessions`)
|
|
128
|
+
.get();
|
|
129
|
+
if (aggRow.with_prompt > 0)
|
|
130
|
+
return;
|
|
131
|
+
logger.info('[SQLiteStorage] backfilling sessions aggregate from events...');
|
|
132
|
+
try {
|
|
133
|
+
const backfill = this.db.transaction(() => {
|
|
134
|
+
this.db.exec(`
|
|
135
|
+
INSERT INTO sessions (
|
|
136
|
+
session_id, project_path, status, first_prompt,
|
|
137
|
+
start_time, end_time, last_event_time, event_count
|
|
138
|
+
)
|
|
139
|
+
SELECT
|
|
140
|
+
e.session_id,
|
|
141
|
+
e.project_path,
|
|
142
|
+
'active' AS status,
|
|
143
|
+
(SELECT substr(COALESCE(e2.user_prompt, json_extract(e2.tool_input, '$.user_prompt')), 1, 200)
|
|
144
|
+
FROM events e2
|
|
145
|
+
WHERE e2.session_id = e.session_id
|
|
146
|
+
AND e2.hook_type = 'UserPromptSubmit'
|
|
147
|
+
AND (e2.user_prompt IS NOT NULL OR json_extract(e2.tool_input, '$.user_prompt') IS NOT NULL)
|
|
148
|
+
ORDER BY e2.timestamp ASC LIMIT 1) AS first_prompt,
|
|
149
|
+
MIN(e.timestamp) AS start_time,
|
|
150
|
+
MAX(e.timestamp) AS end_time,
|
|
151
|
+
MAX(e.timestamp) AS last_event_time,
|
|
152
|
+
COUNT(*) AS event_count
|
|
153
|
+
FROM events e
|
|
154
|
+
GROUP BY e.session_id, e.project_path
|
|
155
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
156
|
+
first_prompt = COALESCE(sessions.first_prompt, excluded.first_prompt),
|
|
157
|
+
end_time = MAX(COALESCE(sessions.end_time, ''), excluded.end_time),
|
|
158
|
+
last_event_time = MAX(COALESCE(sessions.last_event_time, ''), excluded.last_event_time),
|
|
159
|
+
event_count = excluded.event_count,
|
|
160
|
+
updated_at = datetime('now')
|
|
161
|
+
`);
|
|
162
|
+
});
|
|
163
|
+
backfill();
|
|
164
|
+
const migrated = this.db.prepare('SELECT COUNT(*) AS c FROM sessions').get();
|
|
165
|
+
logger.info(`[SQLiteStorage] backfilled ${migrated.c} sessions from events`);
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
logger.warn(`[SQLiteStorage] backfillSessionsIfNeeded failed: ${err}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* SQLite 无法直接修改 CHECK 约束。若旧库的 phase_executions.status CHECK
|
|
173
|
+
* 还没有 'cancelled',走经典的"新表 + 拷数据 + 重命名"路径升级。
|
|
174
|
+
*
|
|
175
|
+
* 幂等:检测到当前 CREATE TABLE 语句里已有 'cancelled' 就跳过。fresh install
|
|
176
|
+
* 的库会直接命中 schema.sql 里的新定义,这里也直接跳过。
|
|
177
|
+
*/
|
|
178
|
+
rebuildPhaseExecutionsIfNeeded() {
|
|
179
|
+
const row = this.db
|
|
180
|
+
.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='phase_executions'`)
|
|
181
|
+
.get();
|
|
182
|
+
if (!row || typeof row.sql !== 'string')
|
|
183
|
+
return;
|
|
184
|
+
if (row.sql.includes(`'cancelled'`))
|
|
185
|
+
return;
|
|
186
|
+
// 兜底列齐校验:rebuild 的新表定义必须覆盖所有期望列;如果前面 addColumnIfMissing
|
|
187
|
+
// 漏补,这里最后再补一次,避免"列在旧表不存在 → 拷数据 SELECT 报 no such column"。
|
|
188
|
+
const expectedPhaseColumns = [
|
|
189
|
+
['output_text', 'TEXT'],
|
|
190
|
+
['error_message', 'TEXT'],
|
|
191
|
+
['stream_log_path', 'TEXT'],
|
|
192
|
+
];
|
|
193
|
+
for (const [col, def] of expectedPhaseColumns) {
|
|
194
|
+
this.addColumnIfMissing('phase_executions', col, def);
|
|
195
|
+
}
|
|
196
|
+
logger.info('[SQLiteStorage] migration: rebuilding phase_executions to extend status CHECK with cancelled');
|
|
197
|
+
// 列列表来自最新 schema —— 新增过的列(output_text / error_message / stream_log_path)
|
|
198
|
+
// 在前面的 addColumnIfMissing 已经补齐,这里可以安全地全量拷贝。
|
|
199
|
+
const migrate = this.db.transaction(() => {
|
|
200
|
+
this.db.exec(`
|
|
201
|
+
CREATE TABLE phase_executions_new (
|
|
202
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
203
|
+
methodology_execution_id INTEGER NOT NULL,
|
|
204
|
+
phase_id TEXT NOT NULL,
|
|
205
|
+
phase_index INTEGER NOT NULL,
|
|
206
|
+
agent_name TEXT NOT NULL,
|
|
207
|
+
prompt TEXT NOT NULL,
|
|
208
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'running', 'completed', 'failed', 'cancelled')),
|
|
209
|
+
started_at INTEGER,
|
|
210
|
+
completed_at INTEGER,
|
|
211
|
+
duration_ms INTEGER,
|
|
212
|
+
artifacts_json TEXT,
|
|
213
|
+
output_text TEXT,
|
|
214
|
+
error_message TEXT,
|
|
215
|
+
stream_log_path TEXT,
|
|
216
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
217
|
+
FOREIGN KEY (methodology_execution_id) REFERENCES methodology_executions(id)
|
|
218
|
+
);
|
|
219
|
+
`);
|
|
220
|
+
this.db.exec(`
|
|
221
|
+
INSERT INTO phase_executions_new (
|
|
222
|
+
id, methodology_execution_id, phase_id, phase_index, agent_name, prompt,
|
|
223
|
+
status, started_at, completed_at, duration_ms, artifacts_json,
|
|
224
|
+
output_text, error_message, stream_log_path, created_at
|
|
225
|
+
)
|
|
226
|
+
SELECT
|
|
227
|
+
id, methodology_execution_id, phase_id, phase_index, agent_name, prompt,
|
|
228
|
+
status, started_at, completed_at, duration_ms, artifacts_json,
|
|
229
|
+
output_text, error_message, stream_log_path, created_at
|
|
230
|
+
FROM phase_executions;
|
|
231
|
+
`);
|
|
232
|
+
this.db.exec(`DROP TABLE phase_executions;`);
|
|
233
|
+
this.db.exec(`ALTER TABLE phase_executions_new RENAME TO phase_executions;`);
|
|
234
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_phase_exec_methodology ON phase_executions(methodology_execution_id);`);
|
|
235
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_phase_exec_status ON phase_executions(status);`);
|
|
236
|
+
});
|
|
237
|
+
try {
|
|
238
|
+
migrate();
|
|
239
|
+
logger.info('[SQLiteStorage] migration: phase_executions rebuild complete');
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
logger.warn(`[SQLiteStorage] migration: phase_executions rebuild failed: ${err}`);
|
|
243
|
+
throw err;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* methodology_executions.status CHECK 升级:加入 'stale' 枚举值。
|
|
248
|
+
* 幂等:CREATE TABLE 语句里已含 'stale' 则跳过;fresh install 会命中 schema.sql
|
|
249
|
+
* 的新定义,这里也跳过。
|
|
250
|
+
*
|
|
251
|
+
* 注意:必须在 addColumnIfMissing('last_progress_at' / 'retry_count' /
|
|
252
|
+
* 'original_plan_json' / 'trigger_type', ...) 之后执行,重建表时才能把它们一起
|
|
253
|
+
* 拷贝过去。重建方法内部再做一次兜底 addColumnIfMissing,避免未来新列漏同步。
|
|
254
|
+
*/
|
|
255
|
+
rebuildMethodologyExecutionsIfNeeded() {
|
|
256
|
+
const row = this.db
|
|
257
|
+
.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='methodology_executions'`)
|
|
258
|
+
.get();
|
|
259
|
+
if (!row || typeof row.sql !== 'string')
|
|
260
|
+
return;
|
|
261
|
+
if (row.sql.includes(`'stale'`))
|
|
262
|
+
return;
|
|
263
|
+
// 兜底列齐校验:重建涉及到 INSERT ... SELECT,任何漏列都会让旧列被丢弃或
|
|
264
|
+
// 新列 SELECT 报 `no such column`。所有期望列这里再确认一次。
|
|
265
|
+
const expectedMethodologyColumns = [
|
|
266
|
+
['mode', "TEXT NOT NULL DEFAULT 'foreground'"],
|
|
267
|
+
['worker_pid', 'INTEGER'],
|
|
268
|
+
['worker_session_id', 'TEXT'],
|
|
269
|
+
['last_progress_at', 'INTEGER'],
|
|
270
|
+
['retry_count', 'INTEGER DEFAULT 0'],
|
|
271
|
+
['original_plan_json', 'TEXT'],
|
|
272
|
+
['trigger_type', "TEXT DEFAULT 'manual'"],
|
|
273
|
+
];
|
|
274
|
+
for (const [col, def] of expectedMethodologyColumns) {
|
|
275
|
+
this.addColumnIfMissing('methodology_executions', col, def);
|
|
276
|
+
}
|
|
277
|
+
logger.info('[SQLiteStorage] migration: rebuilding methodology_executions to extend status CHECK with stale');
|
|
278
|
+
// 重建母表会触发依赖它的外键(phase_executions.methodology_execution_id)。
|
|
279
|
+
// PRAGMA foreign_keys 不能在事务内改,所以在事务外临时关闭,完成后恢复。
|
|
280
|
+
const fkBefore = this.db.pragma('foreign_keys', { simple: true });
|
|
281
|
+
if (fkBefore)
|
|
282
|
+
this.db.pragma('foreign_keys = OFF');
|
|
283
|
+
const migrate = this.db.transaction(() => {
|
|
284
|
+
this.db.exec(`
|
|
285
|
+
CREATE TABLE methodology_executions_new (
|
|
286
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
287
|
+
session_id TEXT NOT NULL,
|
|
288
|
+
methodology_id TEXT NOT NULL,
|
|
289
|
+
plan_json TEXT NOT NULL,
|
|
290
|
+
current_phase_index INTEGER DEFAULT 0,
|
|
291
|
+
status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running', 'completed', 'failed', 'cancelled', 'stale')),
|
|
292
|
+
started_at INTEGER NOT NULL,
|
|
293
|
+
completed_at INTEGER,
|
|
294
|
+
mode TEXT NOT NULL DEFAULT 'foreground',
|
|
295
|
+
worker_pid INTEGER,
|
|
296
|
+
worker_session_id TEXT,
|
|
297
|
+
last_progress_at INTEGER,
|
|
298
|
+
retry_count INTEGER DEFAULT 0,
|
|
299
|
+
original_plan_json TEXT,
|
|
300
|
+
trigger_type TEXT DEFAULT 'manual',
|
|
301
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
302
|
+
);
|
|
303
|
+
`);
|
|
304
|
+
this.db.exec(`
|
|
305
|
+
INSERT INTO methodology_executions_new (
|
|
306
|
+
id, session_id, methodology_id, plan_json, current_phase_index,
|
|
307
|
+
status, started_at, completed_at, mode, worker_pid, worker_session_id,
|
|
308
|
+
last_progress_at, retry_count, original_plan_json, trigger_type, created_at
|
|
309
|
+
)
|
|
310
|
+
SELECT
|
|
311
|
+
id, session_id, methodology_id, plan_json, current_phase_index,
|
|
312
|
+
status, started_at, completed_at, mode, worker_pid, worker_session_id,
|
|
313
|
+
last_progress_at, retry_count, original_plan_json, trigger_type, created_at
|
|
314
|
+
FROM methodology_executions;
|
|
315
|
+
`);
|
|
316
|
+
this.db.exec(`DROP TABLE methodology_executions;`);
|
|
317
|
+
this.db.exec(`ALTER TABLE methodology_executions_new RENAME TO methodology_executions;`);
|
|
318
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_methodology_exec_session ON methodology_executions(session_id);`);
|
|
319
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_methodology_exec_status ON methodology_executions(status);`);
|
|
320
|
+
});
|
|
321
|
+
try {
|
|
322
|
+
migrate();
|
|
323
|
+
logger.info('[SQLiteStorage] migration: methodology_executions rebuild complete');
|
|
324
|
+
}
|
|
325
|
+
catch (err) {
|
|
326
|
+
logger.warn(`[SQLiteStorage] migration: methodology_executions rebuild failed: ${err}`);
|
|
327
|
+
throw err;
|
|
328
|
+
}
|
|
329
|
+
finally {
|
|
330
|
+
if (fkBefore)
|
|
331
|
+
this.db.pragma('foreign_keys = ON');
|
|
332
|
+
}
|
|
333
|
+
}
|
|
55
334
|
getDatabase() {
|
|
56
335
|
return this.db;
|
|
57
336
|
}
|
|
@@ -67,8 +346,52 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
67
346
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
|
|
68
347
|
`);
|
|
69
348
|
stmt.run(eventId, event.session_id, event.project_path, event.timestamp, event.hook_type, event.tool_name ?? null, event.tool_input ? JSON.stringify(event.tool_input) : null, event.tool_output ? JSON.stringify(event.tool_output) : null, event.user_prompt ?? null, event.ai_response ?? null);
|
|
349
|
+
// 聚合到 sessions 表。单独 try/catch:一旦聚合失败(比如 schema 升级过程中
|
|
350
|
+
// 的短暂窗口),也不能影响原事件的持久化,上层已经 commit 过 events 了。
|
|
351
|
+
try {
|
|
352
|
+
this.upsertSession(event);
|
|
353
|
+
}
|
|
354
|
+
catch (err) {
|
|
355
|
+
logger.warn(`[SQLiteStorage] upsertSession failed (event still written): ${err}`);
|
|
356
|
+
}
|
|
70
357
|
this.emit('event', { ...event, event_id: eventId });
|
|
71
358
|
}
|
|
359
|
+
/**
|
|
360
|
+
* 将事件聚合到 sessions 表,供 querySessions 直接读取,避免对 events 做 O(n²)
|
|
361
|
+
* 的 GROUP BY + 相关子查询。
|
|
362
|
+
*
|
|
363
|
+
* 语义:
|
|
364
|
+
* - 首次出现 session_id → 插入一行,start/end/last_event_time 都取当前事件时间戳
|
|
365
|
+
* - 已存在 → event_count += 1,end/last_event_time 取更晚的,first_prompt 只在
|
|
366
|
+
* 原值为 NULL 时才被 UserPromptSubmit 的前 200 字填充(保留"首条"语义)
|
|
367
|
+
* - 非 UserPromptSubmit 事件或 user_prompt 为空时 first_prompt 传 NULL,不会
|
|
368
|
+
* 覆盖已有值
|
|
369
|
+
*/
|
|
370
|
+
upsertSession(event) {
|
|
371
|
+
const firstPrompt = event.hook_type === 'UserPromptSubmit' && event.user_prompt
|
|
372
|
+
? event.user_prompt.slice(0, 200)
|
|
373
|
+
: null;
|
|
374
|
+
const stmt = this.db.prepare(`
|
|
375
|
+
INSERT INTO sessions (
|
|
376
|
+
session_id, project_path, status, first_prompt,
|
|
377
|
+
start_time, end_time, last_event_time, event_count
|
|
378
|
+
)
|
|
379
|
+
VALUES (?, ?, 'active', ?, ?, ?, ?, 1)
|
|
380
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
381
|
+
end_time = CASE
|
|
382
|
+
WHEN excluded.end_time > COALESCE(sessions.end_time, '') THEN excluded.end_time
|
|
383
|
+
ELSE sessions.end_time
|
|
384
|
+
END,
|
|
385
|
+
last_event_time = CASE
|
|
386
|
+
WHEN excluded.last_event_time > COALESCE(sessions.last_event_time, '') THEN excluded.last_event_time
|
|
387
|
+
ELSE sessions.last_event_time
|
|
388
|
+
END,
|
|
389
|
+
event_count = COALESCE(sessions.event_count, 0) + 1,
|
|
390
|
+
first_prompt = COALESCE(sessions.first_prompt, excluded.first_prompt),
|
|
391
|
+
updated_at = datetime('now')
|
|
392
|
+
`);
|
|
393
|
+
stmt.run(event.session_id, event.project_path, firstPrompt, event.timestamp, event.timestamp, event.timestamp);
|
|
394
|
+
}
|
|
72
395
|
writeToolEvent(event) {
|
|
73
396
|
const stmt = this.db.prepare(`
|
|
74
397
|
INSERT INTO v2_tool_events (session_id, route_request_id, tool, args, result, success, error, timestamp)
|
|
@@ -146,33 +469,31 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
146
469
|
const conditions = [];
|
|
147
470
|
const params = [];
|
|
148
471
|
if (filter.project_path) {
|
|
149
|
-
conditions.push('
|
|
472
|
+
conditions.push('project_path = ?');
|
|
150
473
|
params.push(filter.project_path);
|
|
151
474
|
}
|
|
152
475
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
153
476
|
const limit = filter.limit ?? 10;
|
|
477
|
+
// 直接读 sessions 聚合表 → O(sessions)。writeEvent 的 upsertSession 路径保证
|
|
478
|
+
// 每次事件写入都会同步更新此表;旧库在 runMigrations 里由 backfillSessionsIfNeeded
|
|
479
|
+
// 一次性回填,确保历史 session 也可见。
|
|
154
480
|
const sql = `
|
|
155
481
|
SELECT
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
WHERE e2.session_id = e.session_id AND e2.hook_type = 'UserPromptSubmit'
|
|
163
|
-
AND (e2.user_prompt IS NOT NULL OR json_extract(e2.tool_input, '$.user_prompt') IS NOT NULL)
|
|
164
|
-
ORDER BY e2.timestamp ASC LIMIT 1) as first_prompt
|
|
165
|
-
FROM events e
|
|
482
|
+
session_id,
|
|
483
|
+
first_prompt,
|
|
484
|
+
event_count,
|
|
485
|
+
start_time,
|
|
486
|
+
COALESCE(end_time, last_event_time, start_time) AS end_time
|
|
487
|
+
FROM sessions
|
|
166
488
|
${where}
|
|
167
|
-
|
|
168
|
-
ORDER BY MAX(e.timestamp) DESC
|
|
489
|
+
ORDER BY start_time DESC
|
|
169
490
|
LIMIT ${limit}
|
|
170
491
|
`;
|
|
171
492
|
const rows = this.db.prepare(sql).all(...params);
|
|
172
493
|
return rows.map(r => ({
|
|
173
494
|
session_id: r.session_id,
|
|
174
495
|
first_prompt: r.first_prompt || '',
|
|
175
|
-
event_count: r.event_count,
|
|
496
|
+
event_count: r.event_count ?? 0,
|
|
176
497
|
start_time: r.start_time,
|
|
177
498
|
end_time: r.end_time,
|
|
178
499
|
}));
|
|
@@ -506,18 +827,22 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
506
827
|
}
|
|
507
828
|
// ── Methodology Executions ─────────────────────────────────────────────
|
|
508
829
|
createMethodologyExecution(data) {
|
|
830
|
+
const mode = data.mode ?? 'foreground';
|
|
831
|
+
const trigger_type = data.trigger_type ?? 'manual';
|
|
832
|
+
const now = Date.now();
|
|
509
833
|
const result = this.db.prepare(`
|
|
510
|
-
INSERT INTO methodology_executions (session_id, methodology_id, plan_json, started_at)
|
|
511
|
-
VALUES (?, ?, ?,
|
|
512
|
-
`).run(data.session_id, data.methodology_id, data.plan_json,
|
|
834
|
+
INSERT INTO methodology_executions (session_id, methodology_id, plan_json, original_plan_json, mode, trigger_type, started_at, last_progress_at, retry_count)
|
|
835
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)
|
|
836
|
+
`).run(data.session_id, data.methodology_id, data.plan_json, data.plan_json, mode, trigger_type, now, now);
|
|
513
837
|
return result.lastInsertRowid;
|
|
514
838
|
}
|
|
515
839
|
getActiveMethodologyExecution(session_id) {
|
|
516
|
-
|
|
840
|
+
const row = this.db.prepare(`
|
|
517
841
|
SELECT * FROM methodology_executions
|
|
518
842
|
WHERE session_id = ? AND status = 'running'
|
|
519
843
|
ORDER BY id DESC LIMIT 1
|
|
520
|
-
`).get(session_id)
|
|
844
|
+
`).get(session_id);
|
|
845
|
+
return row ?? null;
|
|
521
846
|
}
|
|
522
847
|
updateMethodologyExecution(id, data) {
|
|
523
848
|
const updates = [];
|
|
@@ -534,6 +859,26 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
534
859
|
updates.push('completed_at = ?');
|
|
535
860
|
values.push(data.completed_at);
|
|
536
861
|
}
|
|
862
|
+
if (data.worker_pid !== undefined) {
|
|
863
|
+
updates.push('worker_pid = ?');
|
|
864
|
+
values.push(data.worker_pid);
|
|
865
|
+
}
|
|
866
|
+
if (data.worker_session_id !== undefined) {
|
|
867
|
+
updates.push('worker_session_id = ?');
|
|
868
|
+
values.push(data.worker_session_id);
|
|
869
|
+
}
|
|
870
|
+
if (data.last_progress_at !== undefined) {
|
|
871
|
+
updates.push('last_progress_at = ?');
|
|
872
|
+
values.push(data.last_progress_at);
|
|
873
|
+
}
|
|
874
|
+
if (data.plan_json !== undefined) {
|
|
875
|
+
updates.push('plan_json = ?');
|
|
876
|
+
values.push(data.plan_json);
|
|
877
|
+
}
|
|
878
|
+
if (data.retry_count !== undefined) {
|
|
879
|
+
updates.push('retry_count = ?');
|
|
880
|
+
values.push(data.retry_count);
|
|
881
|
+
}
|
|
537
882
|
if (updates.length > 0) {
|
|
538
883
|
values.push(id);
|
|
539
884
|
this.db.prepare(`
|
|
@@ -544,9 +889,34 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
544
889
|
}
|
|
545
890
|
}
|
|
546
891
|
getMethodologyExecution(id) {
|
|
547
|
-
|
|
892
|
+
const row = this.db.prepare(`
|
|
548
893
|
SELECT * FROM methodology_executions WHERE id = ?
|
|
549
|
-
`).get(id)
|
|
894
|
+
`).get(id);
|
|
895
|
+
return row ?? null;
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* List all methodology_executions with status='running' and mode='background'.
|
|
899
|
+
* Used at daemon startup to detect crashed workers (worker_pid not alive).
|
|
900
|
+
*/
|
|
901
|
+
listRunningBackgroundExecutions() {
|
|
902
|
+
return this.db.prepare(`
|
|
903
|
+
SELECT * FROM methodology_executions
|
|
904
|
+
WHERE status = 'running' AND mode = 'background'
|
|
905
|
+
ORDER BY id DESC
|
|
906
|
+
`).all();
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* List all methodology_executions with status='running' and mode='foreground'.
|
|
910
|
+
* Used at daemon startup to sweep stale foreground executions — rows left
|
|
911
|
+
* behind when the originating Claude session ended without Stop hook firing
|
|
912
|
+
* (crash / detach / pre-guard legacy data).
|
|
913
|
+
*/
|
|
914
|
+
listRunningForegroundExecutions() {
|
|
915
|
+
return this.db.prepare(`
|
|
916
|
+
SELECT * FROM methodology_executions
|
|
917
|
+
WHERE status = 'running' AND mode = 'foreground'
|
|
918
|
+
ORDER BY id DESC
|
|
919
|
+
`).all();
|
|
550
920
|
}
|
|
551
921
|
// ── Phase Executions ───────────────────────────────────────────────────
|
|
552
922
|
createPhaseExecution(data) {
|
|
@@ -568,13 +938,29 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
568
938
|
updates.push('completed_at = ?');
|
|
569
939
|
values.push(data.completed_at);
|
|
570
940
|
if (data.status === 'completed') {
|
|
571
|
-
|
|
941
|
+
// SQLite UPDATE 的 SET 子句里引用列名取的是更新前的值,
|
|
942
|
+
// 不能写 `duration_ms = completed_at - started_at`(RHS 的 completed_at 仍是 NULL)。
|
|
943
|
+
// 用参数占位符复写一次 completed_at 的值,减去旧的 started_at。
|
|
944
|
+
updates.push('duration_ms = ? - started_at');
|
|
945
|
+
values.push(data.completed_at);
|
|
572
946
|
}
|
|
573
947
|
}
|
|
574
948
|
if (data.artifacts_json) {
|
|
575
949
|
updates.push('artifacts_json = ?');
|
|
576
950
|
values.push(data.artifacts_json);
|
|
577
951
|
}
|
|
952
|
+
if (data.output_text !== undefined) {
|
|
953
|
+
updates.push('output_text = ?');
|
|
954
|
+
values.push(data.output_text);
|
|
955
|
+
}
|
|
956
|
+
if (data.error_message !== undefined) {
|
|
957
|
+
updates.push('error_message = ?');
|
|
958
|
+
values.push(data.error_message);
|
|
959
|
+
}
|
|
960
|
+
if (data.stream_log_path !== undefined) {
|
|
961
|
+
updates.push('stream_log_path = ?');
|
|
962
|
+
values.push(data.stream_log_path);
|
|
963
|
+
}
|
|
578
964
|
if (updates.length > 0) {
|
|
579
965
|
values.push(id);
|
|
580
966
|
this.db.prepare(`
|
|
@@ -591,5 +977,77 @@ export class SQLiteStorage extends EventEmitter {
|
|
|
591
977
|
ORDER BY phase_index ASC
|
|
592
978
|
`).all(methodology_execution_id);
|
|
593
979
|
}
|
|
980
|
+
/**
|
|
981
|
+
* 获取指定 session 和 methodology 的最后一次 idle 触发时间
|
|
982
|
+
*/
|
|
983
|
+
getLastIdleTrigger(session_id, methodology_id) {
|
|
984
|
+
const row = this.db.prepare(`
|
|
985
|
+
SELECT MAX(started_at) as last_trigger
|
|
986
|
+
FROM methodology_executions
|
|
987
|
+
WHERE session_id = ? AND methodology_id = ? AND trigger_type = 'idle'
|
|
988
|
+
`).get(session_id, methodology_id);
|
|
989
|
+
return row?.last_trigger ?? null;
|
|
990
|
+
}
|
|
991
|
+
// ── Token Usage ────────────────────────────────────────────────────────
|
|
992
|
+
recordTokenUsage(params) {
|
|
993
|
+
const total_tokens = params.input_tokens + params.output_tokens;
|
|
994
|
+
try {
|
|
995
|
+
this.db.prepare(`
|
|
996
|
+
INSERT INTO token_usage (session_id, methodology_execution_id, timestamp,
|
|
997
|
+
input_tokens, output_tokens, total_tokens, model, tool_name)
|
|
998
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
999
|
+
`).run(params.session_id, params.methodology_execution_id ?? null, Date.now(), params.input_tokens, params.output_tokens, total_tokens, params.model ?? null, params.tool_name ?? null);
|
|
1000
|
+
}
|
|
1001
|
+
catch (err) {
|
|
1002
|
+
logger.debug(`[Storage] Failed to record token usage: ${err}`);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
getTokenUsageBySession(session_id) {
|
|
1006
|
+
const result = this.db.prepare(`
|
|
1007
|
+
SELECT
|
|
1008
|
+
COALESCE(SUM(input_tokens), 0) as input_tokens,
|
|
1009
|
+
COALESCE(SUM(output_tokens), 0) as output_tokens,
|
|
1010
|
+
COALESCE(SUM(total_tokens), 0) as total_tokens
|
|
1011
|
+
FROM token_usage WHERE session_id = ?
|
|
1012
|
+
`).get(session_id);
|
|
1013
|
+
return result;
|
|
1014
|
+
}
|
|
1015
|
+
getTokenUsageByMethodology(methodology_execution_id) {
|
|
1016
|
+
const result = this.db.prepare(`
|
|
1017
|
+
SELECT
|
|
1018
|
+
COALESCE(SUM(input_tokens), 0) as input_tokens,
|
|
1019
|
+
COALESCE(SUM(output_tokens), 0) as output_tokens,
|
|
1020
|
+
COALESCE(SUM(total_tokens), 0) as total_tokens
|
|
1021
|
+
FROM token_usage WHERE methodology_execution_id = ?
|
|
1022
|
+
`).get(methodology_execution_id);
|
|
1023
|
+
return result;
|
|
1024
|
+
}
|
|
1025
|
+
listTokenUsage(filter = {}) {
|
|
1026
|
+
const conditions = [];
|
|
1027
|
+
const params = [];
|
|
1028
|
+
if (filter.session_id) {
|
|
1029
|
+
conditions.push('session_id = ?');
|
|
1030
|
+
params.push(filter.session_id);
|
|
1031
|
+
}
|
|
1032
|
+
if (filter.methodology_execution_id !== undefined) {
|
|
1033
|
+
conditions.push('methodology_execution_id = ?');
|
|
1034
|
+
params.push(filter.methodology_execution_id);
|
|
1035
|
+
}
|
|
1036
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
1037
|
+
const limit = filter.limit ?? 100;
|
|
1038
|
+
const sql = `SELECT * FROM token_usage ${where} ORDER BY timestamp DESC LIMIT ${limit}`;
|
|
1039
|
+
const rows = this.db.prepare(sql).all(...params);
|
|
1040
|
+
return rows.map(r => ({
|
|
1041
|
+
id: r.id,
|
|
1042
|
+
session_id: r.session_id,
|
|
1043
|
+
methodology_execution_id: r.methodology_execution_id || null,
|
|
1044
|
+
timestamp: r.timestamp,
|
|
1045
|
+
input_tokens: r.input_tokens,
|
|
1046
|
+
output_tokens: r.output_tokens,
|
|
1047
|
+
total_tokens: r.total_tokens,
|
|
1048
|
+
model: r.model || null,
|
|
1049
|
+
tool_name: r.tool_name || null,
|
|
1050
|
+
}));
|
|
1051
|
+
}
|
|
594
1052
|
}
|
|
595
1053
|
//# sourceMappingURL=sqlite.js.map
|