session-report-service.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import type { Dirent } from 'node:fs';
  2. import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
  3. import { isAbsolute, relative, resolve, sep } from 'node:path';
  4. import type {
  5. ReportLocations,
  6. ReportSession,
  7. ReportSessions,
  8. SessionReportArtifact,
  9. SessionReportCapability,
  10. SessionReportManifest,
  11. } from './contracts.js';
  12. export interface SessionReportServiceOptions {
  13. readonly sessions: ReportSessions;
  14. readonly locations: ReportLocations;
  15. }
  16. interface LocatedSession {
  17. readonly session: ReportSession;
  18. readonly sessionDir: string;
  19. }
  20. interface SkippedArtifact {
  21. readonly name: string;
  22. readonly reason: string;
  23. }
  24. type ReportFailure = (name: string, error: unknown) => void;
  25. const REWIND_STAGING_PREFIX = '.history-mutation-';
  26. const LLM_CALL_REPORT_TEMP_PREFIX = '.llm-call-report-';
  27. const IGNORED_FILE_NAMES = new Set(['.DS_Store']);
  28. const IGNORED_DIRECTORY_NAMES = new Set(['llm-call', 'llm-context-inspector']);
  29. // Publication intermediates owned by jsonl/materializer/tool-output writers,
  30. // canonical-history-index (including rollback), and session-history-paths.
  31. const ATOMIC_PUBLICATION_TEMP_FILES = [
  32. /\.\d+[.-][0-9a-f-]{36}\.tmp$/u,
  33. /^(?:history-catalog\.json|user-message-locators\.jsonl)\.\d+\.\d+\.[0-9a-f]*\.(?:tmp|restore)$/u,
  34. /^manifest\.json\.\d+\.tmp$/u,
  35. ];
  36. /** Collects readable artifacts independently; diagnostics must survive partial history loss. */
  37. export class SessionReportService implements SessionReportCapability {
  38. constructor(private readonly options: SessionReportServiceOptions) {}
  39. async collect(sessionId: string): Promise<SessionReportManifest> {
  40. if (!sessionId.trim()) throw new Error('session_report_session_id_required');
  41. const skipped: SkippedArtifact[] = [];
  42. const reportFailure: ReportFailure = (name, error) => {
  43. const code = typeof error === 'object' && error !== null && Reflect.get(error, 'code');
  44. skipped.push({ name, reason: typeof code === 'string' ? code : String(error) });
  45. };
  46. const sessions = await this.collectSubtree(sessionId, reportFailure);
  47. const artifacts: SessionReportArtifact[] = [];
  48. for (const located of sessions) {
  49. try {
  50. artifacts.push(...(await collectSessionFiles(located, reportFailure)));
  51. } catch (error) {
  52. reportFailure(archiveSessionPrefix(located.session.sessionId), error);
  53. }
  54. if (located.session.sessionKind === 'task') {
  55. try {
  56. const binding = await this.options.sessions.getTaskAgentBinding(
  57. located.session.sessionId,
  58. );
  59. if (!binding) {
  60. throw new Error(`session_report_task_binding_missing:${located.session.sessionId}`);
  61. }
  62. const content = `${JSON.stringify(binding.definition, null, 2)}\n`;
  63. artifacts.push({
  64. name: `${archiveSessionPrefix(located.session.sessionId)}/task-agent-definition.json`,
  65. content,
  66. bytes: Buffer.byteLength(content, 'utf8'),
  67. required: true,
  68. });
  69. } catch (error) {
  70. reportFailure(
  71. `${archiveSessionPrefix(located.session.sessionId)}/task-agent-definition.json`,
  72. error,
  73. );
  74. }
  75. }
  76. }
  77. const unique = new Map<string, SessionReportArtifact>();
  78. for (const artifact of artifacts) {
  79. if (unique.has(artifact.name)) reportFailure(artifact.name, 'duplicate_artifact');
  80. else unique.set(artifact.name, artifact);
  81. }
  82. if (skipped.length > 0) {
  83. const content = `${JSON.stringify({ schemaVersion: 1, skipped }, null, 2)}\n`;
  84. unique.set('session-report-collection.json', {
  85. name: 'session-report-collection.json',
  86. content,
  87. bytes: Buffer.byteLength(content, 'utf8'),
  88. required: true,
  89. });
  90. }
  91. return {
  92. schemaVersion: 1,
  93. rootSessionId: sessionId,
  94. sessionIds: sessions.map(({ session }) => session.sessionId),
  95. artifacts: [...unique.values()].sort((left, right) => left.name.localeCompare(right.name)),
  96. };
  97. }
  98. private async collectSubtree(
  99. rootSessionId: string,
  100. reportFailure: ReportFailure,
  101. ): Promise<LocatedSession[]> {
  102. const located: LocatedSession[] = [];
  103. const pending = [rootSessionId];
  104. const visited = new Set<string>();
  105. while (pending.length > 0) {
  106. const currentSessionId = pending.shift();
  107. if (!currentSessionId || visited.has(currentSessionId)) continue;
  108. visited.add(currentSessionId);
  109. try {
  110. const resolved = await this.options.locations.inspectSession(currentSessionId);
  111. if (!resolved) throw new Error(`session_report_session_missing:${currentSessionId}`);
  112. located.push({ session: resolved.session, sessionDir: resolved.paths.sessionDir });
  113. } catch (error) {
  114. reportFailure(archiveSessionPrefix(currentSessionId), error);
  115. }
  116. // A missing parent directory/identity must not hide discoverable descendants.
  117. try {
  118. const children = await this.options.sessions.listChildren(currentSessionId);
  119. for (const child of children) {
  120. if (!visited.has(child.sessionId)) pending.push(child.sessionId);
  121. }
  122. } catch (error) {
  123. reportFailure(`${archiveSessionPrefix(currentSessionId)}/children`, error);
  124. }
  125. }
  126. return located;
  127. }
  128. }
  129. async function collectSessionFiles(
  130. input: LocatedSession,
  131. reportFailure: ReportFailure,
  132. ): Promise<SessionReportArtifact[]> {
  133. await requireDirectory(input.sessionDir, input.session.sessionId);
  134. const root = await realpath(input.sessionDir);
  135. const entries: SessionReportArtifact[] = [];
  136. await visit('');
  137. if (
  138. !entries.some(
  139. (entry) => entry.name === `${archiveSessionPrefix(input.session.sessionId)}/manifest.json`,
  140. )
  141. ) {
  142. reportFailure(
  143. `${archiveSessionPrefix(input.session.sessionId)}/manifest.json`,
  144. 'manifest_missing',
  145. );
  146. }
  147. return entries;
  148. async function visit(relativeDirectory: string): Promise<void> {
  149. const directory = resolve(root, relativeDirectory);
  150. let children: Dirent[];
  151. try {
  152. children = await readdir(directory, { withFileTypes: true });
  153. } catch (error) {
  154. reportFailure(`${archiveSessionPrefix(input.session.sessionId)}/${relativeDirectory}`, error);
  155. return;
  156. }
  157. for (const child of children.sort((left, right) => left.name.localeCompare(right.name))) {
  158. if (ignoredSessionEntry(child)) continue;
  159. const relativeName = relativeDirectory ? `${relativeDirectory}/${child.name}` : child.name;
  160. const path = resolve(root, relativeName);
  161. try {
  162. if (child.isSymbolicLink()) {
  163. throw new Error(
  164. `session_report_unsafe_symlink:${input.session.sessionId}:${relativeName}`,
  165. );
  166. }
  167. if (child.isDirectory()) {
  168. await visit(relativeName);
  169. continue;
  170. }
  171. if (!child.isFile()) continue;
  172. if (isLlmCallReportFile(relativeName)) {
  173. entries.push(await collectLlmCallReportArtifact(input, root, path, relativeName));
  174. continue;
  175. }
  176. const info = await lstat(path);
  177. const resolvedPath = await realpath(path);
  178. if (!pathInside(root, resolvedPath)) {
  179. throw new Error(`session_report_path_escape:${input.session.sessionId}:${relativeName}`);
  180. }
  181. entries.push({
  182. name: `${archiveSessionPrefix(input.session.sessionId)}/${relativeName}`,
  183. path,
  184. bytes: info.size,
  185. required: true,
  186. });
  187. } catch (error) {
  188. reportFailure(`${archiveSessionPrefix(input.session.sessionId)}/${relativeName}`, error);
  189. }
  190. }
  191. }
  192. }
  193. async function collectLlmCallReportArtifact(
  194. input: LocatedSession,
  195. root: string,
  196. path: string,
  197. relativeName: string,
  198. ): Promise<SessionReportArtifact> {
  199. const info = await lstat(path);
  200. const resolvedPath = await realpath(path);
  201. if (!info.isFile() || !pathInside(root, resolvedPath)) {
  202. throw new Error(`session_report_path_escape:${input.session.sessionId}:${relativeName}`);
  203. }
  204. const content = await readFile(path, 'utf8');
  205. return {
  206. name: `${archiveSessionPrefix(input.session.sessionId)}/${relativeName}`,
  207. content,
  208. bytes: Buffer.byteLength(content, 'utf8'),
  209. required: true,
  210. };
  211. }
  212. function ignoredSessionEntry(entry: Dirent): boolean {
  213. if (IGNORED_FILE_NAMES.has(entry.name)) return true;
  214. if (entry.name.startsWith(LLM_CALL_REPORT_TEMP_PREFIX)) return true;
  215. if (entry.isFile() && ATOMIC_PUBLICATION_TEMP_FILES.some((pattern) => pattern.test(entry.name))) {
  216. return true;
  217. }
  218. return (
  219. entry.isDirectory() &&
  220. (IGNORED_DIRECTORY_NAMES.has(entry.name) || entry.name.startsWith(REWIND_STAGING_PREFIX))
  221. );
  222. }
  223. function isLlmCallReportFile(relativeName: string): boolean {
  224. return (
  225. relativeName === 'llm-call.json' ||
  226. /^snapshots\/env-g\d{12}--[A-Za-z0-9][A-Za-z0-9._-]*\.json$/u.test(relativeName)
  227. );
  228. }
  229. async function requireDirectory(path: string, sessionId: string): Promise<void> {
  230. try {
  231. const info = await lstat(path);
  232. if (info.isDirectory() && !info.isSymbolicLink()) return;
  233. } catch (error) {
  234. if (!isMissing(error)) throw error;
  235. }
  236. throw new Error(`session_report_history_missing:${sessionId}`);
  237. }
  238. function archiveSessionPrefix(sessionId: string): string {
  239. return `session/${encodeURIComponent(sessionId)}`;
  240. }
  241. function pathInside(root: string, child: string): boolean {
  242. const value = relative(root, child);
  243. return value === '' || (value !== '..' && !value.startsWith(`..${sep}`) && !isAbsolute(value));
  244. }
  245. function isMissing(error: unknown): boolean {
  246. return typeof error === 'object' && error !== null && Reflect.get(error, 'code') === 'ENOENT';
  247. }