claude-code-session-manager 0.138.0 → 0.140.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/.claude-plugin/marketplace.json +1 -1
- package/README.md +352 -79
- package/dist/assets/AppSettings-CMFEM68R.js +2 -0
- package/dist/assets/History--JwsFnbn.js +2 -0
- package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
- package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
- package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
- package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
- package/dist/assets/Skills-DtRzghn5.js +67 -0
- package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
- package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
- package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
- package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
- package/dist/assets/index-CtxruO1L.js +3121 -0
- package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +467 -451
- package/package.json +17 -6
- package/plugins/AGENTS.md +60 -0
- package/plugins/CLAUDE.md +1 -60
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
- package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
- package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
- package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
- package/scripts/README.md +2 -0
- package/scripts/hooks/guard-tool-risk.cjs +91 -0
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
- package/scripts/ops-sweep.cjs +53 -23
- package/scripts/scheduler-mcp-server.cjs +360 -35
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +2 -2
- package/src/main/config.cjs +112 -8
- package/src/main/docEdit.cjs +6 -1
- package/src/main/exchanges.cjs +70 -5
- package/src/main/files.cjs +7 -27
- package/src/main/health.cjs +48 -15
- package/src/main/historyAggregator.cjs +172 -63
- package/src/main/historyDashboard.cjs +87 -17
- package/src/main/index.cjs +78 -4
- package/src/main/ipcSchemas.cjs +233 -20
- package/src/main/lib/AGENTS.md +54 -0
- package/src/main/lib/CLAUDE.md +1 -54
- package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
- package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
- package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
- package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
- package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
- package/src/main/lib/claude/modelPricing.cjs +148 -0
- package/src/main/lib/claude/personaToolScope.cjs +12 -6
- package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
- package/src/main/lib/claude/runClaudeP.cjs +6 -1
- package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
- package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
- package/src/main/lib/ephemeralCwd.cjs +37 -2
- package/src/main/lib/epic/delegationReadiness.cjs +42 -9
- package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
- package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
- package/src/main/lib/epic/epicOutsideState.cjs +233 -0
- package/src/main/lib/epic/epicSettle.cjs +1 -1
- package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
- package/src/main/lib/epic/epicValidationHook.cjs +24 -4
- package/src/main/lib/epic/externalRef.cjs +37 -0
- package/src/main/lib/epic/externalRefIndex.cjs +136 -0
- package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
- package/src/main/lib/epic/restorableSessions.cjs +151 -17
- package/src/main/lib/epic/transcriptUsage.cjs +197 -0
- package/src/main/lib/externalContract.cjs +137 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
- package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
- package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
- package/src/main/lib/git/branchSweep.cjs +209 -4
- package/src/main/lib/git/gitWorktree.cjs +41 -5
- package/src/main/lib/guardShims.cjs +1 -1
- package/src/main/lib/historyRollup.cjs +58 -5
- package/src/main/lib/insideHome.cjs +27 -1
- package/src/main/lib/mcpToolCatalog.cjs +232 -25
- package/src/main/lib/mdDocCensus.cjs +59 -78
- package/src/main/lib/mdDocRefs.cjs +71 -93
- package/src/main/lib/mdNetworkScan.cjs +245 -250
- package/src/main/lib/mdReviewRecord.cjs +22 -9
- package/src/main/lib/memoryMdNetwork.cjs +5 -12
- package/src/main/lib/opsOwnership.cjs +18 -2
- package/src/main/lib/opsRetentionSettings.cjs +28 -4
- package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
- package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
- package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
- package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
- package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/depSlugResolve.cjs +104 -4
- package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
- package/src/main/lib/prd/prdCreate.cjs +351 -23
- package/src/main/lib/prd/prdDisposition.cjs +11 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
- package/src/main/lib/process/loginItem.cjs +171 -0
- package/src/main/lib/process/loginItemPlan.cjs +193 -0
- package/src/main/lib/project-pages/playerBridge.cjs +4 -0
- package/src/main/lib/project-pages/videoReview.cjs +268 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
- package/src/main/lib/promptSessionSchema.cjs +4 -0
- package/src/main/lib/remoteTranscriptTail.cjs +32 -1
- package/src/main/lib/scheduler/cpuSample.cjs +131 -4
- package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
- package/src/main/lib/scheduler/loadGate.cjs +24 -6
- package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
- package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
- package/src/main/lib/scheduler/queueStore.cjs +7 -0
- package/src/main/lib/scheduler/rcaReport.cjs +21 -1
- package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
- package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
- package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
- package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
- package/src/main/lib/scheduler/validationQuality.cjs +282 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
- package/src/main/lib/tasks/taskIpc.cjs +80 -0
- package/src/main/lib/tasks/taskLedger.cjs +502 -0
- package/src/main/lib/tasks/taskRun.cjs +313 -0
- package/src/main/lib/tasks/taskSwitch.cjs +120 -0
- package/src/main/lib/telemetry/auditEvents.cjs +176 -0
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
- package/src/main/loginItemIpc.cjs +35 -0
- package/src/main/loopEfficiencyHandlers.cjs +11 -2
- package/src/main/projectPages.cjs +6 -15
- package/src/main/promptSessionEvents.cjs +9 -1
- package/src/main/queueOps.cjs +260 -3
- package/src/main/runVerify.cjs +53 -25
- package/src/main/scheduler/AGENTS.md +26 -0
- package/src/main/scheduler/CLAUDE.md +1 -26
- package/src/main/scheduler/budget.cjs +239 -9
- package/src/main/scheduler/cancelDependents.cjs +154 -0
- package/src/main/scheduler/prdParser.cjs +4 -1
- package/src/main/scheduler/starvation.cjs +20 -18
- package/src/main/scheduler.cjs +774 -64
- package/src/main/supervisor.cjs +5 -1
- package/src/main/templates/PRD_AUTHORING.md +7 -1
- package/src/main/transcripts.cjs +62 -7
- package/src/main/validationQualityHandlers.cjs +199 -0
- package/src/main/webRemote.cjs +132 -20
- package/src/preload/api.d.ts +434 -28
- package/src/preload/apiSurface.cjs +7 -0
- package/src/preload/apiSurface.json +485 -81
- package/src/preload/index.cjs +38 -5
- package/src/seed/agents/validator.md +19 -8
- package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
- package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
- package/dist/assets/Button-Bk23rEnZ.js +0 -1
- package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
- package/dist/assets/Extensions-CXem-uwI.js +0 -2
- package/dist/assets/History-BwO3coo4.js +0 -2
- package/dist/assets/Library-BDV69fSe.js +0 -32
- package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
- package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
- package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
- package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
- package/dist/assets/Settings-COT34hBF.js +0 -2
- package/dist/assets/Skills-BgexoUkQ.js +0 -29
- package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
- package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
- package/dist/assets/Toggle-CENi19iK.js +0 -1
- package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
- package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
- package/dist/assets/index-CgCxpunJ.js +0 -3116
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* epicAdminRoutes.cjs — read-only admin HTTP routes over epicOutsideRead.cjs,
|
|
3
|
+
* so a script or another project can read an Epic's state without touching
|
|
4
|
+
* Session Manager's files.
|
|
5
|
+
*
|
|
6
|
+
* GET /admin/epics?cwd=<abs>&state=<state>&limit=<1..200>&offset=<0..>
|
|
7
|
+
* → 200 { ok: true, epics, total, limit, offset, hasMore }
|
|
8
|
+
* GET /admin/epic?cwd=<abs>&(id=<epicId> | externalRef=<ref>)[&receipt=1|true]
|
|
9
|
+
* → 200 { ok: true, epic } (epic.receipt = { jobs, chat } only when receipt was asked for) | 404 { ok: false, error: 'not found' }
|
|
10
|
+
* GET /admin/epic?id=<epicId>[&receipt=1|true] (no cwd)
|
|
11
|
+
* → the Epic is found among the registered projects (findEpicProject):
|
|
12
|
+
* one → as above; none → 404; several → 409 { ok: false, error: 'ambiguous epic id', cwds }
|
|
13
|
+
*
|
|
14
|
+
* A query the schema rejects → 400 { ok: false, error: 'invalid query', details }.
|
|
15
|
+
* A cwd that is not absolute or has no session-manager-operations folder →
|
|
16
|
+
* 400 { ok: false, error: <reason> }.
|
|
17
|
+
*
|
|
18
|
+
* Writes no file and no audit row. Auth/loopback binding are the injected
|
|
19
|
+
* localAdminHttp.cjs transport's job (see index.cjs).
|
|
20
|
+
*/
|
|
21
|
+
'use strict';
|
|
22
|
+
|
|
23
|
+
const fs = require('node:fs');
|
|
24
|
+
const path = require('node:path');
|
|
25
|
+
const { schemas } = require('../../ipcSchemas.cjs');
|
|
26
|
+
const { sendJson } = require('../feedback-remote/localAdminHttp.cjs');
|
|
27
|
+
const { opsPath } = require('../opsOwnership.cjs');
|
|
28
|
+
const { listOpenEpicRecords, getEpicRecord, findEpicProject } = require('./epicOutsideRead.cjs');
|
|
29
|
+
|
|
30
|
+
/** @param {unknown} cwd @returns {string | null} the reason this cwd is not a project, or null. */
|
|
31
|
+
function projectProblem(cwd) {
|
|
32
|
+
if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return 'cwd must be an absolute path';
|
|
33
|
+
let dir;
|
|
34
|
+
try {
|
|
35
|
+
dir = opsPath(cwd);
|
|
36
|
+
} catch (e) {
|
|
37
|
+
return e instanceof Error ? e.message : String(e);
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
if (!fs.statSync(dir).isDirectory()) return 'cwd has no session-manager-operations folder';
|
|
41
|
+
} catch {
|
|
42
|
+
return 'cwd has no session-manager-operations folder';
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {{ registerRoute: Function }} adminHttp
|
|
49
|
+
* @param {{ isTabBusy?: (epicId: string) => boolean | Promise<boolean>, listJobs?: () => any, projectRoots?: () => string[] }} [deps]
|
|
50
|
+
*/
|
|
51
|
+
function registerAdminRoute(adminHttp, deps = {}) {
|
|
52
|
+
/** @type {Record<string, unknown>} */
|
|
53
|
+
const readOpts = {};
|
|
54
|
+
if (typeof deps.isTabBusy === 'function') readOpts.isTabBusy = deps.isTabBusy;
|
|
55
|
+
if (typeof deps.listJobs === 'function') readOpts.listJobs = deps.listJobs;
|
|
56
|
+
if (typeof deps.projectRoots === 'function') readOpts.projectRoots = deps.projectRoots;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {any} schema @param {any} query @param {any} res
|
|
60
|
+
* @param {(input: any) => boolean} [cwdOptional] true when this input may omit cwd
|
|
61
|
+
*/
|
|
62
|
+
function parseQuery(schema, query, res, cwdOptional) {
|
|
63
|
+
let input;
|
|
64
|
+
try {
|
|
65
|
+
input = schema.parse(Object.fromEntries(query ?? []));
|
|
66
|
+
} catch (e) {
|
|
67
|
+
sendJson(res, 400, { ok: false, error: 'invalid query', details: e?.issues ?? e?.message });
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
if (input.cwd === undefined && cwdOptional && cwdOptional(input)) return input;
|
|
71
|
+
const problem = projectProblem(input.cwd);
|
|
72
|
+
if (problem) {
|
|
73
|
+
sendJson(res, 400, { ok: false, error: problem });
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
return input;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
adminHttp.registerRoute('GET', '/admin/epics', async (/** @type {any} */ req, /** @type {any} */ res, /** @type {any} */ query) => {
|
|
80
|
+
const input = parseQuery(schemas.adminListEpicsQuery, query, res);
|
|
81
|
+
if (!input) return;
|
|
82
|
+
const { epics, total, limit, offset, hasMore } = await listOpenEpicRecords(input.cwd, {
|
|
83
|
+
...readOpts,
|
|
84
|
+
state: input.state,
|
|
85
|
+
limit: input.limit,
|
|
86
|
+
offset: input.offset,
|
|
87
|
+
});
|
|
88
|
+
sendJson(res, 200, { ok: true, epics, total, limit, offset, hasMore });
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
adminHttp.registerRoute('GET', '/admin/epic', async (/** @type {any} */ req, /** @type {any} */ res, /** @type {any} */ query) => {
|
|
92
|
+
const input = parseQuery(schemas.adminGetEpicQuery, query, res, (v) => v.id !== undefined);
|
|
93
|
+
if (!input) return;
|
|
94
|
+
let cwd = input.cwd;
|
|
95
|
+
if (cwd === undefined) {
|
|
96
|
+
const found = findEpicProject(input.id, readOpts.projectRoots ? { projectRoots: /** @type {() => string[]} */ (readOpts.projectRoots) } : {});
|
|
97
|
+
if (found && 'ambiguous' in found) {
|
|
98
|
+
sendJson(res, 409, { ok: false, error: 'ambiguous epic id', cwds: found.ambiguous });
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (!found) {
|
|
102
|
+
sendJson(res, 404, { ok: false, error: 'not found' });
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
cwd = found.cwd;
|
|
106
|
+
}
|
|
107
|
+
const epic = await getEpicRecord(cwd, {
|
|
108
|
+
...readOpts,
|
|
109
|
+
id: input.id,
|
|
110
|
+
externalRef: input.externalRef,
|
|
111
|
+
receipt: input.receipt === true,
|
|
112
|
+
});
|
|
113
|
+
if (!epic) {
|
|
114
|
+
sendJson(res, 404, { ok: false, error: 'not found' });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
sendJson(res, 200, { ok: true, epic });
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
module.exports = { registerAdminRoute };
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* epicJobReceipt.cjs — sums the scheduler run metadata (`<runId>/<slug>.meta.json`)
|
|
3
|
+
* of one Epic's PRDs, every attempt included, into a cost/usage receipt.
|
|
4
|
+
*
|
|
5
|
+
* Complexity: one listing per run dir since sinceMs; only wanted meta files that exist are
|
|
6
|
+
* opened. Never rejects: a missing runs dir, unreadable run dir or malformed meta file is skipped.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const fsp = require('node:fs/promises');
|
|
12
|
+
const path = require('node:path');
|
|
13
|
+
const { runIdToMs } = require('../../loopEfficiencyHandlers.cjs');
|
|
14
|
+
|
|
15
|
+
const META_SUFFIX = '.meta.json';
|
|
16
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
17
|
+
|
|
18
|
+
async function readJson(p) {
|
|
19
|
+
try { return JSON.parse(await fsp.readFile(p, 'utf8')); } catch { return null; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {{ cwd: string, slugs: string[], sinceMs?: number, runsRoot?: string }} opts
|
|
24
|
+
* @returns {Promise<{ runs: number, costUsd: number, costKnownRuns: number, outputTokens: number,
|
|
25
|
+
* numTurns: number, durationMs: number,
|
|
26
|
+
* byPrd: Array<{ slug: string, runs: number, costUsd: number, lastExitCode: number|null, lastFinishedAt: number|null }> }>}
|
|
27
|
+
*/
|
|
28
|
+
async function gatherEpicJobReceipt({ cwd, slugs, sinceMs, runsRoot } = /** @type {any} */ ({})) {
|
|
29
|
+
const out = { runs: 0, costUsd: 0, costKnownRuns: 0, outputTokens: 0, numTurns: 0, durationMs: 0, byPrd: [] };
|
|
30
|
+
try {
|
|
31
|
+
const root = runsRoot || require('../scheduler/schedulerPaths.cjs').runsDir();
|
|
32
|
+
const since = typeof sinceMs === 'number' && Number.isFinite(sinceMs) ? sinceMs : -Infinity;
|
|
33
|
+
// Slugs name files inside a run dir — reject anything that could escape it.
|
|
34
|
+
const wanted = new Set((Array.isArray(slugs) ? slugs : [])
|
|
35
|
+
.filter((s) => typeof s === 'string' && s && !s.includes('/') && !s.includes('\\') && s !== '.' && s !== '..'));
|
|
36
|
+
/** @type {Map<string, { slug: string, runs: number, costUsd: number, lastExitCode: number|null, lastFinishedAt: number|null, lastAt: number }>} */
|
|
37
|
+
const per = new Map();
|
|
38
|
+
|
|
39
|
+
let dirs = [];
|
|
40
|
+
try { dirs = await fsp.readdir(root); } catch { /* no runs dir */ }
|
|
41
|
+
|
|
42
|
+
for (const runId of dirs) {
|
|
43
|
+
const t = runIdToMs(runId);
|
|
44
|
+
if (!Number.isFinite(t) || t < since) continue;
|
|
45
|
+
const runDir = path.join(root, runId);
|
|
46
|
+
let files;
|
|
47
|
+
try { files = await fsp.readdir(runDir); } catch { continue; }
|
|
48
|
+
for (const f of files) {
|
|
49
|
+
if (!f.endsWith(META_SUFFIX)) continue;
|
|
50
|
+
// Slug comes from the filename and must be in the guarded wanted set.
|
|
51
|
+
const slug = f.slice(0, -META_SUFFIX.length);
|
|
52
|
+
if (!wanted.has(slug)) continue;
|
|
53
|
+
const meta = await readJson(path.join(runDir, f));
|
|
54
|
+
if (!meta || typeof meta !== 'object' || meta.cwd !== cwd) continue;
|
|
55
|
+
let row = per.get(slug);
|
|
56
|
+
if (!row) {
|
|
57
|
+
row = { slug, runs: 0, costUsd: 0, lastExitCode: null, lastFinishedAt: null, lastAt: -Infinity };
|
|
58
|
+
per.set(slug, row);
|
|
59
|
+
}
|
|
60
|
+
out.runs += 1;
|
|
61
|
+
row.runs += 1;
|
|
62
|
+
if (typeof meta.totalCostUsd === 'number' && Number.isFinite(meta.totalCostUsd)) {
|
|
63
|
+
out.costUsd += meta.totalCostUsd;
|
|
64
|
+
out.costKnownRuns += 1;
|
|
65
|
+
row.costUsd += meta.totalCostUsd;
|
|
66
|
+
}
|
|
67
|
+
out.outputTokens += num(meta.outputTokens);
|
|
68
|
+
out.numTurns += num(meta.numTurns);
|
|
69
|
+
out.durationMs += num(meta.durationMs);
|
|
70
|
+
const finishedAt = typeof meta.finishedAt === 'number' ? meta.finishedAt : null;
|
|
71
|
+
const at = finishedAt != null ? finishedAt : t;
|
|
72
|
+
if (at >= row.lastAt) {
|
|
73
|
+
row.lastAt = at;
|
|
74
|
+
row.lastExitCode = typeof meta.exitCode === 'number' ? meta.exitCode : null;
|
|
75
|
+
row.lastFinishedAt = finishedAt;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
out.byPrd = [...per.values()]
|
|
81
|
+
.sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))
|
|
82
|
+
.map(({ slug, runs, costUsd, lastExitCode, lastFinishedAt }) => ({ slug, runs, costUsd, lastExitCode, lastFinishedAt }));
|
|
83
|
+
} catch { /* never reject — return what was gathered */ }
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { gatherEpicJobReceipt };
|
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* epicOutsideRead.cjs — the record an outside app reads for one Epic.
|
|
5
|
+
*
|
|
6
|
+
* Joins the project's active index (or, for a completed Epic, its archive
|
|
7
|
+
* file), the scheduler job rows, the awaiting-input reader and
|
|
8
|
+
* computeEpicOutsideState into one plain record. Read-only; every read is
|
|
9
|
+
* guarded so a broken file yields null or an empty list, and nothing throws.
|
|
10
|
+
*
|
|
11
|
+
* Scheduler + chat liveness come in as injected functions (listJobs,
|
|
12
|
+
* isTabBusy) with safe defaults (no jobs, never busy) so this module needs no
|
|
13
|
+
* running scheduler. Open-Epic reads (active index) skip the registration
|
|
14
|
+
* check: it enumerates ~/.claude/projects (11k+ dirs, ~21 s cold). Only the
|
|
15
|
+
* archive path checks it, because readArchived requires a registered project,
|
|
16
|
+
* so a completed Epic in an unregistered project reads as nothing.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const path = require('node:path');
|
|
20
|
+
const { readActiveIndex } = require('./epicMint.cjs');
|
|
21
|
+
const { computeEpicOutsideState, knownPrdSlugs } = require('./epicOutsideState.cjs');
|
|
22
|
+
const { findEpicByExternalRef } = require('./externalRefIndex.cjs');
|
|
23
|
+
const { awaitingInputSessions } = require('../../exchanges.cjs');
|
|
24
|
+
const { readArchived, defaultProjectRoots, makeRegisteredRootsCache } = require('../../promptSessionsIpc.cjs');
|
|
25
|
+
const { gatherEpicJobReceipt } = require('./epicJobReceipt.cjs');
|
|
26
|
+
const { summarizeTranscriptFile } = require('./transcriptUsage.cjs');
|
|
27
|
+
const { resolveEpicTranscriptPath } = require('./epicTranscriptPath.cjs');
|
|
28
|
+
const { isSafeEpicId } = require('../prd/prdLocations.cjs');
|
|
29
|
+
const fs = require('node:fs');
|
|
30
|
+
const { opsPath } = require('../opsOwnership.cjs');
|
|
31
|
+
const { readJsonOrSync } = require('../util/atomicFs.cjs');
|
|
32
|
+
const { parseValidatorVerdict } = require('../scheduler/validatorVerdictSchema.cjs');
|
|
33
|
+
const { bareSlug } = require('../prd/depSlugResolve.cjs');
|
|
34
|
+
|
|
35
|
+
const DEFAULT_LIMIT = 50;
|
|
36
|
+
const MAX_LIMIT = 200;
|
|
37
|
+
const OPEN_STATUSES = new Set(['proposed', 'active']);
|
|
38
|
+
|
|
39
|
+
const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
40
|
+
const str = (v) => (typeof v === 'string' && v !== '' ? v : null);
|
|
41
|
+
const norm = (p) => path.resolve(String(p)).replace(/[\\/]+$/, '');
|
|
42
|
+
|
|
43
|
+
let defaultRootsCache = null;
|
|
44
|
+
|
|
45
|
+
/** Same rule as promptSessionsIpc's assertRegistered, but answers a boolean. */
|
|
46
|
+
function isRegistered(cwd, projectRoots) {
|
|
47
|
+
try {
|
|
48
|
+
if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) return false;
|
|
49
|
+
const { projectRootOf } = require('../activeSessions.cjs');
|
|
50
|
+
const want = norm(projectRootOf(cwd) || cwd);
|
|
51
|
+
if (projectRoots === defaultProjectRoots) {
|
|
52
|
+
if (!defaultRootsCache) defaultRootsCache = makeRegisteredRootsCache(defaultProjectRoots);
|
|
53
|
+
return defaultRootsCache.has(want);
|
|
54
|
+
}
|
|
55
|
+
for (const r of projectRoots() || []) {
|
|
56
|
+
if (typeof r !== 'string' || !r) continue;
|
|
57
|
+
if (norm(r) === want || norm(projectRootOf(r) || r) === want) return true;
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const DEFAULT_ROOTS_TTL_MS = 10000;
|
|
66
|
+
let defaultRootsList = null;
|
|
67
|
+
let defaultRootsListAt = 0;
|
|
68
|
+
|
|
69
|
+
/** The registered roots, each folded to its project root and de-duplicated. */
|
|
70
|
+
function registeredRoots(projectRoots) {
|
|
71
|
+
let raw;
|
|
72
|
+
if (projectRoots === defaultProjectRoots) {
|
|
73
|
+
if (!defaultRootsList || Date.now() - defaultRootsListAt >= DEFAULT_ROOTS_TTL_MS) {
|
|
74
|
+
defaultRootsList = defaultProjectRoots() || [];
|
|
75
|
+
defaultRootsListAt = Date.now();
|
|
76
|
+
}
|
|
77
|
+
raw = defaultRootsList;
|
|
78
|
+
} else {
|
|
79
|
+
raw = projectRoots() || [];
|
|
80
|
+
}
|
|
81
|
+
const { projectRootOf } = require('../activeSessions.cjs');
|
|
82
|
+
const out = new Set();
|
|
83
|
+
for (const r of raw) {
|
|
84
|
+
if (typeof r !== 'string' || !r || !path.isAbsolute(r)) continue;
|
|
85
|
+
out.add(norm(projectRootOf(r) || r));
|
|
86
|
+
}
|
|
87
|
+
return [...out];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Which registered project holds this Epic — open in its active index, or
|
|
92
|
+
* completed in its per-Epic archive. { cwd } on one match, { ambiguous: cwds }
|
|
93
|
+
* on several, null on none or an unsafe id. Reads only each root's
|
|
94
|
+
* prompt-sessions/ folder; never throws.
|
|
95
|
+
*
|
|
96
|
+
* @param {string} epicId
|
|
97
|
+
* @param {{ projectRoots?: () => string[] }} [opts]
|
|
98
|
+
* @returns {{ cwd: string } | { ambiguous: string[] } | null}
|
|
99
|
+
*/
|
|
100
|
+
function findEpicProject(epicId, opts = {}) {
|
|
101
|
+
try {
|
|
102
|
+
if (!isSafeEpicId(epicId)) return null;
|
|
103
|
+
const { projectRoots = defaultProjectRoots } = isObj(opts) ? opts : {};
|
|
104
|
+
const hits = [];
|
|
105
|
+
for (const root of registeredRoots(projectRoots)) {
|
|
106
|
+
try {
|
|
107
|
+
if (openSession(readActiveIndex(root), epicId) || archivedEntry(root, epicId, projectRoots)) hits.push(root);
|
|
108
|
+
} catch { /* this root holds nothing readable */ }
|
|
109
|
+
}
|
|
110
|
+
if (hits.length === 0) return null;
|
|
111
|
+
if (hits.length === 1) return { cwd: hits[0] };
|
|
112
|
+
return { ambiguous: hits.sort() };
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function loadJobs(listJobs) {
|
|
119
|
+
try {
|
|
120
|
+
const out = await listJobs();
|
|
121
|
+
if (Array.isArray(out)) return out;
|
|
122
|
+
if (isObj(out) && Array.isArray(out.jobs)) return out.jobs;
|
|
123
|
+
} catch { /* no jobs */ }
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function loadAwaiting(cwd) {
|
|
128
|
+
try {
|
|
129
|
+
const set = await awaitingInputSessions(cwd);
|
|
130
|
+
return set instanceof Set ? set : new Set();
|
|
131
|
+
} catch {
|
|
132
|
+
return new Set();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function busy(isTabBusy, epicId) {
|
|
137
|
+
try {
|
|
138
|
+
return (await isTabBusy(epicId)) === true;
|
|
139
|
+
} catch {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** goalText split at the first blank line → { title, goal }; absent parts are null. */
|
|
145
|
+
function splitGoal(goalText) {
|
|
146
|
+
if (typeof goalText !== 'string') return { title: null, goal: null };
|
|
147
|
+
const m = /\r?\n[ \t]*\r?\n/.exec(goalText);
|
|
148
|
+
const head = (m ? goalText.slice(0, m.index) : goalText).trim();
|
|
149
|
+
const tail = m ? goalText.slice(m.index + m[0].length).trim() : '';
|
|
150
|
+
return { title: head || null, goal: tail || null };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const atMs = (v) => (typeof v === 'string' ? Date.parse(v) : NaN);
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Checked validator verdicts for an Epic, from the scheduler's
|
|
157
|
+
* plan-records/<epicId>/*.verdicts.json files ({ validator, runId, at,
|
|
158
|
+
* schedulerVerdict, verdicts }). Newest `at` per bare PRD slug wins (a file
|
|
159
|
+
* with no parseable `at` loses to any dated one; later file name wins a tie);
|
|
160
|
+
* sorted by prd. Unreadable or invalid files are skipped; a missing folder
|
|
161
|
+
* gives []. Read-only; never throws.
|
|
162
|
+
*
|
|
163
|
+
* @param {string} cwd
|
|
164
|
+
* @param {string} epicId
|
|
165
|
+
* @returns {{ prd: string, verdict: string, reason: string, criteria: any[], findings: any[], validator: string|null, at: string|null }[]}
|
|
166
|
+
*/
|
|
167
|
+
function readVerdictFiles(cwd, epicId) {
|
|
168
|
+
try {
|
|
169
|
+
if (!isSafeEpicId(epicId)) return [];
|
|
170
|
+
const dir = opsPath(cwd, 'plan-records', epicId);
|
|
171
|
+
let names;
|
|
172
|
+
try { names = fs.readdirSync(dir); } catch { return []; }
|
|
173
|
+
const best = new Map(); // bare -> { entry, t }
|
|
174
|
+
for (const name of names.filter((n) => n.endsWith('.verdicts.json')).sort()) {
|
|
175
|
+
const data = readJsonOrSync(path.join(dir, name), null);
|
|
176
|
+
if (!isObj(data)) continue;
|
|
177
|
+
const input = { schedulerVerdict: data.schedulerVerdict, verdicts: data.verdicts };
|
|
178
|
+
if (typeof data.failReason === 'string') input.failReason = data.failReason;
|
|
179
|
+
const parsed = parseValidatorVerdict(input);
|
|
180
|
+
if (!parsed.ok) continue;
|
|
181
|
+
const fileAt = str(data.at);
|
|
182
|
+
const t = atMs(fileAt);
|
|
183
|
+
for (const v of parsed.value.verdicts) {
|
|
184
|
+
const bare = bareSlug(v.prd);
|
|
185
|
+
const prev = best.get(bare);
|
|
186
|
+
const newer = !prev
|
|
187
|
+
|| (Number.isFinite(t) && (!Number.isFinite(prev.t) || t >= prev.t))
|
|
188
|
+
|| (!Number.isFinite(t) && !Number.isFinite(prev.t));
|
|
189
|
+
if (!newer) continue;
|
|
190
|
+
best.set(bare, {
|
|
191
|
+
t,
|
|
192
|
+
entry: {
|
|
193
|
+
prd: bare,
|
|
194
|
+
verdict: v.verdict,
|
|
195
|
+
reason: v.reason,
|
|
196
|
+
criteria: v.criteria,
|
|
197
|
+
findings: v.findings,
|
|
198
|
+
validator: str(data.validator),
|
|
199
|
+
at: fileAt,
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return [...best.values()].map((b) => b.entry).sort((a, b) => (a.prd < b.prd ? -1 : a.prd > b.prd ? 1 : 0));
|
|
205
|
+
} catch {
|
|
206
|
+
return [];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function buildRecord(cwd, epicId, session, events, jobs, needsInput, chatBusy) {
|
|
211
|
+
const computed = computeEpicOutsideState({ session: { ...session, id: epicId }, events, jobs, needsInput, chatBusy });
|
|
212
|
+
const source = isObj(session.source) ? session.source : {};
|
|
213
|
+
const { title, goal } = splitGoal(session.goalText);
|
|
214
|
+
return {
|
|
215
|
+
epicId,
|
|
216
|
+
cwd: str(session.cwd) || cwd,
|
|
217
|
+
title,
|
|
218
|
+
goal,
|
|
219
|
+
tag: str(session.tag),
|
|
220
|
+
agentType: str(session.agentType),
|
|
221
|
+
status: str(session.status),
|
|
222
|
+
state: computed.state,
|
|
223
|
+
blocked: computed.blocked,
|
|
224
|
+
prds: computed.prds,
|
|
225
|
+
verified: computed.verified,
|
|
226
|
+
refuted: computed.refuted,
|
|
227
|
+
unvalidated: computed.unvalidated,
|
|
228
|
+
externalRef: str(source.externalRef),
|
|
229
|
+
source: {
|
|
230
|
+
producer: str(source.producer),
|
|
231
|
+
fromCwd: str(source.fromCwd),
|
|
232
|
+
fromEpicId: str(source.fromEpicId),
|
|
233
|
+
macroId: str(source.macroId),
|
|
234
|
+
},
|
|
235
|
+
createdAt: str(session.createdAt),
|
|
236
|
+
completedAt: str(session.completedAt),
|
|
237
|
+
verdicts: readVerdictFiles(cwd, epicId),
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function eventsOf(index, epicId) {
|
|
242
|
+
const chain = isObj(index.events) ? index.events[epicId] : null;
|
|
243
|
+
return Array.isArray(chain) ? chain : [];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function openSession(index, epicId) {
|
|
247
|
+
const s = isObj(index.sessions) && Object.prototype.hasOwnProperty.call(index.sessions, epicId)
|
|
248
|
+
? index.sessions[epicId]
|
|
249
|
+
: null;
|
|
250
|
+
return isObj(s) && OPEN_STATUSES.has(s.status) ? s : null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function openRecord(cwd, epicId, session, index, jobs, awaiting, isTabBusy) {
|
|
254
|
+
const claudeSessionId = str(session.claudeSessionId);
|
|
255
|
+
const needsInput = claudeSessionId != null && awaiting.has(claudeSessionId);
|
|
256
|
+
const chatBusy = await busy(isTabBusy, epicId);
|
|
257
|
+
return buildRecord(cwd, epicId, session, eventsOf(index, epicId), jobs, needsInput, chatBusy);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** The archived (completed) session + its events, or null (also for an unregistered project). */
|
|
261
|
+
function archivedEntry(cwd, epicId, projectRoots) {
|
|
262
|
+
try {
|
|
263
|
+
if (!isRegistered(cwd, projectRoots)) return null;
|
|
264
|
+
const res = readArchived(cwd, epicId, { projectRoots });
|
|
265
|
+
const data = res && res.exists ? res.data : null;
|
|
266
|
+
if (!isObj(data) || !str(data.archivedAt) || !isObj(data.session)) return null;
|
|
267
|
+
return {
|
|
268
|
+
session: { ...data.session, status: 'completed' },
|
|
269
|
+
events: Array.isArray(data.events) ? data.events : [],
|
|
270
|
+
};
|
|
271
|
+
} catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Job-run cost for every PRD the Epic is known to have (live rows + check-ins
|
|
278
|
+
* on its chain, so finished PRDs whose rows are gone still count) since the
|
|
279
|
+
* session was created; null on failure.
|
|
280
|
+
*/
|
|
281
|
+
async function jobsReceipt(cwd, epicId, session, events, jobs, runsRoot) {
|
|
282
|
+
try {
|
|
283
|
+
const slugs = knownPrdSlugs({ session: { ...session, id: epicId }, events, jobs });
|
|
284
|
+
const created = Date.parse(session.createdAt);
|
|
285
|
+
return await gatherEpicJobReceipt({
|
|
286
|
+
cwd,
|
|
287
|
+
slugs,
|
|
288
|
+
sinceMs: Number.isFinite(created) ? created : undefined,
|
|
289
|
+
runsRoot,
|
|
290
|
+
});
|
|
291
|
+
} catch {
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Token usage of the Epic's chat transcript; null when no file is found or on failure. */
|
|
297
|
+
async function chatReceipt(cwd, session, resolveTranscriptPath) {
|
|
298
|
+
try {
|
|
299
|
+
const claudeSessionId = str(session.claudeSessionId);
|
|
300
|
+
if (!claudeSessionId) return null;
|
|
301
|
+
const hit = resolveTranscriptPath({ cwd, claudeSessionId });
|
|
302
|
+
// The real resolver hands back its first candidate even when nothing exists.
|
|
303
|
+
if (!isObj(hit) || !str(hit.path) || hit.existsAnywhere === false) return null;
|
|
304
|
+
return await summarizeTranscriptFile(hit.path);
|
|
305
|
+
} catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function buildReceipt(cwd, epicId, session, events, jobs, runsRoot, resolveTranscriptPath) {
|
|
311
|
+
const [jobsPart, chatPart] = await Promise.all([
|
|
312
|
+
jobsReceipt(cwd, epicId, session, events, jobs, runsRoot),
|
|
313
|
+
chatReceipt(cwd, session, resolveTranscriptPath),
|
|
314
|
+
]);
|
|
315
|
+
return { jobs: jobsPart, chat: chatPart };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* One Epic by id or externalRef: open from the active index, else completed
|
|
320
|
+
* from its archive file (only when archivedAt is set). Null on no match.
|
|
321
|
+
*
|
|
322
|
+
* `receipt: true` adds `receipt: { jobs, chat }` — jobs = gatherEpicJobReceipt
|
|
323
|
+
* over the Epic's known PRD slugs (knownPrdSlugs) since createdAt, chat = summarizeTranscriptFile of
|
|
324
|
+
* the resolved transcript (null when none). Each part is null on failure.
|
|
325
|
+
* Without it no run folder or transcript is read. `runsRoot` and
|
|
326
|
+
* `resolveTranscriptPath` are injectable for tests.
|
|
327
|
+
*
|
|
328
|
+
* @param {string} cwd
|
|
329
|
+
* @param {{ id?: string, externalRef?: string, receipt?: boolean, isTabBusy?: (epicId: string) => boolean | Promise<boolean>, listJobs?: () => any, projectRoots?: () => string[], runsRoot?: string, resolveTranscriptPath?: (a: { cwd: string, claudeSessionId: string }) => any }} [opts]
|
|
330
|
+
*/
|
|
331
|
+
async function getEpicRecord(cwd, opts = {}) {
|
|
332
|
+
try {
|
|
333
|
+
const {
|
|
334
|
+
id, externalRef, receipt,
|
|
335
|
+
isTabBusy = () => false,
|
|
336
|
+
listJobs = () => [],
|
|
337
|
+
projectRoots = defaultProjectRoots,
|
|
338
|
+
runsRoot,
|
|
339
|
+
resolveTranscriptPath = resolveEpicTranscriptPath,
|
|
340
|
+
} = isObj(opts) ? opts : {};
|
|
341
|
+
if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) return null;
|
|
342
|
+
|
|
343
|
+
let epicId = str(id);
|
|
344
|
+
if (!epicId && str(externalRef)) {
|
|
345
|
+
const hit = await findEpicByExternalRef({ cwd, externalRef });
|
|
346
|
+
epicId = hit ? str(hit.epicId) : null;
|
|
347
|
+
}
|
|
348
|
+
if (!epicId) return null;
|
|
349
|
+
|
|
350
|
+
const index = readActiveIndex(cwd);
|
|
351
|
+
const open = openSession(index, epicId);
|
|
352
|
+
const jobs = await loadJobs(listJobs);
|
|
353
|
+
let session;
|
|
354
|
+
let events;
|
|
355
|
+
let record;
|
|
356
|
+
if (open) {
|
|
357
|
+
session = open;
|
|
358
|
+
events = eventsOf(index, epicId);
|
|
359
|
+
const awaiting = await loadAwaiting(cwd);
|
|
360
|
+
record = await openRecord(cwd, epicId, open, index, jobs, awaiting, isTabBusy);
|
|
361
|
+
} else {
|
|
362
|
+
const archived = archivedEntry(cwd, epicId, projectRoots);
|
|
363
|
+
if (!archived) return null;
|
|
364
|
+
session = archived.session;
|
|
365
|
+
events = archived.events;
|
|
366
|
+
record = buildRecord(cwd, epicId, session, archived.events, jobs, false, false);
|
|
367
|
+
}
|
|
368
|
+
if (receipt !== true) return record;
|
|
369
|
+
return { ...record, receipt: await buildReceipt(cwd, epicId, session, events, jobs, runsRoot, resolveTranscriptPath) };
|
|
370
|
+
} catch {
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function clampInt(v, dflt, min, max) {
|
|
376
|
+
const n = Number(v);
|
|
377
|
+
if (!Number.isFinite(n)) return dflt;
|
|
378
|
+
return Math.min(max, Math.max(min, Math.floor(n)));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* A project's open (proposed/active) Epics, newest createdAt first.
|
|
383
|
+
*
|
|
384
|
+
* @param {string} cwd
|
|
385
|
+
* @param {{ state?: string, limit?: number, offset?: number, isTabBusy?: (epicId: string) => boolean | Promise<boolean>, listJobs?: () => any, projectRoots?: () => string[] }} [opts]
|
|
386
|
+
*/
|
|
387
|
+
async function listOpenEpicRecords(cwd, opts = {}) {
|
|
388
|
+
const o = isObj(opts) ? opts : {};
|
|
389
|
+
const limit = o.limit == null ? DEFAULT_LIMIT : clampInt(o.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
|
|
390
|
+
const offset = o.offset == null ? 0 : clampInt(o.offset, 0, 0, Number.MAX_SAFE_INTEGER);
|
|
391
|
+
const empty = { epics: [], total: 0, limit, offset, hasMore: false };
|
|
392
|
+
try {
|
|
393
|
+
const {
|
|
394
|
+
state,
|
|
395
|
+
isTabBusy = () => false,
|
|
396
|
+
listJobs = () => [],
|
|
397
|
+
} = o;
|
|
398
|
+
if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) return empty;
|
|
399
|
+
|
|
400
|
+
const index = readActiveIndex(cwd);
|
|
401
|
+
const open = [];
|
|
402
|
+
for (const epicId of Object.keys(isObj(index.sessions) ? index.sessions : {})) {
|
|
403
|
+
const s = openSession(index, epicId);
|
|
404
|
+
if (s) open.push([epicId, s]);
|
|
405
|
+
}
|
|
406
|
+
const t = (s) => { const n = Date.parse(s.createdAt); return Number.isFinite(n) ? n : -Infinity; };
|
|
407
|
+
open.sort((a, b) => t(b[1]) - t(a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
|
|
408
|
+
|
|
409
|
+
const jobs = await loadJobs(listJobs);
|
|
410
|
+
const awaiting = await loadAwaiting(cwd);
|
|
411
|
+
const records = [];
|
|
412
|
+
for (const [epicId, s] of open) {
|
|
413
|
+
records.push(await openRecord(cwd, epicId, s, index, jobs, awaiting, isTabBusy));
|
|
414
|
+
}
|
|
415
|
+
const filtered = typeof state === 'string' && state ? records.filter((r) => r.state === state) : records;
|
|
416
|
+
const epics = filtered.slice(offset, offset + limit);
|
|
417
|
+
return { epics, total: filtered.length, limit, offset, hasMore: offset + epics.length < filtered.length };
|
|
418
|
+
} catch {
|
|
419
|
+
return empty;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
module.exports = { readVerdictFiles, listOpenEpicRecords, getEpicRecord, findEpicProject };
|