@howaboua/pi-agent-comms 0.0.1-dev.14.1.g7d1d3da173aa → 0.0.2
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/CHANGELOG.md +22 -0
- package/README.md +4 -4
- package/docs/BOARD.md +2 -2
- package/docs/NOTES.md +14 -2
- package/package.json +5 -5
- package/src/board/briefing.ts +2 -2
- package/src/board/contract.ts +31 -27
- package/src/board/identity.ts +49 -29
- package/src/board/protocol.ts +98 -59
- package/src/board/settings/panel.ts +11 -8
- package/src/board/tool.ts +5 -0
- package/src/guidance.ts +14 -14
- package/src/notes/AGENTS.md +1 -1
- package/src/notes/attachment-snapshot.ts +33 -20
- package/src/notes/feature.ts +67 -1
- package/src/notes/history-search-pruning.mjs +110 -76
- package/src/notes/history-search-worker.mjs +1 -1
- package/src/notes/integrations.ts +6 -3
- package/src/notes/note-result.ts +70 -39
- package/src/notes/notes-lookup.ts +1 -1
- package/src/notes/query-input.ts +1 -0
- package/src/notes/saved-session-access.ts +12 -8
- package/src/notes/saved-session.ts +31 -15
- package/src/notes/saved-sharing-records.ts +110 -75
- package/src/notes/session-pruning-cleanup.mjs +163 -0
- package/src/notes/session-pruning-exit.mjs +312 -0
- package/src/notes/session-pruning-screen.ts +1 -1
- package/src/notes/session-pruning-sparse.mjs +133 -0
- package/src/notes/session-pruning-state.mjs +123 -0
- package/src/notes/session-pruning.ts +34 -1
- package/src/notes/settings-controls.ts +13 -17
- package/src/notes/settings-screen.ts +2 -6
- package/src/notes/shared-notes.ts +19 -11
- package/src/notes/shared-session-reader.ts +4 -2
- package/src/notes/tool-contracts.ts +71 -44
- package/src/notes/tools.ts +2 -2
- package/src/notes/tree-handoff-read.ts +47 -32
- package/src/notes/window-message.ts +6 -18
package/src/notes/note-result.ts
CHANGED
|
@@ -1,85 +1,116 @@
|
|
|
1
1
|
import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import {
|
|
3
|
+
arr,
|
|
4
|
+
bool,
|
|
5
|
+
compile,
|
|
6
|
+
int,
|
|
7
|
+
nul,
|
|
8
|
+
obj,
|
|
9
|
+
opt,
|
|
10
|
+
str,
|
|
11
|
+
union,
|
|
12
|
+
unsafe,
|
|
13
|
+
} from "@earendil-works/pi-schema";
|
|
4
14
|
|
|
5
|
-
const OPTIONAL_STRING =
|
|
6
|
-
const OPTIONAL_BOOLEAN =
|
|
7
|
-
const MATCH =
|
|
15
|
+
const OPTIONAL_STRING = opt(str());
|
|
16
|
+
const OPTIONAL_BOOLEAN = opt(bool());
|
|
17
|
+
const MATCH = obj({ line_number: int(), line: str() }, { open: true });
|
|
8
18
|
|
|
9
19
|
// Pi codemode needs this declaration to return structuredContent rather than text.
|
|
10
|
-
export const NOTES_OUTPUT_SCHEMA =
|
|
11
|
-
{},
|
|
12
|
-
|
|
13
|
-
|
|
20
|
+
export const NOTES_OUTPUT_SCHEMA = {
|
|
21
|
+
...obj({}, { open: true }),
|
|
22
|
+
additionalProperties: true,
|
|
23
|
+
};
|
|
14
24
|
|
|
15
|
-
const NOTES_RESULT_SCHEMA =
|
|
25
|
+
const NOTES_RESULT_SCHEMA = obj(
|
|
16
26
|
{
|
|
17
|
-
file:
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
27
|
+
file: opt(
|
|
28
|
+
union([
|
|
29
|
+
obj(
|
|
30
|
+
{
|
|
31
|
+
path: str(),
|
|
32
|
+
content: OPTIONAL_STRING,
|
|
33
|
+
append_only: OPTIONAL_BOOLEAN,
|
|
34
|
+
},
|
|
35
|
+
{ open: true },
|
|
36
|
+
),
|
|
37
|
+
nul(),
|
|
25
38
|
]),
|
|
26
39
|
),
|
|
27
|
-
files:
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
40
|
+
files: opt(
|
|
41
|
+
arr(
|
|
42
|
+
obj(
|
|
43
|
+
{
|
|
44
|
+
path: str(),
|
|
45
|
+
updated_at: OPTIONAL_STRING,
|
|
46
|
+
created_at: OPTIONAL_STRING,
|
|
47
|
+
matches: opt(arr(MATCH)),
|
|
48
|
+
truncated: OPTIONAL_BOOLEAN,
|
|
49
|
+
append_only: OPTIONAL_BOOLEAN,
|
|
50
|
+
},
|
|
51
|
+
{ open: true },
|
|
52
|
+
),
|
|
37
53
|
),
|
|
38
54
|
),
|
|
39
55
|
usage: OPTIONAL_STRING,
|
|
40
|
-
warnings:
|
|
56
|
+
warnings: opt(arr(str())),
|
|
41
57
|
warning: OPTIONAL_STRING,
|
|
42
58
|
truncated: OPTIONAL_BOOLEAN,
|
|
43
59
|
read_only: OPTIONAL_BOOLEAN,
|
|
44
60
|
saved_at: OPTIONAL_STRING,
|
|
45
61
|
captured_at: OPTIONAL_STRING,
|
|
46
62
|
results: OPTIONAL_STRING,
|
|
47
|
-
actions:
|
|
63
|
+
actions: opt(
|
|
64
|
+
unsafe<Record<string, string>>({
|
|
65
|
+
type: "object",
|
|
66
|
+
patternProperties: { "^.*$": str() },
|
|
67
|
+
}),
|
|
68
|
+
),
|
|
48
69
|
writes: OPTIONAL_STRING,
|
|
49
70
|
paths: OPTIONAL_STRING,
|
|
50
71
|
ranges: OPTIONAL_STRING,
|
|
51
72
|
defaults: OPTIONAL_STRING,
|
|
52
73
|
},
|
|
53
|
-
{
|
|
74
|
+
{ open: false },
|
|
54
75
|
);
|
|
55
76
|
|
|
77
|
+
const notesResultSchemaValidator = compile(NOTES_RESULT_SCHEMA);
|
|
78
|
+
|
|
56
79
|
/** One canonical payload for native text and every programmatic caller. */
|
|
57
80
|
export function noteResult(payload: unknown): AgentToolResult<unknown> {
|
|
58
|
-
if (!
|
|
81
|
+
if (!notesResultSchemaValidator.check(payload))
|
|
59
82
|
throw new Error(
|
|
60
83
|
"Notes returned invalid data. Read the note before retrying a write.",
|
|
61
84
|
);
|
|
62
|
-
//
|
|
85
|
+
// Keep recovery warnings, but omit sharing and storage bookkeeping.
|
|
63
86
|
const {
|
|
64
87
|
read_only: _readOnly,
|
|
65
|
-
warning
|
|
88
|
+
warning,
|
|
66
89
|
saved_at: _savedAt,
|
|
67
90
|
captured_at: _capturedAt,
|
|
68
91
|
...visible
|
|
69
92
|
} = payload;
|
|
93
|
+
if (warning !== undefined)
|
|
94
|
+
visible.warnings = [...(visible.warnings ?? []), warning];
|
|
70
95
|
if (visible.file)
|
|
71
96
|
visible.file = {
|
|
72
97
|
path: visible.file.path,
|
|
73
98
|
...(visible.file.content === undefined
|
|
74
99
|
? {}
|
|
75
100
|
: { content: visible.file.content }),
|
|
101
|
+
...(visible.file.append_only === undefined
|
|
102
|
+
? {}
|
|
103
|
+
: { append_only: visible.file.append_only }),
|
|
76
104
|
};
|
|
77
105
|
if (visible.files)
|
|
78
|
-
visible.files = visible.files.map(
|
|
79
|
-
path,
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
106
|
+
visible.files = visible.files.map(
|
|
107
|
+
({ path, matches, truncated, append_only }) => ({
|
|
108
|
+
path,
|
|
109
|
+
...(matches === undefined ? {} : { matches }),
|
|
110
|
+
...(truncated === undefined ? {} : { truncated }),
|
|
111
|
+
...(append_only === undefined ? {} : { append_only }),
|
|
112
|
+
}),
|
|
113
|
+
);
|
|
83
114
|
return {
|
|
84
115
|
content: [{ type: "text", text: JSON.stringify(visible) }],
|
|
85
116
|
structuredContent: visible,
|
|
@@ -79,7 +79,7 @@ export async function lookupNotes(
|
|
|
79
79
|
);
|
|
80
80
|
else if (lookupFailed)
|
|
81
81
|
warnings.push(
|
|
82
|
-
"
|
|
82
|
+
"Remote notes could not be checked. Local results are shown; retry to check for remote-only notes.",
|
|
83
83
|
);
|
|
84
84
|
if (responses.length && canProject && replacementsInScope)
|
|
85
85
|
warnings.push(
|
package/src/notes/query-input.ts
CHANGED
|
@@ -69,6 +69,7 @@ export function normalizeQueryInput(
|
|
|
69
69
|
if (action !== undefined) params["action"] = action;
|
|
70
70
|
if (namespace === "notes") {
|
|
71
71
|
alias(params, "address", "path");
|
|
72
|
+
if (action === "read") alias(params, "end_line", "stop_line");
|
|
72
73
|
if (action === "write" || action === "append") {
|
|
73
74
|
alias(params, "content", "text");
|
|
74
75
|
alias(params, "body", "text");
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Check } from "typebox/value";
|
|
1
|
+
import { arr, compile, obj, str } from "@earendil-works/pi-schema";
|
|
3
2
|
import type {
|
|
4
3
|
SavedSessionLoader,
|
|
5
4
|
SavedSessionLocator,
|
|
@@ -12,13 +11,18 @@ import {
|
|
|
12
11
|
import { savedFamilyIdentity } from "./saved-sharing-records.js";
|
|
13
12
|
import type { NotesStore } from "./store.js";
|
|
14
13
|
|
|
15
|
-
const Locations =
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
const Locations = arr(
|
|
15
|
+
obj(
|
|
16
|
+
{
|
|
17
|
+
machine: str({ minLength: 1 }),
|
|
18
|
+
sessionFile: str({ minLength: 1 }),
|
|
19
|
+
},
|
|
20
|
+
{ open: true },
|
|
21
|
+
),
|
|
20
22
|
);
|
|
21
23
|
|
|
24
|
+
const locationsValidator = compile(Locations);
|
|
25
|
+
|
|
22
26
|
/** Local is relative to the session carrying the edge, not the machine running this reader. */
|
|
23
27
|
export function createSavedSessionAccess(
|
|
24
28
|
store: Pick<NotesStore, "sessionFile">,
|
|
@@ -100,7 +104,7 @@ export function createSavedSessionAccess(
|
|
|
100
104
|
signal?.throwIfAborted();
|
|
101
105
|
const value = await loader.find(threadId, signal);
|
|
102
106
|
signal?.throwIfAborted();
|
|
103
|
-
if (!
|
|
107
|
+
if (!locationsValidator.check(value))
|
|
104
108
|
throw new Error(
|
|
105
109
|
"Saved session discovery response is invalid. Update Notes on the other machine and retry.",
|
|
106
110
|
);
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import {
|
|
3
|
+
arr,
|
|
4
|
+
compile,
|
|
5
|
+
nul,
|
|
6
|
+
num,
|
|
7
|
+
obj,
|
|
8
|
+
opt,
|
|
9
|
+
str,
|
|
10
|
+
union,
|
|
11
|
+
} from "@earendil-works/pi-schema";
|
|
4
12
|
|
|
5
13
|
export { readSavedNotesSession } from "./saved-session.mjs";
|
|
6
14
|
export interface SavedNotesSession {
|
|
@@ -10,22 +18,30 @@ export interface SavedNotesSession {
|
|
|
10
18
|
savedAt?: number;
|
|
11
19
|
}
|
|
12
20
|
|
|
13
|
-
const SavedEntry =
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
})
|
|
21
|
+
const SavedEntry = obj(
|
|
22
|
+
{
|
|
23
|
+
type: str(),
|
|
24
|
+
id: str(),
|
|
25
|
+
parentId: union([str(), nul()]),
|
|
26
|
+
timestamp: str(),
|
|
27
|
+
},
|
|
28
|
+
{ open: true },
|
|
29
|
+
);
|
|
30
|
+
const SavedSession = obj(
|
|
31
|
+
{
|
|
32
|
+
threadId: str({ minLength: 1 }),
|
|
33
|
+
entries: arr(SavedEntry),
|
|
34
|
+
branch: arr(SavedEntry),
|
|
35
|
+
savedAt: opt(num()),
|
|
36
|
+
},
|
|
37
|
+
{ open: true },
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
const savedSessionValidator = compile(SavedSession);
|
|
25
41
|
|
|
26
42
|
/** Remote loaders carry data, not authority. Native identity is checked by the graph reader. */
|
|
27
43
|
export function validateSavedNotesSession(value: unknown): SavedNotesSession {
|
|
28
|
-
if (!
|
|
44
|
+
if (!savedSessionValidator.check(value))
|
|
29
45
|
throw new Error(
|
|
30
46
|
"Saved session response is invalid. Update Notes on the other machine and retry.",
|
|
31
47
|
);
|
|
@@ -1,5 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
arr,
|
|
3
|
+
compile,
|
|
4
|
+
lit,
|
|
5
|
+
num,
|
|
6
|
+
obj,
|
|
7
|
+
opt,
|
|
8
|
+
type Static,
|
|
9
|
+
str,
|
|
10
|
+
union,
|
|
11
|
+
unknown,
|
|
12
|
+
} from "@earendil-works/pi-schema";
|
|
3
13
|
import {
|
|
4
14
|
CONTEXT_AGENT_PATTERN,
|
|
5
15
|
canonicalAgentName,
|
|
@@ -9,79 +19,104 @@ import {
|
|
|
9
19
|
} from "./agent-identity.js";
|
|
10
20
|
import type { SavedNotesSession } from "./saved-session.js";
|
|
11
21
|
|
|
12
|
-
const Agent =
|
|
13
|
-
export const Identity =
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
22
|
+
const Agent = str({ pattern: CONTEXT_AGENT_PATTERN });
|
|
23
|
+
export const Identity = obj(
|
|
24
|
+
{
|
|
25
|
+
protocol: lit(1),
|
|
26
|
+
sessionId: str(),
|
|
27
|
+
threadId: str(),
|
|
28
|
+
agentName: Agent,
|
|
29
|
+
storageAgentName: opt(Agent),
|
|
30
|
+
storage: opt(union([lit("session"), lit("remote")])),
|
|
31
|
+
routing: opt(unknown()),
|
|
32
|
+
},
|
|
33
|
+
{ open: true },
|
|
34
|
+
);
|
|
35
|
+
export const Member = obj(
|
|
36
|
+
{
|
|
37
|
+
threadId: str(),
|
|
38
|
+
sessionId: str(),
|
|
39
|
+
agentName: Agent,
|
|
40
|
+
machine: str(),
|
|
41
|
+
sessionFile: str(),
|
|
42
|
+
},
|
|
43
|
+
{ open: true },
|
|
44
|
+
);
|
|
45
|
+
export const Plan = obj(
|
|
46
|
+
{
|
|
47
|
+
controllerSessionId: str(),
|
|
48
|
+
targetSessionId: str(),
|
|
49
|
+
context: opt(
|
|
50
|
+
obj(
|
|
51
|
+
{
|
|
52
|
+
controller: Identity,
|
|
53
|
+
target: Identity,
|
|
54
|
+
alias: Agent,
|
|
55
|
+
controllerAlias: Agent,
|
|
56
|
+
controllerFile: opt(str()),
|
|
57
|
+
controllerMachine: opt(str()),
|
|
58
|
+
controllerNotes: unknown(),
|
|
59
|
+
targetNotes: unknown(),
|
|
60
|
+
},
|
|
61
|
+
{ open: true },
|
|
62
|
+
),
|
|
63
|
+
),
|
|
64
|
+
},
|
|
65
|
+
{ open: true },
|
|
66
|
+
);
|
|
67
|
+
export const Route = obj(
|
|
68
|
+
{
|
|
69
|
+
plan: Plan,
|
|
70
|
+
machine: str(),
|
|
71
|
+
sessionFile: str(),
|
|
72
|
+
phase: union([lit("pending"), lit("ready")]),
|
|
73
|
+
detached: opt(obj({ context: opt(unknown()) }, { open: true })),
|
|
74
|
+
},
|
|
75
|
+
{ open: true },
|
|
76
|
+
);
|
|
77
|
+
export const Detachment = obj(
|
|
78
|
+
{
|
|
79
|
+
plan: Plan,
|
|
80
|
+
context: opt(unknown()),
|
|
81
|
+
},
|
|
82
|
+
{ open: true },
|
|
83
|
+
);
|
|
84
|
+
export const Snapshot = obj(
|
|
85
|
+
{
|
|
86
|
+
protocol: lit(1),
|
|
87
|
+
timestamp: num(),
|
|
88
|
+
files: arr(
|
|
89
|
+
obj(
|
|
90
|
+
{
|
|
91
|
+
path: str(),
|
|
92
|
+
text: str(),
|
|
93
|
+
createdAt: num(),
|
|
94
|
+
updatedAt: num(),
|
|
95
|
+
operation: union([
|
|
96
|
+
lit("local_append_overlay"),
|
|
97
|
+
lit("local_replacement"),
|
|
98
|
+
]),
|
|
99
|
+
},
|
|
100
|
+
{ open: true },
|
|
101
|
+
),
|
|
102
|
+
),
|
|
103
|
+
},
|
|
104
|
+
{ open: true },
|
|
105
|
+
);
|
|
106
|
+
export const Parent = obj(
|
|
107
|
+
{
|
|
108
|
+
transport: lit("shepherdr"),
|
|
109
|
+
parent: str(),
|
|
110
|
+
savedParent: opt(
|
|
111
|
+
obj({ machine: str(), sessionFile: str() }, { open: true }),
|
|
112
|
+
),
|
|
113
|
+
},
|
|
114
|
+
{ open: true },
|
|
115
|
+
);
|
|
83
116
|
export type Identity = Static<typeof Identity>;
|
|
84
117
|
|
|
118
|
+
const identityValidator = compile(Identity);
|
|
119
|
+
|
|
85
120
|
/** Ordinary family membership is immutable, explicit and native-session owned. */
|
|
86
121
|
export function savedFamilyIdentity(
|
|
87
122
|
session: Pick<SavedNotesSession, "threadId" | "entries">,
|
|
@@ -93,7 +128,7 @@ export function savedFamilyIdentity(
|
|
|
93
128
|
(entry) =>
|
|
94
129
|
entry.type === "custom" &&
|
|
95
130
|
entry.customType === "codex-context-agent" &&
|
|
96
|
-
|
|
131
|
+
identityValidator.check(entry.data) &&
|
|
97
132
|
entry.data.threadId === session.threadId,
|
|
98
133
|
)
|
|
99
134
|
)
|
|
@@ -109,7 +144,7 @@ export function savedNotesIdentity(
|
|
|
109
144
|
for (const entry of session.entries) {
|
|
110
145
|
if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
|
|
111
146
|
continue;
|
|
112
|
-
if (!
|
|
147
|
+
if (!identityValidator.check(entry.data))
|
|
113
148
|
throw new Error("Invalid saved notes identity");
|
|
114
149
|
if (entry.data.threadId !== session.threadId) continue;
|
|
115
150
|
if (found) throw new Error("Conflicting saved notes identities");
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
fsyncSync,
|
|
5
|
+
lstatSync,
|
|
6
|
+
openSync,
|
|
7
|
+
readdirSync,
|
|
8
|
+
renameSync,
|
|
9
|
+
statSync,
|
|
10
|
+
unlinkSync,
|
|
11
|
+
} from "node:fs";
|
|
12
|
+
import { open } from "node:fs/promises";
|
|
13
|
+
import { resolve } from "node:path";
|
|
14
|
+
import {
|
|
15
|
+
planSparsePruning,
|
|
16
|
+
scanSparseSource,
|
|
17
|
+
} from "./session-pruning-sparse.mjs";
|
|
18
|
+
import { cleanupPaths, tryCleanupLock } from "./session-pruning-state.mjs";
|
|
19
|
+
|
|
20
|
+
/** @param {string} path @param {import("node:fs").Stats} source */
|
|
21
|
+
function checkSource(path, source) {
|
|
22
|
+
const current = lstatSync(path);
|
|
23
|
+
if (
|
|
24
|
+
!current.isFile() ||
|
|
25
|
+
current.nlink !== 1 ||
|
|
26
|
+
current.dev !== source.dev ||
|
|
27
|
+
current.ino !== source.ino ||
|
|
28
|
+
current.size !== source.size ||
|
|
29
|
+
current.mtimeMs !== source.mtimeMs ||
|
|
30
|
+
current.ctimeMs !== source.ctimeMs
|
|
31
|
+
)
|
|
32
|
+
throw new Error(
|
|
33
|
+
"Session changed during cleanup. Nothing was replaced. Cleanup will retry on the next normal Pi exit.",
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Open descriptors supplement the registered session owners, not replace them.
|
|
38
|
+
* @param {import("node:fs").Stats} source
|
|
39
|
+
*/
|
|
40
|
+
function checkHolders(source) {
|
|
41
|
+
if (process.platform !== "linux")
|
|
42
|
+
throw new Error(
|
|
43
|
+
"Automatic session cleanup is unavailable on this platform. Retired payloads remain pruned.",
|
|
44
|
+
);
|
|
45
|
+
const holders = new Set();
|
|
46
|
+
for (const pid of readdirSync("/proc")) {
|
|
47
|
+
if (!/^\d+$/.test(pid) || Number(pid) === process.pid) continue;
|
|
48
|
+
const dir = `/proc/${pid}`;
|
|
49
|
+
try {
|
|
50
|
+
if (statSync(dir).uid !== process.getuid?.()) continue;
|
|
51
|
+
for (const fd of readdirSync(`${dir}/fd`)) {
|
|
52
|
+
try {
|
|
53
|
+
const file = statSync(`${dir}/fd/${fd}`);
|
|
54
|
+
if (file.dev === source.dev && file.ino === source.ino)
|
|
55
|
+
holders.add(pid);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (!vanished(error)) throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (
|
|
62
|
+
error instanceof Error &&
|
|
63
|
+
"code" in error &&
|
|
64
|
+
(error.code === "EACCES" || error.code === "EPERM")
|
|
65
|
+
)
|
|
66
|
+
continue;
|
|
67
|
+
else if (!vanished(error))
|
|
68
|
+
throw new Error(
|
|
69
|
+
`Cannot inspect open holders for PID ${pid}: ${String(error)}`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (holders.size)
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Session record cleanup was skipped because process(es) ${[...holders].join(", ")} still hold it open. It will retry on the next normal Pi exit.`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** @param {unknown} error */
|
|
80
|
+
function vanished(error) {
|
|
81
|
+
return (
|
|
82
|
+
error instanceof Error &&
|
|
83
|
+
"code" in error &&
|
|
84
|
+
(error.code === "ENOENT" || error.code === "ESRCH")
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Called only by the after-exit worker.
|
|
89
|
+
* @param {string} file @param {string} sessionId @param {()=>void} checkOwners
|
|
90
|
+
*/
|
|
91
|
+
export async function cleanSparseSession(file, sessionId, checkOwners) {
|
|
92
|
+
const path = resolve(file);
|
|
93
|
+
const source = lstatSync(path);
|
|
94
|
+
if (!source.isFile() || source.nlink !== 1)
|
|
95
|
+
throw new Error(
|
|
96
|
+
"Session record cleanup requires a regular session file without symbolic or hard links. Retired payloads remain pruned.",
|
|
97
|
+
);
|
|
98
|
+
checkOwners();
|
|
99
|
+
checkHolders(source);
|
|
100
|
+
const lock = cleanupPaths(path).lock;
|
|
101
|
+
let releaseLock;
|
|
102
|
+
const temp = `${path}.notes-prune-${randomUUID()}.tmp`;
|
|
103
|
+
/** @type {Awaited<ReturnType<typeof open>>|undefined} */
|
|
104
|
+
let output;
|
|
105
|
+
try {
|
|
106
|
+
releaseLock = tryCleanupLock(path);
|
|
107
|
+
if (!releaseLock)
|
|
108
|
+
throw new Error(
|
|
109
|
+
`Another session cleanup may be running. Only after verifying that none is active, remove the stale lock ${JSON.stringify(lock)}. Cleanup will retry on the next normal Pi exit. Do not remove an active cleanup's lock.`,
|
|
110
|
+
);
|
|
111
|
+
checkOwners();
|
|
112
|
+
const plan = await planSparsePruning(path, source.size);
|
|
113
|
+
if (plan.header.id !== sessionId)
|
|
114
|
+
throw new Error("Session identity changed. Cleanup was skipped.");
|
|
115
|
+
checkSource(path, source);
|
|
116
|
+
if (!plan.removed.size)
|
|
117
|
+
return { removed: 0, before: source.size, after: source.size };
|
|
118
|
+
output = await open(temp, "wx", source.mode & 0o777);
|
|
119
|
+
const target = output;
|
|
120
|
+
const generation = randomUUID();
|
|
121
|
+
await scanSparseSource(path, source.size, async (entry, raw) => {
|
|
122
|
+
if (plan.removed.has(entry.id)) return;
|
|
123
|
+
const parentId = plan.parents.get(entry.id) ?? null;
|
|
124
|
+
const replacement =
|
|
125
|
+
entry.type === "session"
|
|
126
|
+
? {
|
|
127
|
+
...entry,
|
|
128
|
+
notesPruning: { version: 1, sessionId: entry.id, generation },
|
|
129
|
+
}
|
|
130
|
+
: entry.parentId === parentId
|
|
131
|
+
? entry
|
|
132
|
+
: { ...entry, parentId };
|
|
133
|
+
await target.writeFile(
|
|
134
|
+
`${replacement === entry ? raw : JSON.stringify(replacement)}\n`,
|
|
135
|
+
);
|
|
136
|
+
});
|
|
137
|
+
await output.sync();
|
|
138
|
+
await output.close();
|
|
139
|
+
output = undefined;
|
|
140
|
+
// No await from final holder/source validation through atomic replacement.
|
|
141
|
+
checkOwners();
|
|
142
|
+
checkHolders(source);
|
|
143
|
+
checkSource(path, source);
|
|
144
|
+
const after = statSync(temp).size;
|
|
145
|
+
renameSync(temp, path);
|
|
146
|
+
const directory = openSync(resolve(path, ".."), "r");
|
|
147
|
+
try {
|
|
148
|
+
fsyncSync(directory);
|
|
149
|
+
} finally {
|
|
150
|
+
closeSync(directory);
|
|
151
|
+
}
|
|
152
|
+
return { removed: plan.removed.size, before: source.size, after };
|
|
153
|
+
} finally {
|
|
154
|
+
await output?.close();
|
|
155
|
+
try {
|
|
156
|
+
unlinkSync(temp);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (!vanished(error)) throw error;
|
|
159
|
+
} finally {
|
|
160
|
+
releaseLock?.();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|