@kanadego/dsh-heartbeat 1.9.3 → 2.0.0
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/LICENSE +21 -21
- package/README.md +103 -110
- package/client.js +12 -0
- package/config/policy.json +74 -74
- package/config/profile-schema.json +306 -306
- package/dist/{bindings-225SI7KC.js → bindings-U2M3CO2D.js} +3 -3
- package/dist/{chunk-TY6UP74X.js → chunk-3DNGY4DS.js} +2 -2
- package/dist/{chunk-CUOSICYJ.js → chunk-544QOJN5.js} +397 -23
- package/dist/chunk-544QOJN5.js.map +1 -0
- package/dist/{chunk-TRO4E6WG.js → chunk-6MVKWICX.js} +587 -139
- package/dist/chunk-6MVKWICX.js.map +1 -0
- package/dist/{chunk-WLZSABBH.js → chunk-6XM6KY7M.js} +27 -10
- package/dist/chunk-6XM6KY7M.js.map +1 -0
- package/dist/chunk-AKIJ4LS2.js +680 -0
- package/dist/chunk-AKIJ4LS2.js.map +1 -0
- package/dist/{chunk-KB5SMG3F.js → chunk-DC5HMCJC.js} +3 -3
- package/dist/{chunk-3MDBU6WY.js → chunk-DZ7YCFGX.js} +37 -7
- package/dist/chunk-DZ7YCFGX.js.map +1 -0
- package/dist/{chunk-WRUTATW4.js → chunk-IBBAISSW.js} +13 -2
- package/dist/chunk-IBBAISSW.js.map +1 -0
- package/dist/{chunk-XYYEJK3W.js → chunk-IFRMKVIC.js} +82 -21
- package/dist/chunk-IFRMKVIC.js.map +1 -0
- package/dist/{chunk-XFNCTOW7.js → chunk-NCPKOWS7.js} +52 -4
- package/dist/chunk-NCPKOWS7.js.map +1 -0
- package/dist/{chunk-JDH2LDFS.js → chunk-TVX4HV4Y.js} +4 -6
- package/dist/{chunk-JDH2LDFS.js.map → chunk-TVX4HV4Y.js.map} +1 -1
- package/dist/cli/index.js +149 -26
- package/dist/cli/index.js.map +1 -1
- package/dist/{inbox-P26DDMWC.js → inbox-OWBK6PE2.js} +8 -7
- package/dist/index.d.ts +48 -315
- package/dist/index.js +259 -918
- package/dist/index.js.map +1 -1
- package/dist/migrate-TQ5PB2DI.js +27 -0
- package/dist/{orchestrator-ZPRGVDCB.js → orchestrator-P7AEWVYR.js} +23 -12
- package/dist/{pool-UTXQJJ5C.js → pool-2T6TVS2L.js} +4 -5
- package/dist/{snapshot-K5VHETTK.js → snapshot-F5B2DD56.js} +5 -5
- package/package.json +84 -83
- package/dist/chunk-3MDBU6WY.js.map +0 -1
- package/dist/chunk-CUOSICYJ.js.map +0 -1
- package/dist/chunk-IV2ZWQA3.js +0 -56
- package/dist/chunk-IV2ZWQA3.js.map +0 -1
- package/dist/chunk-K5Y6JP2B.js +0 -399
- package/dist/chunk-K5Y6JP2B.js.map +0 -1
- package/dist/chunk-TRO4E6WG.js.map +0 -1
- package/dist/chunk-WLZSABBH.js.map +0 -1
- package/dist/chunk-WRUTATW4.js.map +0 -1
- package/dist/chunk-XFNCTOW7.js.map +0 -1
- package/dist/chunk-XYYEJK3W.js.map +0 -1
- package/dist/migrate-D4VKAKYT.js +0 -21
- /package/dist/{bindings-225SI7KC.js.map → bindings-U2M3CO2D.js.map} +0 -0
- /package/dist/{chunk-TY6UP74X.js.map → chunk-3DNGY4DS.js.map} +0 -0
- /package/dist/{chunk-KB5SMG3F.js.map → chunk-DC5HMCJC.js.map} +0 -0
- /package/dist/{inbox-P26DDMWC.js.map → inbox-OWBK6PE2.js.map} +0 -0
- /package/dist/{migrate-D4VKAKYT.js.map → migrate-TQ5PB2DI.js.map} +0 -0
- /package/dist/{orchestrator-ZPRGVDCB.js.map → orchestrator-P7AEWVYR.js.map} +0 -0
- /package/dist/{pool-UTXQJJ5C.js.map → pool-2T6TVS2L.js.map} +0 -0
- /package/dist/{snapshot-K5VHETTK.js.map → snapshot-F5B2DD56.js.map} +0 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MIGRATE_FILES,
|
|
3
|
+
MIGRATE_MAGIC,
|
|
4
|
+
MIGRATE_MAX_BYTES,
|
|
5
|
+
MIGRATE_MAX_FILES,
|
|
6
|
+
MIGRATE_VERSION,
|
|
7
|
+
applyMigrationEntries,
|
|
8
|
+
collectMigrationEntries,
|
|
9
|
+
decryptContainer,
|
|
10
|
+
encryptContainer,
|
|
11
|
+
isMigratablePath
|
|
12
|
+
} from "./chunk-NCPKOWS7.js";
|
|
13
|
+
import "./chunk-AKIJ4LS2.js";
|
|
14
|
+
import "./chunk-IBBAISSW.js";
|
|
15
|
+
export {
|
|
16
|
+
MIGRATE_FILES,
|
|
17
|
+
MIGRATE_MAGIC,
|
|
18
|
+
MIGRATE_MAX_BYTES,
|
|
19
|
+
MIGRATE_MAX_FILES,
|
|
20
|
+
MIGRATE_VERSION,
|
|
21
|
+
applyMigrationEntries,
|
|
22
|
+
collectMigrationEntries,
|
|
23
|
+
decryptContainer,
|
|
24
|
+
encryptContainer,
|
|
25
|
+
isMigratablePath
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=migrate-TQ5PB2DI.js.map
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
|
+
BeatAbortedError,
|
|
2
3
|
ENGINE_ROOM_EXTRA_TOOLS,
|
|
3
4
|
HOME_ROTATE_EVENT_COUNT,
|
|
4
5
|
TOKEN_SAVER_IDLE_SECONDS,
|
|
5
6
|
TOKEN_SAVER_WAKE_MS,
|
|
6
7
|
agentLooksAlive,
|
|
8
|
+
agentTurn,
|
|
7
9
|
applyHeartbeatInterval,
|
|
8
10
|
beat,
|
|
9
11
|
buildEngineRoomAllowList,
|
|
@@ -16,31 +18,36 @@ import {
|
|
|
16
18
|
markHomeRotateIfOverflow,
|
|
17
19
|
parseJsonBlock,
|
|
18
20
|
pickSpokenLine,
|
|
21
|
+
pinEngineRoomTools,
|
|
19
22
|
resetHomeAgent,
|
|
20
23
|
resetHomeSession,
|
|
24
|
+
selectedPresetId,
|
|
21
25
|
sessionEventCount,
|
|
22
26
|
sessionEvents,
|
|
23
27
|
shouldArchiveRotatedHome,
|
|
24
28
|
shouldRotateHome,
|
|
25
29
|
spokeTextSince,
|
|
26
30
|
startOrchestrator,
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
31
|
+
throwIfAborted,
|
|
32
|
+
userActiveInBoundSessions,
|
|
33
|
+
withTimeout
|
|
34
|
+
} from "./chunk-6MVKWICX.js";
|
|
35
|
+
import "./chunk-6XM6KY7M.js";
|
|
30
36
|
import "./chunk-3QJJRXIR.js";
|
|
31
|
-
import "./chunk-
|
|
32
|
-
import "./chunk-
|
|
33
|
-
import "./chunk-
|
|
34
|
-
import "./chunk-
|
|
35
|
-
import "./chunk-
|
|
36
|
-
import "./chunk-
|
|
37
|
-
import "./chunk-WRUTATW4.js";
|
|
37
|
+
import "./chunk-TVX4HV4Y.js";
|
|
38
|
+
import "./chunk-DZ7YCFGX.js";
|
|
39
|
+
import "./chunk-DC5HMCJC.js";
|
|
40
|
+
import "./chunk-544QOJN5.js";
|
|
41
|
+
import "./chunk-AKIJ4LS2.js";
|
|
42
|
+
import "./chunk-IBBAISSW.js";
|
|
38
43
|
export {
|
|
44
|
+
BeatAbortedError,
|
|
39
45
|
ENGINE_ROOM_EXTRA_TOOLS,
|
|
40
46
|
HOME_ROTATE_EVENT_COUNT,
|
|
41
47
|
TOKEN_SAVER_IDLE_SECONDS,
|
|
42
48
|
TOKEN_SAVER_WAKE_MS,
|
|
43
49
|
agentLooksAlive,
|
|
50
|
+
agentTurn,
|
|
44
51
|
applyHeartbeatInterval,
|
|
45
52
|
beat,
|
|
46
53
|
buildEngineRoomAllowList,
|
|
@@ -53,14 +60,18 @@ export {
|
|
|
53
60
|
markHomeRotateIfOverflow,
|
|
54
61
|
parseJsonBlock,
|
|
55
62
|
pickSpokenLine,
|
|
63
|
+
pinEngineRoomTools,
|
|
56
64
|
resetHomeAgent,
|
|
57
65
|
resetHomeSession,
|
|
66
|
+
selectedPresetId,
|
|
58
67
|
sessionEventCount,
|
|
59
68
|
sessionEvents,
|
|
60
69
|
shouldArchiveRotatedHome,
|
|
61
70
|
shouldRotateHome,
|
|
62
71
|
spokeTextSince,
|
|
63
72
|
startOrchestrator,
|
|
64
|
-
|
|
73
|
+
throwIfAborted,
|
|
74
|
+
userActiveInBoundSessions,
|
|
75
|
+
withTimeout
|
|
65
76
|
};
|
|
66
|
-
//# sourceMappingURL=orchestrator-
|
|
77
|
+
//# sourceMappingURL=orchestrator-P7AEWVYR.js.map
|
|
@@ -16,10 +16,9 @@ import {
|
|
|
16
16
|
savePool,
|
|
17
17
|
seedsFilePath,
|
|
18
18
|
surfaceSeed
|
|
19
|
-
} from "./chunk-
|
|
20
|
-
import "./chunk-
|
|
21
|
-
import "./chunk-
|
|
22
|
-
import "./chunk-WRUTATW4.js";
|
|
19
|
+
} from "./chunk-TVX4HV4Y.js";
|
|
20
|
+
import "./chunk-AKIJ4LS2.js";
|
|
21
|
+
import "./chunk-IBBAISSW.js";
|
|
23
22
|
export {
|
|
24
23
|
SEED_CATEGORY_CAPS,
|
|
25
24
|
TTL_KEYS,
|
|
@@ -39,4 +38,4 @@ export {
|
|
|
39
38
|
seedsFilePath,
|
|
40
39
|
surfaceSeed
|
|
41
40
|
};
|
|
42
|
-
//# sourceMappingURL=pool-
|
|
41
|
+
//# sourceMappingURL=pool-2T6TVS2L.js.map
|
|
@@ -3,14 +3,14 @@ import {
|
|
|
3
3
|
snapshotDue,
|
|
4
4
|
snapshotIfDue,
|
|
5
5
|
snapshotProfile
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import "./chunk-
|
|
8
|
-
import "./chunk-
|
|
9
|
-
import "./chunk-
|
|
6
|
+
} from "./chunk-DC5HMCJC.js";
|
|
7
|
+
import "./chunk-544QOJN5.js";
|
|
8
|
+
import "./chunk-AKIJ4LS2.js";
|
|
9
|
+
import "./chunk-IBBAISSW.js";
|
|
10
10
|
export {
|
|
11
11
|
SNAPSHOT_THRESHOLD,
|
|
12
12
|
snapshotDue,
|
|
13
13
|
snapshotIfDue,
|
|
14
14
|
snapshotProfile
|
|
15
15
|
};
|
|
16
|
-
//# sourceMappingURL=snapshot-
|
|
16
|
+
//# sourceMappingURL=snapshot-F5B2DD56.js.map
|
package/package.json
CHANGED
|
@@ -1,83 +1,84 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@kanadego/dsh-heartbeat",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Heartbeat plugin for DeepSeek Harness: scheduled autonomous reflection loop with user profile, material pool, pace gate, and gated proactive expression.",
|
|
5
|
-
"repository": {
|
|
6
|
-
"type": "git",
|
|
7
|
-
"url": "git+https://github.com/Kanadego/dsh-heartbeat.git"
|
|
8
|
-
},
|
|
9
|
-
"homepage": "https://github.com/Kanadego/dsh-heartbeat",
|
|
10
|
-
"bugs": {
|
|
11
|
-
"url": "https://github.com/Kanadego/dsh-heartbeat/issues"
|
|
12
|
-
},
|
|
13
|
-
"keywords": [
|
|
14
|
-
"dsh",
|
|
15
|
-
"dsh-plugin",
|
|
16
|
-
"deepseek-harness",
|
|
17
|
-
"heartbeat",
|
|
18
|
-
"proactive",
|
|
19
|
-
"agent"
|
|
20
|
-
],
|
|
21
|
-
"publishConfig": {
|
|
22
|
-
"registry": "https://registry.npmjs.org"
|
|
23
|
-
},
|
|
24
|
-
"type": "module",
|
|
25
|
-
"main": "dist/index.js",
|
|
26
|
-
"types": "dist/index.d.ts",
|
|
27
|
-
"exports": {
|
|
28
|
-
".": {
|
|
29
|
-
"types": "./dist/index.d.ts",
|
|
30
|
-
"default": "./dist/index.js"
|
|
31
|
-
},
|
|
32
|
-
"./cli": {
|
|
33
|
-
"types": "./dist/cli/index.d.ts",
|
|
34
|
-
"default": "./dist/cli/index.js"
|
|
35
|
-
},
|
|
36
|
-
"./client": "./client.js",
|
|
37
|
-
"./package.json": "./package.json",
|
|
38
|
-
"./cordis.patch.yml": "./cordis.patch.yml"
|
|
39
|
-
},
|
|
40
|
-
"files": [
|
|
41
|
-
"dist",
|
|
42
|
-
"config",
|
|
43
|
-
"assets",
|
|
44
|
-
"client.js",
|
|
45
|
-
"cordis.patch.yml",
|
|
46
|
-
"README.md",
|
|
47
|
-
"LICENSE"
|
|
48
|
-
],
|
|
49
|
-
"engines": {
|
|
50
|
-
"node": ">=22.19.0"
|
|
51
|
-
},
|
|
52
|
-
"os": [
|
|
53
|
-
"win32"
|
|
54
|
-
],
|
|
55
|
-
"dependencies": {
|
|
56
|
-
"@deepseek-ai/dsh-settings": "^0.1.1-rc.2 || ^0.1.5-rc.2 || ^0.1.7-rc.1 || ^0.2.0-rc.1"
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
"@deepseek-ai/dsh-
|
|
64
|
-
"@deepseek-ai/
|
|
65
|
-
"@types/node": "^24.0.0",
|
|
66
|
-
"tsup": "^8.3.0",
|
|
67
|
-
"tsx": "^4.19.0",
|
|
68
|
-
"typescript": "^5.7.0"
|
|
69
|
-
},
|
|
70
|
-
"scripts": {
|
|
71
|
-
"build": "tsup",
|
|
72
|
-
"typecheck": "tsc --noEmit",
|
|
73
|
-
"
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@kanadego/dsh-heartbeat",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Heartbeat plugin for DeepSeek Harness: scheduled autonomous reflection loop with user profile, material pool, pace gate, and gated proactive expression.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/Kanadego/dsh-heartbeat.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://github.com/Kanadego/dsh-heartbeat",
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/Kanadego/dsh-heartbeat/issues"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"dsh",
|
|
15
|
+
"dsh-plugin",
|
|
16
|
+
"deepseek-harness",
|
|
17
|
+
"heartbeat",
|
|
18
|
+
"proactive",
|
|
19
|
+
"agent"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"registry": "https://registry.npmjs.org"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"main": "dist/index.js",
|
|
26
|
+
"types": "dist/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./cli": {
|
|
33
|
+
"types": "./dist/cli/index.d.ts",
|
|
34
|
+
"default": "./dist/cli/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./client": "./client.js",
|
|
37
|
+
"./package.json": "./package.json",
|
|
38
|
+
"./cordis.patch.yml": "./cordis.patch.yml"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"dist",
|
|
42
|
+
"config",
|
|
43
|
+
"assets",
|
|
44
|
+
"client.js",
|
|
45
|
+
"cordis.patch.yml",
|
|
46
|
+
"README.md",
|
|
47
|
+
"LICENSE"
|
|
48
|
+
],
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=22.19.0"
|
|
51
|
+
},
|
|
52
|
+
"os": [
|
|
53
|
+
"win32"
|
|
54
|
+
],
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@deepseek-ai/dsh-settings": "^0.1.1-rc.2 || ^0.1.5-rc.2 || ^0.1.7-rc.1 || ^0.2.0-rc.1 || ^0.2.1-rc.1 || ^0.2.1-rc.2",
|
|
57
|
+
"@deepseek-ai/schemastery": "^3.18.2"
|
|
58
|
+
},
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"@deepseek-ai/dsh-llm": "^0.1.1-rc.2 || ^0.1.5-rc.2 || ^0.1.7-rc.1 || ^0.2.0-rc.1 || ^0.2.1-rc.1 || ^0.2.1-rc.2"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@deepseek-ai/dsh-llm": "^0.1.7-rc.1",
|
|
64
|
+
"@deepseek-ai/dsh-settings": "^0.1.1-rc.2",
|
|
65
|
+
"@types/node": "^24.0.0",
|
|
66
|
+
"tsup": "^8.3.0",
|
|
67
|
+
"tsx": "^4.19.0",
|
|
68
|
+
"typescript": "^5.7.0"
|
|
69
|
+
},
|
|
70
|
+
"scripts": {
|
|
71
|
+
"build": "tsup",
|
|
72
|
+
"typecheck": "tsc --noEmit",
|
|
73
|
+
"check:client": "node --check client.js",
|
|
74
|
+
"test": "node --import tsx --test \"tests/*.test.ts\""
|
|
75
|
+
},
|
|
76
|
+
"dsh": {
|
|
77
|
+
"bundle": {
|
|
78
|
+
"patch": "./cordis.patch.yml"
|
|
79
|
+
},
|
|
80
|
+
"client": {
|
|
81
|
+
"platform": "web"
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/profile/inbox.ts"],"sourcesContent":["// Observation inbox (design doc §3.2): append-only queue of pending\n// observations; drained by the consolidation run. DPAPI-encrypted. Items hold\n// pointers + at most one short sentence - never raw conversation/screen text.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\nimport { withFileLock } from '../core/file-lock.js';\nimport type { InboxItem } from './types.js';\n\nconst MAX_NOTE_CHARS = 120;\n\nexport function inboxFilePath(dataDir: string): string {\n return path.join(dataDir, 'profile_inbox.jsonl');\n}\n\nfunction truncateNote(note: string): string {\n const oneLine = note.replace(/\\r?\\n/g, ' ').trim();\n return oneLine.length > MAX_NOTE_CHARS ? oneLine.slice(0, MAX_NOTE_CHARS) + '…' : oneLine;\n}\n\nexport function inboxAppend(\n guard: PathGuard,\n file: string,\n item: Omit<InboxItem, 'id'> & { id?: string },\n): InboxItem {\n // H-20 (minimal tier): the append is a whole-file encrypted rewrite, so it\n // needs the same cross-process lock the pool uses — the CLI can be draining\n // or writing the same file while a beat appends.\n return withFileLock(file, () => inboxAppendLocked(guard, file, item));\n}\n\nfunction inboxAppendLocked(\n guard: PathGuard,\n file: string,\n item: Omit<InboxItem, 'id'> & { id?: string },\n): InboxItem {\n const full: InboxItem = {\n id: item.id ?? randomUUID().slice(0, 8),\n kind: item.kind,\n at: item.at,\n ref: item.ref,\n note: truncateNote(item.note),\n };\n const prev = loadEncryptedText(guard, file) ?? '';\n // H-16 (minimal tier): this file is a whole-file encrypted rewrite, so a\n // repeated observation used to cost a full decrypt + encrypt + write for a\n // duplicate row. The §3.7 dedupe key is kind+ref — if that row is already\n // queued, hand it back instead of appending a second copy. (A stalled cursor\n // used to grow the queue here and rely on the consumer's dedupeItems.)\n for (const line of prev.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const existing = JSON.parse(trimmed) as InboxItem;\n if (existing.kind === full.kind && existing.ref === full.ref) return existing;\n } catch {\n // corrupt line: ignore (the queue is re-derivable from its sources)\n }\n }\n saveEncryptedText(guard, file, prev + JSON.stringify(full) + '\\n');\n return full;\n}\n\nexport function inboxCount(guard: PathGuard, file: string): number {\n const raw = loadEncryptedText(guard, file);\n if (!raw) return 0;\n return raw.split('\\n').filter((l) => l.trim()).length;\n}\n\n/**\n * Drain all items. `commit` controls crash semantics: on consolidation failure\n * the inbox must SURVIVE (§3.7), so the caller drains with commit=false first,\n * and only rewrites an empty inbox after the run succeeded.\n */\nexport function inboxDrain(guard: PathGuard, file: string): InboxItem[] {\n const raw = loadEncryptedText(guard, file);\n if (!raw) return [];\n const items: InboxItem[] = [];\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n items.push(JSON.parse(trimmed) as InboxItem);\n } catch {\n // corrupt line: drop (queue is re-derivable from sources)\n }\n }\n return items;\n}\n\nexport function inboxClear(guard: PathGuard, file: string): void {\n saveEncryptedText(guard, file, '');\n}\n\n/** Dedupe key (§3.7): same source kind + same ref must not flood the queue. */\nexport function dedupeItems(items: InboxItem[]): InboxItem[] {\n const seen = new Set<string>();\n const out: InboxItem[] = [];\n for (const it of items) {\n const key = `${it.kind}#${it.ref}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(it);\n }\n return out;\n}\n\nexport function inboxHealthCheck(guard: PathGuard, file: string): { total: number; corrupt: number; duplicates: number } {\n const raw = loadEncryptedText(guard, file) ?? '';\n let total = 0;\n let corrupt = 0;\n const keys = new Set<string>();\n let duplicates = 0;\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const it = JSON.parse(trimmed) as InboxItem;\n total += 1;\n const key = `${it.kind}#${it.ref}`;\n if (keys.has(key)) duplicates += 1;\n keys.add(key);\n } catch {\n corrupt += 1;\n }\n }\n return { total, corrupt, duplicates };\n}\n\nexport function inboxFileExists(guard: PathGuard, file: string): boolean {\n return fs.existsSync(guard.assert(file));\n}\n"],"mappings":";;;;;;;;;AAIA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAM3B,IAAM,iBAAiB;AAEhB,SAAS,cAAc,SAAyB;AACrD,SAAO,KAAK,KAAK,SAAS,qBAAqB;AACjD;AAEA,SAAS,aAAa,MAAsB;AAC1C,QAAM,UAAU,KAAK,QAAQ,UAAU,GAAG,EAAE,KAAK;AACjD,SAAO,QAAQ,SAAS,iBAAiB,QAAQ,MAAM,GAAG,cAAc,IAAI,WAAM;AACpF;AAEO,SAAS,YACd,OACA,MACA,MACW;AAIX,SAAO,aAAa,MAAM,MAAM,kBAAkB,OAAO,MAAM,IAAI,CAAC;AACtE;AAEA,SAAS,kBACP,OACA,MACA,MACW;AACX,QAAM,OAAkB;AAAA,IACtB,IAAI,KAAK,MAAM,WAAW,EAAE,MAAM,GAAG,CAA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AG,IAAI,IAAI,GAAG,GAAG;AAChC,QAAI,KAAK,IAAI,GAAG,EAAG;AACnB,SAAK,IAAI,GAAG;AACZ,QAAI,KAAK,EAAE;AAAA,EACb;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,OAAkB,MAAsE;AACvH,QAAM,MAAM,kBAAkB,OAAO,IAAI,KAAK;AAC9C,MAAI,QAAQ;AACZ,MAAI,UAAU;AACd,QAAM,OAAO,oBAAI,IAAY;AAC7B,MAAI,aAAa;AACjB,aAAW,QAAQ,IAAI,MAAM,IAAI,GAAG;AAClC,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,CAAC,QAAS;AACd,QAAI;AACF,YAAM,KAAK,KAAK,MAAM,OAAO;AAC7B,eAAS;AACT,YAAM,MAAM,GAAG,GAAG,IAAI,IAAI,GAAG,GAAG;AAChC,UAAI,KAAK,IAAI,GAAG,EAAG,eAAc;AACjC,WAAK,IAAI,GAAG;AAAA,IACd,QAAQ;AACN,iBAAW;AAAA,IACb;AAAA,EACF;AACA,SAAO,EAAE,OAAO,SAAS,WAAW;AACtC;AAEO,SAAS,gBAAgB,OAAkB,MAAuB;AACvE,SAAO,GAAG,WAAW,MAAM,OAAO,IAAI,CAAC;AACzC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/audit-log.ts","../src/profile/store.ts","../src/profile/types.ts","../src/profile/schema.ts"],"sourcesContent":["// Append-only JSONL audit log with age-based retention pruning.\n// Audit files are plaintext by charter (transparency), and must never contain\n// sensitive raw observations (window titles, conversation text).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteFileSync } from './atomic-fs.js';\n\nexport interface AuditEvent {\n ts: string;\n [key: string]: unknown;\n}\n\n/**\n * H-15: audit is best-effort by contract — a full disk, a locked log file or an\n * unserialisable payload must never abort a beat (one caller inside a catch\n * block turning a handled failure into an unhandled one is the worst case).\n * Failures go to stderr so they stay visible instead of silently vanishing.\n */\nexport function appendAuditLine(file: string, event: Omit<AuditEvent, 'ts'> & { ts?: string }): void {\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const line = JSON.stringify({ ts: event.ts ?? new Date().toISOString(), ...event });\n fs.appendFileSync(file, line + '\\n', 'utf8');\n } catch (e) {\n process.stderr.write(`[heartbeat] audit append failed: ${file}: ${String(e)}\\n`);\n }\n}\n\nexport function readAuditLines<T = AuditEvent>(file: string): T[] {\n if (!fs.existsSync(file)) return [];\n const out: T[] = [];\n const raw = fs.readFileSync(file, 'utf8');\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n out.push(JSON.parse(trimmed) as T);\n } catch {\n // Skip corrupt lines; the log is diagnostic, not authoritative data.\n out.push({ ts: '', corrupt: true, raw: trimmed.slice(0, 200) } as unknown as T);\n }\n }\n return out;\n}\n\n/**\n * Drop entries older than maxAgeMs. Returns the number of removed lines.\n * Rewrites the file atomically; on rewrite failure the original is untouched.\n */\nexport function pruneAuditFile(file: string, maxAgeMs: number, now = Date.now()): number {\n if (!fs.existsSync(file)) return 0;\n const lines = readAuditLines(file);\n const kept = lines.filter((e) => {\n const ev = e as unknown as AuditEvent;\n const ts = Date.parse(ev.ts ?? '');\n if (!Number.isFinite(ts)) return true; // keep unparseable lines, never lose audit data silently\n return now - ts <= maxAgeMs;\n });\n const removed = lines.length - kept.length;\n if (removed === 0) return 0;\n const body = kept.map((e) => JSON.stringify(e)).join('\\n');\n atomicWriteFileSync(file, body ? body + '\\n' : '');\n return removed;\n}\n","// Profile store: materialized view + journal (the journal is the ONLY\n// authority; profile.json is a pure projection - r2 §14 verify/rebuild).\n// Every LLM-proposed op passes deterministic guards here (LLM nominates,\n// code decides - §3.3).\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadJson, saveJson, readText, writeText } from '../vault/vault.js';\nimport type { Policy } from '../config/schema.js';\nimport {\n CONFIDENCE_CAP,\n emptyProfile,\n PARTITIONS,\n type ApplyReport,\n type Evidence,\n type EvidenceKind,\n type InboxItem,\n type JournalRecord,\n type Partition,\n type ProfileDoc,\n type ProfileEntry,\n type ProfileOp,\n} from './types.js';\nimport { checkAddAgainstSchema, type ProfileSchema } from './schema.js';\n\nconst DAY_MS = 86_400_000;\n\nexport function profileFilePath(dataDir: string): string {\n return path.join(dataDir, 'profile.json');\n}\n\nexport function journalFilePath(dataDir: string): string {\n return path.join(dataDir, 'profile_journal.jsonl');\n}\n\n// ── snapshot basepoint (v1.8.0, design doc §14 ③) ─────────────────────────\n// The journal grows forever; the snapshot folds its history into one DPAPI\n// document and moves the folded records into a timestamped archive shard.\n// Replay order: snapshot → archives (name order) → live journal, skipping\n// records at or before the snapshot baseline — so verify/rebuild stay correct\n// without knowing whether a snapshot exists.\n\nexport const SNAPSHOT_FILE = 'profile_snapshot.json';\nexport const ARCHIVE_PREFIX = 'profile_journal.archive-';\n\nexport interface ProfileSnapshot {\n version: 1;\n /** ts of the LAST journal record folded into `doc`. */\n baselineTs: string;\n recordsFolded: number;\n doc: ProfileDoc;\n}\n\nexport function snapshotFilePath(dataDir: string): string {\n return path.join(dataDir, SNAPSHOT_FILE);\n}\n\nfunction loadSnapshot(guard: PathGuard, dataDir: string): ProfileSnapshot | null {\n const snap = loadJson<ProfileSnapshot>(guard, snapshotFilePath(dataDir));\n if (!snap || snap.version !== 1 || typeof snap.baselineTs !== 'string' || !snap.doc?.partitions) return null;\n return snap;\n}\n\nfunction listArchiveFiles(guard: PathGuard, dataDir: string): string[] {\n try {\n return fs.readdirSync(guard.assert(dataDir))\n .filter((f) => f.startsWith(ARCHIVE_PREFIX) && f.endsWith('.jsonl'))\n .sort(); // timestamped names sort chronologically\n } catch {\n return [];\n }\n}\n\n/** Replay one JSONL text into `doc`, skipping records at/before the baseline. */\nfunction replayText(doc: ProfileDoc, text: string, baselineTs: string, stats: { records: number; truncatedTail: number; isLive: boolean }): void {\n const lines = text.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i]!.trim();\n if (!trimmed) continue;\n try {\n const rec = JSON.parse(trimmed) as JournalRecord;\n // Baseline skip: only records CARRYING a ts can be proven folded. A\n // ts-less record is always applied (applyOpPermissive tolerates it).\n if (baselineTs && rec.ts && String(rec.ts) <= baselineTs) continue;\n for (const op of rec.applied ?? []) applyOpPermissive(doc, op, rec.ts);\n stats.records += 1;\n } catch {\n // Torn tail only counts on the LIVE journal — archives are closed files.\n const isLast = lines.slice(i + 1).every((l) => !l.trim());\n if (stats.isLive && isLast) {\n stats.truncatedTail = lines.length - i;\n break;\n }\n // mid-file corrupt record: skip (journal stays append-only/immutable)\n }\n }\n}\n\n/** Full replay: snapshot basepoint + archive shards + live journal. */\nexport function replayJournal(guard: PathGuard, dataDir: string): ReplayResult {\n const snap = loadSnapshot(guard, dataDir);\n const doc = snap ? snap.doc : emptyProfile();\n const baselineTs = snap?.baselineTs ?? '';\n const stats = { records: snap?.recordsFolded ?? 0, truncatedTail: 0, isLive: false };\n for (const file of listArchiveFiles(guard, dataDir)) {\n try {\n // shard record counts are not reported (the snapshot already folded\n // them); only the live journal's torn tail is meaningful.\n replayText(doc, fs.readFileSync(path.join(dataDir, file), 'utf8'), baselineTs, { records: 0, truncatedTail: 0, isLive: false });\n } catch { /* unreadable shard: skip */ }\n }\n stats.isLive = true;\n replayText(doc, readText(guard, journalFilePath(dataDir), ''), baselineTs, stats);\n return { doc, truncatedTail: stats.truncatedTail, records: stats.records };\n}\n\n/** Every plaintext journal text in chronological order: archive shards first,\n * then the live journal — the RAW record timeline, for callers that need the\n * history itself rather than the accumulated doc (the weekly report counts\n * the week's ADD ops). A rotation must not hide history from them (H-01). */\nexport function readJournalTexts(guard: PathGuard, dataDir: string): string[] {\n const texts: string[] = [];\n for (const file of listArchiveFiles(guard, dataDir)) {\n try {\n texts.push(fs.readFileSync(path.join(dataDir, file), 'utf8'));\n } catch { /* unreadable shard: skip */ }\n }\n texts.push(readText(guard, journalFilePath(dataDir), ''));\n return texts;\n}\n\nexport function loadProfile(guard: PathGuard, file: string): ProfileDoc {\n const doc = loadJson<ProfileDoc>(guard, file);\n if (!doc || !doc.partitions) return emptyProfile();\n // ensure all partitions exist\n for (const p of PARTITIONS) {\n if (!doc.partitions[p]) doc.partitions[p] = { entries: [] };\n }\n return doc;\n}\n\nfunction parseIso(v: string): number {\n const t = Date.parse(v);\n return Number.isFinite(t) ? t : 0;\n}\n\n/** ref format \"<datafile>#<locator>\": the referenced file must exist under data/. */\nfunction refExists(guard: PathGuard, dataDir: string, ref: string): boolean {\n const base = ref.split('#')[0] ?? '';\n if (!base) return false;\n const target = path.join(dataDir, base);\n try {\n return fs.existsSync(guard.assert(target));\n } catch {\n return false;\n }\n}\n\nfunction capForKinds(kinds: EvidenceKind[]): number {\n if (kinds.length === 0) return 0.4;\n return Math.min(...kinds.map((k) => CONFIDENCE_CAP[k] ?? 0.4));\n}\n\nfunction findActive(doc: ProfileDoc, id: string): ProfileEntry | undefined {\n for (const p of PARTITIONS) {\n const hit = doc.partitions[p]!.entries.find((e) => e.id === id && e.validTo === null);\n if (hit) return hit;\n }\n return undefined;\n}\n\n/**\n * Apply validated ops to the doc (mutates). Returns applied/rejected.\n * Guards (§3.3): whitelist, evidence gate, per-run ops cap is enforced by the\n * caller, confidence caps by evidence kind, psy gating, INVALIDATE ownership:\n * volatile expiry is code-driven (LLM may not), stable invalidation needs a\n * contradicting observation attached.\n */\nexport function applyOpsToDoc(\n guard: PathGuard,\n dataDir: string,\n doc: ProfileDoc,\n ops: ProfileOp[],\n schema: ProfileSchema | undefined,\n policy: Policy,\n now: number,\n): ApplyReport {\n const applied: ProfileOp[] = [];\n const rejected: { op: ProfileOp; reason: string }[] = [];\n const nowIso = new Date(now).toISOString();\n\n for (const op of ops) {\n if (op.op === 'NOOP') {\n applied.push(op);\n continue;\n }\n if (op.op === 'ADD') {\n if (op.partition === 'psy' && !policy.profile.psyEnabled) {\n rejected.push({ op, reason: 'psy partition is disabled' });\n continue;\n }\n let temporal: 'stable' | 'volatile' = 'stable';\n if (schema) {\n const check = checkAddAgainstSchema(schema, op.partition, op.topic, op.subTopic, op.temporal);\n if (!check.ok) {\n rejected.push({ op, reason: check.reason! });\n continue;\n }\n temporal = check.temporal;\n } else if (!(op.partition in doc.partitions)) {\n // H-17: no usable schema — the partition set is the only boundary left.\n rejected.push({ op, reason: `unknown partition: ${op.partition}` });\n continue;\n } else {\n temporal = op.temporal === 'volatile' ? 'volatile' : 'stable';\n }\n if (!op.evidence || op.evidence.length === 0) {\n rejected.push({ op, reason: 'ADD without evidence (no provenance, axiom 1)' });\n continue;\n }\n const badRef = op.evidence.find((e) => !refExists(guard, dataDir, e.ref));\n if (badRef) {\n rejected.push({ op, reason: `evidence ref does not resolve: ${badRef.ref}` });\n continue;\n }\n const cap = capForKinds(op.evidence.map((e) => e.kind));\n const active = doc.partitions[op.partition]!.entries.filter((e) => e.validTo === null);\n if (active.length >= policy.profile.partitionCap) {\n rejected.push({ op, reason: `partition ${op.partition} at cap (${policy.profile.partitionCap}); converge first` });\n continue;\n }\n dbSeq += 1;\n const entry: ProfileEntry = {\n id: `p${dbSeq.toString(36)}${randomUUID().slice(0, 4)}`,\n partition: op.partition,\n topic: op.topic,\n subTopic: op.subTopic,\n content: op.content.trim(),\n confidence: Math.min(op.confidence ?? cap, cap),\n temporal,\n validFrom: nowIso,\n validTo: null,\n supersededBy: null,\n evidence: op.evidence,\n createdAt: nowIso,\n updatedAt: nowIso,\n updateCount: 0,\n };\n op.assignedId = entry.id; // journal replay must reproduce this id\n doc.partitions[op.partition]!.entries.push(entry);\n applied.push(op);\n continue;\n }\n if (op.op === 'UPDATE') {\n const entry = findActive(doc, op.id);\n if (!entry) {\n rejected.push({ op, reason: `unknown or inactive entry: ${op.id}` });\n continue;\n }\n if (op.changes.content !== undefined) entry.content = op.changes.content.trim();\n if (op.changes.confidence !== undefined) {\n const cap = capForKinds(entry.evidence.map((e) => e.kind));\n // confidence upgrades need a second confirming observation (§3.3):\n // only allowed up to cap, and only when the entry already has 2+ evidence\n if (op.changes.confidence > entry.confidence && entry.evidence.length < 2) {\n rejected.push({ op, reason: 'confidence upgrade requires a second confirming observation' });\n continue;\n }\n entry.confidence = Math.min(op.changes.confidence, cap);\n }\n entry.updatedAt = nowIso;\n entry.updateCount += 1;\n applied.push(op);\n continue;\n }\n if (op.op === 'INVALIDATE') {\n const entry = findActive(doc, op.id);\n if (!entry) {\n rejected.push({ op, reason: `unknown or inactive entry: ${op.id}` });\n continue;\n }\n if (entry.temporal === 'volatile') {\n rejected.push({ op, reason: 'volatile expiry is code-owned (time-driven), not LLM-nominated' });\n continue;\n }\n // stable: rebuttal-driven; requires a contradicting observation attached\n const hasNewObservation = (op.evidence ?? []).length > 0\n && (op.evidence ?? []).some((e) => parseIso(e.at) > parseIso(entry.evidence[entry.evidence.length - 1]?.at ?? ''));\n if (!hasNewObservation) {\n rejected.push({ op, reason: 'stable INVALIDATE requires a newer contradicting observation' });\n continue;\n }\n entry.validTo = nowIso;\n entry.supersededBy = null;\n entry.updatedAt = nowIso;\n entry.updateCount += 1;\n if (op.evidence) entry.evidence.push(...op.evidence);\n applied.push(op);\n continue;\n }\n }\n return { applied, rejected };\n}\n\nlet dbSeq = 0;\n\n/** Deterministic aging (D9): volatile expiry + stable low-activity marking. */\nexport function runDeterministicAging(\n doc: ProfileDoc,\n policy: Policy,\n now: number,\n): { volatileExpired: number; lowActivityMarked: number } {\n const nowIso = new Date(now).toISOString();\n let volatileExpired = 0;\n let lowActivityMarked = 0;\n for (const p of PARTITIONS) {\n for (const e of doc.partitions[p]!.entries) {\n if (e.validTo !== null) continue;\n const lastEvidence = Math.max(...e.evidence.map((x) => parseIso(x.at)), parseIso(e.updatedAt));\n if (e.temporal === 'volatile') {\n if (now - lastEvidence > policy.profile.volatileDays * DAY_MS) {\n e.validTo = nowIso;\n e.updatedAt = nowIso;\n e.updateCount += 1;\n volatileExpired += 1;\n }\n } else if (!e.lowActivity && now - lastEvidence > policy.profile.stableLowActivityDays * DAY_MS) {\n e.lowActivity = true;\n lowActivityMarked += 1;\n }\n }\n }\n return { volatileExpired, lowActivityMarked };\n}\n\n/** Persist the materialized view atomically + append the journal record. */\nexport function persistWithJournal(\n guard: PathGuard,\n dataDir: string,\n doc: ProfileDoc,\n record: Omit<JournalRecord, 'ts'>,\n): void {\n saveJson(guard, profileFilePath(dataDir), doc);\n const line = JSON.stringify({ ts: new Date().toISOString(), ...record });\n const journal = journalFilePath(dataDir);\n try {\n fs.appendFileSync(guard.assert(journal), line + '\\n', 'utf8');\n } catch {\n fs.mkdirSync(dataDir, { recursive: true });\n fs.appendFileSync(guard.assert(journal), line + '\\n', 'utf8');\n }\n}\n\n// ── journal replay (verify / rebuild, r2 §14) ───────────────────────────\n\nfunction applyOpPermissive(doc: ProfileDoc, op: ProfileOp, ts: string): void {\n // Journal is trusted history: replay applies without revalidation.\n if (op.op === 'ADD') {\n dbSeq += 1;\n doc.partitions[op.partition]!.entries.push({\n id: op.assignedId ?? `r${dbSeq.toString(36)}${randomUUID().slice(0, 4)}`,\n partition: op.partition,\n topic: op.topic,\n subTopic: op.subTopic,\n content: op.content,\n confidence: op.confidence ?? 0.5,\n temporal: op.temporal ?? 'stable',\n validFrom: ts,\n validTo: null,\n supersededBy: null,\n evidence: op.evidence,\n createdAt: ts,\n updatedAt: ts,\n updateCount: 0,\n });\n return;\n }\n if (op.op === 'UPDATE') {\n const e = [...PARTITIONS].flatMap((p) => doc.partitions[p]!.entries).find((x) => x.id === op.id);\n if (e) {\n if (op.changes.content !== undefined) e.content = op.changes.content;\n if (op.changes.confidence !== undefined) e.confidence = op.changes.confidence;\n e.updatedAt = ts;\n e.updateCount += 1;\n }\n return;\n }\n if (op.op === 'INVALIDATE') {\n const e = [...PARTITIONS].flatMap((p) => doc.partitions[p]!.entries).find((x) => x.id === op.id);\n if (e) {\n e.validTo = ts;\n e.updatedAt = ts;\n e.updateCount += 1;\n }\n }\n // NOOP: nothing\n}\n\nexport interface ReplayResult {\n doc: ProfileDoc;\n truncatedTail: number;\n records: number;\n}\n\nexport interface VerifyReport {\n ok: boolean;\n firstDivergence?: { id: string; expected: string; actual: string };\n truncatedTail: number;\n records: number;\n}\n\n/** profile verify: replay vs disk, report first divergence, never fix. */\nexport function verifyProfile(guard: PathGuard, dataDir: string): VerifyReport {\n const replayed = replayJournal(guard, dataDir);\n const onDisk = loadProfile(guard, profileFilePath(dataDir));\n // Timestamps legitimately differ (journal record ts >= op ts); identity\n // fields are also normalized. Compare semantic content only.\n const strip = (doc: ProfileDoc): string =>\n JSON.stringify(doc.partitions, (k, v) => (['id', 'supersededBy', 'validFrom', 'createdAt', 'updatedAt', 'retiredAt'].includes(k) ? '<norm>' : v));\n const ok = strip(replayed.doc) === strip(onDisk);\n if (ok) return { ok: true, truncatedTail: replayed.truncatedTail, records: replayed.records };\n // first divergence: first entry id present in only one view\n const diskIds = new Set([...PARTITIONS].flatMap((p) => onDisk.partitions[p]!.entries.map((e) => e.content))); const replayIds = new Set([...PARTITIONS].flatMap((p) => replayed.doc.partitions[p]!.entries.map((e) => e.content)));\n const onlyDisk = [...diskIds].find((c) => !replayIds.has(c));\n const onlyReplay = [...replayIds].find((c) => !diskIds.has(c));\n return {\n ok: false,\n firstDivergence: {\n id: onlyDisk ?? onlyReplay ?? '(content)',\n expected: onlyReplay ? 'absent in journal replay' : 'present in journal replay',\n actual: onlyDisk ? 'present on disk' : 'absent on disk',\n },\n truncatedTail: replayed.truncatedTail,\n records: replayed.records,\n };\n}\n\nexport interface RebuildReport {\n ok: boolean;\n truncatedTail: number;\n records: number;\n wrote: boolean;\n}\n\n/** profile rebuild: journal is authoritative; atomic replace; torn tail reported. */\nexport function rebuildProfile(\n guard: PathGuard,\n dataDir: string,\n opts: { check?: boolean } = {},\n): RebuildReport & { diffSummary?: string } {\n const replayed = replayJournal(guard, dataDir);\n const target = profileFilePath(dataDir);\n if (opts.check) {\n const onDisk = loadProfile(guard, target);\n const same = JSON.stringify(onDisk) === JSON.stringify(replayed.doc);\n return {\n ok: same,\n truncatedTail: replayed.truncatedTail,\n records: replayed.records,\n wrote: false,\n diffSummary: same ? 'no diff' : 'materialized view differs from journal replay',\n };\n }\n saveJson(guard, target, replayed.doc);\n if (replayed.truncatedTail > 0) {\n // explicit audit: never silently rebuild a view that lost its tail\n writeText(\n guard,\n path.join(dataDir, 'logs', 'rebuild-report.txt'),\n `rebuild truncated ${replayed.truncatedTail} torn line(s) at journal tail; ${replayed.records} records applied\\n`,\n );\n }\n return { ok: true, truncatedTail: replayed.truncatedTail, records: replayed.records, wrote: true };\n}\n","// User profile types (design doc §3). Fourth store: warm, structured,\n// slow-evolving model of the user. Not the material pool (hot cache), not\n// DSH long-term memory (conversation-validated layer).\n\nexport type Partition = 'interest' | 'projects' | 'comm' | 'psy';\nexport type Temporal = 'volatile' | 'stable';\nexport type EvidenceKind = 'chat' | 'screen' | 'browse' | 'hand' | 'ledger';\n\nexport interface Evidence {\n kind: EvidenceKind;\n at: string;\n /** Pointer to an existing audit/log location, e.g. \"heartbeat.jsonl#2026-09-06T12:00:00Z\". */\n ref: string;\n /** At most ONE short quote (<=1 sentence). Never raw conversation/screen text. */\n quote?: string;\n}\n\nexport interface ProfileEntry {\n id: string;\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n /** 0..1; capped per source kind (chat .6 / screen .4 / browse .4). */\n confidence: number;\n temporal: Temporal;\n validFrom: string;\n validTo: string | null;\n supersededBy: string | null;\n evidence: Evidence[];\n createdAt: string;\n updatedAt: string;\n updateCount: number;\n /** stable-tier audit flag (180d without observation): digest deprioritizes. */\n lowActivity?: boolean;\n}\n\nexport interface ProfileDoc {\n version: number;\n partitions: Record<Partition, { entries: ProfileEntry[] }>;\n}\n\nexport interface InboxItem {\n id?: string;\n kind: EvidenceKind;\n at: string;\n ref: string;\n /** <= 1 short sentence; never raw conversation/screen text (truncated by writer). */\n note: string;\n}\n\nexport type ProfileOp =\n | {\n op: 'ADD';\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n temporal?: Temporal;\n confidence?: number;\n why: string;\n evidence: Evidence[];\n /** Assigned by the store at apply time so journal replay preserves ids. */\n assignedId?: string;\n }\n | { op: 'UPDATE'; id: string; changes: { content?: string; confidence?: number }; why: string }\n | { op: 'INVALIDATE'; id: string; why: string; evidence?: Evidence[] }\n | { op: 'NOOP'; why: string };\n\nexport interface JournalRecord {\n ts: string;\n runId: string;\n applied: ProfileOp[];\n rejected: { op: ProfileOp; reason: string }[];\n}\n\nexport interface ApplyReport {\n applied: ProfileOp[];\n rejected: { op: ProfileOp; reason: string }[];\n}\n\nexport const PARTITIONS: readonly Partition[] = ['interest', 'projects', 'comm', 'psy'];\n\nexport const CONFIDENCE_CAP: Record<EvidenceKind, number> = {\n chat: 0.6,\n screen: 0.4,\n browse: 0.4,\n hand: 1.0,\n ledger: 0.6,\n};\n\nexport function emptyProfile(): ProfileDoc {\n return {\n version: 1,\n partitions: { interest: { entries: [] }, projects: { entries: [] }, comm: { entries: [] }, psy: { entries: [] } },\n };\n}\n","// profile-schema.json loading + ADD validation (r4 B10: temporal tier is an\n// ENTRY-level attribute; the schema declares, per sub_topic, the ALLOWED tier\n// set and the DEFAULT. Unlisted defaults to 'stable'.)\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Partition, Temporal } from './types.js';\n\nexport interface SubTopicDecl {\n allowed?: Temporal[];\n default?: Temporal;\n}\n\nexport interface ProfileSchema {\n version: number;\n partitions: Partial<Record<Partition, {\n topics: Record<string, { subtopics: Record<string, SubTopicDecl> }>;\n }>>;\n}\n\nexport interface SchemaLoad {\n /** The schema to use, or undefined when even the factory copy is unusable. */\n schema?: ProfileSchema;\n /** Where the returned schema came from. */\n source: 'user' | 'factory' | 'none';\n /** Set when the chosen schema is not the first choice (H-17 fallback). */\n fallbackReason?: string;\n}\n\n/**\n * H-17: three-tier load. This file is user-editable by design, so a broken\n * comma used to throw on every beat — `runConsolidation` aborted before\n * `inboxClear`, the inbox grew forever and the profile froze with no way back.\n * Now: a bad user copy falls back to the factory copy (audited by the caller);\n * an unusable factory copy yields `undefined`, which callers read as \"no\n * whitelist\" instead of a fatal error.\n */\nexport function loadProfileSchema(paths: { configDir: string; settingsDir: string }): SchemaLoad {\n const userPath = path.join(paths.settingsDir, 'profile-schema.json');\n const factoryPath = path.join(paths.configDir, 'profile-schema.json');\n const read = (file: string): { schema?: ProfileSchema; error: string } => {\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as ProfileSchema;\n if (!raw.partitions) return { error: 'partitions missing' };\n return { schema: raw, error: '' };\n } catch (e) {\n return { error: String(e) };\n }\n };\n const user = fs.existsSync(userPath) ? read(userPath) : null;\n if (user?.schema) return { schema: user.schema, source: 'user' };\n const factory = read(factoryPath);\n if (factory.schema) {\n return user\n ? {\n schema: factory.schema,\n source: 'factory',\n fallbackReason: `user profile-schema.json unusable (${user.error}) — fell back to the factory copy`,\n }\n : { schema: factory.schema, source: 'factory' };\n }\n return {\n source: 'none',\n fallbackReason: `no usable profile-schema.json (user: ${user?.error ?? 'absent'}; factory: ${factory.error})`,\n };\n}\n\nexport interface SchemaCheck {\n ok: boolean;\n reason?: string;\n temporal: Temporal;\n}\n\n/**\n * Validate an ADD against the whitelist and resolve the entry's temporal tier:\n * LLM nominates within the sub_topic's allowed set; missing nomination falls\n * back to the declared default; fully unlisted -> reject (charter boundary).\n */\nexport function checkAddAgainstSchema(\n schema: ProfileSchema,\n partition: Partition,\n topic: string,\n subTopic: string,\n nominated?: Temporal,\n): SchemaCheck {\n const p = schema.partitions[partition];\n if (!p) return { ok: false, reason: `partition not in schema: ${partition}`, temporal: 'stable' };\n const t = p.topics[topic];\n if (!t) return { ok: false, reason: `topic not in schema: ${partition}/${topic}`, temporal: 'stable' };\n const st = t.subtopics[subTopic];\n if (!st) return { ok: false, reason: `sub_topic not in schema: ${partition}/${topic}/${subTopic}`, temporal: 'stable' };\n const allowed: Temporal[] = st.allowed && st.allowed.length > 0 ? st.allowed : ['stable'];\n const def: Temporal = st.default && allowed.includes(st.default) ? st.default : allowed[0]!;\n if (!nominated) return { ok: true, temporal: def };\n if (!allowed.includes(nominated)) {\n return {\n ok: false,\n reason: `temporal \"${nominated}\" not allowed for ${partition}/${topic}/${subTopic} (allowed: ${allowed.join('|')})`,\n temporal: def,\n };\n }\n return { ok: true, temporal: nominated };\n}\n"],"mappings":";;;;;;;;;;;AAIA,OAAO,QAAQ;AACf,OAAO,UAAU;AAcV,SAAS,gBAAgB,MAAc,OAAuD;AACnG,MAAI;AACF,OAAG,UAAU,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AACpD,UAAM,OAAO,KAAK,UAAU,EAAE,IAAI,MAAM,OAAM,oBAAI,KAAK,GAAE,YAAY,GAAG,GAAG,MAAM,CAAC;AAClF,OAAG,eAAe,MAAM,OAAO,MAAM,MAAM;AAAA,EAC7C,SAAS,GAAG;AACV,YAAQ,OAAO,MAAM,oCAAoC,IAAI,KAAK,OAAO,CAAC,CAAC;AAAA,CAAI;AAAA,EACjF;AACF;AAEO,SAAS,eAA+B,MAAmB;AAChE,MAAI,CAAC,GAAG,WAAW,IAAI,EAAG,QAAO,CAAC;AAClC,QAAM,MAAW,CAAC;AAClB,QAAM,MAAM,GAAG,aAAa,MAAM,MAAM;AACxC,aAAW,QAAQ,IAAI,MAAM,IAAI,GAAG;AAClC,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,CAAC,QAAS;AACd,QAAI;AACF,UAAI,KAAK,KAAK,MAAM,OAAO,CAAM;AAAA,IACnC,QAAQ;AAEN,UAAI,KAAK,EAAE,IAAI,IAAI,SAAS,MAAM,KAAK,QAAQ,MAAM,GAAG,GAAG,EAAE,CAAiB;AAAA,IAChF;AAAA,EACF;AACA,SAAO;AACT;AAMO,SAAS,eAAe,MAAc,UAAkB,MAAM,KAAK,IAAI,GAAW;AACvF,MAAI,CAAC,GAAG,WAAW,IAAI,EAAG,QAAO;AACjC,QAA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Aa,kCAAkC,SAAS,OAAO;AAAA;AAAA,IAC/F;AAAA,EACF;AACA,SAAO,EAAE,IAAI,MAAM,eAAe,SAAS,eAAe,SAAS,SAAS,SAAS,OAAO,KAAK;AACnG;","names":["path","fs","fs","path","path","fs"]}
|
package/dist/chunk-IV2ZWQA3.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
// src/core/file-lock.ts
|
|
2
|
-
import fs from "fs";
|
|
3
|
-
var STALE_MS = 15e3;
|
|
4
|
-
var WAIT_MS = 3e3;
|
|
5
|
-
var POLL_MS = 25;
|
|
6
|
-
function sleepSync(ms) {
|
|
7
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
8
|
-
}
|
|
9
|
-
function tryAcquire(lock) {
|
|
10
|
-
try {
|
|
11
|
-
const fd = fs.openSync(lock, "wx");
|
|
12
|
-
fs.writeSync(fd, `${process.pid} ${(/* @__PURE__ */ new Date()).toISOString()}
|
|
13
|
-
`);
|
|
14
|
-
fs.closeSync(fd);
|
|
15
|
-
return true;
|
|
16
|
-
} catch (e) {
|
|
17
|
-
if (e.code !== "EEXIST") throw e;
|
|
18
|
-
try {
|
|
19
|
-
if (Date.now() - fs.statSync(lock).mtimeMs > STALE_MS) {
|
|
20
|
-
fs.rmSync(lock, { force: true });
|
|
21
|
-
return tryAcquire(lock);
|
|
22
|
-
}
|
|
23
|
-
} catch {
|
|
24
|
-
return tryAcquire(lock);
|
|
25
|
-
}
|
|
26
|
-
return false;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
function withFileLock(target, fn) {
|
|
30
|
-
const lock = `${target}.lock`;
|
|
31
|
-
const deadline = Date.now() + WAIT_MS;
|
|
32
|
-
let held = false;
|
|
33
|
-
for (; ; ) {
|
|
34
|
-
if (tryAcquire(lock)) {
|
|
35
|
-
held = true;
|
|
36
|
-
break;
|
|
37
|
-
}
|
|
38
|
-
if (Date.now() >= deadline) break;
|
|
39
|
-
sleepSync(POLL_MS);
|
|
40
|
-
}
|
|
41
|
-
try {
|
|
42
|
-
return fn();
|
|
43
|
-
} finally {
|
|
44
|
-
if (held) {
|
|
45
|
-
try {
|
|
46
|
-
fs.rmSync(lock, { force: true });
|
|
47
|
-
} catch {
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export {
|
|
54
|
-
withFileLock
|
|
55
|
-
};
|
|
56
|
-
//# sourceMappingURL=chunk-IV2ZWQA3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/file-lock.ts"],"sourcesContent":["// Cross-process advisory file lock (H-20, minimal tier).\n//\n// The seed pool and the observation inbox are WHOLE-FILE rewrites of DPAPI\n// ciphertext — the vault cannot append to them — and the CLI runs as a second\n// process against the same files. Two interleaved load→mutate→save cycles\n// therefore let one side silently overwrite the other's write. The full fix\n// (append-only journal + compaction) is v2.0 work; this keeps the writers\n// honest in the meantime.\n//\n// The lock itself is a sibling file created with O_EXCL. A lock older than\n// STALE_MS is treated as abandoned (its holder died mid-write) and reclaimed.\n\nimport fs from 'node:fs';\n\nconst STALE_MS = 15_000;\nconst WAIT_MS = 3_000;\nconst POLL_MS = 25;\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n\nfunction tryAcquire(lock: string): boolean {\n try {\n const fd = fs.openSync(lock, 'wx');\n fs.writeSync(fd, `${process.pid} ${new Date().toISOString()}\\n`);\n fs.closeSync(fd);\n return true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;\n // Reclaim a lock whose holder is gone.\n try {\n if (Date.now() - fs.statSync(lock).mtimeMs > STALE_MS) {\n fs.rmSync(lock, { force: true });\n return tryAcquire(lock);\n }\n } catch {\n return tryAcquire(lock); // vanished between open and stat\n }\n return false;\n }\n}\n\n/**\n * Run `fn` while holding the lock for `target`. Acquisition waits up to\n * WAIT_MS, then gives up and runs anyway: a heartbeat must not be stopped by a\n * stale lock, and the caller's own read-modify-write is still the last writer\n * in the common (uncontended) case.\n */\nexport function withFileLock<T>(target: string, fn: () => T): T {\n const lock = `${target}.lock`;\n const deadline = Date.now() + WAIT_MS;\n let held = false;\n for (;;) {\n if (tryAcquire(lock)) {\n held = true;\n break;\n }\n if (Date.now() >= deadline) break;\n sleepSync(POLL_MS);\n }\n try {\n return fn();\n } finally {\n if (held) {\n try {\n fs.rmSync(lock, { force: true });\n } catch { /* already gone */ }\n }\n }\n}\n"],"mappings":";AAYA,OAAO,QAAQ;AAEf,IAAM,WAAW;AACjB,IAAM,UAAU;AAChB,IAAM,UAAU;AAEhB,SAAS,UAAU,IAAkB;AACnC,UAAQ,KAAK,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC,GAAG,GAAG,GAAG,EAAE;AACjE;AAEA,SAAS,WAAW,MAAuB;AACzC,MAAI;AACF,UAAM,KAAK,GAAG,SAAS,MAAM,IAAI;AACjC,OAAG,UAAU,IAAI,GAAG,QAAQ,GAAG,KAAI,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA,CAAI;AAC/D,OAAG,UAAU,EAAE;AACf,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAK,EAA4B,SAAS,SAAU,OAAM;AAE1D,QAAI;AACF,UAAI,KAAK,IAAI,IAAI,GAAG,SAAS,IAAI,EAAE,UAAU,UAAU;AACrD,WAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;AAC/B,eAAO,WAAW,IAAI;AAAA,MACxB;AAAA,IACF,QAAQ;AACN,aAAO,WAAW,IAAI;AAAA,IACxB;AACA,WAAO;AAAA,EACT;AACF;AAQO,SAAS,aAAgB,QAAgB,IAAgB;AAC9D,QAAM,OAAO,GAAG,MAAM;AACtB,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,MAAI,OAAO;AACX,aAAS;AACP,QAAI,WAAW,IAAI,GAAG;AACpB,aAAO;AACP;AAAA,IACF;AACA,QAAI,KAAK,IAAI,KAAK,SAAU;AAC5B,cAAU,OAAO;AAAA,EACnB;AACA,MAAI;AACF,WAAO,GAAG;AAAA,EACZ,UAAE;AACA,QAAI,MAAM;AACR,UAAI;AACF,WAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;AAAA,MACjC,QAAQ;AAAA,MAAqB;AAAA,IAC/B;AAAA,EACF;AACF;","names":[]}
|