@evandu/super-pi 0.1.222 → 0.1.224

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 (57) hide show
  1. package/dist/client/.super-pi-client-sources.json +12 -8
  2. package/dist/client/assets/{CodeMirrorEditor-IWcAz6oz.js → CodeMirrorEditor-CophJ9Eb.js} +2 -2
  3. package/dist/client/assets/{dist-D73UQVEK.js → dist-BGVYvXYo.js} +1 -1
  4. package/dist/client/assets/{dist-Bx-zvsek.js → dist-BYjXg164.js} +1 -1
  5. package/dist/client/assets/{dist-DglikBo1.js → dist-BxcN7lnR.js} +1 -1
  6. package/dist/client/assets/{dist-Cd2jBngi.js → dist-C0s45hG8.js} +1 -1
  7. package/dist/client/assets/{dist-DZFnjuKR.js → dist-C3BgT3PU.js} +1 -1
  8. package/dist/client/assets/{dist-B4YZqIKX.js → dist-C3amppza.js} +1 -1
  9. package/dist/client/assets/{dist-ChJliyoT.js → dist-C8FqYuNv.js} +1 -1
  10. package/dist/client/assets/{dist-Brmqe6G6.js → dist-CEbbDGoy.js} +1 -1
  11. package/dist/client/assets/{dist-DgRXONWV.js → dist-CFMeFXLU.js} +1 -1
  12. package/dist/client/assets/{dist-KddcFuL2.js → dist-CMPtWQjx.js} +1 -1
  13. package/dist/client/assets/{dist-DR-NR2sl.js → dist-Ch4dVwk4.js} +1 -1
  14. package/dist/client/assets/{dist-B2WzMUqb.js → dist-Clk6Knpv.js} +1 -1
  15. package/dist/client/assets/{dist-CRfBzL2s.js → dist-CxeSxC9m.js} +1 -1
  16. package/dist/client/assets/{dist-B41_P-GB.js → dist-D-s1GEbP.js} +1 -1
  17. package/dist/client/assets/{dist-fzY9qpWd.js → dist-D7On6h3N.js} +1 -1
  18. package/dist/client/assets/{dist-C-CsTWFq.js → dist-DBdR1Wph.js} +1 -1
  19. package/dist/client/assets/{dist-ByhQMTZz.js → dist-TcwefdPn.js} +1 -1
  20. package/dist/client/assets/{dist-BPhtg6ss.js → dist-ZuNGtw_8.js} +1 -1
  21. package/dist/client/assets/{dist-DftBUe3J.js → dist-i8fMtdTP.js} +1 -1
  22. package/dist/client/assets/{dist-CLfjxR6r.js → dist-nSNA_ze3.js} +1 -1
  23. package/dist/client/assets/{dist-0tDquiIc.js → dist-pVo8vQ15.js} +1 -1
  24. package/dist/client/assets/{dist-JFHBsRN8.js → dist-ukIdoKjd.js} +1 -1
  25. package/dist/client/assets/index-CoJT13t0.js +105 -0
  26. package/dist/client/assets/index-DK_mME9e.css +1 -0
  27. package/dist/client/index.html +2 -2
  28. package/dist/server/application/conversation-service.d.ts +15 -0
  29. package/dist/server/application/conversation-service.js +28 -0
  30. package/dist/server/application/project-service.d.ts +7 -1
  31. package/dist/server/application/project-service.js +29 -9
  32. package/dist/server/application/run-service.js +44 -17
  33. package/dist/server/file-index.d.ts +13 -1
  34. package/dist/server/file-index.js +108 -12
  35. package/dist/server/file-name-index.d.ts +8 -0
  36. package/dist/server/file-name-index.js +58 -11
  37. package/dist/server/files.js +4 -0
  38. package/dist/server/http-server.js +143 -17
  39. package/dist/server/session-cwd.d.ts +2 -0
  40. package/dist/server/session-cwd.js +16 -1
  41. package/dist/server/store.js +7 -0
  42. package/dist/server/types.d.ts +21 -0
  43. package/dist/server/workspace-file-indexes.d.ts +2 -0
  44. package/dist/server/workspace-file-indexes.js +61 -0
  45. package/dist/server/workspace-file-operations.d.ts +36 -0
  46. package/dist/server/workspace-file-operations.js +281 -0
  47. package/dist/server/workspace-file-response.d.ts +3 -0
  48. package/dist/server/workspace-file-response.js +79 -0
  49. package/dist/shared/archive-decisions.d.ts +37 -0
  50. package/dist/shared/archive-decisions.js +86 -0
  51. package/dist/shared/project-overview.d.ts +35 -0
  52. package/dist/shared/project-overview.js +39 -1
  53. package/dist/shared/workspace-file-preview.d.ts +4 -0
  54. package/dist/shared/workspace-file-preview.js +28 -0
  55. package/package.json +4 -1
  56. package/dist/client/assets/index-DbtNmSyS.js +0 -103
  57. package/dist/client/assets/index-OmaD3l6r.css +0 -1
