skillar 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/NOTICE +280 -0
  2. package/README.md +37 -5
  3. package/dist/analysis/finding.js +8 -190
  4. package/dist/analysis/kernel.js +896 -0
  5. package/dist/analysis/tree.js +7 -154
  6. package/dist/analysis/usage.js +9 -394
  7. package/dist/api/flows.js +42 -212
  8. package/dist/api/report-kernel.js +1063 -0
  9. package/dist/api/routes.js +12 -2
  10. package/dist/catalog/fields.js +138 -146
  11. package/dist/catalog/watcher.js +7 -2
  12. package/dist/cli/init.js +45 -0
  13. package/dist/cli/main.js +76 -3
  14. package/dist/cli/private-skills.js +122 -0
  15. package/dist/cli/serve.js +15 -1
  16. package/dist/cli/sync.js +124 -0
  17. package/dist/dashboard/NOTICE +280 -0
  18. package/dist/dashboard/assets/app.js +737 -275
  19. package/dist/dashboard/assets/astryx-reset.css +407 -0
  20. package/dist/dashboard/assets/astryx.css +1077 -0
  21. package/dist/dashboard/assets/charts.css +54 -0
  22. package/dist/dashboard/assets/chunk-TPGDA2J4.js +1 -0
  23. package/dist/dashboard/assets/chunk-YLWHVDMP.js +36 -0
  24. package/dist/dashboard/assets/controls.css +207 -0
  25. package/dist/dashboard/assets/overlays.css +132 -0
  26. package/dist/dashboard/assets/p1.css +135 -0
  27. package/dist/dashboard/assets/shell.css +71 -0
  28. package/dist/dashboard/assets/skillar-theme.css +692 -0
  29. package/dist/dashboard/assets/styles.css +224 -121
  30. package/dist/dashboard/assets/tokens.css +278 -0
  31. package/dist/dashboard/assets/widgets.css +83 -0
  32. package/dist/dashboard/index.html +11 -2
  33. package/dist/dashboard/viewers/viewers.css +61 -0
  34. package/dist/ingest/attribution.js +5 -1
  35. package/dist/ingest/pipeline.js +2 -0
  36. package/dist/ingest/request-recorder.js +39 -0
  37. package/dist/mcp/dispatch.js +2 -2
  38. package/dist/mcp/http.js +43 -3
  39. package/dist/mcp/skills-extension.js +42 -15
  40. package/dist/mcp/stdio-proxy.js +24 -3
  41. package/dist/mcp/tools.js +38 -24
  42. package/dist/packs/claude-code.js +22 -11
  43. package/dist/packs/cursor.js +9 -4
  44. package/dist/packs/gemini.js +9 -4
  45. package/dist/packs/json-config.js +41 -0
  46. package/dist/packs/omo.js +15 -6
  47. package/dist/request-status.js +81 -0
  48. package/dist/search/fts.js +93 -58
  49. package/dist/search/fusion.js +49 -47
  50. package/dist/search/guidance.js +18 -6
  51. package/dist/search/index.js +291 -70
  52. package/dist/search/lexical.js +71 -63
  53. package/dist/server.js +12 -0
  54. package/dist/skills/apply.js +130 -0
  55. package/dist/skills/capture.js +54 -0
  56. package/dist/skills/cloud-plan.js +57 -0
  57. package/dist/skills/cloud.js +81 -0
  58. package/dist/skills/fs.js +133 -0
  59. package/dist/skills/package.js +734 -0
  60. package/dist/skills/plan.js +83 -0
  61. package/dist/skills/receipt.js +44 -0
  62. package/dist/skills/rollback.js +119 -0
  63. package/dist/skills/transfer.js +51 -0
  64. package/dist/store/db.js +7 -1
  65. package/dist/store/execution.js +2 -34
  66. package/dist/store/export.js +25 -4
  67. package/dist/store/migrations/007_sync.sql +49 -0
  68. package/dist/store/migrations/008_connector_commands.sql +12 -0
  69. package/dist/store/queries.js +33 -7
  70. package/dist/store/writes.js +38 -5
  71. package/dist/sync/cloud-blobs.js +175 -0
  72. package/dist/sync/cloud-commands.js +101 -0
  73. package/dist/sync/cloud-connection.js +105 -0
  74. package/dist/sync/cloud-delivery.js +114 -0
  75. package/dist/sync/cloud-documents.js +103 -0
  76. package/dist/sync/cloud-export.js +67 -0
  77. package/dist/sync/cloud-http.js +150 -0
  78. package/dist/sync/cloud-jobs.js +94 -0
  79. package/dist/sync/cloud-pending.js +143 -0
  80. package/dist/sync/cloud-prepare.js +101 -0
  81. package/dist/sync/cloud-restore.js +136 -0
  82. package/dist/sync/cloud-rollback.js +24 -0
  83. package/dist/sync/cloud-runner.js +86 -0
  84. package/dist/sync/cloud-runtime.js +293 -0
  85. package/dist/sync/cloud-schema.js +32 -0
  86. package/dist/sync/cloud-stage.js +112 -0
  87. package/dist/sync/cloud-wire.js +693 -0
  88. package/dist/sync/cloud-worker.js +57 -0
  89. package/dist/sync/cloud.js +157 -0
  90. package/dist/sync/command-apply.js +140 -0
  91. package/dist/sync/command-control.js +25 -0
  92. package/dist/sync/command-wire.js +437 -0
  93. package/dist/sync/consent.js +130 -0
  94. package/dist/sync/journal.js +43 -0
  95. package/dist/sync/outbox.js +134 -0
  96. package/dist/sync/restore-rows.js +125 -0
  97. package/dist/sync/restore.js +174 -0
  98. package/dist/sync/snapshot.js +78 -0
  99. package/dist/sync/spool-request.js +103 -0
  100. package/dist/sync/tables.js +27 -0
  101. package/dist/sync/triggers.js +34 -0
  102. package/dist/workflow/compare.js +3 -43
  103. package/docs/cloud-sync.md +94 -0
  104. package/docs/private-skills.md +75 -0
  105. package/docs/sync-p4.md +102 -0
  106. package/docs/sync-restore.md +167 -0
  107. package/package.json +18 -5
  108. package/src/store/migrations/007_sync.sql +49 -0
  109. package/src/store/migrations/008_connector_commands.sql +12 -0
  110. package/dist/dashboard/assets/chunk-5DFWNJC2.js +0 -1
  111. package/dist/dashboard/assets/chunk-S6B2HJQA.js +0 -17
