solopup-memory 0.0.0-stage → 0.21.0-beta.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 +453 -0
- package/COMPATIBILITY.md +155 -0
- package/LICENSE +21 -0
- package/README.en.md +62 -0
- package/README.md +105 -2
- package/RELEASE.md +43 -0
- package/SECURITY.md +73 -0
- package/accept.mjs +18 -0
- package/belief-revision.mjs +48 -0
- package/candidates.mjs +355 -0
- package/capture-diagnostics.mjs +77 -0
- package/capture-evidence.mjs +49 -0
- package/capture-inputs.mjs +171 -0
- package/capture-jobs.mjs +195 -0
- package/capture-llm.mjs +299 -0
- package/capture-projections.mjs +7 -0
- package/capture-revision.mjs +13 -0
- package/capture-source-aliases.mjs +20 -0
- package/capture-submission.mjs +75 -0
- package/capture-validation-contract.mjs +30 -0
- package/capture-validation-job.mjs +43 -0
- package/capture-validation.mjs +112 -0
- package/capture.mjs +109 -0
- package/context-history.mjs +123 -0
- package/control-schema.mjs +18 -0
- package/cordis.patch.yml +3 -0
- package/corpus/capture-contract-v25.json +59 -0
- package/corpus/external-labeled.json +187 -0
- package/corpus/holdout-v2.json +217 -0
- package/corpus/holdout-v3.json +145 -0
- package/corpus/injections.json +699 -0
- package/corpus/legacy-self-excluding-dev36.json +7 -0
- package/corpus/legacy-summary-v15.json +12 -0
- package/episodes.mjs +130 -0
- package/eval/mechanical-table.mjs +470 -0
- package/eval/paired-analysis.mjs +47 -0
- package/eval/run-eval.mjs +493 -0
- package/field-lineage.mjs +62 -0
- package/fixture-host.mjs +96 -0
- package/host-services.mjs +8 -0
- package/icon.svg +1 -0
- package/index.mjs +2931 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/managed-access.mjs +182 -0
- package/managed-activation.mjs +36 -0
- package/managed-hooks.mjs +110 -0
- package/managed-logs.mjs +34 -0
- package/managed-policy.mjs +296 -0
- package/meaning.mjs +117 -0
- package/memory-policy.mjs +18 -0
- package/memory-protocol.mjs +21 -0
- package/memory-rule-policy.mjs +11 -0
- package/memory-scope-policy.mjs +7 -0
- package/native-write-validation.mjs +45 -0
- package/package.json +206 -4
- package/plugin-config.mjs +34 -0
- package/project-stores.mjs +222 -0
- package/publication.mjs +92 -0
- package/restoration-lock.mjs +9 -0
- package/restore.mjs +173 -0
- package/retrieval.mjs +43 -0
- package/revision-admission.mjs +6 -0
- package/runtime-startup.mjs +36 -0
- package/scripts/backup.mjs +15 -0
- package/scripts/candidates.mjs +46 -0
- package/scripts/capture-jobs.mjs +41 -0
- package/scripts/control.mjs +25 -0
- package/scripts/patch.mjs +152 -0
- package/scripts/probe-env.mjs +8 -0
- package/scripts/probe-load.mjs +88 -0
- package/scripts/probe-package.mjs +104 -0
- package/scripts/projects.mjs +19 -0
- package/scripts/verify.mjs +81 -0
- package/security.mjs +489 -0
- package/service-readiness.mjs +34 -0
- package/snapshots.mjs +76 -0
- package/source-identity.mjs +29 -0
- package/source-record.mjs +59 -0
- package/source-retirement.mjs +76 -0
- package/store-lock-guard.mjs +4 -0
- package/test-adversarial.mjs +331 -0
- package/test-belief-revision.mjs +166 -0
- package/test-candidates.mjs +147 -0
- package/test-capture-diagnostics.mjs +98 -0
- package/test-capture-field-lineage.mjs +63 -0
- package/test-capture-inputs.mjs +271 -0
- package/test-capture-jobs.mjs +301 -0
- package/test-capture-projections.mjs +78 -0
- package/test-capture-revision.mjs +77 -0
- package/test-capture-submission.mjs +68 -0
- package/test-capture-validation-flow.mjs +47 -0
- package/test-capture-validation-job.mjs +76 -0
- package/test-capture-validation-lineage.mjs +40 -0
- package/test-capture-validation.mjs +84 -0
- package/test-capture.mjs +808 -0
- package/test-compaction-compat.mjs +307 -0
- package/test-compat.mjs +126 -0
- package/test-concurrency.mjs +204 -0
- package/test-conflict.mjs +133 -0
- package/test-context-history.mjs +105 -0
- package/test-control-schema.mjs +26 -0
- package/test-episodes.mjs +157 -0
- package/test-explicit-memory.mjs +43 -0
- package/test-field-lineage.mjs +105 -0
- package/test-history.mjs +305 -0
- package/test-inline-summary.mjs +52 -0
- package/test-legacy-source-identity.mjs +46 -0
- package/test-links.mjs +245 -0
- package/test-managed-access.mjs +114 -0
- package/test-managed-activation.mjs +93 -0
- package/test-meaning.mjs +178 -0
- package/test-native-service-lifecycle.mjs +25 -0
- package/test-native-write-validation.mjs +154 -0
- package/test-packaging.mjs +102 -0
- package/test-paired-analysis.mjs +26 -0
- package/test-patch.mjs +218 -0
- package/test-plugin-contract.mjs +118 -0
- package/test-project-stores.mjs +228 -0
- package/test-publication.mjs +145 -0
- package/test-restore.mjs +127 -0
- package/test-retrieval.mjs +75 -0
- package/test-revision-admission.mjs +23 -0
- package/test-rule-admission.mjs +52 -0
- package/test-runtime-startup.mjs +68 -0
- package/test-schema.mjs +187 -0
- package/test-security.mjs +448 -0
- package/test-service-readiness.mjs +50 -0
- package/test-smell.mjs +201 -0
- package/test-snapshots.mjs +58 -0
- package/test-source-completeness.mjs +44 -0
- package/test-source-key.mjs +17 -0
- package/test-source-retirement.mjs +83 -0
- package/test-status-both.mjs +42 -0
- package/test-supersede.mjs +216 -0
- package/test-text-admission.mjs +82 -0
- package/test-tool-inputs.mjs +13 -0
- package/test-tool-observations.mjs +124 -0
- package/test-tool-write-guard.mjs +23 -0
- package/test-tool-write-lifecycle.mjs +52 -0
- package/test-usability.mjs +588 -0
- package/test-validation-source-refs.mjs +27 -0
- package/test-validation-transition-context.mjs +41 -0
- package/test-withdrawal-archives.mjs +156 -0
- package/test-withdrawal.mjs +167 -0
- package/test.mjs +515 -0
- package/tool-inputs.mjs +68 -0
- package/tool-observations.mjs +115 -0
- package/validation-transition-context.mjs +30 -0
- package/version.mjs +5 -0
- package/withdrawal.mjs +155 -0
- package/worker-write.mjs +13 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import {prepareMountedFixture} from './fixture-host.mjs'
|
|
2
|
+
import {realpathSync} from 'node:fs'
|
|
3
|
+
import { test } from 'node:test'
|
|
4
|
+
import assert from 'node:assert/strict'
|
|
5
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync, linkSync, existsSync, utimesSync } from 'node:fs'
|
|
6
|
+
import { spawnSync } from 'node:child_process'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { tmpdir } from 'node:os'
|
|
9
|
+
import { fileURLToPath } from 'node:url'
|
|
10
|
+
import { projectStoreDir, projectIdentity, legacyProjectSlug, inspectProjectStore, migrateProjectStore, recoverProjectStore } from './project-stores.mjs'
|
|
11
|
+
import { storeDirFor, writeMemory, indexLine, searchStore, apply } from './index.mjs'
|
|
12
|
+
|
|
13
|
+
function box(run) {
|
|
14
|
+
const root = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-project-store-'))), store = join(root, 'memory'), a = join(root, 'A B'), b = join(root, 'A-B')
|
|
15
|
+
mkdirSync(a); mkdirSync(b)
|
|
16
|
+
const previous = process.env.DSH_HOME; process.env.DSH_HOME = root
|
|
17
|
+
try { return run({ root, store, a, b }) } finally { if (previous === undefined) delete process.env.DSH_HOME; else process.env.DSH_HOME = previous; rmSync(root, { recursive: true, force: true }) }
|
|
18
|
+
}
|
|
19
|
+
function legacy(box) {
|
|
20
|
+
const dir = join(box.store, 'projects', legacyProjectSlug(box.a))
|
|
21
|
+
writeMemory({ type: 'project', dir, line: indexLine('project', '合成旧项目独有决定 cobalt-1234', undefined, false), provenance: { sessionId: 'synthetic-project', evidence: [{ messageId: 'm1', hash: 'a'.repeat(64), quote: '合成旧项目独有决定 cobalt-1234' }] } })
|
|
22
|
+
return dir
|
|
23
|
+
}
|
|
24
|
+
function reviewed(box, extra = {}) {
|
|
25
|
+
const view = inspectProjectStore(box.store, box.a)
|
|
26
|
+
return { apply: true, reviewedTree: view.reviewedTree, reviewedClaim: view.reviewedClaim, ...extra }
|
|
27
|
+
}
|
|
28
|
+
const contents = dir => Object.fromEntries(readdirSync(dir).filter(name => name !== '.write.lock').map(name => [name, readFileSync(join(dir, name), 'utf8')]))
|
|
29
|
+
|
|
30
|
+
test('space, dash and separator collisions in legacy slugs have distinct full-hash project stores', () => box(({ root, store, a, b }) => {
|
|
31
|
+
assert.equal(legacyProjectSlug(a), legacyProjectSlug(b))
|
|
32
|
+
assert.notEqual(projectStoreDir(store, a), projectStoreDir(store, b))
|
|
33
|
+
assert.notEqual(projectStoreDir(store, join(root, 'nested/path')), projectStoreDir(store, join(root, 'nested-path')))
|
|
34
|
+
assert.match(projectStoreDir(store, a), /v2-[a-f0-9]{64}$/)
|
|
35
|
+
assert.equal(existsSync(store), false)
|
|
36
|
+
}))
|
|
37
|
+
test('new projects cannot retrieve each other through write, search or runtime injection', () => box(box => {
|
|
38
|
+
const a = storeDirFor('project', box.a), b = storeDirFor('project', box.b)
|
|
39
|
+
writeMemory({ type: 'project', dir: a, line: indexLine('project', '合成A项目保密决定', undefined, false) })
|
|
40
|
+
writeMemory({ type: 'project', dir: b, line: indexLine('project', '合成B项目独立决定', undefined, false) })
|
|
41
|
+
assert.equal(searchStore(b, '保密决定').hits.length, 0)
|
|
42
|
+
let context
|
|
43
|
+
prepareMountedFixture()
|
|
44
|
+
apply({ systemPrompt: { context: entry => context = entry }, tools: { register() {} }, workingDirectory: { get: () => box.b } }, { autoCapture: { enabled: false } })
|
|
45
|
+
const text = context.text({ agent: { session: {} } })
|
|
46
|
+
assert.match(text, /合成B项目独立决定/)
|
|
47
|
+
assert.doesNotMatch(text, /合成A项目保密决定/)
|
|
48
|
+
}))
|
|
49
|
+
test('one provider resolves the current project afresh each render and stops when control disappears',()=>box(box=>{
|
|
50
|
+
const a=storeDirFor('project',box.a),b=storeDirFor('project',box.b);
|
|
51
|
+
writeMemory({type:'project',dir:a,line:indexLine('project','Synthetic-A-render-secret',undefined,false)});
|
|
52
|
+
writeMemory({type:'project',dir:b,line:indexLine('project','Synthetic-B-render-private',undefined,false)});
|
|
53
|
+
prepareMountedFixture();let provider,cwd=box.a;
|
|
54
|
+
apply({systemPrompt:{context:value=>provider=value},tools:{register(){}},workingDirectory:{get:()=>cwd}},{autoCapture:{enabled:false}});
|
|
55
|
+
const read=()=>provider.text({agent:{session:{id:'same-runtime-session'}}});
|
|
56
|
+
let text=read();assert.match(text,/Synthetic-A-render-secret/);assert.doesNotMatch(text,/Synthetic-B-render-private/);
|
|
57
|
+
cwd=box.b;text=read();assert.match(text,/Synthetic-B-render-private/);assert.doesNotMatch(text,/Synthetic-A-render-secret/);
|
|
58
|
+
rmSync(box.store+'.control',{recursive:true});text=read();assert.match(text,/暂不可用/);assert.doesNotMatch(text,/Synthetic-[AB]-render-/);
|
|
59
|
+
}))
|
|
60
|
+
test('project roots remain stable in descendants and long names have bounded store basenames', () => box(box => {
|
|
61
|
+
mkdirSync(join(box.a, '.git')); mkdirSync(join(box.a, 'child'))
|
|
62
|
+
assert.equal(storeDirFor('project', box.a), storeDirFor('project', join(box.a, 'child')))
|
|
63
|
+
assert.equal(projectStoreDir(box.store, join(box.root, 'x'.repeat(220))).split('/').at(-1).length, 67)
|
|
64
|
+
}))
|
|
65
|
+
test('inspection and migration preview do not change or create any source metadata', () => box(box => {
|
|
66
|
+
assert.equal(inspectProjectStore(box.store, box.a).state, 'fresh')
|
|
67
|
+
assert.equal(existsSync(box.store), false)
|
|
68
|
+
const dir = legacy(box), before = contents(dir)
|
|
69
|
+
assert.equal(migrateProjectStore(box.store, box.a).state, 'legacy-needs-review')
|
|
70
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, { apply: 'yes' }), /invalid-apply/)
|
|
71
|
+
assert.deepEqual(contents(dir), before)
|
|
72
|
+
assert.equal(existsSync(join(box.store, 'projects/.legacy-claims')), false)
|
|
73
|
+
}))
|
|
74
|
+
test('ambiguous old libraries are not assigned by first access; global memory stays visible', () => box(box => {
|
|
75
|
+
legacy(box)
|
|
76
|
+
assert.throws(() => storeDirFor('project', box.a), /legacy-needs-review/)
|
|
77
|
+
assert.throws(() => storeDirFor('project', box.b), /legacy-needs-review/)
|
|
78
|
+
writeMemory({ type: 'user', dir: box.store, line: indexLine('user', '合成全局偏好继续可用', undefined, false) })
|
|
79
|
+
let context
|
|
80
|
+
prepareMountedFixture()
|
|
81
|
+
apply({ systemPrompt: { context: value => context = value }, tools: { register() {} }, workingDirectory: { get: () => box.b } }, { autoCapture: { enabled: false } })
|
|
82
|
+
const text = context.text({ agent: { session: {} } })
|
|
83
|
+
assert.match(text, /合成全局偏好继续可用/); assert.match(text, /归属审查/)
|
|
84
|
+
assert.doesNotMatch(text, /合成旧项目独有决定/)
|
|
85
|
+
}))
|
|
86
|
+
test('reviewed migration copies original bytes and binds the legacy library to exactly one project', () => box(box => {
|
|
87
|
+
const dir = legacy(box), before = contents(dir)
|
|
88
|
+
const result = migrateProjectStore(box.store, box.a, reviewed(box))
|
|
89
|
+
assert.equal(result.originalPreserved, true)
|
|
90
|
+
assert.deepEqual(contents(dir), before)
|
|
91
|
+
assert.equal(searchStore(storeDirFor('project', box.a), 'cobalt-1234').hits.length, 1)
|
|
92
|
+
assert.equal(searchStore(storeDirFor('project', box.b), 'cobalt-1234').hits.length, 0)
|
|
93
|
+
for (const [name, raw] of Object.entries(before)) assert.equal(readFileSync(join(result.targetDir, name), 'utf8'), raw)
|
|
94
|
+
assert.throws(() => migrateProjectStore(box.store, box.b, { apply: true }), /legacy-owned-by-another-project/)
|
|
95
|
+
assert.equal(inspectProjectStore(box.store, box.b).state, 'legacy-owned-by-another-project')
|
|
96
|
+
}))
|
|
97
|
+
test('stale source or claim review and an existing target are not overwritten', () => box(box => {
|
|
98
|
+
const dir = legacy(box), options = reviewed(box)
|
|
99
|
+
writeFileSync(join(dir, 'extra.md'), 'new synthetic source')
|
|
100
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, options), /stale-tree-review/)
|
|
101
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, { ...reviewed(box), reviewedClaim: 'f'.repeat(64) }), /stale-claim-review/)
|
|
102
|
+
const target = inspectProjectStore(box.store, box.a).targetDir
|
|
103
|
+
mkdirSync(target); writeFileSync(join(target, 'keep.txt'), 'independent target')
|
|
104
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, reviewed(box)), /target-exists-no-merge/)
|
|
105
|
+
assert.equal(readFileSync(join(target, 'keep.txt'), 'utf8'), 'independent target')
|
|
106
|
+
}))
|
|
107
|
+
for (const phase of ['prepared', 'renamed']) test(`interrupted migration at ${phase} is blocked until reviewed recovery`, () => box(box => {
|
|
108
|
+
const dir = legacy(box), before = contents(dir)
|
|
109
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, reviewed(box, { fault: event => { if (event.phase === phase) throw Error('controlled interruption') } })), /controlled interruption/)
|
|
110
|
+
assert.throws(() => storeDirFor('project', box.a), /migration-needs-recovery/)
|
|
111
|
+
const view = recoverProjectStore(box.store, box.a)
|
|
112
|
+
assert.throws(() => recoverProjectStore(box.store, box.a, { apply: 'yes' }), /invalid-apply/)
|
|
113
|
+
assert.equal(view.recoverable, true)
|
|
114
|
+
assert.equal(recoverProjectStore(box.store, box.a, { apply: true, reviewedMigration: view.reviewedMigration }).applied, true)
|
|
115
|
+
assert.deepEqual(contents(dir), before)
|
|
116
|
+
assert.equal(searchStore(storeDirFor('project', box.a), 'cobalt-1234').hits.length, 1)
|
|
117
|
+
}))
|
|
118
|
+
test('changed legacy source during interrupted copying cannot be silently superseded by a stale snapshot', () => box(box => {
|
|
119
|
+
const dir = legacy(box)
|
|
120
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, reviewed(box, { fault: () => { throw Error('pause') } })))
|
|
121
|
+
writeFileSync(join(dir, 'extra.md'), 'synthetic later source update')
|
|
122
|
+
const view = recoverProjectStore(box.store, box.a)
|
|
123
|
+
assert.throws(() => recoverProjectStore(box.store, box.a, { apply: true, reviewedMigration: view.reviewedMigration }), /legacy-diverged/)
|
|
124
|
+
assert.throws(() => storeDirFor('project', box.a), /needs-recovery/)
|
|
125
|
+
}))
|
|
126
|
+
test('damaged staged copy or changed migration review refuses recovery with original source preserved', () => box(box => {
|
|
127
|
+
const dir = legacy(box), before = contents(dir)
|
|
128
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, reviewed(box, { fault: () => { throw Error('pause') } })))
|
|
129
|
+
const view = recoverProjectStore(box.store, box.a)
|
|
130
|
+
assert.throws(() => recoverProjectStore(box.store, box.a, { apply: true, reviewedMigration: 'f'.repeat(64) }), /stale-migration-review/)
|
|
131
|
+
const projects = join(box.store, 'projects'), stage = readdirSync(projects).find(name => name.startsWith('.migration-'))
|
|
132
|
+
writeFileSync(join(projects, stage, 'MEMORY.md'), 'damaged synthetic staged copy')
|
|
133
|
+
assert.equal(recoverProjectStore(box.store, box.a).recoverable, false)
|
|
134
|
+
assert.throws(() => recoverProjectStore(box.store, box.a, { apply: true, reviewedMigration: view.reviewedMigration }), /migration-conflict/)
|
|
135
|
+
assert.deepEqual(contents(dir), before)
|
|
136
|
+
}))
|
|
137
|
+
for (const kind of ['symlink', 'hardlink']) test(`${kind} cannot enter a reviewed legacy copy`, () => box(box => {
|
|
138
|
+
const dir = legacy(box), target = join(box.root, 'outside.json')
|
|
139
|
+
writeFileSync(target, '{"synthetic":"private other file"}\n')
|
|
140
|
+
if (kind === 'symlink') symlinkSync(target, join(dir, 'linked.json'))
|
|
141
|
+
else linkSync(target, join(dir, 'linked.json'))
|
|
142
|
+
assert.throws(() => inspectProjectStore(box.store, box.a))
|
|
143
|
+
assert.equal(readFileSync(target, 'utf8'), '{"synthetic":"private other file"}\n')
|
|
144
|
+
}))
|
|
145
|
+
test('symlinked memory directory, pending publication and tampered identity fail closed', () => box(box => {
|
|
146
|
+
const outside = join(box.root, 'outside'); mkdirSync(outside); symlinkSync(outside, box.store)
|
|
147
|
+
assert.throws(() => projectStoreDir(box.store, box.a), /unsafe-directory/)
|
|
148
|
+
rmSync(box.store); const dir = legacy(box)
|
|
149
|
+
writeFileSync(join(dir, '.publication.json'), '{}')
|
|
150
|
+
assert.throws(() => inspectProjectStore(box.store, box.a), /needs-recovery/)
|
|
151
|
+
rmSync(join(dir, '.publication.json'))
|
|
152
|
+
const result = migrateProjectStore(box.store, box.a, reviewed(box))
|
|
153
|
+
writeFileSync(join(result.targetDir, '.project-identity.json'), JSON.stringify({ schema: 1, projectId: projectIdentity(box.b) }))
|
|
154
|
+
assert.throws(() => storeDirFor('project', box.a), /identity-mismatch/)
|
|
155
|
+
}))
|
|
156
|
+
test('a live loaded host blocks applying migration while read-only inspection remains available', () => box(box => {
|
|
157
|
+
legacy(box); writeFileSync(join(box.store, '.loaded.json'), JSON.stringify({ pid: process.pid }))
|
|
158
|
+
assert.equal(inspectProjectStore(box.store, box.a).state, 'legacy-needs-review')
|
|
159
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, reviewed(box)), /host-must-stop/)
|
|
160
|
+
}))
|
|
161
|
+
test('actual SIGKILL after directory publication is recoverable and never assigns the copy to a colliding project', () => box(box => {
|
|
162
|
+
const dir = legacy(box), before = contents(dir), options = reviewed(box)
|
|
163
|
+
const worker = `import {migrateProjectStore} from ${JSON.stringify(new URL('./project-stores.mjs', import.meta.url).href)};migrateProjectStore(process.argv[1],process.argv[2],{...JSON.parse(process.argv[3]),fault:event=>{if(event.phase==='renamed')process.kill(process.pid,'SIGKILL')}})`
|
|
164
|
+
const result = spawnSync(process.execPath, ['--input-type=module', '-e', worker, box.store, box.a, JSON.stringify(options)], { encoding: 'utf8', timeout: 15000 })
|
|
165
|
+
assert.equal(result.signal, 'SIGKILL', result.stderr)
|
|
166
|
+
assert.throws(() => storeDirFor('project', box.a), /migration-needs-recovery/)
|
|
167
|
+
const past = new Date(Date.now() - 20000)
|
|
168
|
+
for (const path of [join(dir, '.write.lock'), join(box.store, 'projects/.legacy-claims/.write.lock')]) utimesSync(path, past, past)
|
|
169
|
+
const view = recoverProjectStore(box.store, box.a)
|
|
170
|
+
recoverProjectStore(box.store, box.a, { apply: true, reviewedMigration: view.reviewedMigration })
|
|
171
|
+
assert.deepEqual(contents(dir), before)
|
|
172
|
+
assert.equal(searchStore(storeDirFor('project', box.b), 'cobalt-1234').hits.length, 0)
|
|
173
|
+
assert.equal(searchStore(storeDirFor('project', box.a), 'cobalt-1234').hits.length, 1)
|
|
174
|
+
}))
|
|
175
|
+
|
|
176
|
+
test('opaque binary files refuse migration without leaving a prepared claim or scratch copy', () => box(box => {
|
|
177
|
+
const dir = legacy(box)
|
|
178
|
+
writeFileSync(join(dir, 'unknown.bin'), Buffer.from([255, 254, 0, 128]))
|
|
179
|
+
const before = contents(dir), options = reviewed(box)
|
|
180
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, options), /non-text-file-or-copy-diverged/)
|
|
181
|
+
assert.equal(readdirSync(join(box.store, 'projects')).some(name => name.startsWith('.migration-')), false)
|
|
182
|
+
assert.deepEqual(contents(dir), before)
|
|
183
|
+
assert.equal(inspectProjectStore(box.store, box.a).state, 'legacy-needs-review')
|
|
184
|
+
}))
|
|
185
|
+
test('oversized files, overly deep trees and FIFO entries are refused before copying', () => box(box => {
|
|
186
|
+
const dir = legacy(box)
|
|
187
|
+
writeFileSync(join(dir, 'oversized.md'), 'x'.repeat(2 * 1024 * 1024 + 1))
|
|
188
|
+
assert.throws(() => inspectProjectStore(box.store, box.a), /unsafe-file/)
|
|
189
|
+
rmSync(join(dir, 'oversized.md'))
|
|
190
|
+
const nested = join(dir, ...Array(9).fill('sub'))
|
|
191
|
+
mkdirSync(nested, { recursive: true })
|
|
192
|
+
assert.throws(() => inspectProjectStore(box.store, box.a), /tree-too-deep/)
|
|
193
|
+
rmSync(join(dir, 'sub'), { recursive: true })
|
|
194
|
+
const made = spawnSync('mkfifo', [join(dir, 'pipe')], { encoding: 'utf8', timeout: 3000 })
|
|
195
|
+
assert.equal(made.status, 0, made.stderr)
|
|
196
|
+
assert.throws(() => inspectProjectStore(box.store, box.a), /unsafe-file/)
|
|
197
|
+
}))
|
|
198
|
+
test('source edits after completed migration are diagnosed and never silently merged', () => box(box => {
|
|
199
|
+
const dir = legacy(box)
|
|
200
|
+
migrateProjectStore(box.store, box.a, reviewed(box))
|
|
201
|
+
writeFileSync(join(dir, 'late.md'), 'synthetic old version later write')
|
|
202
|
+
assert.equal(inspectProjectStore(box.store, box.a).sourceChangedSinceMigration, true)
|
|
203
|
+
assert.equal(existsSync(join(storeDirFor('project', box.a), 'late.md')), false)
|
|
204
|
+
}))
|
|
205
|
+
test('local CLI previews and applies with both review hashes without package installation', () => box(box => {
|
|
206
|
+
legacy(box)
|
|
207
|
+
const cli = fileURLToPath(new URL('./scripts/projects.mjs', import.meta.url))
|
|
208
|
+
const run = args => spawnSync(process.execPath, [cli, ...args, '--cwd', box.a], { env: process.env, encoding: 'utf8', timeout: 10000 })
|
|
209
|
+
const preview = run(['migrate'])
|
|
210
|
+
assert.equal(preview.status, 0, preview.stderr)
|
|
211
|
+
const view = JSON.parse(preview.stdout)
|
|
212
|
+
assert.equal(view.applied, false)
|
|
213
|
+
const applied = run(['migrate', '--apply', '--reviewed-tree', view.reviewedTree, '--reviewed-claim', view.reviewedClaim])
|
|
214
|
+
assert.equal(applied.status, 0, applied.stderr)
|
|
215
|
+
assert.equal(JSON.parse(applied.stdout).originalPreserved, true)
|
|
216
|
+
assert.equal(searchStore(storeDirFor('project', box.a), 'cobalt-1234').hits.length, 1)
|
|
217
|
+
}))
|
|
218
|
+
|
|
219
|
+
test('an old but live migration lock is not stolen by another apply attempt', () => box(box => {
|
|
220
|
+
legacy(box)
|
|
221
|
+
const options = reviewed(box), locks = join(box.store, 'projects/.legacy-claims')
|
|
222
|
+
mkdirSync(locks)
|
|
223
|
+
const lock = join(locks, '.write.lock'), raw = JSON.stringify({ pid: process.pid, token: 'synthetic-live-owner' })
|
|
224
|
+
writeFileSync(lock, raw)
|
|
225
|
+
const past = new Date(Date.now() - 600000); utimesSync(lock, past, past)
|
|
226
|
+
assert.throws(() => migrateProjectStore(box.store, box.a, options), /migration-busy/)
|
|
227
|
+
assert.equal(readFileSync(lock, 'utf8'), raw)
|
|
228
|
+
}))
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import {realpathSync} from 'node:fs'
|
|
2
|
+
import { test } from 'node:test'
|
|
3
|
+
import assert from 'node:assert/strict'
|
|
4
|
+
import { mkdtempSync, readFileSync, writeFileSync, rmSync, existsSync, readdirSync, utimesSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { tmpdir } from 'node:os'
|
|
7
|
+
import { spawnSync } from 'node:child_process'
|
|
8
|
+
import { fileURLToPath } from 'node:url'
|
|
9
|
+
import { stageCandidate, listCandidates, rejectCandidate, withdrawSource, pruneCandidates } from './candidates.mjs'
|
|
10
|
+
import { adoptCandidate, recoverMemoryPublication, writeMemory, storeRevision, indexLine, searchStore, apply } from './index.mjs'
|
|
11
|
+
import { commitPublication } from './publication.mjs'
|
|
12
|
+
|
|
13
|
+
const modulePath = fileURLToPath(new URL('./index.mjs', import.meta.url))
|
|
14
|
+
function fixture(dir) {
|
|
15
|
+
return { type: 'user', scope: 'project', summary: '本项目偏好柔和低反差的光线', detail: '仅限本项目的夜间室内对白场景。',
|
|
16
|
+
sessionId: 'review-session', indexRevision: storeRevision(dir),
|
|
17
|
+
evidence: [{ messageId: 'review-message', hash: 'b'.repeat(64), quote: '这个项目的夜戏采用低反差光线' }] }
|
|
18
|
+
}
|
|
19
|
+
function box(run) { const dir = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-publication-'))); try { return run(dir) } finally { rmSync(dir, { recursive: true, force: true }) } }
|
|
20
|
+
function reviewed(dir) {
|
|
21
|
+
const item = stageCandidate(dir, fixture(dir))
|
|
22
|
+
const preview = adoptCandidate(dir, item.id)
|
|
23
|
+
return { id: item.id, options: { apply: true, scope: 'project', reviewedIndex: preview.reviewedIndex, candidateRevision: preview.candidateRevision } }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
test('采纳默认仅预览,无 index/topic 写入', () => box((dir) => {
|
|
27
|
+
const item = stageCandidate(dir, fixture(dir)); const before = readFileSync(join(dir, '.candidates.json'), 'utf8')
|
|
28
|
+
const preview = adoptCandidate(dir, item.id)
|
|
29
|
+
assert.equal(preview.applied, false)
|
|
30
|
+
assert.equal(preview.candidate.summary, fixture(dir).summary)
|
|
31
|
+
assert.equal(readFileSync(join(dir, '.candidates.json'), 'utf8'), before)
|
|
32
|
+
assert.equal(existsSync(join(dir, 'MEMORY.md')), false)
|
|
33
|
+
}))
|
|
34
|
+
test('采纳将索引、细节和候选状态一起发布,重复操作不再追加', () => box((dir) => {
|
|
35
|
+
const { id, options } = reviewed(dir)
|
|
36
|
+
assert.equal(adoptCandidate(dir, id, options).status, 'adopted')
|
|
37
|
+
assert.equal(listCandidates(dir, { status: 'adopted' }).total, 1)
|
|
38
|
+
assert.equal(listCandidates(dir).total, 0)
|
|
39
|
+
assert.equal(searchStore(dir, '低反差').hits.length, 1)
|
|
40
|
+
assert.match(readFileSync(join(dir, 'user.md'), 'utf8'), /夜间室内/)
|
|
41
|
+
const before = readFileSync(join(dir, 'user.md'), 'utf8')
|
|
42
|
+
assert.equal(adoptCandidate(dir, id, options).duplicate, true)
|
|
43
|
+
assert.equal(readFileSync(join(dir, 'user.md'), 'utf8'), before)
|
|
44
|
+
assert.ok(!readdirSync(dir).some((name) => name.startsWith('.publication')))
|
|
45
|
+
pruneCandidates(dir, { apply: true })
|
|
46
|
+
assert.equal(listCandidates(dir, { status: 'adopted' }).total, 1)
|
|
47
|
+
}))
|
|
48
|
+
test('预览后索引改变,旧审批令牌不能发布', () => box((dir) => {
|
|
49
|
+
const { id, options } = reviewed(dir)
|
|
50
|
+
writeMemory({ type: 'project', dir, line: indexLine('project', '新的独立项目决定需要人工复核') })
|
|
51
|
+
assert.throws(() => adoptCandidate(dir, id, options), { code: 'capture-stale-revision' })
|
|
52
|
+
assert.equal(listCandidates(dir).total, 1)
|
|
53
|
+
assert.equal(searchStore(dir, '低反差').hits.length, 0)
|
|
54
|
+
}))
|
|
55
|
+
test('预览后候选箱改变,必须重新审阅', () => box((dir) => {
|
|
56
|
+
const { id, options } = reviewed(dir)
|
|
57
|
+
stageCandidate(dir, { ...fixture(dir), summary: '另一个需要独立审阅的构图判断' })
|
|
58
|
+
assert.throws(() => adoptCandidate(dir, id, options), /stale-review/)
|
|
59
|
+
assert.equal(existsSync(join(dir, 'MEMORY.md')), false)
|
|
60
|
+
}))
|
|
61
|
+
test('拒绝、撤回、跨范围与缺审批参数均不能采纳', () => box((dir) => {
|
|
62
|
+
const { id, options } = reviewed(dir)
|
|
63
|
+
assert.throws(() => adoptCandidate(dir, id, { ...options, scope: 'global' }), /scope-mismatch/)
|
|
64
|
+
assert.throws(() => adoptCandidate(dir, id, { apply: true }), /stale-review/)
|
|
65
|
+
rejectCandidate(dir, id)
|
|
66
|
+
assert.throws(() => adoptCandidate(dir, id, options), /not-reviewable/)
|
|
67
|
+
withdrawSource(dir, 'review-session', 'review-message')
|
|
68
|
+
assert.throws(() => adoptCandidate(dir, id, options), /not-reviewable/)
|
|
69
|
+
}))
|
|
70
|
+
test('已采纳来源不能只撤回候选元数据,须处理有效记忆', () => box((dir) => {
|
|
71
|
+
const { id, options } = reviewed(dir); adoptCandidate(dir, id, options)
|
|
72
|
+
assert.throws(() => withdrawSource(dir, 'review-session', 'review-message'), /needs-effective-withdrawal/)
|
|
73
|
+
assert.equal(listCandidates(dir, { status: 'adopted' }).total, 1)
|
|
74
|
+
}))
|
|
75
|
+
|
|
76
|
+
for (const at of ['journal', 0, 1, 2]) test(`采纳在 ${at} 中断后可恢复全部投影`, () => box((dir) => {
|
|
77
|
+
const { id, options } = reviewed(dir)
|
|
78
|
+
assert.throws(() => adoptCandidate(dir, id, { ...options, publicationFault: (event) => {
|
|
79
|
+
if (event.phase === at || event.phase === 'file' && event.index === at) throw new Error('simulated interruption')
|
|
80
|
+
} }), /simulated interruption/)
|
|
81
|
+
assert.equal(recoverMemoryPublication(dir).recoverable, true)
|
|
82
|
+
assert.throws(() => searchStore(dir, '低反差'), /needs-recovery/)
|
|
83
|
+
assert.throws(() => listCandidates(dir), /needs-recovery/)
|
|
84
|
+
assert.throws(() => writeMemory({ type: 'project', dir, line: indexLine('project', '不应插队的新条目') }), /needs-recovery/)
|
|
85
|
+
assert.equal(recoverMemoryPublication(dir, { apply: true }).applied, true)
|
|
86
|
+
assert.equal(listCandidates(dir, { status: 'adopted' }).total, 1)
|
|
87
|
+
assert.match(readFileSync(join(dir, 'MEMORY.md'), 'utf8'), /低反差/)
|
|
88
|
+
assert.match(readFileSync(join(dir, 'user.md'), 'utf8'), /夜间室内/)
|
|
89
|
+
assert.equal(adoptCandidate(dir, id, options).duplicate, true)
|
|
90
|
+
}))
|
|
91
|
+
test('恢复前发现外部编辑,不强行覆写,也不清掉日志', () => box((dir) => {
|
|
92
|
+
const { id, options } = reviewed(dir)
|
|
93
|
+
assert.throws(() => adoptCandidate(dir, id, { ...options, publicationFault: (e) => { if (e.phase === 'journal') throw new Error('interrupt') } }))
|
|
94
|
+
writeFileSync(join(dir, 'MEMORY.md'), 'human-edited-version')
|
|
95
|
+
assert.equal(recoverMemoryPublication(dir).recoverable, false)
|
|
96
|
+
assert.throws(() => recoverMemoryPublication(dir, { apply: true }), /conflict/)
|
|
97
|
+
assert.equal(readFileSync(join(dir, 'MEMORY.md'), 'utf8'), 'human-edited-version')
|
|
98
|
+
assert.equal(existsSync(join(dir, '.publication.json')), true)
|
|
99
|
+
}))
|
|
100
|
+
test('恢复前阶段文件损坏,不发布任意内容', () => box((dir) => {
|
|
101
|
+
const { id, options } = reviewed(dir)
|
|
102
|
+
assert.throws(() => adoptCandidate(dir, id, { ...options, publicationFault: (e) => { if (e.phase === 'journal') throw new Error('interrupt') } }))
|
|
103
|
+
const journal = JSON.parse(readFileSync(join(dir, '.publication.json'), 'utf8'))
|
|
104
|
+
writeFileSync(join(dir, journal.files[0].stage), 'changed stage')
|
|
105
|
+
assert.equal(recoverMemoryPublication(dir).recoverable, false)
|
|
106
|
+
assert.equal(existsSync(join(dir, 'MEMORY.md')), false)
|
|
107
|
+
}))
|
|
108
|
+
test('未恢复的半发布索引不进入真实上下文 provider', () => box((dir) => {
|
|
109
|
+
const previous = process.env.DSH_HOME; process.env.DSH_HOME = dir
|
|
110
|
+
try {
|
|
111
|
+
const global = join(dir, 'memory'); const { id, options } = reviewed(global)
|
|
112
|
+
assert.throws(() => adoptCandidate(global, id, { ...options, publicationFault: (e) => { if (e.phase === 'file' && e.index === 0) throw new Error('interrupt') } }))
|
|
113
|
+
let context
|
|
114
|
+
apply({ systemPrompt: { context: (c) => context = c }, workingDirectory: { get: () => dir }, tools: { register() {} } }, { autoCapture: { enabled: false } })
|
|
115
|
+
const rendered = context.text({ agent: { session: {} } })
|
|
116
|
+
assert.doesNotMatch(rendered, /本项目偏好柔和低反差/)
|
|
117
|
+
assert.match(rendered, /中断发布/)
|
|
118
|
+
} finally { if (previous === undefined) delete process.env.DSH_HOME; else process.env.DSH_HOME = previous }
|
|
119
|
+
}))
|
|
120
|
+
test('真实进程被强制退出后,过期残留锁与发布日志可恢复', () => box((dir) => {
|
|
121
|
+
const { id, options } = reviewed(dir)
|
|
122
|
+
const worker = `import {adoptCandidate} from ${JSON.stringify(modulePath)};adoptCandidate(process.argv[1],process.argv[2],{...JSON.parse(process.argv[3]),publicationFault:(e)=>{if(e.phase==='file'&&e.index===0)process.kill(process.pid,'SIGKILL')}})`
|
|
123
|
+
const result = spawnSync(process.execPath, ['--input-type=module', '-e', worker, dir, id, JSON.stringify(options)], { encoding: 'utf8', timeout: 5000 })
|
|
124
|
+
assert.equal(result.signal, 'SIGKILL', result.stderr)
|
|
125
|
+
// Simulate the documented 15-second stale-lock age, without a wall-clock sleep.
|
|
126
|
+
const past = new Date(Date.now() - 20000); utimesSync(join(dir, '.write.lock'), past, past)
|
|
127
|
+
assert.equal(recoverMemoryPublication(dir, { apply: true }).applied, true)
|
|
128
|
+
assert.equal(listCandidates(dir, { status: 'adopted' }).total, 1)
|
|
129
|
+
}))
|
|
130
|
+
test('发布路径限制阻止写出库外', () => box((dir) => {
|
|
131
|
+
assert.throws(() => commitPublication(dir, [{ name: '../outside', text: 'bad' }]), /invalid-writes/)
|
|
132
|
+
assert.equal(existsSync(join(dir, '.publication.json')), false)
|
|
133
|
+
}))
|
|
134
|
+
test('发布前校验失败,不提前写索引或虚构成功历史', () => box((dir) => {
|
|
135
|
+
assert.throws(() => writeMemory({ type: 'user', dir, line: indexLine('user', '新的内容不应在失败后留下记录'), detail: 'x'.repeat(512 * 1024) }), /invalid-writes/)
|
|
136
|
+
assert.equal(existsSync(join(dir, 'MEMORY.md')), false)
|
|
137
|
+
assert.equal(existsSync(join(dir, '.history.jsonl')), false)
|
|
138
|
+
assert.equal(existsSync(join(dir, '.publication.json')), false)
|
|
139
|
+
}))
|
|
140
|
+
test('已采纳记忆被移走后,重复审批不会偷偷重建它', () => box((dir) => {
|
|
141
|
+
const { id, options } = reviewed(dir); adoptCandidate(dir, id, options)
|
|
142
|
+
writeFileSync(join(dir, 'MEMORY.md'), '# 用户已经修改了当前索引\n')
|
|
143
|
+
assert.throws(() => adoptCandidate(dir, id, options), /effective-memory-missing/)
|
|
144
|
+
assert.doesNotMatch(readFileSync(join(dir, 'MEMORY.md'), 'utf8'), /低反差/)
|
|
145
|
+
}))
|
package/test-restore.mjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import {mkdtempSync,realpathSync,mkdirSync,readFileSync,writeFileSync,rmSync,existsSync,readdirSync,cpSync,symlinkSync} from 'node:fs'
|
|
4
|
+
import {join,dirname} from 'node:path'
|
|
5
|
+
import {tmpdir} from 'node:os'
|
|
6
|
+
import {spawnSync} from 'node:child_process'
|
|
7
|
+
import {fileURLToPath} from 'node:url'
|
|
8
|
+
import {createHash} from 'node:crypto'
|
|
9
|
+
import {createMemorySnapshot,snapshotIO} from './snapshots.mjs'
|
|
10
|
+
import {restoreMemorySnapshot,reviewMemoryRestore,resumeMemoryRestore} from './restore.mjs'
|
|
11
|
+
import {restorationPending,restorationJournalPath} from './restoration-lock.mjs'
|
|
12
|
+
import {initializeManagedMemory,managedMemoryStatus,writeMemory,indexLine,searchStore,withdrawManagedSource,storeDirFor,apply} from './index.mjs'
|
|
13
|
+
import {controlStatus} from './managed-policy.mjs'
|
|
14
|
+
import {claimCaptureJob,finishCaptureJob,listCaptureJobs} from './capture-jobs.mjs'
|
|
15
|
+
import {captureInputDescriptor,enqueueCaptureInput,listCaptureInputs,bindCaptureInput} from './capture-inputs.mjs'
|
|
16
|
+
import {compileValueRevision} from './field-lineage.mjs'
|
|
17
|
+
import {candidateSnapshot} from './candidates.mjs'
|
|
18
|
+
import {episodeSnapshot} from './episodes.mjs'
|
|
19
|
+
const here=dirname(fileURLToPath(import.meta.url)),hash=b=>createHash('sha256').update(b).digest('hex')
|
|
20
|
+
async function box(run){const root=realpathSync(mkdtempSync(join(tmpdir(),'memory-restore-'))),home=join(root,'home'),data=join(home,'memory'),snapshot=join(root,'snapshot'),cwd=join(root,'project'),previous=process.env.DSH_HOME;mkdirSync(home);mkdirSync(data);mkdirSync(cwd);writeFileSync(join(cwd,'.dsh-root'),'');process.env.DSH_HOME=home;const p=initializeManagedMemory(data);initializeManagedMemory(data,undefined,{apply:true,reviewed:p.review});try{return await run({root,home,data,snapshot,cwd})}finally{if(previous===undefined)delete process.env.DSH_HOME;else process.env.DSH_HOME=previous;rmSync(root,{recursive:true,force:true})}}
|
|
21
|
+
function seed(dir,word,owner='owner-'+word,scope='global'){const summary='Synthetic lasting preference '+word;return writeMemory({dir,scope,type:'user',summary,detail:summary,line:indexLine('user',summary,undefined,true),provenance:{basis:'tool-context',sessionId:owner,callHash:hash(owner+word),evidence:[{messageId:'root',hash:hash('quote '+word),quote:summary}]}})}
|
|
22
|
+
function revoke(data,owner){const p=withdrawManagedSource(data,owner,'root');return withdrawManagedSource(data,owner,'root',{apply:true,controlReview:p.controlReview})}
|
|
23
|
+
function tree(data){return snapshotIO.digest(snapshotIO.inventory(data,{dataOnly:true}))}
|
|
24
|
+
function restore(f,options={}){const p=reviewMemoryRestore(f.data,f.snapshot,options);return restoreMemorySnapshot(f.data,f.snapshot,{...options,apply:true,reviewed:p.review})}
|
|
25
|
+
const options={everyTurns:4,maxEntries:3,maxTokens:800,maxInputBytes:24000,timeoutMs:25000}
|
|
26
|
+
function input(id){return captureInputDescriptor({id,header:{createdAt:1234}},[{seq:1,role:'user',hash:hash('synthetic '+id)}],'/synthetic/project',options,{provider:'fixture',model:'fixture'})}
|
|
27
|
+
function fieldValue(f,n,parent){
|
|
28
|
+
const summary='Synthetic draft palette field-'+n,compiled=parent?compileValueRevision(parent,{kind:'preference'},'global'):undefined;
|
|
29
|
+
writeMemory({dir:f.data,type:'user',scope:'global',summary,line:indexLine('user',summary,undefined,false),meaning:compiled?.meaning??{kind:'preference',conditions:[{dimension:'document_kind',value:'draft'}]},...parent?{supersedes:parent.indexLine}:{},provenance:{basis:'tool-context',sessionId:'field-owner-'+n,callHash:hash('field-call-'+n),evidence:[{messageId:'root',hash:hash('field-source-'+n),quote:'Synthetic field palette original source '+n}],...compiled?{fieldLineage:compiled.fieldLineage}:{}}});
|
|
30
|
+
return candidateSnapshot(f.data,'global').records.find(r=>r.status==='recorded'&&r.summary===summary);
|
|
31
|
+
}
|
|
32
|
+
test('schema4 source ledger and schema2 history restore together and retain inherited-source withdrawals',()=>box(f=>{
|
|
33
|
+
const a=fieldValue(f,1),b=fieldValue(f,2,a);assert.equal(episodeSnapshot(f.data).state.schema,2);createMemorySnapshot(f.data,f.snapshot);
|
|
34
|
+
fieldValue(f,3,b);revoke(f.data,'field-owner-1');restore(f);
|
|
35
|
+
assert.equal(searchStore(f.data,'field-2').hits.length,0);assert.equal(episodeSnapshot(f.data).state.entries.some(r=>r.source.sources.includes(a.sources[0])),false);
|
|
36
|
+
assert.equal(JSON.parse(readFileSync(join(f.data,'.candidates.json'))).schema,4);
|
|
37
|
+
}))
|
|
38
|
+
test('a field-lineage snapshot cannot be reviewed for a legacy archive lacking its data capability',()=>box(f=>{
|
|
39
|
+
const a=fieldValue(f,1);createMemorySnapshot(f.data,join(f.root,'legacy-snapshot'));fieldValue(f,2,a);createMemorySnapshot(f.data,f.snapshot);
|
|
40
|
+
const p=join(f.root,'target/package');mkdirSync(p,{recursive:true});const archive=join(f.root,'target.tgz'),json=join(p,'package.json');
|
|
41
|
+
const pack=()=>assert.equal(spawnSync('tar',['-czf',archive,'-C',dirname(p),'package']).status,0);
|
|
42
|
+
const legacy={name:'dsh-memory',version:'0.21.0-dev.31',dshMemoryRestoreProtocol:1};writeFileSync(json,JSON.stringify(legacy));pack();const before=tree(f.data);
|
|
43
|
+
assert.throws(()=>reviewMemoryRestore(f.data,f.snapshot,{targetArchive:archive}),/target-data-schema-unsupported/);assert.equal(tree(f.data),before);assert.equal(restorationPending(f.data),false);
|
|
44
|
+
// A real pre-field snapshot can still be selected for supported data rollback.
|
|
45
|
+
assert.equal(reviewMemoryRestore(f.data,join(f.root,'legacy-snapshot'),{targetArchive:archive}).target.version,legacy.version);
|
|
46
|
+
writeFileSync(json,JSON.stringify({...legacy,version:'0.21.0-dev.33',dshMemoryDataSchemas:{candidates:[1,2,3,4],episodes:[1,2]}}));pack();assert.equal(reviewMemoryRestore(f.data,f.snapshot,{targetArchive:archive}).target.version,'0.21.0-dev.33');
|
|
47
|
+
writeFileSync(json,JSON.stringify({...legacy,dshMemoryDataSchemas:{candidates:[1,2,3,4],episodes:[1]}}));pack();assert.throws(()=>reviewMemoryRestore(f.data,f.snapshot,{targetArchive:archive}),/target-data-schema-unsupported/);
|
|
48
|
+
}))
|
|
49
|
+
test('review is readonly; restore selects old data, keeps independent control, and quarantines every newer file',()=>box(f=>{
|
|
50
|
+
seed(f.data,'before4826');createMemorySnapshot(f.data,f.snapshot);seed(f.data,'after5937');const before=tree(f.data),status=managedMemoryStatus(f.data),pin=readFileSync(f.data+'.control-binding.json')
|
|
51
|
+
const p=reviewMemoryRestore(f.data,f.snapshot);assert.equal(p.applied,false);assert.equal(tree(f.data),before);assert.equal(restorationPending(f.data),false)
|
|
52
|
+
const r=restoreMemorySnapshot(f.data,f.snapshot,{apply:true,reviewed:p.review});assert.equal(r.pending,false);assert.equal(r.codeChanged,false);assert.equal(r.modelRequestResent,false);assert.ok(searchStore(f.data,'before4826').hits.length);assert.equal(searchStore(f.data,'after5937').hits.length,0);assert.equal(tree(r.quarantine),before);assert.deepEqual(readFileSync(f.data+'.control-binding.json'),pin);assert.equal(managedMemoryStatus(f.data).installationId,status.installationId);assert.ok(existsSync(r.receipt));assert.equal(restorationPending(f.data),false);assert.deepEqual(resumeMemoryRestore(f.data,{apply:true}),{applied:false,pending:false,modelRequestResent:false,codeChanged:false})
|
|
53
|
+
}))
|
|
54
|
+
test('post-backup withdrawal remains effective and is physically reapplied in global and project history',()=>box(f=>{
|
|
55
|
+
const project=storeDirFor('project',f.cwd);for(const [dir,scope]of [[f.data,'global'],[project,'project']])seed(dir,'private6048','withdrawn-owner',scope)
|
|
56
|
+
createMemorySnapshot(f.data,f.snapshot);revoke(f.data,'withdrawn-owner');seed(f.data,'fresh6159');const before=controlStatus(f.data);const r=restore(f)
|
|
57
|
+
assert.equal(r.latestControlRetained,true);assert.equal(managedMemoryStatus(f.data).installationId,before.installationId);assert.deepEqual(controlStatus(f.data).operations.map(r=>r.source),before.operations.map(r=>r.source))
|
|
58
|
+
for(const dir of [f.data,project]){assert.equal(searchStore(dir,'private6048').hits.length,0);assert.doesNotMatch(readFileSync(join(dir,'MEMORY.md'),'utf8'),/private6048/);assert.doesNotMatch(readFileSync(join(dir,'user.md'),'utf8'),/private6048/);assert.doesNotMatch(readFileSync(join(dir,'.episodes.json'),'utf8'),/private6048/)}
|
|
59
|
+
assert.throws(()=>seed(storeDirFor('project',f.cwd),'repeat6260','withdrawn-owner','project'),/source-revoked/)
|
|
60
|
+
}))
|
|
61
|
+
test('current known failure and unknown invocation ids survive; restoring never creates a new claim for them',()=>box(f=>{
|
|
62
|
+
seed(f.data,'prior6371');createMemorySnapshot(f.data,f.snapshot)
|
|
63
|
+
const known=claimCaptureJob(f.data,hash('known'));finishCaptureJob(f.data,known,{outcome:'error',reason:'capture-provider-error',counts:{proposed:0}})
|
|
64
|
+
const unknown=claimCaptureJob(f.data,hash('unknown'),{now:Date.now()-10000,leaseMs:1000}),old=readFileSync(join(f.data,'.capture-jobs.json'))
|
|
65
|
+
restore(f);assert.deepEqual(readFileSync(join(f.data,'.capture-jobs.json')),old);assert.equal(claimCaptureJob(f.data,hash('known')).claimed,false);assert.equal(claimCaptureJob(f.data,hash('unknown')).claimed,false);assert.equal(listCaptureJobs(f.data).jobs.find(j=>j.id===unknown.id).status,'uncertain')
|
|
66
|
+
}))
|
|
67
|
+
test('backup-only pending input is blocked for review; latest bound input and job are retained',()=>box(f=>{
|
|
68
|
+
const pending=enqueueCaptureInput(f.data,input('old-pending'));createMemorySnapshot(f.data,f.snapshot);rmSync(join(f.data,'.capture-inputs.json'))
|
|
69
|
+
const current=enqueueCaptureInput(f.data,input('current-bound')),job=claimCaptureJob(f.data,current.id);bindCaptureInput(f.data,current.id,job.id);finishCaptureJob(f.data,job,{outcome:'ok',counts:{proposed:0}})
|
|
70
|
+
const r=restore(f),rows=listCaptureInputs(f.data).inputs;assert.equal(r.metadataCounts.blockedBackupInputs,1);assert.equal(rows.find(r=>r.id===pending.id).reason,'restore-review-required');assert.equal(rows.find(r=>r.id===current.id).status,'bound');assert.equal(claimCaptureJob(f.data,current.id).claimed,false)
|
|
71
|
+
}))
|
|
72
|
+
test('backup-only completed invocation is retained even if current metadata no longer lists it',()=>box(f=>{
|
|
73
|
+
const job=claimCaptureJob(f.data,hash('old-complete'));finishCaptureJob(f.data,job,{outcome:'ok',counts:{proposed:0}});createMemorySnapshot(f.data,f.snapshot);rmSync(join(f.data,'.capture-jobs.json'));restore(f);assert.equal(claimCaptureJob(f.data,hash('old-complete')).claimed,false)
|
|
74
|
+
}))
|
|
75
|
+
test('stale review, wrong root, lost control and different installation reject without replacing any data',()=>box(f=>{
|
|
76
|
+
seed(f.data,'old6482');createMemorySnapshot(f.data,f.snapshot);const p=reviewMemoryRestore(f.data,f.snapshot);seed(f.data,'new6593');const before=tree(f.data)
|
|
77
|
+
assert.throws(()=>restoreMemorySnapshot(f.data,f.snapshot,{apply:true,reviewed:p.review}),/stale-review/);assert.equal(tree(f.data),before);assert.equal(restorationPending(f.data),false)
|
|
78
|
+
assert.throws(()=>reviewMemoryRestore(join(f.root,'other'),f.snapshot),/different-source-root/)
|
|
79
|
+
const controls=f.data+'.control';cpSync(controls,join(f.root,'saved-control'),{recursive:true});rmSync(controls,{recursive:true});assert.throws(()=>reviewMemoryRestore(f.data,f.snapshot),/control-missing/);assert.equal(tree(f.data),before)
|
|
80
|
+
}))
|
|
81
|
+
for(const phase of ['prepared','old-renamed','old-moved','new-renamed','new-live','cleaning','restored-operation','complete','receipt'])test('interrupted '+phase+' stays guarded and resumes once with the latest withdrawal barrier',()=>box(f=>{
|
|
82
|
+
seed(f.data,'withdraw6704','withdrawn-owner');seed(f.data,'keep6815');createMemorySnapshot(f.data,f.snapshot);revoke(f.data,'withdrawn-owner');seed(f.data,'new6926');let hit=false
|
|
83
|
+
assert.throws(()=>restore(f,{fault:e=>{if(e.phase===phase){hit=true;throw Error('synthetic-interruption')}}}),/synthetic-interruption/);assert.equal(hit,true);assert.equal(restorationPending(f.data),true);assert.throws(()=>searchStore(f.data,'withdraw6704'),/restore-in-progress/);assert.throws(()=>seed(f.data,'blocked7037'),/restore-in-progress/)
|
|
84
|
+
const view=resumeMemoryRestore(f.data);assert.equal(view.pending,true);const result=resumeMemoryRestore(f.data,{apply:true});assert.equal(result.pending,false);assert.equal(searchStore(f.data,'withdraw6704').hits.length,0);assert.equal(searchStore(f.data,'new6926').hits.length,0);assert.ok(searchStore(f.data,'keep6815').hits.length);assert.equal(resumeMemoryRestore(f.data,{apply:true}).pending,false)
|
|
85
|
+
}))
|
|
86
|
+
test('a corrupt restore journal blocks ordinary reads and cannot redirect replacement paths',()=>box(f=>{
|
|
87
|
+
seed(f.data,'safe7148');createMemorySnapshot(f.data,f.snapshot);assert.throws(()=>restore(f,{fault:e=>{if(e.phase==='prepared')throw Error('stop')}}),/stop/)
|
|
88
|
+
const p=restorationJournalPath(f.data),j=JSON.parse(readFileSync(p));j.quarantine='../outside';writeFileSync(p,JSON.stringify(j));assert.throws(()=>resumeMemoryRestore(f.data,{apply:true}),/invalid-journal/);assert.throws(()=>searchStore(f.data,'safe7148'),/restore-in-progress/);assert.ok(readFileSync(join(f.data,'MEMORY.md'),'utf8').includes('safe7148'))
|
|
89
|
+
}))
|
|
90
|
+
test('a live second worker cannot resume or steal the in-progress journal',()=>box(f=>{
|
|
91
|
+
seed(f.data,'old7259');createMemorySnapshot(f.data,f.snapshot);assert.throws(()=>restore(f,{fault:e=>{if(e.phase==='prepared')throw Error('stop')}}),/stop/)
|
|
92
|
+
writeFileSync(f.data+'.restore-worker.lock',JSON.stringify({pid:process.pid,token:'00000000-0000-0000-0000-000000000000'}));assert.throws(()=>resumeMemoryRestore(f.data,{apply:true}),/worker-busy/)
|
|
93
|
+
}))
|
|
94
|
+
test('a host mounted during the missing-directory phase writes no new root and sees only a restore notice',()=>box(async f=>{
|
|
95
|
+
seed(f.data,'private7360');createMemorySnapshot(f.data,f.snapshot);assert.throws(()=>restore(f,{fault:e=>{if(e.phase==='old-moved')throw Error('stop')}}),/stop/);assert.equal(existsSync(f.data),false)
|
|
96
|
+
const tools=[],providers=[],effects=[];let calls=0;const ctx={systemPrompt:{context:p=>providers.push(p)},tools:{register:t=>tools.push(t)},workingDirectory:{get:()=>f.cwd},llm:{listProviders:()=>[],prepareCall(){calls++;throw Error('must not call')}},on(){},effect(fn){effects.push(fn())}}
|
|
97
|
+
apply(ctx,{autoCapture:{everyTurns:1}});const status=await tools.find(t=>t.name==='memory_status').execute({scope:'global'});assert.equal(status.sourceControl.code,'managed-memory-restore-in-progress');const text=providers.find(p=>p.name==='memory:index').text({agent:{session:{id:'during-restore'}}});assert.match(text,/恢复尚未完成/);assert.doesNotMatch(text,/private7360/);assert.equal(existsSync(f.data),false);assert.equal(calls,0);for(const fn of effects.reverse())fn?.();resumeMemoryRestore(f.data,{apply:true})
|
|
98
|
+
}))
|
|
99
|
+
test('CLI performs a reviewed restore in a fresh process; incomplete arguments cannot mutate the target',()=>box(f=>{
|
|
100
|
+
seed(f.data,'before7471');createMemorySnapshot(f.data,f.snapshot);seed(f.data,'after7582');const cli=join(here,'scripts/backup.mjs'),run=args=>spawnSync(process.execPath,[cli,...args],{encoding:'utf8'}),base=['restore','--root',f.data,'--snapshot',f.snapshot]
|
|
101
|
+
let r=run(base);assert.equal(r.status,0,r.stderr);const plan=JSON.parse(r.stdout);assert.equal(plan.applied,false);r=run([...base,'--apply']);assert.notEqual(r.status,0);assert.ok(searchStore(f.data,'after7582').hits.length);r=run([...base,'--apply','--reviewed',plan.review]);assert.equal(r.status,0,r.stderr);assert.equal(JSON.parse(r.stdout).codeChanged,false);assert.equal(searchStore(f.data,'after7582').hits.length,0)
|
|
102
|
+
}))
|
|
103
|
+
test('an actual archive without the restore protocol is rejected; a declared protocol is bound to its SHA',()=>box(f=>{
|
|
104
|
+
seed(f.data,'archive7693');createMemorySnapshot(f.data,f.snapshot);const p=join(f.root,'target/package');mkdirSync(p,{recursive:true});const file=join(p,'package.json'),archive=join(f.root,'target.tgz'),pack=()=>assert.equal(spawnSync('tar',['-czf',archive,'-C',dirname(p),'package']).status,0)
|
|
105
|
+
writeFileSync(file,JSON.stringify({name:'dsh-memory',version:'0.20.0',dsh:{}}));pack();const before=tree(f.data);assert.throws(()=>reviewMemoryRestore(f.data,f.snapshot,{targetArchive:archive}),/incompatible-target-archive/);assert.equal(tree(f.data),before);assert.equal(restorationPending(f.data),false)
|
|
106
|
+
writeFileSync(file,JSON.stringify({name:'dsh-memory',version:'0.21.0-dev.22',dshMemoryRestoreProtocol:1}));pack();const p1=reviewMemoryRestore(f.data,f.snapshot,{targetArchive:archive});assert.equal(p1.target.sha256,hash(readFileSync(archive)));writeFileSync(file,JSON.stringify({name:'dsh-memory',version:'0.21.0-dev.23',dshMemoryRestoreProtocol:1}));pack();assert.throws(()=>restoreMemorySnapshot(f.data,f.snapshot,{targetArchive:archive,apply:true,reviewed:p1.review}),/stale-review/)
|
|
107
|
+
}))
|
|
108
|
+
test('corrupt snapshot and unregistered snapshot project are rejected before any journal or replacement',()=>box(f=>{
|
|
109
|
+
seed(f.data,'damage7804');createMemorySnapshot(f.data,f.snapshot);const file=join(f.snapshot,'data/MEMORY.md'),body=readFileSync(file),before=tree(f.data);writeFileSync(file,'Synthetic corrupted snapshot');assert.throws(()=>reviewMemoryRestore(f.data,f.snapshot),/content-mismatch/);assert.equal(tree(f.data),before);assert.equal(restorationPending(f.data),false);writeFileSync(file,body);const unknown=join(f.data,'projects/unregistered');mkdirSync(unknown,{recursive:true});writeFileSync(join(unknown,'MEMORY.md'),'Synthetic unknown project');const second=join(f.root,'second-snapshot');createMemorySnapshot(f.data,second);const unchanged=tree(f.data);assert.throws(()=>reviewMemoryRestore(f.data,second),/snapshot-store-needs-review/);assert.equal(tree(f.data),unchanged)
|
|
110
|
+
}))
|
|
111
|
+
test('restoration refuses a union that would silently evict invocation history',()=>box(f=>{
|
|
112
|
+
for(let i=0;i<256;i++){const job=claimCaptureJob(f.data,hash('retained-'+i));finishCaptureJob(f.data,job,{outcome:'ok',counts:{proposed:0}})}createMemorySnapshot(f.data,f.snapshot)
|
|
113
|
+
rmSync(join(f.data,'.capture-jobs.json'));const extra=claimCaptureJob(f.data,hash('extra'));finishCaptureJob(f.data,extra,{outcome:'ok',counts:{proposed:0}});const before=tree(f.data);assert.throws(()=>reviewMemoryRestore(f.data,f.snapshot),/invocation-retention-capacity/);assert.equal(tree(f.data),before);assert.equal(restorationPending(f.data),false)
|
|
114
|
+
}))
|
|
115
|
+
test('rewinding the independent control during an interrupted restore cannot erase captured withdrawals',()=>box(f=>{
|
|
116
|
+
seed(f.data,'source7915','withdrawn-owner');createMemorySnapshot(f.data,f.snapshot);revoke(f.data,'withdrawn-owner');assert.throws(()=>restore(f,{fault:e=>{if(e.phase==='cleaning')throw Error('stop')}}),/stop/)
|
|
117
|
+
rmSync(f.data+'.control',{recursive:true});cpSync(join(f.snapshot,'control'),f.data+'.control',{recursive:true});assert.throws(()=>resumeMemoryRestore(f.data,{apply:true}),/control-state-regressed/);assert.equal(restorationPending(f.data),true);assert.throws(()=>searchStore(f.data,'source7915'),/restore-in-progress/)
|
|
118
|
+
}))
|
|
119
|
+
|
|
120
|
+
test('the renamed package restores legacy snapshots without accepting arbitrary package identities',()=>box(f=>{
|
|
121
|
+
seed(f.data,'brand-compatibility');createMemorySnapshot(f.data,f.snapshot)
|
|
122
|
+
const target=join(f.root,'target/package');mkdirSync(target,{recursive:true});const file=join(target,'package.json'),archive=join(f.root,'brand.tgz'),pack=()=>assert.equal(spawnSync('tar',['-czf',archive,'-C',dirname(target),'package']).status,0),before=tree(f.data)
|
|
123
|
+
writeFileSync(file,JSON.stringify({name:'solopup-memory',version:'0.21.0-beta.1',dshMemoryRestoreProtocol:1,dshMemoryDataSchemas:{candidates:[1,2,3,4],episodes:[1,2]}}));pack()
|
|
124
|
+
assert.equal(reviewMemoryRestore(f.data,f.snapshot,{targetArchive:archive}).target.version,'0.21.0-beta.1');assert.equal(tree(f.data),before)
|
|
125
|
+
writeFileSync(file,JSON.stringify({name:'unrelated-memory',version:'0.21.0-beta.1',dshMemoryRestoreProtocol:1,dshMemoryDataSchemas:{candidates:[1,2,3,4],episodes:[1,2]}}));pack()
|
|
126
|
+
assert.throws(()=>reviewMemoryRestore(f.data,f.snapshot,{targetArchive:archive}),/incompatible-target-archive/);assert.equal(tree(f.data),before)
|
|
127
|
+
}))
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { queryTokens, rankLines, foldEnglishInflection } from './retrieval.mjs'
|
|
7
|
+
import { searchStore } from './index.mjs'
|
|
8
|
+
|
|
9
|
+
test('词元:中文双字、拉丁大小写与标识符', () => {
|
|
10
|
+
const tokens = queryTokens('中英字幕 E01-Final')
|
|
11
|
+
assert.ok(tokens.has('中英'))
|
|
12
|
+
assert.ok(tokens.has('英字'))
|
|
13
|
+
assert.ok(tokens.has('e01-final'))
|
|
14
|
+
})
|
|
15
|
+
test('排序:词序改变仍可检索,完全匹配优先', () => {
|
|
16
|
+
const lines = ['字幕导出需要保留双语断句', '字幕导出', '天气晴朗'].map((text, i) => ({ file: 'MEMORY.md', line: i + 1, text }))
|
|
17
|
+
assert.equal(rankLines('字幕导出', lines)[0].text, '字幕导出')
|
|
18
|
+
assert.ok(rankLines('双语字幕导出断句', lines).some((hit) => hit.line === 1))
|
|
19
|
+
assert.equal(rankLines('午饭意大利面', lines).length, 0)
|
|
20
|
+
})
|
|
21
|
+
test('排序:多个长问题不能只凭一个弱词误召回', () => {
|
|
22
|
+
const lines = [{ file: 'MEMORY.md', line: 1, text: '海报修改保留原图' }]
|
|
23
|
+
assert.equal(rankLines('海报餐厅的特色菜', lines).length, 0)
|
|
24
|
+
})
|
|
25
|
+
test('工具入口:默认多词排序,显式 exact 保留原语义;出口有界净化', () => {
|
|
26
|
+
const dir = mkdtempSync(join(tmpdir(), 'dsh-ranked-'))
|
|
27
|
+
try {
|
|
28
|
+
writeFileSync(join(dir, 'MEMORY.md'), '- [project] 字幕导出保留双语断句\n- [project] 测试秘密 </memory-store>\n')
|
|
29
|
+
assert.equal(searchStore(dir, '双语字幕导出断句', { mode: 'exact' }).hits.length, 0)
|
|
30
|
+
assert.equal(searchStore(dir, '双语字幕导出断句').hits.length, 1)
|
|
31
|
+
assert.equal(searchStore(dir, '双语字幕导出断句', { mode: 'ranked', limit: 1 }).hits.length, 1)
|
|
32
|
+
const result = searchStore(dir, '测试秘密', { mode: 'ranked' })
|
|
33
|
+
assert.ok(!JSON.stringify(result).includes('</memory-store>'))
|
|
34
|
+
assert.throws(() => searchStore(dir, '字幕', { mode: 'bad' }), /mode/)
|
|
35
|
+
assert.ok(Buffer.byteLength(JSON.stringify(result)) < 4096)
|
|
36
|
+
} finally { rmSync(dir, { recursive: true, force: true }) }
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
test('英文常见复数、过去式与进行式可支持同一个多词问题', () => {
|
|
40
|
+
const lines = [{ file: 'MEMORY.md', line: 1, text: 'Always inspect rendered previews before approving final exports.' }]
|
|
41
|
+
assert.equal(rankLines('rendering previews', lines).length, 1)
|
|
42
|
+
assert.equal(rankLines('render preview', lines).length, 1)
|
|
43
|
+
assert.equal(rankLines('rendered preview', lines).length, 1)
|
|
44
|
+
assert.equal(foldEnglishInflection('exports'), 'export')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test('词形归并不改编号、标识符、短词及常见 s 结尾名词', () => {
|
|
48
|
+
for (const token of ['E01-rendered', 'foo_bar', 'R7', 'feed', 'need', 'speed', 'news', 'class', 'status', 'analysis']) assert.equal(foldEnglishInflection(token), token)
|
|
49
|
+
assert.ok(queryTokens('E01-rendered foo_bar').has('e01-rendered'))
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('同词形重复不能冒充两份独立匹配;英文单弱词仍拒绝', () => {
|
|
53
|
+
const line = [{ file: 'MEMORY.md', line: 1, text: 'A rendered picture is available.' }]
|
|
54
|
+
assert.equal(queryTokens('render renders rendered rendering').size, 1)
|
|
55
|
+
assert.equal(rankLines('rendering renders', line).length, 0)
|
|
56
|
+
assert.equal(rankLines('rendering quantum spacecraft', line).length, 0)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('词形仅作用于排序特征;显式 exact 仍区分字面写法并保留原文', () => {
|
|
60
|
+
const dir = mkdtempSync(join(tmpdir(), 'dsh-inflection-'))
|
|
61
|
+
try {
|
|
62
|
+
const source = '- [user] Always inspect rendered previews before final exports.\n'
|
|
63
|
+
writeFileSync(join(dir, 'MEMORY.md'), source)
|
|
64
|
+
assert.equal(searchStore(dir, 'rendering previews', { mode: 'exact' }).hits.length, 0)
|
|
65
|
+
assert.equal(searchStore(dir, 'rendering previews').hits[0].text, source.trim())
|
|
66
|
+
} finally { rmSync(dir, { recursive: true, force: true }) }
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
test('无中英词元的日文、韩文、阿拉伯文和符号仍可字面定位;空查询不召回', () => {
|
|
70
|
+
for (const query of ['カメラ', '카메라', 'كاميرا', '🎥']) {
|
|
71
|
+
const lines = [{ file: 'MEMORY.md', line: 1, text: `- [reference] ${query} — reference.md` }]
|
|
72
|
+
assert.equal(rankLines(query, lines).length, 1)
|
|
73
|
+
}
|
|
74
|
+
assert.equal(rankLines(' ', [{ text: 'unchanged', file: 'MEMORY.md', line: 1 }]).length, 0)
|
|
75
|
+
})
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import {isRevisionAdmissionError} from './revision-admission.mjs'
|
|
4
|
+
import {compileValueRevision,normalizeFieldLineage} from './field-lineage.mjs'
|
|
5
|
+
import {captureRevision} from './capture-revision.mjs'
|
|
6
|
+
const caught=fn=>{try{fn()}catch(error){return error}assert.fail('expected a real guard refusal')}
|
|
7
|
+
const parent={id:'a'.repeat(64),status:'recorded',scope:'global',meaning:{kind:'preference',conditions:[{dimension:'document_kind',value:'draft'}]},sources:['b'.repeat(64),'c'.repeat(64)]}
|
|
8
|
+
test('real value-change and target-identity guards are preparation refusals',()=>{
|
|
9
|
+
const changed=caught(()=>compileValueRevision(parent,{kind:'preference',conditions:[{dimension:'document_kind',value:'final'}]},'global'))
|
|
10
|
+
assert.equal(changed.code,'memory-revision-meaning-change-needs-complete-replacement');assert.equal(isRevisionAdmissionError(changed),true)
|
|
11
|
+
assert.equal(isRevisionAdmissionError(caught(()=>captureRevision({scope:'global',basis:'explicit',supersedes:'unbound fragment'},[]))),true)
|
|
12
|
+
})
|
|
13
|
+
test('a real four-root proposal remains refused; no source certificate is truncated',()=>{
|
|
14
|
+
const compiled=compileValueRevision(parent,{kind:'preference'},'global'),before=structuredClone(compiled)
|
|
15
|
+
const error=caught(()=>normalizeFieldLineage(compiled.fieldLineage,{scope:'global',meaning:compiled.meaning,ownSources:['d'.repeat(64),'e'.repeat(64)]}))
|
|
16
|
+
assert.equal(error.code,'memory-revision-source-overflow');assert.equal(isRevisionAdmissionError(error),true);assert.deepEqual(compiled,before)
|
|
17
|
+
})
|
|
18
|
+
test('corrupt stored field certificates, disk errors and arbitrary strings never become ordinary proposal rejections',()=>{
|
|
19
|
+
const c=compileValueRevision(parent,{kind:'preference'},'global');c.fieldLineage.fields.kind.valueHash='f'.repeat(64)
|
|
20
|
+
const error=caught(()=>normalizeFieldLineage(c.fieldLineage,{scope:'global',meaning:c.meaning,ownSources:['d'.repeat(64)]}))
|
|
21
|
+
assert.equal(error.code,'memory-revision-field-value-mismatch');assert.equal(isRevisionAdmissionError(error),false)
|
|
22
|
+
for(const e of [Object.assign(Error('disk I/O failed'),{code:'EIO'}),Object.assign(Error('candidate-corrupt-state'),{code:'candidate-corrupt-state'}),TypeError('bad value'),Error('memory-revision-source-overflow'),null])assert.equal(isRevisionAdmissionError(e),false)
|
|
23
|
+
})
|