@@ -8,8 +8,8 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-DbtNmSyS.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-OmaD3l6r.css">
11
+ <script type="module" crossorigin src="/assets/index-CoJT13t0.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-DK_mME9e.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
@@ -117,8 +117,23 @@ export declare class ConversationService {
117
117
  selectConversation(conversationId: string): Promise<void>;
118
118
  /**
119
119
  * Archives a conversation.
120
+ *
121
+ * 归档这件事带三件事:树被归档、**欠着用户的决策随之作废**、然后广播一次。
122
+ *
123
+ * 为什么作废:负责人会话被归档 ⇒ 那个项目从此没人管 ⇒ 它欠用户的决定没有人会再去问了。
124
+ * 用户自己说过:「一旦决定归档了,过往所有的待决策项都是垃圾」。所以那些决策作废。
125
+ *
126
+ * 作废是**定性**,不是删除:例外仍然留在 `p.escalations` 里,`status` 变成 `dismissed`,
127
+ * `decision` 写下为什么,`resolvedAt` 记下什么时候 —— 可查、可导出。supervisor 级的内部事
128
+ * 不作废,别的项目的例外也不动。
129
+ *
130
+ * 顺序有讲究:先归档再作废。归档失败(运行中的会话)时什么也不该发生。
120
131
  */
121
132
  archiveConversation(conversationId: string): Promise<void>;
133
+ /**
134
+ * 把「负责人会话被归档」的那些项目的未决用户级例外作废。记录留下,状态改掉。
135
+ */
136
+ private dismissDecisionsOfArchivedOwners;
122
137
  /**
123
138
  * Unarchives an archived tree root and every archived descendant. Descendants that are
124
139
  * already active need no write; they are already in the live tree this restore rejoins.
@@ -2,6 +2,7 @@ import { assertModelAllowed } from "../model-filter.js";
2
2
  import { newConversationId } from "../store.js";
3
3
  import { normalizeSessionCwd, resolveSessionCwd } from "../session-cwd.js";
4
4
  import { isChildSession } from "../../shared/child-session-lock.js";
5
+ import { dismissArchivedOwnerDecisions } from "../../shared/archive-decisions.js";
5
6
  import { rm } from "node:fs/promises";
6
7
  import { copyForkUploads, deleteConversationUploads } from "../upload.js";
7
8
  function isMissingPrimaryAgent(error, agentId) {
@@ -237,12 +238,39 @@ export class ConversationService {
237
238
  }
238
239
  /**
239
240
  * Archives a conversation.
241
+ *
242
+ * 归档这件事带三件事:树被归档、**欠着用户的决策随之作废**、然后广播一次。
243
+ *
244
+ * 为什么作废:负责人会话被归档 ⇒ 那个项目从此没人管 ⇒ 它欠用户的决定没有人会再去问了。
245
+ * 用户自己说过:「一旦决定归档了,过往所有的待决策项都是垃圾」。所以那些决策作废。
246
+ *
247
+ * 作废是**定性**,不是删除:例外仍然留在 `p.escalations` 里,`status` 变成 `dismissed`,
248
+ * `decision` 写下为什么,`resolvedAt` 记下什么时候 —— 可查、可导出。supervisor 级的内部事
249
+ * 不作废,别的项目的例外也不动。
250
+ *
251
+ * 顺序有讲究:先归档再作废。归档失败(运行中的会话)时什么也不该发生。
240
252
  */
241
253
  async archiveConversation(conversationId) {
242
254
  this.runService.reviewMemoryBoundary(conversationId);
255
+ const archivedIds = this.store.conversationSubtreeIds(conversationId);
243
256
  await this.store.archiveConversationTree(conversationId);
257
+ await this.dismissDecisionsOfArchivedOwners(archivedIds);
244
258
  this.broadcaster.broadcastState();
245
259
  }
260
+ /**
261
+ * 把「负责人会话被归档」的那些项目的未决用户级例外作废。记录留下,状态改掉。
262
+ */
263
+ async dismissDecisionsOfArchivedOwners(conversationIds) {
264
+ if (!conversationIds.length)
265
+ return;
266
+ const projects = this.store.projects();
267
+ const updated = dismissArchivedOwnerDecisions(projects, conversationIds, new Date().toISOString());
268
+ for (const [index, project] of updated.entries()) {
269
+ if (project === projects[index])
270
+ continue;
271
+ await this.store.setProject(project);
272
+ }
273
+ }
246
274
  /**
247
275
  * Unarchives an archived tree root and every archived descendant. Descendants that are
248
276
  * already active need no write; they are already in the live tree this restore rejoins.
@@ -300,7 +300,13 @@ export declare class ProjectService {
300
300
  };
301
301
  private reconcile;
302
302
  private resources;
303
- list(workspaceId?: string): Project[];
303
+ list(workspaceId?: string, view?: "current" | "history"): Project[];
304
+ /**
305
+ * IS THE OWNER SESSION IN THE ARCHIVE? A project whose leader was archived has nobody left to
306
+ * run it. The server is the one that knows what is archived, so it computes the answer and
307
+ * hands the client the same fact in the project payload (`ownerArchived`).
308
+ */
309
+ private ownerArchived;
304
310
  headline(p: Project, actor?: string, resources?: Project["resources"]): string;
305
311
  private activitySessions;
306
312
  private isActorRelated;
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { deriveProjectActivity, deriveTaskActivity } from "../../shared/project-presentation.js";
3
- import { deliveryCoversTasks, latestProjectDelivery } from "../../shared/project-overview.js";
3
+ import { deliveryCoversTasks, latestProjectDelivery, projectInView } from "../../shared/project-overview.js";
4
4
  import { buildTeamHandoff, discoverTeamFiles, parseTeamContext, pathsOverlap, publishTeamContext, teamPaths } from "../team-context.js";
5
5
  import { deriveReportingState, deriveSessionState, sessionStateWord, } from "../../shared/session-reporting.js";
6
6
  const stamp = () => new Date().toISOString();
@@ -639,6 +639,10 @@ export class ProjectService {
639
639
  return {
640
640
  ...p,
641
641
  status: this.statusWithInterruptions(p),
642
+ /* THE CLIENT MIRRORS THE VIEW RULE, so it needs the same fact: is the owner session in the
643
+ archive? The server computes it (it is the one that knows), and the client re-applies the
644
+ rule rather than guessing. */
645
+ ownerArchived: this.ownerArchived(p),
642
646
  resources,
643
647
  activity: deriveProjectActivity({ ...p, status: this.statusWithInterruptions(p), resources }),
644
648
  tasks: p.tasks.map((t) => ({ ...ProjectService.taskView(t, p), activity: deriveTaskActivity(t, resources.sessions, p.mode, p.tasks) })),
@@ -1038,11 +1042,13 @@ export class ProjectService {
1038
1042
  * "project" by the same rule as everybody else - there is no special case for it. */
1039
1043
  const projectTreeId = p.ownerConversationId ? this.store.conversation(p.ownerConversationId)?.treeId : undefined;
1040
1044
  const memberConversations = state.conversations.filter((c) => c.workspaceId === p.workspaceId && members.has(c.id));
1045
+ // Match the sidebar's archive marker without removing historical usage.
1046
+ const visibleMemberConversations = memberConversations.filter((c) => !c.archivedAt);
1041
1047
  const openEscalationRequesters = new Set((p.escalations ?? [])
1042
1048
  .filter((e) => e.status === "open" && e.requestedByConversationId)
1043
1049
  .map((e) => e.requestedByConversationId));
1044
1050
  const snapshotMap = new Map();
1045
- for (const c of memberConversations) {
1051
+ for (const c of visibleMemberConversations) {
1046
1052
  snapshotMap.set(c.id, {
1047
1053
  id: c.id,
1048
1054
  parentConversationId: c.parentConversationId,
@@ -1053,9 +1059,9 @@ export class ProjectService {
1053
1059
  ...(c.hasPendingResult ? { hasPendingResult: true } : {}),
1054
1060
  });
1055
1061
  }
1056
- const sessions = memberConversations.map((c) => {
1062
+ const sessions = visibleMemberConversations.map((c) => {
1057
1063
  const parent = c.parentConversationId ? this.store.conversation(c.parentConversationId) : undefined;
1058
- const directChildren = memberConversations
1064
+ const directChildren = visibleMemberConversations
1059
1065
  .filter((child) => child.parentConversationId === c.id)
1060
1066
  .map((child) => snapshotMap.get(child.id));
1061
1067
  const snapshot = snapshotMap.get(c.id);
@@ -1128,17 +1134,31 @@ export class ProjectService {
1128
1134
  return acc;
1129
1135
  }, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
1130
1136
  return { tokens: tokens(usage),
1131
- usageKnown: sessions.length > 0 && sessions.every((s) => Boolean(this.store.conversation(s.id)?.usage)) && runs.every((r) => Boolean(r.usage)),
1132
- activeWorkers: sessions.filter((s) => (!coordinatorIds.has(s.id) || (leaderIsWorker && s.id === p.ownerConversationId)) && busy(s.status)).length + runs.filter((r) => r.status === "running").length,
1137
+ usageKnown: memberConversations.length > 0 && memberConversations.every((c) => Boolean(c.usage)) && runs.every((r) => Boolean(r.usage)),
1138
+ activeWorkers: sessions.filter((s) => (!coordinatorIds.has(s.id) || (leaderIsWorker && s.id === p.ownerConversationId)) && busy(s.status)).length + runs.filter((r) => r.status === "running" && visibleMemberConversations.some((c) => c.id === r.conversationId)).length,
1133
1139
  // THE PROJECT'S OWN MEMORY TREE, named once so the client does not have to infer it from
1134
1140
  // the sessions. Absent only when the project has no leader session yet.
1135
1141
  memoryTreeId: projectTreeId, sessions,
1142
+ // Evidence keeps its original base directory even when the owner is archived.
1143
+ ownerCwd: memberConversations.find((c) => c.id === p.ownerConversationId)?.cwd,
1136
1144
  // THE RAW 1:1 PICTURE OF THE SAME MONEY, next to the equivalent number it is spent in.
1137
1145
  usage, rawTokens: usage.input + usage.output + usage.cacheRead + usage.cacheWrite };
1138
1146
  }
1139
- list(workspaceId) {
1147
+ list(workspaceId, view = "current") {
1140
1148
  const scope = this.workspace(workspaceId);
1141
- return this.store.projects().filter((p) => p.workspaceId === scope).map((p) => this.projectView(p));
1149
+ return this.store.projects()
1150
+ .filter((p) => p.workspaceId === scope && projectInView(p, this.ownerArchived(p), view))
1151
+ .map((p) => this.projectView(p));
1152
+ }
1153
+ /**
1154
+ * IS THE OWNER SESSION IN THE ARCHIVE? A project whose leader was archived has nobody left to
1155
+ * run it. The server is the one that knows what is archived, so it computes the answer and
1156
+ * hands the client the same fact in the project payload (`ownerArchived`).
1157
+ */
1158
+ ownerArchived(p) {
1159
+ if (!p.ownerConversationId)
1160
+ return false;
1161
+ return Boolean(this.store.conversation(p.ownerConversationId)?.archivedAt);
1142
1162
  }
1143
1163
  headline(p, actor, resources) {
1144
1164
  const total = p.tasks.length;
@@ -1180,7 +1200,7 @@ export class ProjectService {
1180
1200
  }
1181
1201
  activitySessions(p) {
1182
1202
  const ids = new Set([p.ownerConversationId, ...p.tasks.flatMap(task => [task.ownerConversationId, task.reviewerConversationId])].filter(Boolean));
1183
- return [...ids].flatMap(id => { const session = this.store.conversation(id); return session ? [{ id, status: session.status }] : []; });
1203
+ return [...ids].flatMap(id => { const session = this.store.conversation(id); return session && !session.archivedAt ? [{ id, status: session.status }] : []; });
1184
1204
  }
1185
1205
  isActorRelated(p, actor) {
1186
1206
  return this.isMember(p, actor);
@@ -9,12 +9,15 @@ import { formatTurnFailure, isLengthExceededError } from "../turn-failure.js";
9
9
  import { isLengthContinuation, lengthContinuationText, MAX_LENGTH_CONTINUATIONS, buildLengthContinuationPrompt } from "../length-continuation.js";
10
10
  import { describeThrownWithStack } from "../failure-text.js";
11
11
  import { toWorkspaceRelative } from "../files.js";
12
- import { refreshWorkspaceIndex } from "../file-index.js";
12
+ import { inScope, refreshWorkspaceIndex } from "../file-index.js";
13
13
  import { resolveSessionCwd } from "../session-cwd.js";
14
14
  import { CHILD_QUESTION_LOCK_REASON, isChildSession } from "../../shared/child-session-lock.js";
15
15
  import { execFile } from "node:child_process";
16
16
  import { promisify } from "node:util";
17
17
  import { randomUUID } from "node:crypto";
18
+ import { isAbsolute, resolve } from "node:path";
19
+ import { lstat } from "node:fs/promises";
20
+ import { explorerPath, serializeWorkspaceWrite } from "../workspace-file-operations.js";
18
21
  const execFileAsync = promisify(execFile);
19
22
  /**
20
23
  * Validates a caller-supplied delivery mode without silently falling back on bogus values.
@@ -1392,6 +1395,7 @@ export class RunService {
1392
1395
  * back as a path with one space.
1393
1396
  */
1394
1397
  const fileWritePaths = new Map();
1398
+ let runCwd = workspace.path;
1395
1399
  const onFileWrite = (path, _toolName, toolCallId) => {
1396
1400
  if (!acceptsEvent("file.write"))
1397
1401
  return;
@@ -1410,17 +1414,16 @@ export class RunService {
1410
1414
  // it right, while the name index stored the absolute path with its leading slash stripped
1411
1415
  // (`home/me/project/src/a.ts`) - an entry that matched by name and then pointed at a file that
1412
1416
  // does not exist.
1413
- const relative = toWorkspaceRelative(workspace.path, path);
1414
- tracker.record(workspace.id, relative, { root: workspace.path, conversationId: conversation.id });
1415
- refreshWorkspaceIndex(this.fileIndexes, workspace.id, relative, workspace.path);
1416
- // The name index learns about the write as well, so the file the agent just created is
1417
- // findable by name straight away rather than after the next background scan. It goes through
1418
- // the SAME `ensureNameIndex` the HTTP layer uses, so there is one index per workspace rather
1419
- // than one per layer.
1420
- if (this.nameIndexes) {
1421
- ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1422
- recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, relative);
1417
+ let relative;
1418
+ try {
1419
+ relative = toWorkspaceRelative(workspace.path, isAbsolute(path) ? path : resolve(runCwd, path));
1420
+ }
1421
+ catch {
1422
+ return;
1423
1423
  }
1424
+ if (!relative)
1425
+ return;
1426
+ tracker.record(workspace.id, relative, { root: workspace.path, conversationId: conversation.id });
1424
1427
  if (toolCallId)
1425
1428
  fileWritePaths.set(toolCallId, relative);
1426
1429
  this.broadcastFileChanges(workspace.id);
@@ -1524,14 +1527,37 @@ export class RunService {
1524
1527
  const writtenPath = call.id ? fileWritePaths.get(call.id) : undefined;
1525
1528
  if (writtenPath) {
1526
1529
  this.fileChanges?.confirm(workspace.id, writtenPath, workspace.path);
1527
- refreshWorkspaceIndex(this.fileIndexes, workspace.id, writtenPath, workspace.path);
1528
- if (this.nameIndexes) {
1529
- ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1530
- recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, writtenPath);
1531
- }
1532
1530
  if (call.id)
1533
1531
  fileWritePaths.delete(call.id);
1534
1532
  this.broadcastFileChanges(workspace.id);
1533
+ void serializeWorkspaceWrite(workspace.path, async () => {
1534
+ const target = await explorerPath(workspace.path, workspace.path, writtenPath);
1535
+ const info = await lstat(target).catch((error) => {
1536
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR")
1537
+ throw error;
1538
+ });
1539
+ refreshWorkspaceIndex(this.fileIndexes, workspace.id, writtenPath, workspace.path);
1540
+ if (this.nameIndexes && info?.isFile()) {
1541
+ ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1542
+ recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, writtenPath);
1543
+ }
1544
+ else if (!info)
1545
+ for (const index of this.nameIndexes?.values() ?? []) {
1546
+ if (index.workspaceId !== workspace.id)
1547
+ continue;
1548
+ const target = inScope(workspace.path, index.cwd, writtenPath);
1549
+ if (target)
1550
+ index.removeTree(target);
1551
+ }
1552
+ this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id, paths: [writtenPath] });
1553
+ }).catch((error) => {
1554
+ if (error && typeof error === "object" && "status" in error && error.status === 403)
1555
+ return;
1556
+ console.warn("Super Pi: could not update the workspace file tree", error);
1557
+ });
1558
+ }
1559
+ else if (/^(bash|powershell|shell|command|apply_patch|write|edit)$/i.test(call.name)) {
1560
+ this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id });
1535
1561
  }
1536
1562
  const index = call.id ? rowByToolCallId.get(call.id) : undefined;
1537
1563
  if (index === undefined)
@@ -1605,11 +1631,12 @@ export class RunService {
1605
1631
  return pendingTools;
1606
1632
  };
1607
1633
  try {
1634
+ runCwd = await resolveSessionCwd(workspace.path, conversation.cwd);
1608
1635
  for await (const delta of this.runtime.answer({
1609
1636
  conversation,
1610
1637
  prompt,
1611
1638
  signal: controller.signal,
1612
- cwd: await resolveSessionCwd(workspace.path, conversation.cwd),
1639
+ cwd: runCwd,
1613
1640
  host: {
1614
1641
  notify: (request) => { if (acceptsEvent("ui.notify"))
1615
1642
  uiHost.notify(request); },
@@ -1,4 +1,8 @@
1
- import { type FileMeta } from "./files.js";
1
+ import { type DirEntry, type FileMeta } from "./files.js";
2
+ export declare function belowPath(path: string, parent: string): boolean;
3
+ export declare function inScope(workspaceRoot: string, cwd: string, path: string): string | undefined;
4
+ export declare function blockedBy(path: string, blocked: ReadonlySet<string>): boolean;
5
+ export declare function matchesDirectoryReads(path: string, snapshots: ReadonlyMap<string, ReadonlySet<string>>): boolean;
2
6
  export type IndexedFile = {
3
7
  path: string;
4
8
  kind: "file" | "directory";
@@ -40,12 +44,17 @@ export declare class FileIndex {
40
44
  private root;
41
45
  private queue;
42
46
  private building;
47
+ private needsScan;
43
48
  private skipped;
49
+ private readonly touched;
50
+ private readonly removedDuringScan;
51
+ private readonly directoriesReadDuringScan;
44
52
  version: number;
45
53
  builtAt: number;
46
54
  complete: boolean;
47
55
  constructor(workspaceId: string, broadcast: (event: FileIndexEvent) => void, cwd?: string);
48
56
  start(root: string): void;
57
+ markStale(): void;
49
58
  stop(): void;
50
59
  snapshot(since?: number): FileIndexSnapshot;
51
60
  /**
@@ -66,6 +75,9 @@ export declare class FileIndex {
66
75
  * caller's file API operation has already passed the sole containment guard and read this metadata. */
67
76
  recordFile(path: string, meta: FileMeta, mtimeMs?: number): void;
68
77
  remove(path: string): void;
78
+ removeTree(path: string): void;
79
+ recordEntries(entries: Pick<IndexedFile, "path" | "kind">[]): void;
80
+ reconcileDirectory(directory: string, entries: DirEntry[]): void;
69
81
  private scan;
70
82
  private publish;
71
83
  }
@@ -1,6 +1,34 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
- import { resolve } from "node:path";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
3
  import { SEARCH_SKIP_DIRS, createRootGuard, fileMeta, isTextName, toRelative, toWorkspaceRelative } from "./files.js";
4
+ export function belowPath(path, parent) {
5
+ return !parent || path === parent || path.startsWith(`${parent}/`);
6
+ }
7
+ export function inScope(workspaceRoot, cwd, path) {
8
+ const local = relative(resolve(workspaceRoot, cwd), resolve(workspaceRoot, path));
9
+ if (local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local))
10
+ return;
11
+ return local.split(sep).join("/");
12
+ }
13
+ export function blockedBy(path, blocked) {
14
+ if (blocked.has(""))
15
+ return true;
16
+ for (let prefix = path; prefix; prefix = prefix.slice(0, Math.max(0, prefix.lastIndexOf("/")))) {
17
+ if (blocked.has(prefix))
18
+ return true;
19
+ }
20
+ return false;
21
+ }
22
+ export function matchesDirectoryReads(path, snapshots) {
23
+ for (let entry = path; entry;) {
24
+ const parent = entry.slice(0, Math.max(0, entry.lastIndexOf("/")));
25
+ const present = snapshots.get(parent);
26
+ if (present && !present.has(entry))
27
+ return false;
28
+ entry = parent;
29
+ }
30
+ return true;
31
+ }
4
32
  const MAX_DIRECTORIES = 4000;
5
33
  const MAX_FILES = 30000;
6
34
  const MAX_MS = 4000;
@@ -19,7 +47,11 @@ export class FileIndex {
19
47
  root = "";
20
48
  queue = [];
21
49
  building = false;
50
+ needsScan = false;
22
51
  skipped = [];
52
+ touched = new Set();
53
+ removedDuringScan = new Set();
54
+ directoriesReadDuringScan = new Map();
23
55
  version = 0;
24
56
  builtAt = 0;
25
57
  complete = false;
@@ -29,20 +61,39 @@ export class FileIndex {
29
61
  this.cwd = cwd;
30
62
  }
31
63
  start(root) {
32
- if (this.building || this.builtAt)
64
+ if (this.building || (this.builtAt && !this.needsScan))
33
65
  return;
66
+ const replacing = !!this.builtAt;
67
+ this.needsScan = false;
34
68
  this.root = root;
35
69
  this.building = true;
70
+ this.complete = false;
71
+ this.skipped = [];
36
72
  this.queue = [""];
37
- void this.scan();
73
+ void this.scan(replacing);
38
74
  }
75
+ markStale() { if (this.root)
76
+ this.needsScan = true; }
39
77
  stop() { }
40
78
  snapshot(since) {
41
79
  const valid = Number.isFinite(since) && since !== undefined;
42
- const deltas = valid ? this.history.filter((item) => item.version > since) : [];
80
+ const changed = new Map();
81
+ const removed = new Set();
82
+ if (valid)
83
+ for (const item of this.history) {
84
+ if (item.version <= since)
85
+ continue;
86
+ for (const entry of item.changed) {
87
+ removed.delete(entry.path);
88
+ changed.set(entry.path, entry);
89
+ }
90
+ for (const path of item.removed) {
91
+ changed.delete(path);
92
+ removed.add(path);
93
+ }
94
+ }
43
95
  return { version: this.version, builtAt: this.builtAt, complete: this.complete, skipped: this.skipped,
44
- changed: valid ? deltas.flatMap((item) => item.changed) : [...this.entries.values()],
45
- removed: valid ? deltas.flatMap((item) => item.removed) : [] };
96
+ changed: valid ? [...changed.values()] : [...this.entries.values()], removed: [...removed] };
46
97
  }
47
98
  /**
48
99
  * ONE FILE, REFRESHED.
@@ -83,7 +134,7 @@ export class FileIndex {
83
134
  catch (error) {
84
135
  const code = error.code;
85
136
  if (code === "ENOENT" || code === "ENOTDIR")
86
- this.remove(key);
137
+ this.removeTree(key);
87
138
  else
88
139
  throw error;
89
140
  }
@@ -98,7 +149,39 @@ export class FileIndex {
98
149
  }
99
150
  remove(path) { if (this.entries.delete(path))
100
151
  this.publish([], [path]); }
101
- async scan() {
152
+ removeTree(path) {
153
+ if (this.building)
154
+ this.removedDuringScan.add(path);
155
+ const removed = [...this.entries.keys()].filter(key => belowPath(key, path));
156
+ for (const key of removed)
157
+ this.entries.delete(key);
158
+ this.publish([], removed);
159
+ }
160
+ recordEntries(entries) {
161
+ const changed = [];
162
+ for (const { path, kind } of entries) {
163
+ if (!path || path.split("/").some((segment, i, all) => SEARCH_SKIP_DIRS.has(segment) && (i < all.length - 1 || kind === "directory")))
164
+ continue;
165
+ if (this.entries.get(path)?.kind === kind)
166
+ continue;
167
+ changed.push({ path, kind, size: null, mtimeMs: null, etag: null, text: kind === "file" ? isTextName(path) : null });
168
+ }
169
+ this.publish(changed, []);
170
+ }
171
+ reconcileDirectory(directory, entries) {
172
+ const present = new Map(entries.map(entry => [entry.path, entry]));
173
+ if (this.building)
174
+ this.directoriesReadDuringScan.set(directory, new Set(entries.filter(entry => !entry.symlink && entry.kind !== "symlink").map(entry => entry.path)));
175
+ for (const [path, existing] of this.entries) {
176
+ if (path.slice(0, Math.max(0, path.lastIndexOf("/"))) !== directory)
177
+ continue;
178
+ const entry = present.get(path);
179
+ if (!entry || entry.symlink || entry.kind !== existing.kind)
180
+ this.removeTree(path);
181
+ }
182
+ this.recordEntries(entries.flatMap(entry => !entry.symlink && entry.kind !== "symlink" ? [{ path: entry.path, kind: entry.kind }] : []));
183
+ }
184
+ async scan(replacing) {
102
185
  const started = Date.now();
103
186
  let dirs = 0;
104
187
  let files = 0;
@@ -151,14 +234,25 @@ export class FileIndex {
151
234
  this.builtAt = Date.now();
152
235
  // Quick Open does not need per-directory progress. One final batch bounds WS traffic and keeps the
153
236
  // existing on-demand tree interactive throughout the scan (including dependency directories).
154
- this.publish(changed, [], true);
237
+ const scanned = changed.filter(entry => !this.touched.has(entry.path) && !blockedBy(entry.path, this.removedDuringScan)
238
+ && matchesDirectoryReads(entry.path, this.directoriesReadDuringScan));
239
+ const found = replacing && !incomplete ? new Set(scanned.map(entry => entry.path)) : undefined;
240
+ const removed = found ? [...this.entries.keys()].filter(path => !this.touched.has(path) && !found.has(path)) : [];
241
+ for (const path of removed)
242
+ this.entries.delete(path);
243
+ this.publish(scanned, removed, true, replacing);
244
+ this.touched.clear();
245
+ this.removedDuringScan.clear();
246
+ this.directoriesReadDuringScan.clear();
155
247
  }
156
- publish(changed, removed, force = false) {
248
+ publish(changed, removed, force = false, invalidateMetadata = false) {
157
249
  changed = changed.map((entry) => {
158
250
  // A targeted stat may race the cheap directory walk. Do not let the later readdir-only result erase
159
251
  // metadata that was already paid for and verified.
160
252
  const previous = this.entries.get(entry.path);
161
- const merged = previous?.kind === entry.kind && entry.size === null ? { ...entry, size: previous.size, mtimeMs: previous.mtimeMs, etag: previous.etag } : entry;
253
+ if (this.building)
254
+ this.touched.add(entry.path);
255
+ const merged = !invalidateMetadata && previous?.kind === entry.kind && entry.size === null ? { ...entry, size: previous.size, mtimeMs: previous.mtimeMs, etag: previous.etag } : entry;
162
256
  this.entries.set(entry.path, merged);
163
257
  return merged;
164
258
  });
@@ -192,7 +286,9 @@ export function refreshWorkspaceIndex(indexes, workspaceId, path, workspaceRoot)
192
286
  for (const index of indexes?.values() ?? []) {
193
287
  if (index.workspaceId !== workspaceId)
194
288
  continue;
195
- const target = workspaceRoot && index.cwd ? resolve(workspaceRoot, path) : path;
289
+ const target = workspaceRoot ? inScope(workspaceRoot, index.cwd, path) : path;
290
+ if (!target)
291
+ continue;
196
292
  void index.refresh(target).catch((error) => {
197
293
  console.warn(`Super Pi: the file index did not refresh ${path}: ${error instanceof Error ? error.message : "unknown error"}`);
198
294
  });
@@ -1,3 +1,4 @@
1
+ import { type DirEntry } from "./files.js";
1
2
  /**
2
3
  * THE INDEX FOR ONE WORKSPACE, created on demand and then kept.
3
4
  *
@@ -70,6 +71,10 @@ export declare class FileNameIndex {
70
71
  private scanned;
71
72
  private stopped;
72
73
  private incomplete;
74
+ private needsScan;
75
+ private generation;
76
+ private readonly removedDuringScan;
77
+ private readonly directoriesReadDuringScan;
73
78
  constructor(workspaceId: string, cwd?: string);
74
79
  /**
75
80
  * Whether the first pass has FINISHED.
@@ -85,6 +90,7 @@ export declare class FileNameIndex {
85
90
  get progress(): IndexProgress;
86
91
  /** Begin the background scan. Safe to call more than once; the second call is a no-op. */
87
92
  start(root: string): void;
93
+ markStale(): void;
88
94
  /**
89
95
  * WHY THE SCAN'S FAILURE IS RECORDED RATHER THAN THROWN.
90
96
  *
@@ -108,6 +114,8 @@ export declare class FileNameIndex {
108
114
  upsert(relativePath: string, kind?: "file" | "directory"): void;
109
115
  /** Forget a path that is gone. */
110
116
  remove(relativePath: string): void;
117
+ removeTree(path: string): void;
118
+ reconcileDirectory(directory: string, entries: DirEntry[]): void;
111
119
  /**
112
120
  * The query. A substring filter over an in-memory map - no filesystem access at all.
113
121
  *