arco-workbench 0.1.3 → 0.1.4
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/CONTRIBUTING.md +1 -1
- package/README.md +5 -1
- package/client/dist/assets/{PhosphorBackdrop-CkVIGkeX.js → PhosphorBackdrop-CNumba2X.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-DHF7CnpE.js → ThemedBackgroundShaderImpl-DX5KyCt3.js} +1 -1
- package/client/dist/assets/{XtermView-SY0UcZUS.js → XtermView-DhS5g8Rt.js} +1 -1
- package/client/dist/assets/{galleryEditor-Ca4F8HiM.js → galleryEditor-fPb76Cjv.js} +1 -1
- package/client/dist/assets/index-CjkHb-_n.js +592 -0
- package/client/dist/assets/index-DIbh3ae5.css +1 -0
- package/client/dist/index.html +2 -2
- package/client/src/App.tsx +2 -0
- package/client/src/alerts/desktopAlerts.ts +13 -1
- package/client/src/brief/briefFacts.ts +22 -0
- package/client/src/brief/briefFromStore.ts +7 -2
- package/client/src/components/ArtifactMoveDialog.tsx +64 -0
- package/client/src/components/BriefControl.tsx +38 -47
- package/client/src/components/CatchMeUp.tsx +25 -25
- package/client/src/components/CheckpointActions.tsx +7 -4
- package/client/src/components/ClusterComposerButtons.tsx +6 -3
- package/client/src/components/ClusterPlanTab.tsx +15 -1
- package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +6 -2
- package/client/src/components/ClusterTab.tsx +33 -3
- package/client/src/components/ClusterTaskBoardTab.tsx +62 -8
- package/client/src/components/DialogShell.tsx +115 -0
- package/client/src/components/DocsUpdateDialog.tsx +16 -42
- package/client/src/components/ForwardMessages.tsx +28 -32
- package/client/src/components/GitDialog.tsx +52 -52
- package/client/src/components/GitOtherWork.tsx +4 -2
- package/client/src/components/HandoffDialog.tsx +19 -45
- package/client/src/components/Home/HomeView.tsx +36 -8
- package/client/src/components/Home/home.css +7 -0
- package/client/src/components/KeepButton.tsx +23 -0
- package/client/src/components/MdTuneupDialog.tsx +52 -51
- package/client/src/components/MemberCard.tsx +4 -1
- package/client/src/components/MemberPane.tsx +1 -1
- package/client/src/components/NotificationCenter.tsx +4 -3
- package/client/src/components/NotificationChannelsSettings.tsx +25 -7
- package/client/src/components/PlanCandidateBanner.tsx +111 -57
- package/client/src/components/PlanComposerDialog.tsx +55 -87
- package/client/src/components/ProjectStateNotice.tsx +60 -0
- package/client/src/components/PublicProjectBox.tsx +25 -0
- package/client/src/components/ResearchDialog.tsx +15 -24
- package/client/src/components/ReviewDialog.tsx +32 -57
- package/client/src/components/RightPanel/OutputsPanel.tsx +4 -0
- package/client/src/components/RightPanel/PlanTab.tsx +24 -2
- package/client/src/components/RightPanel/UsageTab.tsx +77 -1
- package/client/src/components/SkillEditorDialog.tsx +38 -73
- package/client/src/components/SpawnDialog.tsx +19 -41
- package/client/src/components/StorageWarnings.tsx +21 -0
- package/client/src/components/SystemHeader.tsx +2 -2
- package/client/src/components/TerminalInput.tsx +6 -2
- package/client/src/components/TidyComposer.tsx +24 -41
- package/client/src/components/TranscriptSendDialog.tsx +151 -202
- package/client/src/components/UtilityAgentPicker.tsx +4 -2
- package/client/src/components/WorkflowCreator/index.tsx +2 -0
- package/client/src/components/WorkflowView.tsx +4 -1
- package/client/src/components/clusterNeedsYou.ts +35 -3
- package/client/src/components/compare/CompareDialog.tsx +26 -2
- package/client/src/components/terminalInput/planDraft.ts +33 -4
- package/client/src/components/utilityResult.ts +5 -1
- package/client/src/explorer/ExplorerApp.tsx +5 -2
- package/client/src/explorer/PlansLens.tsx +60 -19
- package/client/src/explorer/StorageLens.tsx +275 -0
- package/client/src/explorer/launch.ts +3 -3
- package/client/src/explorer/plansGrouping.ts +15 -0
- package/client/src/help/content/cluster.tsx +42 -7
- package/client/src/help/content/composer.tsx +26 -6
- package/client/src/help/content/header.tsx +16 -14
- package/client/src/help/content/misc.tsx +141 -6
- package/client/src/help/content/rightPanel.tsx +16 -0
- package/client/src/help/content/settings.tsx +4 -4
- package/client/src/help/manualSections/actions.tsx +19 -4
- package/client/src/help/manualSections/clusters.tsx +29 -16
- package/client/src/help/manualSections/configuration.tsx +6 -4
- package/client/src/help/manualSections/maintenance.tsx +27 -5
- package/client/src/help/manualSections/plans.tsx +96 -2
- package/client/src/help/manualSections/powerFeatures.tsx +2 -2
- package/client/src/help/manualSections/reference.tsx +6 -0
- package/client/src/help/manualSections/workspace.tsx +9 -5
- package/client/src/stores/appStore.ts +10 -1
- package/client/src/stores/appStore.types.ts +2 -0
- package/client/src/stores/mdTuneupStore.ts +5 -4
- package/client/src/stores/memoryTrim.ts +18 -2
- package/client/src/stores/storageWarningStore.ts +18 -0
- package/client/src/utils/gitDialogMemory.ts +26 -0
- package/client/src/utils/historyEvents.ts +1 -0
- package/client/src/utils/homeModel.ts +19 -0
- package/client/src/utils/publicProject.ts +56 -0
- package/client/src/ws/handleServerMessage.ts +7 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHECKPOINTS.md +2 -0
- package/docs/CLIENT.md +29 -11
- package/docs/FEATURES.md +14 -11
- package/docs/GETTING_STARTED.md +7 -7
- package/docs/GLOSSARY.md +3 -3
- package/docs/GOTCHAS.md +3 -2
- package/docs/HTTP_API.md +31 -1
- package/docs/NOTIFICATIONS.md +13 -14
- package/docs/OPERATIONS.md +27 -1
- package/docs/OPERATOR_ACTIONS.md +1 -1
- package/docs/OUTPUTS.md +9 -0
- package/docs/PERSISTENCE.md +34 -4
- package/docs/PLAN_OR_BOARD.md +7 -0
- package/docs/PRIMITIVES.md +3 -3
- package/docs/PROTOCOL.md +14 -4
- package/docs/PROTOCOL_CLUSTER.md +3 -2
- package/docs/SERVICE_MODE.md +5 -1
- package/docs/SETTINGS.md +8 -6
- package/docs/STORAGE_PLAN.md +324 -0
- package/docs/TASK_LEDGER.md +5 -4
- package/native/linux-arm64/manifest.json +1 -1
- package/node_modules/@arco/shared/dist/index.d.ts +2 -0
- package/node_modules/@arco/shared/dist/index.js +2 -0
- package/node_modules/@arco/shared/dist/protocol/autoPickup.d.ts +1 -1
- package/node_modules/@arco/shared/dist/protocol/autoPickup.js +1 -1
- package/node_modules/@arco/shared/dist/protocol/checkpoints.d.ts +1 -0
- package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +2 -1
- package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
- package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
- package/node_modules/@arco/shared/dist/protocol/mdTuneup.d.ts +6 -0
- package/node_modules/@arco/shared/dist/protocol/notifications.d.ts +2 -1
- package/node_modules/@arco/shared/dist/protocol/notifications.js +3 -2
- package/node_modules/@arco/shared/dist/protocol/plans.d.ts +2 -0
- package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +2 -1
- package/node_modules/@arco/shared/dist/protocol/storage.d.ts +21 -0
- package/node_modules/@arco/shared/dist/protocol/storage.js +3 -0
- package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +3 -0
- package/node_modules/@arco/shared/dist/protocol/utilityAgent.d.ts +2 -2
- package/node_modules/@arco/shared/dist/protocol/utilityAgent.js +2 -2
- package/node_modules/@arco/shared/dist/publicGuardrails.d.ts +7 -0
- package/node_modules/@arco/shared/dist/publicGuardrails.js +47 -0
- package/node_modules/@arco/shared/dist/publicSafetyRules.d.ts +1 -0
- package/node_modules/@arco/shared/dist/publicSafetyRules.js +6 -0
- package/node_modules/@arco/shared/package.json +1 -1
- package/package.json +3 -2
- package/scripts/packaging/arco.mjs +17 -1
- package/scripts/packaging/services.mjs +35 -5
- package/scripts/packaging/storage.mjs +125 -0
- package/scripts/packaging/update.mjs +3 -3
- package/server/dist/artifactCopy.d.ts +26 -0
- package/server/dist/artifactCopy.js +398 -0
- package/server/dist/atomicFile.d.ts +1 -0
- package/server/dist/atomicFile.js +1 -1
- package/server/dist/attention.d.ts +1 -1
- package/server/dist/attention.js +10 -13
- package/server/dist/catchUp.d.ts +2 -0
- package/server/dist/catchUp.js +46 -23
- package/server/dist/clusterPeerOps.d.ts +2 -0
- package/server/dist/clusterPeerOps.js +2 -0
- package/server/dist/clusterSnapshots.js +22 -12
- package/server/dist/eventLog.d.ts +55 -0
- package/server/dist/eventLog.js +792 -0
- package/server/dist/explorerLaunch.d.ts +4 -1
- package/server/dist/explorerLaunch.js +3 -2
- package/server/dist/explorerPlans.d.ts +4 -0
- package/server/dist/explorerPlans.js +27 -2
- package/server/dist/http/clusterRoutes.js +2 -0
- package/server/dist/http/explorerRoutes.js +2 -1
- package/server/dist/http/publicProjectRoutes.d.ts +2 -0
- package/server/dist/http/publicProjectRoutes.js +68 -0
- package/server/dist/http/router.js +6 -0
- package/server/dist/http/storageRoutes.d.ts +2 -0
- package/server/dist/http/storageRoutes.js +254 -0
- package/server/dist/http/usageStatsRoutes.js +3 -12
- package/server/dist/index.js +4 -0
- package/server/dist/keepStore.d.ts +16 -0
- package/server/dist/keepStore.js +119 -0
- package/server/dist/management/clusterActivity.js +6 -20
- package/server/dist/management/initHubLink.js +10 -43
- package/server/dist/mcp/clusterMcpTools.js +8 -1
- package/server/dist/notifications.d.ts +3 -1
- package/server/dist/notifications.js +5 -4
- package/server/dist/outputStore.d.ts +1 -0
- package/server/dist/outputStore.js +1 -1
- package/server/dist/outputs.js +39 -8
- package/server/dist/planHistory.d.ts +3 -0
- package/server/dist/planHistory.js +60 -0
- package/server/dist/primitives/runMdTuneup.d.ts +5 -1
- package/server/dist/primitives/runMdTuneup.js +43 -2
- package/server/dist/project/taskLedger.d.ts +4 -0
- package/server/dist/project/taskLedger.js +19 -0
- package/server/dist/providers/claude-native/peerTools.js +4 -0
- package/server/dist/providers/claude-native/resumeSummary.js +30 -19
- package/server/dist/providers/index.js +8 -13
- package/server/dist/providers/localProviderQueue.d.ts +2 -0
- package/server/dist/providers/localProviderQueue.js +11 -0
- package/server/dist/publicProject.d.ts +54 -0
- package/server/dist/publicProject.js +135 -0
- package/server/dist/recall/index.js +22 -23
- package/server/dist/server/broadcast.d.ts +2 -1
- package/server/dist/server/broadcast.js +56 -1
- package/server/dist/smartPickupAdapters.d.ts +7 -0
- package/server/dist/smartPickupAdapters.js +172 -8
- package/server/dist/storageActions.d.ts +50 -0
- package/server/dist/storageActions.js +326 -0
- package/server/dist/storageArchive.d.ts +24 -0
- package/server/dist/storageArchive.js +358 -0
- package/server/dist/storageOverview.d.ts +47 -0
- package/server/dist/storageOverview.js +197 -0
- package/server/dist/storageReport.d.ts +48 -0
- package/server/dist/storageReport.js +185 -0
- package/server/dist/storageWarnings.d.ts +4 -0
- package/server/dist/storageWarnings.js +96 -0
- package/server/dist/workers/limits.js +4 -1
- package/server/dist/workflowStore.d.ts +2 -0
- package/server/dist/workflowStore.js +88 -72
- package/server/dist/workflows/purgeWorkflow.d.ts +1 -0
- package/server/dist/workflows/purgeWorkflow.js +15 -2
- package/server/dist/workflows/sessionDiscovery.js +5 -17
- package/server/dist/workflows/sessionIndex.js +22 -17
- package/server/dist/ws/taskLedgerHandlers.js +8 -3
- package/server/dist/ws/workflowHandlers.js +5 -4
- package/server/package.json +1 -1
- package/server/src/artifactCopy.ts +254 -0
- package/server/src/atomicFile.ts +1 -1
- package/server/src/attention.ts +9 -10
- package/server/src/catchUp.ts +37 -15
- package/server/src/clusterPeerOps.ts +5 -0
- package/server/src/clusterSnapshots.ts +20 -13
- package/server/src/eventLog.ts +571 -0
- package/server/src/explorerLaunch.ts +3 -2
- package/server/src/explorerPlans.ts +22 -2
- package/server/src/http/clusterRoutes.ts +4 -1
- package/server/src/http/explorerRoutes.ts +2 -1
- package/server/src/http/publicProjectRoutes.ts +54 -0
- package/server/src/http/router.ts +4 -0
- package/server/src/http/storageRoutes.ts +187 -0
- package/server/src/http/usageStatsRoutes.ts +3 -11
- package/server/src/index.ts +4 -0
- package/server/src/keepStore.ts +102 -0
- package/server/src/management/clusterActivity.ts +6 -16
- package/server/src/management/initHubLink.ts +10 -39
- package/server/src/mcp/clusterMcpTools.ts +8 -2
- package/server/src/notifications.ts +4 -3
- package/server/src/outputStore.ts +5 -2
- package/server/src/outputs.ts +30 -6
- package/server/src/planHistory.ts +48 -0
- package/server/src/primitives/runMdTuneup.ts +32 -2
- package/server/src/project/taskLedger.ts +20 -0
- package/server/src/providers/claude-native/peerTools.ts +4 -0
- package/server/src/providers/claude-native/resumeSummary.ts +32 -18
- package/server/src/providers/index.ts +2 -16
- package/server/src/providers/localProviderQueue.ts +13 -0
- package/server/src/publicProject.ts +142 -0
- package/server/src/recall/index.ts +4 -9
- package/server/src/server/broadcast.ts +53 -1
- package/server/src/smartPickupAdapters.ts +128 -5
- package/server/src/storageActions.ts +216 -0
- package/server/src/storageArchive.ts +277 -0
- package/server/src/storageOverview.ts +184 -0
- package/server/src/storageReport.ts +210 -0
- package/server/src/storageWarnings.ts +84 -0
- package/server/src/workers/limits.ts +4 -1
- package/server/src/workflowStore.ts +78 -61
- package/server/src/workflows/purgeWorkflow.ts +12 -3
- package/server/src/workflows/sessionDiscovery.ts +5 -13
- package/server/src/workflows/sessionIndex.ts +5 -9
- package/server/src/ws/taskLedgerHandlers.ts +8 -3
- package/server/src/ws/workflowHandlers.ts +5 -4
- package/shared/dist/index.d.ts +2 -0
- package/shared/dist/index.js +2 -0
- package/shared/dist/protocol/autoPickup.d.ts +1 -1
- package/shared/dist/protocol/autoPickup.js +1 -1
- package/shared/dist/protocol/checkpoints.d.ts +1 -0
- package/shared/dist/protocol/clusters.d.ts +2 -1
- package/shared/dist/protocol/index.d.ts +1 -0
- package/shared/dist/protocol/index.js +1 -0
- package/shared/dist/protocol/mdTuneup.d.ts +6 -0
- package/shared/dist/protocol/notifications.d.ts +2 -1
- package/shared/dist/protocol/notifications.js +3 -2
- package/shared/dist/protocol/plans.d.ts +2 -0
- package/shared/dist/protocol/serverMessages.d.ts +2 -1
- package/shared/dist/protocol/storage.d.ts +21 -0
- package/shared/dist/protocol/storage.js +3 -0
- package/shared/dist/protocol/tasks.d.ts +3 -0
- package/shared/dist/protocol/utilityAgent.d.ts +2 -2
- package/shared/dist/protocol/utilityAgent.js +2 -2
- package/shared/dist/publicGuardrails.d.ts +7 -0
- package/shared/dist/publicGuardrails.js +47 -0
- package/shared/dist/publicSafetyRules.d.ts +1 -0
- package/shared/dist/publicSafetyRules.js +6 -0
- package/shared/src/index.ts +3 -0
- package/shared/src/protocol/autoPickup.ts +1 -1
- package/shared/src/protocol/checkpoints.ts +4 -0
- package/shared/src/protocol/clusters.ts +6 -1
- package/shared/src/protocol/index.ts +1 -0
- package/shared/src/protocol/mdTuneup.ts +5 -0
- package/shared/src/protocol/notifications.ts +6 -2
- package/shared/src/protocol/plans.ts +2 -0
- package/shared/src/protocol/serverMessages.ts +2 -0
- package/shared/src/protocol/storage.ts +35 -0
- package/shared/src/protocol/tasks.ts +6 -0
- package/shared/src/protocol/utilityAgent.ts +2 -2
- package/shared/src/publicGuardrails.ts +50 -0
- package/shared/src/publicSafetyRules.ts +5 -0
- package/client/dist/assets/index-CcNtMA2y.js +0 -546
- package/client/dist/assets/index-Dl8tYsSp.css +0 -1
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
// Sealed, compressed log segments (P7.3, docs/STORAGE_PLAN.md).
|
|
2
|
+
//
|
|
3
|
+
// A conversation folder holds the live log `events.jsonl` (plain NDJSON,
|
|
4
|
+
// appended by workflowStore) and, once it has grown past the seal threshold,
|
|
5
|
+
// sealed segments `events.<firstSeq>-<lastSeq>.jsonl.br`: Brotli-compressed
|
|
6
|
+
// records, sequence numbers zero-padded to 12 digits so name order is sequence
|
|
7
|
+
// order. Every reader goes through this module and sees one history: segments
|
|
8
|
+
// in order, then the live file, each record once.
|
|
9
|
+
//
|
|
10
|
+
// Sealing never loses a record. Segments are written to a temporary file,
|
|
11
|
+
// flushed and read back before they are renamed into place, and the newest
|
|
12
|
+
// sealed record is copied into the new live file so that a release which
|
|
13
|
+
// reads only `events.jsonl` still continues the sequence. A segment name is
|
|
14
|
+
// never trusted on its own: before a seal drops a live record because a
|
|
15
|
+
// segment's name covers it, that segment is decompressed and checked (every
|
|
16
|
+
// line parses, sequence numbers rise, the first and last match the name). A
|
|
17
|
+
// segment that fails is moved aside (renamed `*.damaged-<time>`, never
|
|
18
|
+
// deleted) and its records are sealed again from the live file. Readers skip
|
|
19
|
+
// live records only up to the newest sequence number they actually read from
|
|
20
|
+
// a segment, or that a checked segment holds.
|
|
21
|
+
|
|
22
|
+
import { promises as fs, createReadStream, closeSync, fstatSync, openSync, readFileSync, readSync, readdirSync, statSync, constants as fsConstants } from 'node:fs';
|
|
23
|
+
import { createInterface } from 'node:readline';
|
|
24
|
+
import { brotliCompress, brotliDecompress, brotliDecompressSync, createBrotliDecompress, constants as zc } from 'node:zlib';
|
|
25
|
+
import { promisify } from 'node:util';
|
|
26
|
+
import { randomUUID } from 'node:crypto';
|
|
27
|
+
import path from 'node:path';
|
|
28
|
+
import type { FileHandle } from 'node:fs/promises';
|
|
29
|
+
import { renameWithRetry } from './atomicFile.js';
|
|
30
|
+
|
|
31
|
+
const compress = promisify(brotliCompress);
|
|
32
|
+
const decompress = promisify(brotliDecompress);
|
|
33
|
+
|
|
34
|
+
export const LIVE_LOG = 'events.jsonl';
|
|
35
|
+
export const FORMAT_FILE = 'log-format.json';
|
|
36
|
+
// Format 2 = sealed segments. A release that knows only format 1 (plain log)
|
|
37
|
+
// refuses nothing; a later release that finds a format above the one it knows
|
|
38
|
+
// must refuse to write.
|
|
39
|
+
export const LOG_FORMAT = 2;
|
|
40
|
+
const SEGMENT_RE = /^events\.(\d{12})-(\d{12})\.jsonl\.br$/;
|
|
41
|
+
const SEGMENT_TMP_RE = /^events\.\d{12}-\d{12}\.jsonl\.br\.[0-9a-f-]+\.tmp$/;
|
|
42
|
+
const LIVE_TMP_RE = /^events\.jsonl\.[0-9a-f-]+\.tmp$/;
|
|
43
|
+
const SEQ_RE = /^\{"seq":(\d+)[,}]/;
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_SEAL_BYTES = 16 * 1024 * 1024;
|
|
46
|
+
export function sealThresholdBytes(): number {
|
|
47
|
+
const raw = Number(process.env.ARCO_EVENT_SEGMENT_BYTES);
|
|
48
|
+
return Number.isFinite(raw) && raw >= 1024 ? Math.floor(raw) : DEFAULT_SEAL_BYTES;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface Segment { name: string; file: string; firstSeq: number; lastSeq: number }
|
|
52
|
+
|
|
53
|
+
function pad(n: number): string { return String(n).padStart(12, '0'); }
|
|
54
|
+
export function segmentName(firstSeq: number, lastSeq: number): string {
|
|
55
|
+
return `events.${pad(firstSeq)}-${pad(lastSeq)}.jsonl.br`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function parseSegments(dir: string, names: string[]): Segment[] {
|
|
59
|
+
const out: Segment[] = [];
|
|
60
|
+
for (const name of names) {
|
|
61
|
+
const m = SEGMENT_RE.exec(name);
|
|
62
|
+
if (!m) continue;
|
|
63
|
+
out.push({ name, file: path.join(dir, name), firstSeq: Number(m[1]), lastSeq: Number(m[2]) });
|
|
64
|
+
}
|
|
65
|
+
return out.sort((a, b) => a.firstSeq - b.firstSeq || a.lastSeq - b.lastSeq);
|
|
66
|
+
}
|
|
67
|
+
export async function listSegments(dir: string): Promise<Segment[]> {
|
|
68
|
+
try { return parseSegments(dir, await fs.readdir(dir)); }
|
|
69
|
+
catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []; throw err; }
|
|
70
|
+
}
|
|
71
|
+
export function listSegmentsSync(dir: string): Segment[] {
|
|
72
|
+
try { return parseSegments(dir, readdirSync(dir)); }
|
|
73
|
+
catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []; throw err; }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Sequence number of a record line without a full parse when the line has the
|
|
77
|
+
// writer's shape (`{"seq":N,...`); falls back to JSON for anything else.
|
|
78
|
+
export function lineSeq(line: string): number | null {
|
|
79
|
+
const m = SEQ_RE.exec(line);
|
|
80
|
+
if (m) return Number(m[1]);
|
|
81
|
+
try {
|
|
82
|
+
const v = JSON.parse(line) as { seq?: unknown };
|
|
83
|
+
return typeof v.seq === 'number' ? v.seq : null;
|
|
84
|
+
} catch { return null; }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// A segment's content matches its name: every line is JSON, sequence numbers
|
|
88
|
+
// rise, and the first and last are the ones in the name.
|
|
89
|
+
export function segmentTextMatches(seg: Pick<Segment, 'firstSeq' | 'lastSeq'>, text: string): boolean {
|
|
90
|
+
if (!text.endsWith('\n')) return false;
|
|
91
|
+
let first: number | null = null, last = 0;
|
|
92
|
+
for (const line of text.slice(0, -1).split('\n')) {
|
|
93
|
+
let v: unknown;
|
|
94
|
+
try { v = JSON.parse(line); } catch { return false; }
|
|
95
|
+
const seq = v && typeof v === 'object' ? (v as { seq?: unknown }).seq : undefined;
|
|
96
|
+
if (typeof seq !== 'number') continue;
|
|
97
|
+
if (first === null) first = seq; else if (seq <= last) return false;
|
|
98
|
+
last = seq;
|
|
99
|
+
}
|
|
100
|
+
return first === seg.firstSeq && last === seg.lastSeq;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Checked segments, by path, size and modification time. A segment this
|
|
104
|
+
// process wrote is entered when its read-back matched.
|
|
105
|
+
const checked = new Map<string, boolean>();
|
|
106
|
+
function checkKey(file: string, st: { size: number; mtimeMs: number }): string { return `${file}\0${st.size}\0${st.mtimeMs}`; }
|
|
107
|
+
function remember(key: string, ok: boolean): boolean {
|
|
108
|
+
if (checked.size > 4096) checked.clear();
|
|
109
|
+
checked.set(key, ok);
|
|
110
|
+
return ok;
|
|
111
|
+
}
|
|
112
|
+
export async function segmentIsSound(seg: Segment): Promise<boolean> {
|
|
113
|
+
let key: string;
|
|
114
|
+
try { key = checkKey(seg.file, await fs.stat(seg.file)); } catch { return false; }
|
|
115
|
+
const known = checked.get(key);
|
|
116
|
+
if (known !== undefined) return known;
|
|
117
|
+
let text: string;
|
|
118
|
+
try { text = (await decompress(await fs.readFile(seg.file))).toString('utf8'); } catch { return remember(key, false); }
|
|
119
|
+
return remember(key, segmentTextMatches(seg, text));
|
|
120
|
+
}
|
|
121
|
+
export function segmentIsSoundSync(seg: Segment): boolean {
|
|
122
|
+
let key: string;
|
|
123
|
+
try { key = checkKey(seg.file, statSync(seg.file)); } catch { return false; }
|
|
124
|
+
const known = checked.get(key);
|
|
125
|
+
if (known !== undefined) return known;
|
|
126
|
+
let text: string;
|
|
127
|
+
try { text = brotliDecompressSync(readFileSync(seg.file)).toString('utf8'); } catch { return remember(key, false); }
|
|
128
|
+
return remember(key, segmentTextMatches(seg, text));
|
|
129
|
+
}
|
|
130
|
+
// Newest sequence number held by a segment that passed the check (0 when
|
|
131
|
+
// none did). Tail and head readers drop live records only up to this.
|
|
132
|
+
function trustedThroughSync(segments: Segment[]): number {
|
|
133
|
+
for (let i = segments.length - 1; i >= 0; i--) if (segmentIsSoundSync(segments[i])) return segments[i].lastSeq;
|
|
134
|
+
return 0;
|
|
135
|
+
}
|
|
136
|
+
async function trustedThrough(segments: Segment[]): Promise<number> {
|
|
137
|
+
for (let i = segments.length - 1; i >= 0; i--) if (await segmentIsSound(segments[i])) return segments[i].lastSeq;
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
function lastSeqIn(text: string): number {
|
|
141
|
+
let end = text.length;
|
|
142
|
+
while (end > 0) {
|
|
143
|
+
const start = text.lastIndexOf('\n', end - 1);
|
|
144
|
+
const line = text.slice(start + 1, end);
|
|
145
|
+
if (line) { const seq = lineSeq(line); if (seq !== null) return seq; }
|
|
146
|
+
if (start < 0) break;
|
|
147
|
+
end = start;
|
|
148
|
+
}
|
|
149
|
+
return 0;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export class SegmentReadError extends Error {
|
|
153
|
+
constructor(readonly file: string, cause: unknown) {
|
|
154
|
+
super(`Sealed log segment ${path.basename(file)} could not be read`);
|
|
155
|
+
this.cause = cause;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function reportUnreadable(err: unknown): void {
|
|
159
|
+
console.error(`[arco] ${err instanceof Error ? err.message : String(err)}; skipping it, the rest of the history stays readable`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function* segmentLines(seg: Segment): AsyncGenerator<string> {
|
|
163
|
+
const input = createReadStream(seg.file);
|
|
164
|
+
const rl = createInterface({ input: input.pipe(createBrotliDecompress()), crlfDelay: Infinity });
|
|
165
|
+
try {
|
|
166
|
+
for await (const line of rl) if (line) yield line;
|
|
167
|
+
} catch (err) {
|
|
168
|
+
throw new SegmentReadError(seg.file, err);
|
|
169
|
+
} finally {
|
|
170
|
+
rl.close(); input.destroy();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function openLive(file: string): Promise<FileHandle | null> {
|
|
175
|
+
try { return await fs.open(file, 'r'); }
|
|
176
|
+
catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null; throw err; }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function* handleLines(fh: FileHandle): AsyncGenerator<string> {
|
|
180
|
+
const input = fh.createReadStream({ autoClose: false });
|
|
181
|
+
const rl = createInterface({ input, crlfDelay: Infinity });
|
|
182
|
+
try { for await (const line of rl) if (line) yield line; }
|
|
183
|
+
finally { rl.close(); input.destroy(); }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function* liveLines(file: string): AsyncGenerator<string> {
|
|
187
|
+
const fh = await openLive(file);
|
|
188
|
+
if (!fh) return;
|
|
189
|
+
try { yield* handleLines(fh); } finally { await fh.close(); }
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Every record line in sequence order: sealed segments, then the live file.
|
|
193
|
+
// `fromSeq` skips whole segments that end at or before it (callers still
|
|
194
|
+
// filter individual lines, as they did on the plain log). An unreadable
|
|
195
|
+
// segment is reported and skipped; its records show as a gap.
|
|
196
|
+
//
|
|
197
|
+
// A seal can finish while this runs. The live file is opened (and so pinned)
|
|
198
|
+
// before the segment list is read a second time: whichever live file is
|
|
199
|
+
// pinned, every record not in a listed segment is in it, and records already
|
|
200
|
+
// read from a segment are skipped by sequence number. Only sequence numbers
|
|
201
|
+
// actually read count, so a damaged segment never hides live records.
|
|
202
|
+
export async function* readLogLines(dir: string, opts: { fromSeq?: number } = {}): AsyncGenerator<string> {
|
|
203
|
+
const fromSeq = opts.fromSeq ?? 0;
|
|
204
|
+
const done = new Set<string>();
|
|
205
|
+
let sealedThrough = 0;
|
|
206
|
+
async function* drainSegments(): AsyncGenerator<string> {
|
|
207
|
+
for (const seg of await listSegments(dir)) {
|
|
208
|
+
if (done.has(seg.name)) continue;
|
|
209
|
+
done.add(seg.name);
|
|
210
|
+
// Records at or below fromSeq are dropped by the callers either way.
|
|
211
|
+
if (seg.lastSeq <= fromSeq) { sealedThrough = Math.max(sealedThrough, seg.lastSeq); continue; }
|
|
212
|
+
try {
|
|
213
|
+
for await (const line of segmentLines(seg)) {
|
|
214
|
+
const seq = lineSeq(line);
|
|
215
|
+
if (seq !== null && seq > sealedThrough) sealedThrough = seq;
|
|
216
|
+
yield line;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
catch (err) { if (err instanceof SegmentReadError) reportUnreadable(err); else throw err; }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
yield* drainSegments();
|
|
223
|
+
const fh = await openLive(path.join(dir, LIVE_LOG));
|
|
224
|
+
try {
|
|
225
|
+
yield* drainSegments();
|
|
226
|
+
if (!fh) return;
|
|
227
|
+
for await (const line of handleLines(fh)) {
|
|
228
|
+
if (sealedThrough > 0) { const seq = lineSeq(line); if (seq !== null && seq <= sealedThrough) continue; }
|
|
229
|
+
yield line;
|
|
230
|
+
}
|
|
231
|
+
} finally { await fh?.close(); }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// The whole history as one NDJSON text (each record once, newline-terminated).
|
|
235
|
+
// Same memory profile as reading a plain log with readFile.
|
|
236
|
+
export async function readLogText(dir: string): Promise<string> {
|
|
237
|
+
const parts: string[] = [];
|
|
238
|
+
for await (const line of readLogLines(dir)) parts.push(line);
|
|
239
|
+
return parts.length ? parts.join('\n') + '\n' : '';
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function decompressSegmentSync(seg: Segment): string {
|
|
243
|
+
try { return brotliDecompressSync(readFileSync(seg.file)).toString('utf8'); }
|
|
244
|
+
catch (err) { throw new SegmentReadError(seg.file, err); }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function liveTextSync(file: string): { text: string; size: number } {
|
|
248
|
+
try { const text = readFileSync(file, 'utf8'); return { text, size: Buffer.byteLength(text) }; }
|
|
249
|
+
catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { text: '', size: 0 }; throw err; }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function dropSealed(text: string, sealedThrough: number): string {
|
|
253
|
+
if (!sealedThrough || !text) return text;
|
|
254
|
+
const lines = text.split('\n');
|
|
255
|
+
let i = 0;
|
|
256
|
+
while (i < lines.length) {
|
|
257
|
+
const line = lines[i];
|
|
258
|
+
if (!line) { i++; continue; }
|
|
259
|
+
const seq = lineSeq(line);
|
|
260
|
+
if (seq !== null && seq <= sealedThrough) { i++; continue; }
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
return lines.slice(i).join('\n');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function readLogTextSync(dir: string): string {
|
|
267
|
+
const segments = listSegmentsSync(dir);
|
|
268
|
+
let out = '', sealedThrough = 0;
|
|
269
|
+
for (const seg of segments) {
|
|
270
|
+
let text = '';
|
|
271
|
+
try { text = decompressSegmentSync(seg); } catch (err) { reportUnreadable(err); }
|
|
272
|
+
out += text;
|
|
273
|
+
sealedThrough = Math.max(sealedThrough, lastSeqIn(text));
|
|
274
|
+
}
|
|
275
|
+
return out + dropSealed(liveTextSync(path.join(dir, LIVE_LOG)).text, sealedThrough);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// The last `maxBytes` of the history, possibly starting mid-record (callers
|
|
279
|
+
// drop the first line when `truncated`, as they did on the plain log). Reads
|
|
280
|
+
// only the live file's tail when it is long enough; otherwise prepends the
|
|
281
|
+
// newest segments. The live file is pinned before segments are listed (see
|
|
282
|
+
// readLogLines).
|
|
283
|
+
export async function readLogTail(dir: string, maxBytes: number): Promise<{ text: string; truncated: boolean }> {
|
|
284
|
+
const fh = await openLive(path.join(dir, LIVE_LOG));
|
|
285
|
+
let live = '';
|
|
286
|
+
try {
|
|
287
|
+
if (fh) {
|
|
288
|
+
const size = (await fh.stat()).size;
|
|
289
|
+
if (size >= maxBytes) {
|
|
290
|
+
const buf = Buffer.alloc(maxBytes);
|
|
291
|
+
const { bytesRead } = await fh.read(buf, 0, maxBytes, size - maxBytes);
|
|
292
|
+
return { text: buf.subarray(0, bytesRead).toString('utf8'), truncated: true };
|
|
293
|
+
}
|
|
294
|
+
const buf = Buffer.alloc(size);
|
|
295
|
+
const { bytesRead } = await fh.read(buf, 0, size, 0);
|
|
296
|
+
live = buf.subarray(0, bytesRead).toString('utf8');
|
|
297
|
+
}
|
|
298
|
+
} finally { await fh?.close(); }
|
|
299
|
+
const segments = await listSegments(dir);
|
|
300
|
+
let text = dropSealed(live, await trustedThrough(segments));
|
|
301
|
+
let i = segments.length - 1;
|
|
302
|
+
// A damaged segment is reported and skipped; older sound ones still count,
|
|
303
|
+
// as in the full reader.
|
|
304
|
+
while (i >= 0 && Buffer.byteLength(text) < maxBytes) {
|
|
305
|
+
if (!(await segmentIsSound(segments[i]))) { reportUnreadable(new SegmentReadError(segments[i].file, 'content does not match its name')); i--; continue; }
|
|
306
|
+
try { text = (await segmentText(segments[i])) + text; }
|
|
307
|
+
catch (err) { if (!(err instanceof SegmentReadError)) throw err; reportUnreadable(err); }
|
|
308
|
+
i--;
|
|
309
|
+
}
|
|
310
|
+
return clipTail(text, maxBytes, i >= 0);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function clipTail(text: string, maxBytes: number, more: boolean): { text: string; truncated: boolean } {
|
|
314
|
+
const bytes = Buffer.from(text, 'utf8');
|
|
315
|
+
if (bytes.length > maxBytes) return { text: bytes.subarray(bytes.length - maxBytes).toString('utf8'), truncated: true };
|
|
316
|
+
return { text, truncated: more };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function segmentText(seg: Segment): Promise<string> {
|
|
320
|
+
const parts: string[] = [];
|
|
321
|
+
for await (const line of segmentLines(seg)) parts.push(line);
|
|
322
|
+
return parts.length ? parts.join('\n') + '\n' : '';
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function readLogTailSync(dir: string, maxBytes: number): { text: string; truncated: boolean } {
|
|
326
|
+
const file = path.join(dir, LIVE_LOG);
|
|
327
|
+
let fd = -1;
|
|
328
|
+
try { fd = openSync(file, fsConstants.O_RDONLY); }
|
|
329
|
+
catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
|
|
330
|
+
let live = '';
|
|
331
|
+
if (fd >= 0) {
|
|
332
|
+
try {
|
|
333
|
+
const size = fstatSync(fd).size;
|
|
334
|
+
const want = Math.min(size, maxBytes);
|
|
335
|
+
const buf = Buffer.alloc(want);
|
|
336
|
+
const n = readSync(fd, buf, 0, want, size - want);
|
|
337
|
+
if (size >= maxBytes) return { text: buf.subarray(0, n).toString('utf8'), truncated: true };
|
|
338
|
+
live = buf.subarray(0, n).toString('utf8');
|
|
339
|
+
} finally { closeSync(fd); }
|
|
340
|
+
}
|
|
341
|
+
const segments = listSegmentsSync(dir);
|
|
342
|
+
let text = dropSealed(live, trustedThroughSync(segments));
|
|
343
|
+
let i = segments.length - 1;
|
|
344
|
+
while (i >= 0 && Buffer.byteLength(text) < maxBytes) {
|
|
345
|
+
if (!segmentIsSoundSync(segments[i])) { reportUnreadable(new SegmentReadError(segments[i].file, 'content does not match its name')); i--; continue; }
|
|
346
|
+
try { text = decompressSegmentSync(segments[i]) + text; } catch (err) { reportUnreadable(err); }
|
|
347
|
+
i--;
|
|
348
|
+
}
|
|
349
|
+
return clipTail(text, maxBytes, i >= 0);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// The first `maxBytes` of the history (synchronous; for head readers such as
|
|
353
|
+
// session titles). Decompresses at most the oldest segments needed.
|
|
354
|
+
export function readLogHeadSync(dir: string, maxBytes: number): string {
|
|
355
|
+
const segments = listSegmentsSync(dir);
|
|
356
|
+
let text = '', sealedThrough = 0;
|
|
357
|
+
for (const seg of segments) {
|
|
358
|
+
let part = '';
|
|
359
|
+
try { part = decompressSegmentSync(seg); } catch (err) { reportUnreadable(err); }
|
|
360
|
+
text += part;
|
|
361
|
+
sealedThrough = Math.max(sealedThrough, lastSeqIn(part));
|
|
362
|
+
if (Buffer.byteLength(text) >= maxBytes) return Buffer.from(text).subarray(0, maxBytes).toString('utf8');
|
|
363
|
+
}
|
|
364
|
+
const file = path.join(dir, LIVE_LOG);
|
|
365
|
+
let live = '';
|
|
366
|
+
let fd = -1;
|
|
367
|
+
try { fd = openSync(file, fsConstants.O_RDONLY); } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
|
|
368
|
+
if (fd >= 0) {
|
|
369
|
+
try {
|
|
370
|
+
const want = maxBytes - Buffer.byteLength(text) + 1024 * 1024; // room for the copied sealed record
|
|
371
|
+
const buf = Buffer.alloc(Math.max(0, want));
|
|
372
|
+
const n = readSync(fd, buf, 0, buf.length, 0);
|
|
373
|
+
live = buf.subarray(0, n).toString('utf8');
|
|
374
|
+
} finally { closeSync(fd); }
|
|
375
|
+
}
|
|
376
|
+
text += dropSealed(live, sealedThrough);
|
|
377
|
+
return Buffer.from(text).subarray(0, maxBytes).toString('utf8');
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Newest sealed sequence number (0 when nothing is sealed). Read from file
|
|
381
|
+
// names only: sequence recovery uses it so that a number is never reused,
|
|
382
|
+
// even one named by a damaged segment. Readers do not use it to drop records.
|
|
383
|
+
export async function sealedThroughSeq(dir: string): Promise<number> {
|
|
384
|
+
const segments = await listSegments(dir);
|
|
385
|
+
return segments.length ? segments[segments.length - 1].lastSeq : 0;
|
|
386
|
+
}
|
|
387
|
+
// Highest sequence number any segment name has ever claimed, including
|
|
388
|
+
// segments moved aside as damaged (`*.damaged-<time>`), so sequence recovery
|
|
389
|
+
// never hands out a number a segment name already used.
|
|
390
|
+
const NAMED_RE = /^events\.\d{12}-(\d{12})\.jsonl\.br(?:\.damaged-\d+)?$/;
|
|
391
|
+
export async function highestNamedSeq(dir: string): Promise<number> {
|
|
392
|
+
let names: string[] = [];
|
|
393
|
+
try { names = await fs.readdir(dir); } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return 0; throw err; }
|
|
394
|
+
let max = 0;
|
|
395
|
+
for (const name of names) { const m = NAMED_RE.exec(name); if (m) max = Math.max(max, Number(m[1])); }
|
|
396
|
+
return max;
|
|
397
|
+
}
|
|
398
|
+
export async function firstSealedSeq(dir: string): Promise<number | null> {
|
|
399
|
+
const segments = await listSegments(dir);
|
|
400
|
+
return segments.length ? segments[0].firstSeq : null;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export async function readLogFormat(dir: string): Promise<number> {
|
|
404
|
+
try {
|
|
405
|
+
const v = JSON.parse(await fs.readFile(path.join(dir, FORMAT_FILE), 'utf8')) as { format?: unknown };
|
|
406
|
+
return typeof v.format === 'number' ? v.format : 1;
|
|
407
|
+
} catch { return 1; }
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async function fsyncDir(dir: string): Promise<void> {
|
|
411
|
+
// Directories cannot be opened for fsync on Windows; the rename is still
|
|
412
|
+
// atomic there.
|
|
413
|
+
if (process.platform === 'win32') return;
|
|
414
|
+
const fh = await fs.open(dir, 'r');
|
|
415
|
+
try { await fh.sync(); } finally { await fh.close(); }
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function writeDurable(dir: string, finalName: string, data: Buffer | string, tmpName: string, verify?: (tmp: string) => Promise<void>): Promise<void> {
|
|
419
|
+
const tmp = path.join(dir, tmpName);
|
|
420
|
+
const fh = await fs.open(tmp, 'wx', 0o600);
|
|
421
|
+
try { await fh.writeFile(data); await fh.sync(); } finally { await fh.close(); }
|
|
422
|
+
if (verify) {
|
|
423
|
+
try { await verify(tmp); } catch (err) { await fs.rm(tmp, { force: true }); throw err; }
|
|
424
|
+
}
|
|
425
|
+
// Windows briefly refuses a rename over a file a reader holds open, and
|
|
426
|
+
// keeps refusing while the reader stays. The temporary file never stays.
|
|
427
|
+
try { await renameWithRetry(tmp, path.join(dir, finalName)); }
|
|
428
|
+
catch (err) { await fs.rm(tmp, { force: true }).catch(() => undefined); throw err; }
|
|
429
|
+
await fsyncDir(dir);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function removeLeftovers(dir: string): Promise<void> {
|
|
433
|
+
let names: string[] = [];
|
|
434
|
+
try { names = await fs.readdir(dir); } catch { return; }
|
|
435
|
+
for (const name of names) {
|
|
436
|
+
if (SEGMENT_TMP_RE.test(name) || LIVE_TMP_RE.test(name)) await fs.rm(path.join(dir, name), { force: true });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// liveReplaced false: the segments are in place but the live file could not be
|
|
441
|
+
// replaced yet (Windows refuses a rename over a file a reader holds open). The
|
|
442
|
+
// live file stays complete, readers skip what is sealed, and the next seal
|
|
443
|
+
// replaces it.
|
|
444
|
+
export interface SealResult { segments: string[]; sealedRecords: number; liveBytes: number; movedAside: string[]; liveReplaced: boolean }
|
|
445
|
+
|
|
446
|
+
// Test seam: runs just before the live file is replaced.
|
|
447
|
+
export const sealTestHooks: { beforeLiveReplace?: () => Promise<void> } = {};
|
|
448
|
+
|
|
449
|
+
// A segment whose content does not match its name is renamed out of the
|
|
450
|
+
// segment list (kept on disk for inspection, never deleted).
|
|
451
|
+
async function moveAside(seg: Segment): Promise<string> {
|
|
452
|
+
const name = `${seg.name}.damaged-${Date.now()}`;
|
|
453
|
+
await renameWithRetry(seg.file, path.join(path.dirname(seg.file), name));
|
|
454
|
+
console.error(`[arco] sealed log segment ${seg.name} does not match its name; moved aside as ${name}, its records are sealed again from the live log`);
|
|
455
|
+
return name;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Seal the live log of one conversation folder. The caller must make sure
|
|
459
|
+
// nothing appends to the live file while this runs (workflowStore runs it in
|
|
460
|
+
// the conversation's flush chain). Records go into segments of at most
|
|
461
|
+
// `segmentBytes` of text each.
|
|
462
|
+
//
|
|
463
|
+
// A live record is dropped only when a segment whose name covers it passes the
|
|
464
|
+
// content check. Live records not covered by a sound segment are sealed into
|
|
465
|
+
// new segments, which never overlap an existing one. The live file is replaced
|
|
466
|
+
// only after every new segment is in place.
|
|
467
|
+
export async function sealLiveLog(dir: string, segmentBytes = sealThresholdBytes()): Promise<SealResult | null> {
|
|
468
|
+
const file = path.join(dir, LIVE_LOG);
|
|
469
|
+
try { await fs.lstat(file); } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null; throw err; }
|
|
470
|
+
if (await readLogFormat(dir) > LOG_FORMAT) throw new Error('This conversation log uses a newer storage format; update Arco to write to it.');
|
|
471
|
+
await removeLeftovers(dir);
|
|
472
|
+
const segments = await listSegments(dir);
|
|
473
|
+
const written: string[] = [], movedAside: string[] = [];
|
|
474
|
+
let records = 0, ptr = 0, coveredAny = false, liveRecords = 0;
|
|
475
|
+
let chunk: string[] = [], chunkBytes = 0, chunkFirst = 0, chunkLast = 0;
|
|
476
|
+
// The newest record that is sealed (in a sound segment or a new one); it is
|
|
477
|
+
// copied into the new live file.
|
|
478
|
+
let topSeq = 0, topLine = '';
|
|
479
|
+
const noteTop = (seq: number, line: string) => { if (seq > topSeq) { topSeq = seq; topLine = line; } };
|
|
480
|
+
// Lines without a sequence number travel with the records around them; any
|
|
481
|
+
// left at the very end stay in the live file.
|
|
482
|
+
let pendingNoSeq: string[] = [];
|
|
483
|
+
const flush = async () => {
|
|
484
|
+
if (!chunk.length) return;
|
|
485
|
+
const text = chunk.join('\n') + '\n';
|
|
486
|
+
const data = await compress(Buffer.from(text, 'utf8'), { params: {
|
|
487
|
+
[zc.BROTLI_PARAM_QUALITY]: 5, [zc.BROTLI_PARAM_LGWIN]: 24, [zc.BROTLI_PARAM_SIZE_HINT]: Buffer.byteLength(text),
|
|
488
|
+
} });
|
|
489
|
+
const name = segmentName(chunkFirst, chunkLast);
|
|
490
|
+
// Read the segment back before it is renamed into place.
|
|
491
|
+
await writeDurable(dir, name, data, `${name}.${randomUUID()}.tmp`, async (tmp) => {
|
|
492
|
+
const back = (await decompress(await fs.readFile(tmp))).toString('utf8');
|
|
493
|
+
if (back !== text) throw new Error(`Sealed log segment ${name} did not read back correctly`);
|
|
494
|
+
});
|
|
495
|
+
try { remember(checkKey(path.join(dir, name), await fs.stat(path.join(dir, name))), true); } catch { /* checked again on use */ }
|
|
496
|
+
written.push(name);
|
|
497
|
+
records += chunk.length;
|
|
498
|
+
noteTop(chunkLast, chunk[chunk.length - 1]);
|
|
499
|
+
chunk = []; chunkBytes = 0; chunkFirst = 0; chunkLast = 0;
|
|
500
|
+
};
|
|
501
|
+
for await (const line of liveLines(file)) {
|
|
502
|
+
const seq = lineSeq(line);
|
|
503
|
+
if (seq === null) { pendingNoSeq.push(line); continue; }
|
|
504
|
+
liveRecords++;
|
|
505
|
+
while (ptr < segments.length && segments[ptr].lastSeq < seq) ptr++;
|
|
506
|
+
const seg = segments[ptr];
|
|
507
|
+
if (seg && seg.firstSeq <= seq) {
|
|
508
|
+
if (await segmentIsSound(seg)) {
|
|
509
|
+
// Already sealed (the copied record, or an interrupted seal).
|
|
510
|
+
await flush();
|
|
511
|
+
pendingNoSeq = [];
|
|
512
|
+
coveredAny = true;
|
|
513
|
+
noteTop(seq, line);
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
movedAside.push(await moveAside(seg));
|
|
517
|
+
segments.splice(ptr, 1);
|
|
518
|
+
}
|
|
519
|
+
const add = [...pendingNoSeq, line];
|
|
520
|
+
pendingNoSeq = [];
|
|
521
|
+
const addBytes = add.reduce((n, l) => n + Buffer.byteLength(l) + 1, 0);
|
|
522
|
+
// A new segment must not span an existing one.
|
|
523
|
+
const between = ptr > 0 && chunk.length > 0 && segments[ptr - 1].firstSeq > chunkLast;
|
|
524
|
+
if (chunk.length && (between || chunkBytes + addBytes > segmentBytes)) await flush();
|
|
525
|
+
if (!chunk.length) chunkFirst = seq;
|
|
526
|
+
chunk.push(...add); chunkBytes += addBytes; chunkLast = Math.max(chunkLast, seq);
|
|
527
|
+
}
|
|
528
|
+
await flush();
|
|
529
|
+
// Nothing new to seal and the live file holds at most the copied record.
|
|
530
|
+
if (!written.length && (!coveredAny || liveRecords <= 1)) return null;
|
|
531
|
+
if (await readLogFormat(dir) < LOG_FORMAT) {
|
|
532
|
+
await writeDurable(dir, FORMAT_FILE, JSON.stringify({ format: LOG_FORMAT }) + '\n', `${FORMAT_FILE}.${randomUUID()}.tmp`);
|
|
533
|
+
}
|
|
534
|
+
const rest = pendingNoSeq.length ? pendingNoSeq.join('\n') + '\n' : '';
|
|
535
|
+
const nextLive = topLine + '\n' + rest;
|
|
536
|
+
try {
|
|
537
|
+
await sealTestHooks.beforeLiveReplace?.();
|
|
538
|
+
await writeDurable(dir, LIVE_LOG, nextLive, `${LIVE_LOG}.${randomUUID()}.tmp`);
|
|
539
|
+
} catch (err) {
|
|
540
|
+
console.error(`[arco] sealed log segments are in place, but the live log could not be replaced yet (${(err as NodeJS.ErrnoException).code ?? 'error'}); it stays complete and the next seal replaces it`);
|
|
541
|
+
let liveBytes = 0;
|
|
542
|
+
try { liveBytes = (await fs.stat(file)).size; } catch { /* gone */ }
|
|
543
|
+
return { segments: written, sealedRecords: records, liveBytes, movedAside, liveReplaced: false };
|
|
544
|
+
}
|
|
545
|
+
return { segments: written, sealedRecords: records, liveBytes: Buffer.byteLength(nextLive), movedAside, liveReplaced: true };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// Write the whole history back to one plain events.jsonl and remove the
|
|
549
|
+
// segments and the format marker (operator-run export before a downgrade).
|
|
550
|
+
// The plain file is complete and checked before anything is removed.
|
|
551
|
+
export async function unsealLog(dir: string): Promise<{ records: number; segments: number } | null> {
|
|
552
|
+
const segments = await listSegments(dir);
|
|
553
|
+
if (!segments.length) return null;
|
|
554
|
+
const parts: string[] = [];
|
|
555
|
+
let last = 0, records = 0;
|
|
556
|
+
for (const seg of segments) {
|
|
557
|
+
for await (const line of segmentLines(seg)) { parts.push(line); records++; const s = lineSeq(line); if (s !== null) last = Math.max(last, s); }
|
|
558
|
+
}
|
|
559
|
+
for await (const line of liveLines(path.join(dir, LIVE_LOG))) {
|
|
560
|
+
const s = lineSeq(line);
|
|
561
|
+
if (s !== null && s <= last) continue;
|
|
562
|
+
parts.push(line); records++; if (s !== null) last = Math.max(last, s);
|
|
563
|
+
}
|
|
564
|
+
const text = parts.join('\n') + '\n';
|
|
565
|
+
await writeDurable(dir, LIVE_LOG, text, `${LIVE_LOG}.${randomUUID()}.tmp`);
|
|
566
|
+
const check = await fs.readFile(path.join(dir, LIVE_LOG), 'utf8');
|
|
567
|
+
if (check !== text) throw new Error('The exported log did not read back correctly; sealed segments were kept.');
|
|
568
|
+
for (const seg of segments) await fs.rm(seg.file, { force: true });
|
|
569
|
+
await fs.rm(path.join(dir, FORMAT_FILE), { force: true });
|
|
570
|
+
return { records, segments: segments.length };
|
|
571
|
+
}
|
|
@@ -88,8 +88,9 @@ function spawnDetachedProbe(bin: string, args: string[], env: NodeJS.ProcessEnv)
|
|
|
88
88
|
// by the route from the request Host/Origin so dev (5173) and prod (3001)
|
|
89
89
|
// both resolve without config. Fail-soft: every non-launch path returns a
|
|
90
90
|
// structured result so the client engages its popup fallback (never a throw).
|
|
91
|
-
export async function launchExplorerWindow(origin: string): Promise<ExplorerLaunchResult> {
|
|
92
|
-
const
|
|
91
|
+
export async function launchExplorerWindow(origin: string, options: { lens?: 'plans'; cwd?: string } = {}): Promise<ExplorerLaunchResult> {
|
|
92
|
+
const params = new URLSearchParams({ app: 'explorer', ...(options.lens ? { lens: options.lens } : {}), ...(options.cwd ? { cwd: options.cwd } : {}) });
|
|
93
|
+
const url = `${origin.replace(/\/$/, '')}/?${params}`;
|
|
93
94
|
// Prefer the service/desktop env so a systemd user unit inherits DISPLAY /
|
|
94
95
|
// WAYLAND_DISPLAY / DBUS; fall back to DISPLAY=:0 when the unit carries
|
|
95
96
|
// neither (§3 — the prod unit may not export a display).
|
|
@@ -7,12 +7,32 @@
|
|
|
7
7
|
// routes and the attached-workflow broadcasts key on the workflow's own cwd
|
|
8
8
|
// string, so a symlinked project must round-trip the same spelling.
|
|
9
9
|
|
|
10
|
-
import { basename } from 'path';
|
|
10
|
+
import { basename, join } from 'path';
|
|
11
|
+
import { open } from 'node:fs/promises';
|
|
11
12
|
import type { PlanLibraryProject } from '@arco/shared';
|
|
12
13
|
import { listPlans, listPlanRefs } from './planStore.js';
|
|
13
14
|
import { readKnownCwds, realpathWithinHome } from './explorerArtifacts.js';
|
|
14
15
|
import * as clusterStore from './clusterStore.js';
|
|
15
16
|
|
|
17
|
+
export function countPlanCheckboxes(body: string): { checkboxTotal: number; checkboxDone: number } {
|
|
18
|
+
const boxes = [...body.matchAll(/^\s*[-*+]\s+\[([ xX])\]/gm)];
|
|
19
|
+
return { checkboxTotal: boxes.length, checkboxDone: boxes.filter((m) => m[1].toLowerCase() === 'x').length };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function checkboxCounts(cwd: string, id: string): Promise<{ checkboxTotal: number; checkboxDone: number }> {
|
|
23
|
+
if (!/^[a-zA-Z0-9-]{1,64}$/.test(id)) return { checkboxTotal: 0, checkboxDone: 0 };
|
|
24
|
+
let file;
|
|
25
|
+
try {
|
|
26
|
+
file = await open(join(cwd, '.arco', 'plans', `${id}.md`), 'r');
|
|
27
|
+
const buffer = Buffer.alloc(256 * 1024 + 1);
|
|
28
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
29
|
+
// An incomplete body cannot safely establish that all boxes are checked.
|
|
30
|
+
if (bytesRead > 256 * 1024) return { checkboxTotal: 0, checkboxDone: 0 };
|
|
31
|
+
return countPlanCheckboxes(buffer.subarray(0, bytesRead).toString('utf8'));
|
|
32
|
+
} catch { return { checkboxTotal: 0, checkboxDone: 0 }; }
|
|
33
|
+
finally { await file?.close(); }
|
|
34
|
+
}
|
|
35
|
+
|
|
16
36
|
export async function collectPlanLibrary(): Promise<PlanLibraryProject[]> {
|
|
17
37
|
const known = [...new Set(await readKnownCwds())];
|
|
18
38
|
const clusters = await clusterStore.loadAllClustersFromDisk().catch(() => []);
|
|
@@ -27,7 +47,7 @@ export async function collectPlanLibrary(): Promise<PlanLibraryProject[]> {
|
|
|
27
47
|
.filter((c) => c.cwd === cwd && c.planId === p.id)
|
|
28
48
|
.map((c) => ({ clusterId: c.clusterId, name: c.name || `${c.clusterId.slice(0, 8)} cluster` }));
|
|
29
49
|
const openSpan = (p.attachments ?? []).some((a) => a.detachedAt === null);
|
|
30
|
-
return { ...p, refCount: refs.length, attached: openSpan || bound.length > 0, clusters: bound };
|
|
50
|
+
return { ...p, ...await checkboxCounts(cwd, p.id), refCount: refs.length, attached: openSpan || bound.length > 0, clusters: bound };
|
|
31
51
|
}));
|
|
32
52
|
out.push({ cwd, name: basename(cwd) || cwd, plans: entries });
|
|
33
53
|
}
|
|
@@ -408,6 +408,7 @@ export async function tryHandleClusterRoutes(
|
|
|
408
408
|
reviewRequired?: boolean;
|
|
409
409
|
goalMode?: boolean;
|
|
410
410
|
goalMaxTurns?: number;
|
|
411
|
+
release?: string;
|
|
411
412
|
status?: string;
|
|
412
413
|
};
|
|
413
414
|
const workflowId = typeof body.workflowId === 'string' ? body.workflowId : '';
|
|
@@ -429,6 +430,7 @@ export async function tryHandleClusterRoutes(
|
|
|
429
430
|
...(typeof body.reviewRequired === 'boolean' ? { reviewRequired: body.reviewRequired } : {}),
|
|
430
431
|
...(typeof body.goalMode === 'boolean' ? { goalMode: body.goalMode } : {}),
|
|
431
432
|
...(typeof body.goalMaxTurns === 'number' ? { goalMaxTurns: body.goalMaxTurns } : {}),
|
|
433
|
+
...(typeof body.release === 'string' ? { release: body.release } : {}),
|
|
432
434
|
...(typeof body.status === 'string' ? { status: body.status as LedgerTaskStatus } : {}),
|
|
433
435
|
},
|
|
434
436
|
(msg) => broadcastCluster(clusterId, msg),
|
|
@@ -609,7 +611,7 @@ export async function tryHandleClusterRoutes(
|
|
|
609
611
|
const chunks: Buffer[] = [];
|
|
610
612
|
for await (const chunk of req) chunks.push(chunk as Buffer);
|
|
611
613
|
const body = JSON.parse(Buffer.concat(chunks).toString('utf-8') || '{}') as {
|
|
612
|
-
workflowId?: string; id?: string; status?: string; notes?: string;
|
|
614
|
+
workflowId?: string; id?: string; status?: string; notes?: string; release?: string;
|
|
613
615
|
signoff?: { state?: string; summary?: string } | null;
|
|
614
616
|
};
|
|
615
617
|
const workflowId = typeof body.workflowId === 'string' ? body.workflowId : '';
|
|
@@ -624,6 +626,7 @@ export async function tryHandleClusterRoutes(
|
|
|
624
626
|
id: typeof body.id === 'string' ? body.id : '',
|
|
625
627
|
...(typeof body.status === 'string' ? { status: body.status as LedgerTaskStatus } : {}),
|
|
626
628
|
...(typeof body.notes === 'string' ? { notes: body.notes } : {}),
|
|
629
|
+
...(typeof body.release === 'string' ? { release: body.release } : {}),
|
|
627
630
|
// §D3 — advisory sign-off; peerTaskUpdate validates + stamps author.
|
|
628
631
|
...(body.signoff !== undefined ? { signoff: body.signoff } : {}),
|
|
629
632
|
},
|
|
@@ -46,7 +46,8 @@ export async function tryHandleExplorerRoutes(
|
|
|
46
46
|
// window.open. A genuinely unexpected error still degrades to a soft result.
|
|
47
47
|
if (url.startsWith('/api/explorer/open') && req.method === 'POST') {
|
|
48
48
|
try {
|
|
49
|
-
const
|
|
49
|
+
const params = new URL(url, 'http://localhost').searchParams;
|
|
50
|
+
const result = await launchExplorerWindow(deriveOrigin(req), { lens: params.get('lens') === 'plans' ? 'plans' : undefined, cwd: params.get('cwd') || undefined });
|
|
50
51
|
return sendJson(res, 200, result);
|
|
51
52
|
} catch (err) {
|
|
52
53
|
const error = err instanceof Error ? err.message : String(err);
|