@@ -0,0 +1,1063 @@
1
+ // ../shared/dist/analysis/scope.js
2
+ function scopeSession(session, scope) {
3
+ const { from, to } = scope;
4
+ const end = to ?? Number.MAX_SAFE_INTEGER;
5
+ const owned = new Set(scope.eventIds);
6
+ const inside = (event) => owned.has(event.id);
7
+ const turns = session.turns.flatMap((turn, index) => {
8
+ const events = turn.events.filter(inside);
9
+ if (!events.length)
10
+ return [];
11
+ const original = new Map(events.map((e) => [e.id, e]));
12
+ const endedAt2 = Math.min(end, session.turns[index + 1]?.startedAt ?? session.endedAt ?? (to ?? turn.endedAt));
13
+ const startedAt = Math.max(from, turn.startedAt);
14
+ const scoped = assembleSession({
15
+ id: session.id,
16
+ runtime: session.runtime,
17
+ startedAt,
18
+ endedAt: endedAt2,
19
+ spans: [],
20
+ events: [
21
+ {
22
+ id: `execution-boundary:${turn.id}`,
23
+ ts: startedAt,
24
+ kind: "prompt",
25
+ source: "hook",
26
+ turnKey: turn.id,
27
+ callId: null,
28
+ spanId: null,
29
+ skillUri: null,
30
+ text: null,
31
+ textLength: null,
32
+ data: {}
33
+ },
34
+ ...events.map((e) => ({ ...e, turnKey: turn.id }))
35
+ ]
36
+ }).turns[0];
37
+ if (!scoped)
38
+ return [];
39
+ const restore = (event) => {
40
+ const source = original.get(event.id);
41
+ return source ? { ...event, turnKey: source.turnKey, basis: source.basis } : event;
42
+ };
43
+ return [{
44
+ ...scoped,
45
+ basis: turn.basis,
46
+ events: scoped.events.filter((e) => original.has(e.id)).map(restore),
47
+ skillSpans: scoped.skillSpans.map((span) => ({ ...span, activation: restore(span.activation), events: span.events.map(restore) }))
48
+ }];
49
+ });
50
+ const endedAt = session.endedAt !== null && (session.endedAt < end || session.endedAt === end && scope.sessionEnds?.[session.id] === end) ? session.endedAt : null;
51
+ return {
52
+ ...session,
53
+ endedAt,
54
+ executionWindow: { from, to },
55
+ turns,
56
+ unassignedEvents: session.unassignedEvents.filter(inside)
57
+ };
58
+ }
59
+
60
+ // ../shared/dist/analysis/tree.js
61
+ var PROMPT_JOIN_WINDOW_MS = 5e3;
62
+ function assembleSession(data) {
63
+ const boundaries = /* @__PURE__ */ new Map();
64
+ const add = (id, startedAt, basis) => {
65
+ const old = boundaries.get(id);
66
+ if (!old || startedAt < old.startedAt)
67
+ boundaries.set(id, { id, startedAt, basis });
68
+ };
69
+ if (data.runtime === "codex") {
70
+ for (const span of data.spans) {
71
+ if (span.name === "codex.turn_input" && span.turnKey !== void 0 && span.startMs !== void 0) {
72
+ add(span.turnKey, span.startMs, "reported");
73
+ }
74
+ }
75
+ }
76
+ const prompts = data.events.filter((e) => e.kind === "prompt");
77
+ for (const prompt of prompts) {
78
+ if (prompt.turnKey !== null && !boundaries.has(prompt.turnKey))
79
+ add(prompt.turnKey, prompt.ts, "reported");
80
+ }
81
+ const reportedBoundaries = [...boundaries.values()].sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
82
+ const pairedPrompts = /* @__PURE__ */ new Map();
83
+ if (data.runtime === "claude-code" || data.runtime === "codex") {
84
+ for (const boundary of reportedBoundaries) {
85
+ const reference = prompts.find((p) => p.turnKey === boundary.id);
86
+ const strength = (prompt) => {
87
+ if (!reference)
88
+ return 0;
89
+ if (reference.text !== null && prompt.text !== null && reference.text !== prompt.text)
90
+ return -1;
91
+ const length = reference.textLength ?? reference.data.promptLength;
92
+ const observedLength = prompt.textLength ?? prompt.data.promptLength;
93
+ if (typeof length === "number" && typeof observedLength === "number" && length !== observedLength)
94
+ return -1;
95
+ if (reference.text !== null && prompt.text !== null)
96
+ return 2;
97
+ return typeof length === "number" && length === observedLength ? 1 : 0;
98
+ };
99
+ const match = prompts.filter((p) => p.turnKey === null && !pairedPrompts.has(p.id) && Math.abs(boundary.startedAt - p.ts) <= PROMPT_JOIN_WINDOW_MS && strength(p) >= 0).sort((a, b) => strength(b) - strength(a) || Math.abs(boundary.startedAt - a.ts) - Math.abs(boundary.startedAt - b.ts) || a.ts - b.ts || a.id.localeCompare(b.id))[0];
100
+ if (match)
101
+ pairedPrompts.set(match.id, boundary.id);
102
+ }
103
+ }
104
+ for (const prompt of prompts) {
105
+ if (prompt.turnKey === null && !pairedPrompts.has(prompt.id)) {
106
+ add(`prompt:${prompt.id}`, prompt.ts, "inferred_time");
107
+ }
108
+ }
109
+ const ordered = [...boundaries.values()].sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
110
+ const newestFirst = [...ordered].reverse();
111
+ const byTurn = /* @__PURE__ */ new Map();
112
+ const unassignedEvents = [];
113
+ for (const event of data.events) {
114
+ let key = event.turnKey ?? pairedPrompts.get(event.id) ?? null;
115
+ let basis = "reported";
116
+ if (key === null && event.kind === "tool_call") {
117
+ const joined = data.spans.filter((s) => s.turnKey !== void 0 && (event.callId !== null && s.callId === event.callId || event.spanId !== null && s.spanId === event.spanId && s.traceId === event.data.otelTraceId));
118
+ const keys = new Set(joined.map((s) => s.turnKey));
119
+ if (keys.size === 1)
120
+ key = joined[0]?.turnKey ?? null;
121
+ basis = "span_join";
122
+ }
123
+ if (key === null) {
124
+ key = newestFirst.find((b) => b.startedAt <= event.ts)?.id ?? null;
125
+ basis = "inferred_time";
126
+ }
127
+ if (key === null || !boundaries.has(key)) {
128
+ unassignedEvents.push(event);
129
+ continue;
130
+ }
131
+ const list = byTurn.get(key) ?? [];
132
+ list.push({ event, basis });
133
+ byTurn.set(key, list);
134
+ }
135
+ const lastTs = data.events.at(-1)?.ts ?? data.startedAt;
136
+ const turns = ordered.map((boundary, i) => {
137
+ const endedAt = ordered[i + 1]?.startedAt ?? data.endedAt ?? lastTs;
138
+ const events = [];
139
+ const active = /* @__PURE__ */ new Map();
140
+ for (const { event, basis } of byTurn.get(boundary.id) ?? []) {
141
+ const name = typeof event.data.name === "string" ? event.data.name : "";
142
+ const uri = event.skillUri ?? (typeof event.data.uri === "string" ? event.data.uri : null);
143
+ if (event.kind === "load" || event.kind === "native_skill") {
144
+ const skillName = name || uri?.split("/").at(-2) || "unknown";
145
+ const skill = uri ?? skillName;
146
+ const existing = [...active.values()].find((s) => s.skill === skill || s.name === skillName && (s.uri === null || uri === null));
147
+ if (!existing) {
148
+ const activation = { ...event, basis, attribution: "no_skill", skills: [] };
149
+ active.set(skill, { id: event.id, skill, uri, name: skillName, startedAt: event.ts, endedAt, activation, events: [] });
150
+ } else if (existing.uri === null && uri !== null) {
151
+ existing.uri = uri;
152
+ }
153
+ }
154
+ const reported = event.kind === "llm_call" && typeof event.data.skillName === "string" ? event.data.skillName : null;
155
+ const action = event.kind === "tool_call" || event.kind === "llm_call";
156
+ const skills = reported !== null ? [reported] : action ? [...active.keys()] : [];
157
+ const assigned = {
158
+ ...event,
159
+ basis,
160
+ skills,
161
+ attribution: reported !== null ? "reported" : skills.length > 1 ? "co_active" : skills.length === 1 ? "single" : "no_skill"
162
+ };
163
+ events.push(assigned);
164
+ if (action) {
165
+ for (const span of active.values()) {
166
+ if (reported === null || span.name === reported || span.skill === reported)
167
+ span.events.push(assigned);
168
+ }
169
+ }
170
+ }
171
+ const skillSpans = [...active.values()];
172
+ return { ...boundary, endedAt, events, skillSpans };
173
+ });
174
+ return { id: data.id, runtime: data.runtime, startedAt: data.startedAt, endedAt: data.endedAt, turns, unassignedEvents };
175
+ }
176
+ function sessionTree(store, sessionId) {
177
+ const data = store.treeSessionData(sessionId);
178
+ return data ? assembleSession(data) : void 0;
179
+ }
180
+ function flowTree(store, flowOrWorkspaceId, scope = store.flowEventScope(flowOrWorkspaceId)) {
181
+ const data = store.treeFlowData(flowOrWorkspaceId, scope);
182
+ if (!data)
183
+ return void 0;
184
+ const sessions = /* @__PURE__ */ new Map();
185
+ for (const link of data.links) {
186
+ if (link.sessionId !== null && !sessions.has(link.sessionId)) {
187
+ const input = store.treeSessionData(link.sessionId, scope);
188
+ const session = input ? assembleSession(input) : null;
189
+ sessions.set(link.sessionId, session && scope ? scopeSession(session, scope) : session);
190
+ }
191
+ }
192
+ return {
193
+ id: data.id,
194
+ workspaceId: data.workspaceId,
195
+ label: data.label,
196
+ registered: data.registered,
197
+ tabs: data.tabs.map((tab) => ({ ...tab, panes: data.panes.filter((p) => p.tabId === tab.id).map((pane) => ({
198
+ ...pane,
199
+ sessions: data.links.filter((l) => l.paneId === pane.id).map((link) => ({
200
+ ...link,
201
+ basis: link.source === "inferred:cwd_time" ? "inferred" : "reported",
202
+ session: link.sessionId === null ? null : sessions.get(link.sessionId) ?? null
203
+ }))
204
+ })) }))
205
+ };
206
+ }
207
+
208
+ // ../shared/dist/analysis/finding.js
209
+ var LABELS = [
210
+ "found_top1",
211
+ "found_lower",
212
+ "loaded_outside_results",
213
+ "native_without_search",
214
+ "searched_none_used",
215
+ "no_search"
216
+ ];
217
+ var str = (value) => typeof value === "string" && value !== "" ? value : null;
218
+ var dirOf = (uri) => uri.split("/").at(-2) ?? "";
219
+ function candidateOf(value) {
220
+ if (typeof value !== "object" || value === null)
221
+ return null;
222
+ const row = value;
223
+ const uri = str(row.uri);
224
+ if (uri === null || typeof row.rank !== "number")
225
+ return null;
226
+ return { uri, name: str(row.name) ?? dirOf(uri), rank: row.rank, digest: str(row.digest) ?? "" };
227
+ }
228
+ function abstainedOf(value) {
229
+ if (typeof value !== "object" || value === null)
230
+ return null;
231
+ const row = value;
232
+ const reason = str(row.reason);
233
+ return reason === null ? null : { reason, hint: str(row.hint) ?? "" };
234
+ }
235
+ function collapse(candidates) {
236
+ const byDigest = /* @__PURE__ */ new Map();
237
+ const groups = [];
238
+ for (const candidate of [...candidates].sort((a, b) => a.rank - b.rank || a.uri.localeCompare(b.uri))) {
239
+ const known = candidate.digest === "" ? void 0 : byDigest.get(candidate.digest);
240
+ if (known) {
241
+ known.push(candidate);
242
+ continue;
243
+ }
244
+ const group = [candidate];
245
+ if (candidate.digest !== "")
246
+ byDigest.set(candidate.digest, group);
247
+ groups.push(group);
248
+ }
249
+ return groups.map((members, i) => ({ rank: i + 1, members }));
250
+ }
251
+ function searchOf(event) {
252
+ const raw = Array.isArray(event.data.candidates) ? event.data.candidates : [];
253
+ return {
254
+ query: str(event.data.query) ?? event.text ?? "",
255
+ abstained: abstainedOf(event.data.abstained),
256
+ groups: collapse(raw.flatMap((value) => candidateOf(value) ?? []))
257
+ };
258
+ }
259
+ function usedSkillOf(event, digestOf) {
260
+ if (event.kind !== "load" && event.kind !== "native_skill")
261
+ return null;
262
+ const uri = event.skillUri ?? str(event.data.uri) ?? str(event.data.skillUri);
263
+ const name = str(event.data.name) ?? (uri === null ? "" : dirOf(uri));
264
+ const loadId = str(event.data.loadId);
265
+ return { uri, name, via: event.kind === "load" ? "load" : "native", loadId, digest: digestOf?.({ uri, loadId }) ?? null };
266
+ }
267
+ var matchesUri = (candidate, used) => used.uri !== null && candidate.uri === used.uri;
268
+ var matchesName = (candidate, used) => used.name !== "" && (candidate.name === used.name || dirOf(candidate.uri) === used.name);
269
+ var matches = (candidate, used) => matchesUri(candidate, used) || matchesName(candidate, used);
270
+ function rankIn(search, used) {
271
+ if (search === null)
272
+ return null;
273
+ const byUri = search.groups.find((group) => group.members.some((member) => matchesUri(member, used)));
274
+ if (byUri)
275
+ return byUri.rank;
276
+ const byDigest = used.digest === null ? void 0 : search.groups.find((group) => group.members.some((member) => member.digest === used.digest));
277
+ if (byDigest)
278
+ return byDigest.rank;
279
+ if (used.uri !== null)
280
+ return null;
281
+ const named = search.groups.filter((group) => group.members.some((member) => matchesName(member, used)));
282
+ return named.length === 1 ? named[0].rank : null;
283
+ }
284
+ function labelOf(searched, used, nativeWithoutSearch) {
285
+ if (used.some((skill) => skill.rankInSearch === 1))
286
+ return "found_top1";
287
+ if (used.some((skill) => skill.rankInSearch !== null))
288
+ return "found_lower";
289
+ if (nativeWithoutSearch)
290
+ return "native_without_search";
291
+ if (used.length > 0)
292
+ return "loaded_outside_results";
293
+ return searched ? "searched_none_used" : "no_search";
294
+ }
295
+ function analyzeTurn(turn, later = [], digestOf) {
296
+ const searches = [];
297
+ const used = [];
298
+ const abstentions = [];
299
+ let latest = null;
300
+ let nativeWithoutSearch = false;
301
+ for (const event of turn.events) {
302
+ if (event.kind === "search") {
303
+ latest = searchOf(event);
304
+ searches.push(latest);
305
+ if (latest.abstained !== null)
306
+ abstentions.push(latest.abstained);
307
+ continue;
308
+ }
309
+ const skill = usedSkillOf(event, digestOf);
310
+ if (skill === null)
311
+ continue;
312
+ if (skill.via === "native" && latest === null)
313
+ nativeWithoutSearch = true;
314
+ used.push({ uri: skill.uri, name: skill.name, via: skill.via, ts: event.ts, rankInSearch: rankIn(latest, skill) });
315
+ }
316
+ const candidates = /* @__PURE__ */ new Map();
317
+ for (const search of searches) {
318
+ for (const group of search.groups) {
319
+ for (const member of group.members) {
320
+ candidates.set(member.uri, { uri: member.uri, name: member.name, rank: group.rank, rawRank: member.rank, copies: group.members.length });
321
+ }
322
+ }
323
+ }
324
+ const surfaced = searches.flatMap((search) => search.groups.flatMap((group) => group.members));
325
+ const missedLater = /* @__PURE__ */ new Map();
326
+ if (searches.length > 0) {
327
+ for (const next of later) {
328
+ for (const event of next.events) {
329
+ const skill = usedSkillOf(event);
330
+ if (skill === null || surfaced.some((candidate) => matches(candidate, skill)))
331
+ continue;
332
+ const key = skill.uri ?? skill.name;
333
+ if (!missedLater.has(key))
334
+ missedLater.set(key, { uri: skill.uri, name: skill.name, via: skill.via, turnId: next.id, ts: event.ts });
335
+ }
336
+ }
337
+ }
338
+ return {
339
+ turnId: turn.id,
340
+ searched: searches.length > 0,
341
+ queries: searches.map((search) => search.query),
342
+ candidates: [...candidates.values()].sort((a, b) => a.rank - b.rank || a.rawRank - b.rawRank || a.uri.localeCompare(b.uri)),
343
+ loadedSkills: used,
344
+ abstained: abstentions.length > 0,
345
+ abstentions,
346
+ nativeWithoutSearch,
347
+ missedLater: [...missedLater.values()],
348
+ label: labelOf(searches.length > 0, used, nativeWithoutSearch)
349
+ };
350
+ }
351
+ function aggregateFindings(turns) {
352
+ const labels = Object.fromEntries(LABELS.map((label) => [label, 0]));
353
+ const ranks = [];
354
+ let abstainedSearches = 0;
355
+ let abstainedTurns = 0;
356
+ for (const turn of turns) {
357
+ labels[turn.label] += 1;
358
+ abstainedSearches += turn.abstentions.length;
359
+ if (turn.abstained)
360
+ abstainedTurns += 1;
361
+ for (const skill of turn.loadedSkills)
362
+ if (skill.rankInSearch !== null)
363
+ ranks.push(skill.rankInSearch);
364
+ }
365
+ return {
366
+ turns: turns.length,
367
+ labels,
368
+ abstainedSearches,
369
+ abstainedTurns,
370
+ meanRank: ranks.length === 0 ? null : ranks.reduce((sum, rank) => sum + rank, 0) / ranks.length
371
+ };
372
+ }
373
+ function analyzeSession(tree, digestOf) {
374
+ const turns = tree.turns.map((turn, i) => analyzeTurn(turn, tree.turns.slice(i + 1), digestOf));
375
+ return { sessionId: tree.id, turns, aggregate: aggregateFindings(turns) };
376
+ }
377
+ function loadedDigests(store) {
378
+ return ({ uri, loadId }) => uri === null || loadId === null ? void 0 : store.getLoad(loadId)?.resources.find((resource) => resource.uri === uri)?.digest;
379
+ }
380
+
381
+ // ../shared/dist/analysis/usage-evidence.js
382
+ function stringOf(value) {
383
+ return typeof value === "string" && value.length > 0 ? value : void 0;
384
+ }
385
+ function skillDirHint(span) {
386
+ const path = stringOf(span.activation.data.path);
387
+ if (path === void 0)
388
+ return null;
389
+ const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
390
+ return cut > 0 ? path.slice(0, cut) : null;
391
+ }
392
+ function readFileBelongsTo(event, span) {
393
+ const skillUri = event.skillUri ?? stringOf(event.data.skillUri) ?? null;
394
+ if (skillUri === null)
395
+ return false;
396
+ if (span.uri !== null)
397
+ return skillUri === span.uri;
398
+ return skillUri.split("/").at(-2) === span.name;
399
+ }
400
+ var COMMAND_KEYS = /* @__PURE__ */ new Set(["command", "full_command", "bash_command", "cmd", "argv", "script", "shell_command"]);
401
+ function collectArgStrings(text) {
402
+ let parsed;
403
+ try {
404
+ parsed = JSON.parse(text);
405
+ } catch {
406
+ return [{ text, command: true }];
407
+ }
408
+ const out = [];
409
+ const walk = (value, command) => {
410
+ if (typeof value === "string")
411
+ out.push({ text: value, command });
412
+ else if (Array.isArray(value))
413
+ for (const item of value)
414
+ walk(item, command);
415
+ else if (value !== null && typeof value === "object") {
416
+ for (const [key, item] of Object.entries(value))
417
+ walk(item, command || COMMAND_KEYS.has(key));
418
+ }
419
+ };
420
+ walk(parsed, false);
421
+ return out.length > 0 ? out : [{ text, command: true }];
422
+ }
423
+ function shellTokens(text) {
424
+ const tokens = [];
425
+ let current = "";
426
+ let open = false;
427
+ let quote = null;
428
+ for (let i = 0; i < text.length; i += 1) {
429
+ const char = text.charAt(i);
430
+ if (quote === null && /\s/.test(char)) {
431
+ if (open)
432
+ tokens.push(current);
433
+ current = "";
434
+ open = false;
435
+ continue;
436
+ }
437
+ if (quote === null && (char === '"' || char === "'")) {
438
+ quote = char;
439
+ open = true;
440
+ continue;
441
+ }
442
+ if (quote === char) {
443
+ quote = null;
444
+ continue;
445
+ }
446
+ const next = text[i + 1];
447
+ if (char === "\\" && quote !== "'" && next !== void 0 && (/\s/.test(next) || next === '"' || next === "'" || next === "\\")) {
448
+ current += next;
449
+ open = true;
450
+ i += 1;
451
+ continue;
452
+ }
453
+ current += char;
454
+ open = true;
455
+ }
456
+ if (open)
457
+ tokens.push(current);
458
+ return tokens;
459
+ }
460
+ function normalizePath(path) {
461
+ return path.replace(/\\+/g, "/").replace(/\/+$/, "");
462
+ }
463
+ function tokenReferencesDir(token, dir, insideOnly) {
464
+ const path = normalizePath(token);
465
+ const target = normalizePath(dir);
466
+ if (path === "" || target === "")
467
+ return false;
468
+ if (path.startsWith(`${target}/`))
469
+ return true;
470
+ const rooted = target.startsWith("/") || /^[A-Za-z]:\//.test(target);
471
+ if (!rooted && path.includes(`/${target}/`))
472
+ return true;
473
+ if (insideOnly)
474
+ return false;
475
+ return path === target || !rooted && path.endsWith(`/${target}`);
476
+ }
477
+ function argsReferenceSkillDir(event, span, dirHint) {
478
+ if (event.text === null)
479
+ return false;
480
+ const target = dirHint ?? span.name;
481
+ for (const { text, command } of collectArgStrings(event.text)) {
482
+ for (const token of command ? shellTokens(text) : [text]) {
483
+ if (tokenReferencesDir(token, target, command))
484
+ return true;
485
+ }
486
+ }
487
+ return false;
488
+ }
489
+ function supportingReadsOf(span, turn) {
490
+ const reads = [];
491
+ const start = turn.events.findIndex((e) => e.id === span.activation.id);
492
+ for (const event of turn.events.slice(start < 0 ? turn.events.length : start + 1)) {
493
+ if (event.kind === "read_file" && readFileBelongsTo(event, span)) {
494
+ reads.push({ eventId: event.id, kind: "read_file", uri: event.skillUri ?? stringOf(event.data.uri) ?? null, label: "reported" });
495
+ }
496
+ }
497
+ if (span.activation.kind !== "native_skill")
498
+ return reads;
499
+ const dirHint = skillDirHint(span);
500
+ for (const event of span.events) {
501
+ if (event.kind !== "tool_call" || isSkillarMcpData(event.data))
502
+ continue;
503
+ if (argsReferenceSkillDir(event, span, dirHint)) {
504
+ reads.push({ eventId: event.id, kind: "tool_call", uri: null, label: "heuristic" });
505
+ }
506
+ }
507
+ return reads;
508
+ }
509
+ function isSkillarMcpData(data) {
510
+ return (data.skillarMcp ?? data.gisoolMcp) === true;
511
+ }
512
+ var SHELL_TOOLS = /* @__PURE__ */ new Set(["exec_command", "Bash", "shell", "local_shell"]);
513
+ function activityKind(event, runtime) {
514
+ const toolName = stringOf(event.data.toolName);
515
+ if (runtime === "codex" && toolName === "exec")
516
+ return "unresolved_exec";
517
+ return toolName !== void 0 && SHELL_TOOLS.has(toolName) ? "command" : "other";
518
+ }
519
+
520
+ // ../shared/dist/analysis/usage.js
521
+ var KOREAN_CORRECTIONS = ["\uC544\uB2C8", "\uB2E4\uC2DC", "\uD2C0\uB838", "\uC798\uBABB", "\uADF8\uAC8C \uC544\uB2C8", "\uC65C \uC548"];
522
+ var ENGLISH_CORRECTIONS = ["no,", "wrong", "again", "that's not", "undo", "revert"];
523
+ function escapeRegex(text) {
524
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
525
+ }
526
+ var ENGLISH_PATTERNS = ENGLISH_CORRECTIONS.map((token) => [
527
+ token,
528
+ new RegExp(`${/^[a-z0-9]/.test(token) ? "(?<![a-z0-9])" : ""}${escapeRegex(token)}${/[a-z0-9]$/.test(token) ? "(?![a-z0-9])" : ""}`, "i")
529
+ ]);
530
+ function numberOf(value) {
531
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
532
+ }
533
+ function correctionMatches(text) {
534
+ const normalized = text.replace(/[\u2018\u2019]/g, "'").toLowerCase();
535
+ const matched = [];
536
+ for (const token of KOREAN_CORRECTIONS)
537
+ if (normalized.includes(token))
538
+ matched.push(token);
539
+ for (const [token, pattern] of ENGLISH_PATTERNS)
540
+ if (pattern.test(normalized))
541
+ matched.push(token);
542
+ return matched;
543
+ }
544
+ function correctionOf(next) {
545
+ if (next === null)
546
+ return { status: "unknown", label: "heuristic", matched: [], reason: "no_next_prompt" };
547
+ if (next.text === null)
548
+ return { status: "unknown", label: "heuristic", matched: [], reason: "text_not_captured" };
549
+ const matched = correctionMatches(next.text);
550
+ return { status: matched.length > 0 ? "correction" : "no_correction", label: "heuristic", matched, reason: null };
551
+ }
552
+ function nextPromptAfterTurn(session, turnIndex) {
553
+ for (let i = turnIndex + 1; i < session.turns.length; i += 1) {
554
+ const prompt = session.turns[i]?.events.find((e) => e.kind === "prompt");
555
+ if (prompt)
556
+ return prompt;
557
+ }
558
+ return null;
559
+ }
560
+ function tokenValues(value) {
561
+ return {
562
+ inputTokens: value("inputTokens"),
563
+ outputTokens: value("outputTokens"),
564
+ cacheReadTokens: value("cacheReadTokens"),
565
+ cacheCreationTokens: value("cacheCreationTokens"),
566
+ cacheWriteTokens: value("cacheWriteTokens"),
567
+ reasoningTokens: value("reasoningTokens"),
568
+ totalTokens: value("totalTokens")
569
+ };
570
+ }
571
+ function callTokens(data) {
572
+ const measured = tokenValues((key) => numberOf(data[key]) ?? null);
573
+ const unknownCalls = tokenValues((key) => measured[key] === null ? 1 : 0);
574
+ return { inputIncludesCache: data.inputIncludesCache === true, calls: 1, ...measured, unknownCalls };
575
+ }
576
+ function sumTokens(a, b) {
577
+ const measured = tokenValues((key) => {
578
+ const left = a[key];
579
+ const right = b[key];
580
+ return left === null ? right : right === null ? left : left + right;
581
+ });
582
+ const unknownCalls = tokenValues((key) => a.unknownCalls[key] + b.unknownCalls[key]);
583
+ return { inputIncludesCache: a.inputIncludesCache, calls: a.calls + b.calls, ...measured, unknownCalls };
584
+ }
585
+ function mergeTokens(into, buckets) {
586
+ for (const bucket of buckets) {
587
+ const current = into.get(bucket.inputIncludesCache);
588
+ into.set(bucket.inputIncludesCache, current ? sumTokens(current, bucket) : bucket);
589
+ }
590
+ }
591
+ function sortedTokens(buckets) {
592
+ return [...buckets.values()].sort((a, b) => Number(a.inputIncludesCache) - Number(b.inputIncludesCache));
593
+ }
594
+ function spanUsage(span, ctx) {
595
+ let followThrough = 0;
596
+ let commands = 0;
597
+ let unresolvedExec = 0;
598
+ const results = { success: 0, failure: 0, unknown: 0 };
599
+ let skillToolCalls = 0;
600
+ let toolFailures = 0;
601
+ let llmCalls = 0;
602
+ let costSum = 0;
603
+ let costUnknownCalls = 0;
604
+ let reported = 0;
605
+ let single = 0;
606
+ let coActive = 0;
607
+ const buckets = /* @__PURE__ */ new Map();
608
+ for (const event of span.events) {
609
+ if (event.attribution === "reported")
610
+ reported += 1;
611
+ else if (event.attribution === "co_active")
612
+ coActive += 1;
613
+ else if (event.attribution === "single")
614
+ single += 1;
615
+ if (event.kind === "tool_call") {
616
+ if (isSkillarMcpData(event.data))
617
+ skillToolCalls += 1;
618
+ else {
619
+ followThrough += 1;
620
+ const kind = activityKind(event, ctx.runtime);
621
+ if (kind === "command")
622
+ commands += 1;
623
+ else if (kind === "unresolved_exec")
624
+ unresolvedExec += 1;
625
+ results[event.data.success === true ? "success" : event.data.success === false ? "failure" : "unknown"] += 1;
626
+ }
627
+ if (event.data.success === false)
628
+ toolFailures += 1;
629
+ }
630
+ if (event.kind === "llm_call") {
631
+ llmCalls += 1;
632
+ const cost = numberOf(event.data.costUsd);
633
+ if (cost === void 0)
634
+ costUnknownCalls += 1;
635
+ else
636
+ costSum += cost;
637
+ mergeTokens(buckets, [callTokens(event.data)]);
638
+ }
639
+ }
640
+ const total = span.events.length;
641
+ return {
642
+ turnId: ctx.turn.id,
643
+ spanId: span.id,
644
+ skill: span.skill,
645
+ name: span.name,
646
+ uri: span.uri,
647
+ activatedAt: span.startedAt,
648
+ durationMs: Math.max(0, span.endedAt - span.startedAt),
649
+ followThrough,
650
+ activity: {
651
+ version: 1,
652
+ observations: followThrough,
653
+ commands,
654
+ unresolvedExec,
655
+ results,
656
+ workExecutions: unresolvedExec > 0 ? null : followThrough
657
+ },
658
+ skillToolCalls,
659
+ toolFailures,
660
+ supportingReads: supportingReadsOf(span, ctx.turn),
661
+ llmCalls,
662
+ costUsd: llmCalls > 0 && costUnknownCalls === 0 ? costSum : null,
663
+ costUnknownCalls,
664
+ tokens: sortedTokens(buckets),
665
+ nextPromptCorrection: correctionOf(ctx.nextPrompt),
666
+ attribution: { reported, single, coActive, total, coActiveShare: total > 0 ? coActive / total : null }
667
+ };
668
+ }
669
+ function sessionUsage(session) {
670
+ const spans = [];
671
+ session.turns.forEach((turn, index) => {
672
+ const nextPrompt = nextPromptAfterTurn(session, index);
673
+ for (const span of turn.skillSpans)
674
+ spans.push(spanUsage(span, { turn, nextPrompt, runtime: session.runtime }));
675
+ });
676
+ return { sessionId: session.id, runtime: session.runtime, spans };
677
+ }
678
+ function aggregateUsage(spans) {
679
+ const bySkill = /* @__PURE__ */ new Map();
680
+ for (const usage of spans) {
681
+ const acc = bySkill.get(usage.skill) ?? {
682
+ skill: usage.skill,
683
+ name: usage.name,
684
+ uri: usage.uri,
685
+ spans: 0,
686
+ spansWithoutFollowThrough: 0,
687
+ followThrough: 0,
688
+ skillToolCalls: 0,
689
+ toolFailures: 0,
690
+ supportingReads: 0,
691
+ heuristicReads: 0,
692
+ durationMs: 0,
693
+ llmCalls: 0,
694
+ costSum: 0,
695
+ costUnknownCalls: 0,
696
+ tokens: /* @__PURE__ */ new Map(),
697
+ corrections: { correction: 0, no_correction: 0, unknown: 0 },
698
+ reported: 0,
699
+ single: 0,
700
+ coActive: 0,
701
+ total: 0,
702
+ commands: 0,
703
+ unresolvedExec: 0,
704
+ results: { success: 0, failure: 0, unknown: 0 },
705
+ workExecutions: 0
706
+ };
707
+ acc.uri = acc.uri ?? usage.uri;
708
+ acc.spans += 1;
709
+ if (usage.followThrough === 0)
710
+ acc.spansWithoutFollowThrough += 1;
711
+ acc.followThrough += usage.followThrough;
712
+ acc.skillToolCalls += usage.skillToolCalls;
713
+ acc.toolFailures += usage.toolFailures;
714
+ acc.supportingReads += usage.supportingReads.length;
715
+ acc.heuristicReads += usage.supportingReads.filter((r) => r.label === "heuristic").length;
716
+ acc.durationMs += usage.durationMs;
717
+ acc.llmCalls += usage.llmCalls;
718
+ acc.costSum += usage.costUsd ?? 0;
719
+ acc.costUnknownCalls += usage.costUnknownCalls;
720
+ mergeTokens(acc.tokens, usage.tokens);
721
+ acc.corrections[usage.nextPromptCorrection.status] += 1;
722
+ acc.reported += usage.attribution.reported;
723
+ acc.single += usage.attribution.single;
724
+ acc.coActive += usage.attribution.coActive;
725
+ acc.total += usage.attribution.total;
726
+ acc.commands += usage.activity.commands;
727
+ acc.unresolvedExec += usage.activity.unresolvedExec;
728
+ acc.results.success += usage.activity.results.success;
729
+ acc.results.failure += usage.activity.results.failure;
730
+ acc.results.unknown += usage.activity.results.unknown;
731
+ acc.workExecutions = acc.workExecutions === null || usage.activity.workExecutions === null ? null : acc.workExecutions + usage.activity.workExecutions;
732
+ bySkill.set(usage.skill, acc);
733
+ }
734
+ return [...bySkill.values()].map((acc) => ({
735
+ skill: acc.skill,
736
+ name: acc.name,
737
+ uri: acc.uri,
738
+ spans: acc.spans,
739
+ spansWithoutFollowThrough: acc.spansWithoutFollowThrough,
740
+ followThrough: acc.followThrough,
741
+ skillToolCalls: acc.skillToolCalls,
742
+ toolFailures: acc.toolFailures,
743
+ supportingReads: acc.supportingReads,
744
+ heuristicReads: acc.heuristicReads,
745
+ durationMs: acc.durationMs,
746
+ llmCalls: acc.llmCalls,
747
+ costUsd: acc.llmCalls > 0 && acc.costUnknownCalls === 0 ? acc.costSum : null,
748
+ costUnknownCalls: acc.costUnknownCalls,
749
+ tokens: sortedTokens(acc.tokens),
750
+ corrections: acc.corrections,
751
+ attribution: {
752
+ reported: acc.reported,
753
+ single: acc.single,
754
+ coActive: acc.coActive,
755
+ total: acc.total,
756
+ coActiveShare: acc.total > 0 ? acc.coActive / acc.total : null
757
+ },
758
+ activity: {
759
+ version: 1,
760
+ observations: acc.followThrough,
761
+ commands: acc.commands,
762
+ unresolvedExec: acc.unresolvedExec,
763
+ results: acc.results,
764
+ workExecutions: acc.workExecutions
765
+ }
766
+ })).sort((a, b) => a.skill.localeCompare(b.skill));
767
+ }
768
+ function rangeUsage(store, opts) {
769
+ const filter = { from: opts.from, to: opts.to, ...opts.automated !== void 0 ? { automated: opts.automated } : {} };
770
+ const detailLimit = opts.detailLimit === void 0 ? void 0 : Math.max(0, Math.floor(opts.detailLimit));
771
+ const sessions = [];
772
+ const spans = [];
773
+ let sessionCount = 0;
774
+ for (const row of store.sessions(filter)) {
775
+ const tree = sessionTree(store, row.id);
776
+ if (!tree)
777
+ continue;
778
+ const usage = sessionUsage(tree);
779
+ sessionCount += 1;
780
+ spans.push(...usage.spans);
781
+ if (detailLimit === void 0 || sessions.length < detailLimit)
782
+ sessions.push(usage);
783
+ }
784
+ return {
785
+ from: opts.from,
786
+ to: opts.to,
787
+ sessionCount,
788
+ truncated: sessions.length < sessionCount,
789
+ sessions,
790
+ skills: aggregateUsage(spans)
791
+ };
792
+ }
793
+
794
+ // ../shared/dist/analysis/compare.js
795
+ var sorted = (values) => [...new Set(values)].sort();
796
+ function compare(input) {
797
+ const panesByStep = /* @__PURE__ */ new Map();
798
+ const mapped = /* @__PURE__ */ new Set();
799
+ for (const { stepId, paneId } of input.steps) {
800
+ panesByStep.set(stepId, [...panesByStep.get(stepId) ?? [], paneId]);
801
+ mapped.add(paneId);
802
+ }
803
+ const skillsOf = (panes) => panes.flatMap((p) => input.paneSkillUse[p] ?? []);
804
+ const steps = input.spec.steps.map((step) => {
805
+ const panes = sorted(panesByStep.get(step.id) ?? []);
806
+ const intended = sorted(step.skills);
807
+ const used = sorted(skillsOf(panes));
808
+ const intendedSet = new Set(intended);
809
+ const usedSet = new Set(used);
810
+ const hit = intended.filter((s) => usedSet.has(s));
811
+ const missingSkills = intended.filter((s) => !usedSet.has(s));
812
+ const extraSkills = used.filter((s) => !intendedSet.has(s));
813
+ const expected = new Set(step.expectTools);
814
+ const unexpectedTools = expected.size === 0 ? [] : sorted(panes.flatMap((p) => input.paneTools[p] ?? [])).filter((t) => !expected.has(t));
815
+ const status = panes.length === 0 ? "not_run" : used.length === 0 ? intended.length === 0 ? "matched" : "no_skill_used" : hit.length === 0 ? "different" : step.together && missingSkills.length > 0 ? "partial" : "matched";
816
+ return { stepId: step.id, panes, intendedSkills: intended, usedSkills: used, status, extraSkills, missingSkills, unexpectedTools };
817
+ });
818
+ const unplanned = sorted(input.panes ?? Object.keys(input.paneSkillUse)).filter((paneId) => !mapped.has(paneId)).map((paneId) => ({ paneId, usedSkills: sorted(input.paneSkillUse[paneId] ?? []) }));
819
+ return { steps, unplanned };
820
+ }
821
+
822
+ // ../shared/dist/reports/assembly.js
823
+ var DAY = 864e5;
824
+ var WEEK = 7 * DAY;
825
+ var AnalysisReportError = class extends Error {
826
+ code;
827
+ automated;
828
+ constructor(code, automated = null) {
829
+ super(code);
830
+ this.code = code;
831
+ this.automated = automated;
832
+ this.name = "AnalysisReportError";
833
+ }
834
+ };
835
+ var keep = (id, automation, mode) => mode === "include" || (mode === "only" ? automation[id] !== void 0 : automation[id] === void 0);
836
+ function findingDto(finding) {
837
+ return {
838
+ sessionId: finding.sessionId,
839
+ turns: finding.turns.map(({ loadedSkills, ...turn }) => ({ ...turn, usedSkills: loadedSkills })),
840
+ aggregate: finding.aggregate
841
+ };
842
+ }
843
+ function sessionIds(tree) {
844
+ return tree.tabs.flatMap((tab) => tab.panes.flatMap((pane) => pane.sessions.flatMap((link) => link.sessionId === null ? [] : [link.sessionId])));
845
+ }
846
+ function sessionsOf(tree) {
847
+ const sessions = new Map((tree.sessions ?? []).map((session) => [session.id, session]));
848
+ for (const tab of tree.tabs)
849
+ for (const pane of tab.panes) {
850
+ for (const link of pane.sessions)
851
+ if (link.session !== null)
852
+ sessions.set(link.session.id, link.session);
853
+ }
854
+ return [...sessions.values()];
855
+ }
856
+ function filteredTree(tree, automation, mode) {
857
+ const excluded = /* @__PURE__ */ new Map();
858
+ const tabs = tree.tabs.map((tab) => ({
859
+ ...tab,
860
+ panes: tab.panes.map((pane) => ({
861
+ ...pane,
862
+ sessions: pane.sessions.filter((link) => {
863
+ if (link.sessionId === null || keep(link.sessionId, automation, mode))
864
+ return true;
865
+ excluded.set(link.sessionId, { sessionId: link.sessionId, reason: automation[link.sessionId] ?? "not_automated" });
866
+ return false;
867
+ })
868
+ }))
869
+ }));
870
+ return { tree: { ...tree, tabs }, excluded };
871
+ }
872
+ function compareFlow(store, id, options = {}) {
873
+ const flow = store.getFlow(id);
874
+ if (!flow?.spec)
875
+ return void 0;
876
+ const usage = store.flowPaneUsage(id, options);
877
+ const paneSkillUse = {}, paneTools = {};
878
+ for (const row of usage) {
879
+ paneSkillUse[row.paneId] = row.skills;
880
+ paneTools[row.paneId] = row.tools;
881
+ }
882
+ return compare({
883
+ spec: flow.spec.spec,
884
+ steps: store.flowSteps(id).map((step) => ({ stepId: step.stepId, paneId: step.paneId })),
885
+ paneSkillUse,
886
+ paneTools,
887
+ panes: usage.map((row) => row.paneId)
888
+ });
889
+ }
890
+ function buildFlows(store, options, now) {
891
+ const { from, to, limit, automated, cursor } = options;
892
+ const rows = store.listFlows({
893
+ automated,
894
+ ...from === void 0 ? {} : { from },
895
+ ...to === void 0 ? {} : { to },
896
+ limit: limit + 1,
897
+ ...cursor === void 0 ? {} : { cursor }
898
+ });
899
+ const page = rows.slice(0, limit), last = page.at(-1);
900
+ const automation = automated === "include" ? {} : store.sessionAutomation(page.flatMap((row) => row.links.flatMap((link) => link.sessionId === null ? [] : [link.sessionId])));
901
+ return {
902
+ generatedAt: now,
903
+ from: from ?? null,
904
+ to: to ?? null,
905
+ limit,
906
+ automated,
907
+ flows: page.map((row) => {
908
+ const links = row.links.filter((link) => link.sessionId === null || keep(link.sessionId, automation, automated));
909
+ const ids = [...new Set(links.flatMap((link) => link.sessionId === null ? [] : [link.sessionId]))];
910
+ let reported = 0, inferred = 0, unlinked = 0;
911
+ for (const link of links) {
912
+ if (link.sessionId === null || link.source === "unlinked")
913
+ unlinked++;
914
+ else if (link.source === "inferred:cwd_time")
915
+ inferred++;
916
+ else
917
+ reported++;
918
+ }
919
+ return {
920
+ id: row.kind === "workspace" ? `ws:${row.workspaceId}` : row.id,
921
+ kind: row.kind,
922
+ workspaceId: row.workspaceId,
923
+ tabId: row.tabId,
924
+ label: row.label,
925
+ registered: row.kind === "flow",
926
+ spec: row.spec,
927
+ startedMs: row.startedMs,
928
+ endedMs: row.endedMs,
929
+ paneIds: row.paneIds,
930
+ sessionIds: ids,
931
+ counts: { panes: row.paneIds.length, sessions: ids.length },
932
+ attribution: { reported, inferred, unlinked }
933
+ };
934
+ }),
935
+ nextCursor: rows.length > limit && last ? encodeFlowCursor(last) : null
936
+ };
937
+ }
938
+ function encodeFlowCursor(row) {
939
+ const bytes = new TextEncoder().encode(`${row.orderMs}:${row.id}`);
940
+ let binary = "";
941
+ for (const byte of bytes)
942
+ binary += String.fromCharCode(byte);
943
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
944
+ }
945
+ function buildFlowReport(store, ref, options, now) {
946
+ const { automated } = options, id = ref.startsWith("ws:") ? ref.slice(3) : ref;
947
+ const eventScope = ref === "outside" ? void 0 : store.flowEventScope(id);
948
+ let full;
949
+ if (ref === "outside") {
950
+ const to = options.to ?? now + 1, from = options.from ?? to - WEEK;
951
+ full = {
952
+ id: "outside",
953
+ workspaceId: "",
954
+ label: "outside herdr",
955
+ registered: false,
956
+ tabs: [],
957
+ sessions: store.outsideHerdrSessions({ from, to, limit: options.limit ?? 100, automated }).flatMap(({ id: sessionId }) => {
958
+ const session = sessionTree(store, sessionId);
959
+ return session ? [session] : [];
960
+ })
961
+ };
962
+ } else
963
+ full = flowTree(store, id, eventScope);
964
+ if (!full)
965
+ throw new AnalysisReportError("flow_not_found");
966
+ const comparisonIds = full.registered ? store.flowSessionIds(full.id, eventScope) : [];
967
+ const automation = automated === "include" ? {} : store.sessionAutomation([...sessionIds(full), ...comparisonIds]);
968
+ const flow = full.registered ? store.getFlow(full.id) : void 0;
969
+ const overlaps = flow ? sessionsOf(full).map((session) => ({
970
+ sessionId: session.id,
971
+ startedBefore: session.startedAt < flow.registeredMs,
972
+ continuesAfter: flow.endedMs !== void 0 && (session.endedAt === null || session.endedAt > flow.endedMs)
973
+ })).filter((session) => session.startedBefore || session.continuesAfter) : [];
974
+ const { tree, excluded } = filteredTree(full, automation, automated);
975
+ for (const sessionId of comparisonIds) {
976
+ if (!keep(sessionId, automation, automated)) {
977
+ excluded.set(sessionId, { sessionId, reason: automation[sessionId] ?? "not_automated" });
978
+ }
979
+ }
980
+ const sessions = sessionsOf(tree), digestOf = loadedDigests(store);
981
+ const findings = sessions.map((session) => analyzeSession(session, digestOf));
982
+ const usages = sessions.map((session) => sessionUsage(session)), spec = flow?.spec;
983
+ const warningSessions = [...sessions.map((session) => session.id), ...comparisonIds.filter((id2) => !excluded.has(id2))];
984
+ const unattributedLoads = flow ? store.flowUnattributedLoads(flow.id, warningSessions, eventScope) : store.reconcileLoads({
985
+ readOnly: true,
986
+ from: ref === "outside" ? options.from ?? now - WEEK : sessions.length === 0 ? 0 : Math.min(...sessions.map((session) => session.startedAt)),
987
+ to: ref === "outside" ? options.to ?? now + 1 : now + 1,
988
+ sessionIds: warningSessions
989
+ });
990
+ return {
991
+ generatedAt: now,
992
+ id: ref === "outside" ? "outside" : tree.registered ? tree.id : `ws:${tree.workspaceId}`,
993
+ kind: ref === "outside" ? "outside_herdr" : tree.registered ? "flow" : "workspace",
994
+ workspaceId: tree.workspaceId,
995
+ label: tree.label,
996
+ registered: tree.registered,
997
+ flow: flow ? { registeredMs: flow.registeredMs, endedMs: flow.endedMs ?? null, tabId: flow.tabId ?? null } : null,
998
+ spec: spec ? { id: spec.id, name: spec.name, version: spec.version } : null,
999
+ automated,
1000
+ tree,
1001
+ executionScope: eventScope ? {
1002
+ from: eventScope.from,
1003
+ to: eventScope.to,
1004
+ boundary: eventScope.boundary,
1005
+ overlaps: overlaps.filter((session) => keep(session.sessionId, automation, automated)),
1006
+ label: eventScope.boundary === "recorded" ? "Events scoped by timestamp; persisted recording order resolves equal-time boundaries independently of membership discovery. Delayed interior evidence can still arrive. Session ends are observed separately." : "Some boundary ordering is unavailable. Unproven equal-time activity is excluded here; workspace history retains it."
1007
+ } : null,
1008
+ finding: { id: tree.id, sessions: findings.map(findingDto), aggregate: aggregateFindings(findings.flatMap((f) => f.turns)) },
1009
+ usage: { id: tree.id, sessions: usages, skills: aggregateUsage(usages.flatMap((u) => u.spans)) },
1010
+ comparison: tree.registered ? compareFlow(store, tree.id, {
1011
+ excludeSessions: [...excluded.keys()],
1012
+ ...eventScope ? { scope: eventScope } : {}
1013
+ }) ?? null : null,
1014
+ excludedSessions: [...excluded.values()],
1015
+ unattributedLoads
1016
+ };
1017
+ }
1018
+ function buildSessionReport(store, id, automated, now) {
1019
+ const unattributedLoads = store.reconcileLoads({ sessionIds: [id], readOnly: true });
1020
+ const tree = sessionTree(store, id);
1021
+ if (!tree)
1022
+ throw new AnalysisReportError("session_not_found");
1023
+ const automation = store.sessionAutomation([id])[id];
1024
+ if (!keep(id, automation === void 0 ? {} : { [id]: automation }, automated)) {
1025
+ throw new AnalysisReportError("automated_excluded", automation ?? null);
1026
+ }
1027
+ return {
1028
+ generatedAt: now,
1029
+ sessionId: tree.id,
1030
+ runtime: tree.runtime,
1031
+ startedAt: tree.startedAt,
1032
+ endedAt: tree.endedAt,
1033
+ automated: automation ?? null,
1034
+ tree,
1035
+ finding: findingDto(analyzeSession(tree, loadedDigests(store))),
1036
+ usage: sessionUsage(tree),
1037
+ unattributedLoads
1038
+ };
1039
+ }
1040
+ function buildSkillUsage(store, options, now) {
1041
+ const { from, to, detailLimit, automated } = options;
1042
+ const usage = rangeUsage(store, { from, to, detailLimit, ...automated === "exclude" ? {} : { automated } });
1043
+ return {
1044
+ generatedAt: now,
1045
+ from,
1046
+ to,
1047
+ automated,
1048
+ detailLimit,
1049
+ sessionCount: usage.sessionCount,
1050
+ truncated: usage.truncated,
1051
+ skills: usage.skills,
1052
+ sessions: usage.sessions
1053
+ };
1054
+ }
1055
+ export {
1056
+ AnalysisReportError,
1057
+ buildFlowReport,
1058
+ buildFlows,
1059
+ buildSessionReport,
1060
+ buildSkillUsage,
1061
+ compareFlow,
1062
+ encodeFlowCursor
1063
+ };