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,76 @@
|
|
|
1
|
+
import {test} from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import {mkdtempSync,readFileSync,rmSync} from 'node:fs'
|
|
4
|
+
import {tmpdir} from 'node:os'
|
|
5
|
+
import {join} from 'node:path'
|
|
6
|
+
import {runCandidateValidation} from './capture-validation-job.mjs'
|
|
7
|
+
import {VALIDATION_FIELDS} from './capture-validation-contract.mjs'
|
|
8
|
+
import {listCaptureJobs,claimCaptureJob,finishCaptureJob,captureJobStatus} from './capture-jobs.mjs'
|
|
9
|
+
import {buildCaptureDiagnostic} from './capture-diagnostics.mjs'
|
|
10
|
+
import {writeFileSync} from 'node:fs'
|
|
11
|
+
import {spawn,spawnSync} from 'node:child_process'
|
|
12
|
+
import {existsSync} from 'node:fs'
|
|
13
|
+
const message={id:'synthetic-owner',role:'user',text:'我处理评审反馈时始终先看两处问题,再看修改办法,跨项目通用。'}
|
|
14
|
+
const candidate={type:'user',scope:'global',basis:'explicit',summary:'处理反馈时先看两处问题再给办法,跨项目通用',meaning:{kind:'preference',conditions:[{dimension:'task',value:'review'}]},evidence:[{messageId:message.id,quote:message.text}]}
|
|
15
|
+
const result=(request,status)=>JSON.stringify({checks:JSON.parse(request.messages[0].content[0].text).candidates.map(r=>({candidateId:r.candidateId,fields:Object.fromEntries(VALIDATION_FIELDS.map(f=>[f,status])),evidence:status==='uncertain'?[]:[{messageId:message.id,quote:message.text}]}))})
|
|
16
|
+
async function box(fn){const dir=mkdtempSync(join(tmpdir(),'dsh-validator-job-'));try{await fn(dir)}finally{rmSync(dir,{recursive:true,force:true})}}
|
|
17
|
+
test('separate durable invocation approves an unchanged candidate once, and no bodies enter the call ledger',()=>box(async dir=>{
|
|
18
|
+
let calls=0,guards=0
|
|
19
|
+
const llm={async prepareCall(config){return{config,async*stream(req){calls++;yield{type:'text-delta',text:result(req,'supported')};yield{type:'finish',reason:{kind:'stop'}}}}}}
|
|
20
|
+
const opts={jobDir:dir,parentId:'a'.repeat(64),llm,messages:[message],candidates:[candidate],sessionId:'synthetic',route:{provider:'fixture',model:'fixture'},assertCurrent(){guards++}}
|
|
21
|
+
const first=await runCandidateValidation(opts);assert.equal(first.verdicts[0].status,'approved');assert.equal(calls,1);assert.ok(guards>=2)
|
|
22
|
+
const again=await runCandidateValidation(opts);assert.equal(again.reason,'previous-invocation');assert.equal(calls,1)
|
|
23
|
+
const raw=readFileSync(join(dir,'.capture-jobs.json'),'utf8');assert.ok(!raw.includes(candidate.summary));assert.ok(!raw.includes(message.text));assert.equal(listCaptureJobs(dir).jobs.length,1)
|
|
24
|
+
}))
|
|
25
|
+
test('bad validation protocol is settled as failed and never resent; it cannot implicitly approve',()=>box(async dir=>{
|
|
26
|
+
let calls=0;const llm={async prepareCall(config){return{config,async*stream(){calls++;yield{type:'text-delta',text:'{"checks":[]}'};yield{type:'finish',reason:{kind:'stop'}}}}}}
|
|
27
|
+
const opts={jobDir:dir,parentId:'b'.repeat(64),llm,messages:[message],candidates:[candidate],sessionId:'synthetic'}
|
|
28
|
+
const first=await runCandidateValidation(opts);assert.equal(first.reason,'capture-invalid-envelope');assert.deepEqual(first.verdicts,[]);assert.equal(listCaptureJobs(dir).jobs[0].status,'failed')
|
|
29
|
+
await runCandidateValidation(opts);assert.equal(calls,1)
|
|
30
|
+
}))
|
|
31
|
+
test('late ignored cancellation has no approval and the same validation is not retried',()=>box(async dir=>{
|
|
32
|
+
let calls=0;const llm={async prepareCall(config){return{config,async*stream(req){calls++;await new Promise(r=>setTimeout(r,60));yield{type:'text-delta',text:result(req,'supported')};yield{type:'finish',reason:{kind:'stop'}}}}}}
|
|
33
|
+
const opts={jobDir:dir,parentId:'c'.repeat(64),llm,messages:[message],candidates:[candidate],sessionId:'synthetic',timeoutMs:15}
|
|
34
|
+
const first=await runCandidateValidation(opts);assert.equal(first.reason,'capture-timeout');assert.deepEqual(first.verdicts,[])
|
|
35
|
+
await new Promise(r=>setTimeout(r,80));const again=await runCandidateValidation(opts);assert.equal(again.reason,'previous-invocation');assert.equal(calls,1)
|
|
36
|
+
}))
|
|
37
|
+
test('a source/revision change during validation propagates and prevents a publishable approval',()=>box(async dir=>{
|
|
38
|
+
let changed=false,calls=0
|
|
39
|
+
const llm={async prepareCall(config){return{config,async*stream(req){calls++;changed=true;yield{type:'text-delta',text:result(req,'supported')};yield{type:'finish',reason:{kind:'stop'}}}}}}
|
|
40
|
+
await assert.rejects(runCandidateValidation({jobDir:dir,parentId:'d'.repeat(64),llm,messages:[message],candidates:[candidate],sessionId:'synthetic',assertCurrent(){if(changed)throw Error('capture-input-source-changed')}}),/source-changed/)
|
|
41
|
+
assert.equal(calls,1);assert.equal(listCaptureJobs(dir).jobs[0].status,'failed')
|
|
42
|
+
}))
|
|
43
|
+
test('SIGKILL after a validation invocation is claimed cannot resend that child from a new process',()=>box(async dir=>{
|
|
44
|
+
const marker=join(dir,'invocation-started'),moduleUrl=new URL('./capture-validation-job.mjs',import.meta.url).href
|
|
45
|
+
const opts={jobDir:dir,parentId:'e'.repeat(64),messages:[message],candidates:[candidate],sessionId:'synthetic-crash',timeoutMs:5000}
|
|
46
|
+
const script=`import{runCandidateValidation}from${JSON.stringify(moduleUrl)};import{writeFileSync}from'node:fs';let calls=0;let ticker;const opts=${JSON.stringify(opts)};opts.llm={async prepareCall(config){return{config,async*stream(){calls++;writeFileSync(${JSON.stringify(marker)},'started');if(process.argv[1]==='issue'){ticker=setInterval(()=>{},1000);await new Promise(()=>{})}yield{type:'text-delta',text:'{"checks":[]}'};yield{type:'finish',reason:{kind:'stop'}}}}}};const r=await runCandidateValidation(opts);clearInterval(ticker);console.log(JSON.stringify({calls,reason:r.reason}));`
|
|
47
|
+
const child=spawn(process.execPath,['--input-type=module','-e',script,'issue'],{stdio:['ignore','pipe','pipe']})
|
|
48
|
+
try{
|
|
49
|
+
const until=Date.now()+4000;while(!existsSync(marker)&&Date.now()<until&&child.exitCode===null)await new Promise(r=>setTimeout(r,10))
|
|
50
|
+
assert.ok(existsSync(marker));const done=new Promise(r=>child.once('exit',r));child.kill('SIGKILL');await done
|
|
51
|
+
assert.equal(child.signalCode,'SIGKILL');assert.equal(listCaptureJobs(dir).jobs.length,1)
|
|
52
|
+
const resumed=spawnSync(process.execPath,['--input-type=module','-e',script,'resume'],{encoding:'utf8',timeout:4000});assert.equal(resumed.status,0,resumed.stderr)
|
|
53
|
+
assert.deepEqual(JSON.parse(resumed.stdout),{calls:0,reason:'previous-invocation'});assert.equal(listCaptureJobs(dir).jobs.length,1)
|
|
54
|
+
}finally{if(child.exitCode===null&&child.signalCode===null)child.kill('SIGKILL')}
|
|
55
|
+
}))
|
|
56
|
+
|
|
57
|
+
test('same-millisecond child completion cannot hide its substantive parent capture status',()=>box(async dir=>{
|
|
58
|
+
const parent=claimCaptureJob(dir,'f'.repeat(64),{now:1000,leaseMs:1000}),child=claimCaptureJob(dir,'0'.repeat(64),{now:1010,leaseMs:1000})
|
|
59
|
+
const noop=buildCaptureDiagnostic({responseItems:0,parsedItems:0,parserRejected:0,deferred:0,wrapped:false,codes:[]})
|
|
60
|
+
finishCaptureJob(dir,child,{outcome:'ok',counts:{proposed:0,inserted:0,staged:0,rejected:0},diagnostic:noop},{now:1020})
|
|
61
|
+
const recorded=buildCaptureDiagnostic({responseItems:1,parsedItems:1,parserRejected:0,deferred:0,wrapped:false,codes:[]},{inserted:1})
|
|
62
|
+
finishCaptureJob(dir,parent,{outcome:'ok',counts:{proposed:1,inserted:1,staged:0,rejected:0},diagnostic:recorded},{now:1020})
|
|
63
|
+
assert.equal(captureJobStatus(dir).latest.jobId,parent.id);assert.equal(captureJobStatus(dir).latest.diagnostic.classification,'recorded')
|
|
64
|
+
}))
|
|
65
|
+
test('transient local source-check contention retries the read without replaying the model invocation',()=>box(async dir=>{
|
|
66
|
+
let reads=0,calls=0,linked=false
|
|
67
|
+
const llm={async prepareCall(config){return{config,async*stream(req){assert.equal(linked,true);calls++;yield{type:'text-delta',text:result(req,'supported')};yield{type:'finish',reason:{kind:'stop'}}}}}}
|
|
68
|
+
const out=await runCandidateValidation({jobDir:dir,parentId:'1'.repeat(64),llm,messages:[message],candidates:[candidate],sessionId:'synthetic',onClaim(){linked=true},assertCurrent(){if(++reads===1){const error=Error('synthetic local contention');error.code='memory-lock-busy';throw error}}})
|
|
69
|
+
assert.equal(calls,1);assert.equal(out.verdicts[0].status,'approved');assert.ok(reads>=3)
|
|
70
|
+
}))
|
|
71
|
+
test('a busy completion ledger retries only metadata persistence, never the settled validation call',()=>box(async dir=>{
|
|
72
|
+
let calls=0,timer;const lock=join(dir,'.write.lock')
|
|
73
|
+
const llm={async prepareCall(config){return{config,async*stream(req){calls++;writeFileSync(lock,JSON.stringify({pid:process.pid,token:'synthetic-lock'}));timer=setTimeout(()=>rmSync(lock,{force:true}),40);yield{type:'text-delta',text:result(req,'supported')};yield{type:'finish',reason:{kind:'stop'}}}}}}
|
|
74
|
+
try{const out=await runCandidateValidation({jobDir:dir,parentId:'2'.repeat(64),llm,messages:[message],candidates:[candidate],sessionId:'synthetic'});assert.equal(calls,1);assert.equal(out.verdicts[0].status,'approved');assert.equal(listCaptureJobs(dir).jobs[0].status,'succeeded')}
|
|
75
|
+
finally{clearTimeout(timer);rmSync(lock,{force:true})}
|
|
76
|
+
}))
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {VALIDATION_FIELDS} from './capture-validation-contract.mjs'
|
|
2
|
+
/** Scripted pipeline regression; optional source override reproduces the frozen dev28 bug. */
|
|
3
|
+
import {test} from 'node:test'
|
|
4
|
+
import assert from 'node:assert/strict'
|
|
5
|
+
import {mkdtempSync,realpathSync,mkdirSync,readFileSync,rmSync} from 'node:fs'
|
|
6
|
+
import {join,resolve} from 'node:path'
|
|
7
|
+
import {tmpdir} from 'node:os'
|
|
8
|
+
import {pathToFileURL} from 'node:url'
|
|
9
|
+
const baseUrl=process.env.DSH_VALIDATION_LINEAGE_SOURCE?pathToFileURL(resolve(process.env.DSH_VALIDATION_LINEAGE_SOURCE)+'/'):new URL('./',import.meta.url)
|
|
10
|
+
const {apply,withdrawManagedSource,searchStore}=await import(new URL('index.mjs',baseUrl))
|
|
11
|
+
const {candidateSnapshot}=await import(new URL('candidates.mjs',baseUrl))
|
|
12
|
+
const {writeFixtureMemory}=await import(new URL('fixture-host.mjs',baseUrl))
|
|
13
|
+
test('every extra owner source used to approve a candidate remains a withdrawal root of the published memory',async()=>{
|
|
14
|
+
const base=realpathSync(mkdtempSync(join(tmpdir(),'dsh-validator-roots-'))),home=join(base,'home'),cwd=join(base,'project'),root=join(home,'memory'),oldHome=process.env.DSH_HOME
|
|
15
|
+
mkdirSync(home);mkdirSync(cwd);process.env.DSH_HOME=home
|
|
16
|
+
try{
|
|
17
|
+
const handlers=[],session={id:'synthetic-validation-extra-root'};let extraSourceId
|
|
18
|
+
const llm={async listProviders(){return[{provider:'fixture',model:'fixture'}]},async prepareCall(config){return{config,async*stream(req){
|
|
19
|
+
if(req.purpose==='memory-validation'){
|
|
20
|
+
const data=JSON.parse(req.messages[0].content[0].text),users=data.ownerMessages;assert.equal(users.length,2);extraSourceId=users[1].id
|
|
21
|
+
yield{type:'text-delta',text:JSON.stringify({checks:data.candidates.map(c=>({candidateId:c.candidateId,fields:Object.fromEntries(VALIDATION_FIELDS.map(k=>[k,'supported'])),evidence:users.map(m=>({messageId:m.id,quote:m.text}))}))})};yield{type:'finish',reason:{kind:'stop'}};return
|
|
22
|
+
}
|
|
23
|
+
const users=req.messages[0].content[0].text.split('\n').flatMap(line=>{try{const x=JSON.parse(line);return x.role==='user'?[x]:[]}catch{return[]}})
|
|
24
|
+
yield{type:'text-delta',text:JSON.stringify([{type:'user',scope:'global',basis:'explicit',summary:'sourceMergeSentinel:跨项目反馈先两处问题再给办法',meaning:{kind:'preference',conditions:[{dimension:'task',value:'review'}]},evidence:[{messageId:users[0].id,quote:users[0].text}]}])};yield{type:'finish',reason:{kind:'stop'}}
|
|
25
|
+
}}}}
|
|
26
|
+
apply({llm,systemPrompt:{context(){}},workingDirectory:{get(){return cwd}},tools:{register(){}},on(name,fn){handlers.push([name,fn])}},{autoCapture:{everyTurns:2}})
|
|
27
|
+
const emit=e=>{for(const[name,fn]of handlers)if(name==='session/event')fn(session,e)}
|
|
28
|
+
for(const text of ['我在这个项目处理反馈时先看最重要的两处问题,再看怎么改。','补充归属:这个反馈顺序跨我的所有项目都一样,是长期约定。'])emit({type:'user/message',data:{message:{source:{kind:'user'},content:[{type:'text',text}]}}})
|
|
29
|
+
emit({type:'step/end',data:{}})
|
|
30
|
+
let state;const until=Date.now()+5000;while(Date.now()<until){try{state=JSON.parse(readFileSync(join(root,'.capture-state.json')))}catch{}if(state?.lastCaptureAt&&!state.running)break;await new Promise(r=>setTimeout(r,20))}
|
|
31
|
+
assert.equal(state?.lastOutcome,'ok');assert.equal(state?.diagnostic.classification,'recorded')
|
|
32
|
+
const published=candidateSnapshot(root,'global').records.find(r=>r.status==='recorded'&&r.summary.includes('sourceMergeSentinel'))
|
|
33
|
+
assert.equal(published.evidence.length,2,'Approval must not discard the additional source authorizing global scope')
|
|
34
|
+
assert.ok(published.evidence.some(e=>e.messageId===extraSourceId))
|
|
35
|
+
writeFixtureMemory({dir:root,type:'user',scope:'global',summary:'independentRootSentinel:另一个独立来源要求长期答复简洁',meaning:{kind:'preference'}})
|
|
36
|
+
const preview=withdrawManagedSource(root,session.id,extraSourceId);withdrawManagedSource(root,session.id,extraSourceId,{apply:true,controlReview:preview.controlReview})
|
|
37
|
+
assert.equal(searchStore(root,'sourceMergeSentinel',{mode:'exact'}).hits.length,0)
|
|
38
|
+
assert.ok(searchStore(root,'independentRootSentinel',{mode:'exact'}).hits.length>0)
|
|
39
|
+
}finally{if(oldHome===undefined)delete process.env.DSH_HOME;else process.env.DSH_HOME=oldHome;rmSync(base,{recursive:true,force:true})}
|
|
40
|
+
})
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import {test} from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import {prepareValidationPrompt,ValidationSubmission,validateCandidatesWithLlm,validationCandidateId} from './capture-validation.mjs'
|
|
4
|
+
import {VALIDATION_FIELDS,VALIDATION_NAME} from './capture-validation-contract.mjs'
|
|
5
|
+
const message={id:'owner-1',role:'user',text:'我在所有项目处理反馈时都先看最重要的两处问题,然后再看怎么改。'}
|
|
6
|
+
const candidate={type:'user',scope:'global',basis:'explicit',summary:'处理反馈先看两处问题再给修改办法,跨项目通用',meaning:{kind:'preference',conditions:[{dimension:'task',value:'review'}]},evidence:[{messageId:message.id,quote:message.text}]}
|
|
7
|
+
const prepared=()=>prepareValidationPrompt([message],[candidate])
|
|
8
|
+
const check=(status='supported')=>({candidateId:validationCandidateId(candidate),fields:Object.fromEntries(VALIDATION_FIELDS.map(f=>[f,status])),evidence:status==='uncertain'?[]:[{messageId:message.id,quote:message.text}]})
|
|
9
|
+
const parse=p=>new ValidationSubmission(prepared()).batch(JSON.stringify(p),3)
|
|
10
|
+
test('source validator can only approve, reject or abstain on the exact whole candidate',()=>{
|
|
11
|
+
assert.equal(parse({checks:[check()]}).verdicts[0].status,'approved')
|
|
12
|
+
assert.equal(parse({checks:[check('unsupported')]}).verdicts[0].status,'rejected')
|
|
13
|
+
assert.equal(parse({checks:[check('uncertain')]}).verdicts[0].status,'uncertain')
|
|
14
|
+
for(const p of [{checks:[check()],entries:[candidate]},{checks:[{...check(),replacement:candidate}]}])assert.throws(()=>parse(p),/invalid-envelope/)
|
|
15
|
+
const c={...candidate,detail:'An added requirement changes the validation identity.'};assert.notEqual(validationCandidateId(c),validationCandidateId(candidate))
|
|
16
|
+
assert.equal(validationCandidateId({...candidate,meaning:{conditions:candidate.meaning.conditions,kind:'preference'}}),validationCandidateId(candidate))
|
|
17
|
+
})
|
|
18
|
+
test('missing, repeated and forged identities cannot approve unchecked candidates',()=>{
|
|
19
|
+
for(const checks of [[],[check(),check()],[{...check(),candidateId:'b'.repeat(64)}]])assert.throws(()=>parse({checks}),/invalid-envelope/)
|
|
20
|
+
})
|
|
21
|
+
test('support must cite all current owner sources; assistant, old, invented and altered quotes fail',()=>{
|
|
22
|
+
for(const e of [{messageId:'old',quote:message.text},{messageId:message.id,quote:'不曾出现的另一段合成用户原话'},{messageId:message.id,quote:'短'}])assert.throws(()=>parse({checks:[{...check(),evidence:[e]}]}),/invalid-envelope/)
|
|
23
|
+
assert.throws(()=>parse({checks:[{...check(),evidence:[]}]}),/invalid-envelope/)
|
|
24
|
+
const other={id:'owner-2',role:'user',text:'这段独立的当前消息提供另一条合成来源用于测试引用覆盖。'},c={...candidate,evidence:[...candidate.evidence,{messageId:other.id,quote:other.text}]},p=prepareValidationPrompt([message,other],[c])
|
|
25
|
+
assert.throws(()=>new ValidationSubmission(p).batch(JSON.stringify({checks:[{...check(),candidateId:validationCandidateId(c)}]})),/invalid-envelope/)
|
|
26
|
+
})
|
|
27
|
+
test('bounded input never splits candidate fields or includes assistant testimony as owner evidence',()=>{
|
|
28
|
+
const large={...candidate,detail:'長'.repeat(4000)}
|
|
29
|
+
for(const limit of [1024,2048,24576,65536]){
|
|
30
|
+
const p=prepareValidationPrompt([message,{id:'assistant',role:'assistant',text:'Invented assistant requirement'}],[candidate,large],limit),data=JSON.parse(p.text)
|
|
31
|
+
assert.ok(Buffer.byteLength(p.text)<=limit);assert.equal(data.candidates.length,p.records.length);assert.ok(!p.text.includes('Invented assistant requirement'));assert.ok(p.records.every(r=>r.candidateId===validationCandidateId(r.value)))
|
|
32
|
+
}
|
|
33
|
+
})
|
|
34
|
+
test('a separate native data tool settles once and cannot return rewritten fields',async()=>{
|
|
35
|
+
let calls=0
|
|
36
|
+
const llm={async prepareCall(config){return{config,async*stream(req){calls++;assert.equal(req.purpose,'memory-validation');assert.equal(req.tools[0].name,VALIDATION_NAME);const args=JSON.stringify({checks:[check()]});yield{type:'block-start',index:0,blockType:'tool-call'};yield{type:'block-end',index:0,block:{type:'tool-call',id:'synthetic',name:VALIDATION_NAME,arguments:args}};yield{type:'finish',reason:{kind:'tool-calls'}}}}}}
|
|
37
|
+
const out=await validateCandidatesWithLlm({llm,messages:[message],candidates:[candidate],sessionId:'fixture',timeoutMs:1000});assert.equal(calls,1);assert.equal(out.verdicts[0].status,'approved')
|
|
38
|
+
})
|
|
39
|
+
test('no whole candidate fits means no model call, not implicit approval',async()=>{
|
|
40
|
+
let calls=0;const out=await validateCandidatesWithLlm({llm:{prepareCall(){calls++}},messages:[message],candidates:[{...candidate,detail:'長'.repeat(4000)}],maxInputBytes:1024})
|
|
41
|
+
assert.equal(calls,0);assert.equal(out.shown,0);assert.equal(out.omitted,1);assert.deepEqual(out.verdicts,[])
|
|
42
|
+
})
|
|
43
|
+
test('a delayed asynchronous pre-dispatch guard cannot issue a model stream after timeout',async()=>{
|
|
44
|
+
let streams=0
|
|
45
|
+
const llm={async prepareCall(config){return{config,async*stream(){streams++;yield{type:'text-delta',text:'{"checks":[]}'};yield{type:'finish',reason:{kind:'stop'}}}}}}
|
|
46
|
+
await assert.rejects(validateCandidatesWithLlm({llm,messages:[message],candidates:[candidate],timeoutMs:15,beforeStream:async()=>{await new Promise(r=>setTimeout(r,60))}}),/capture-timeout/)
|
|
47
|
+
await new Promise(r=>setTimeout(r,80));assert.equal(streams,0)
|
|
48
|
+
})
|
|
49
|
+
const prior=(patch={})=>({id:'a'.repeat(64),status:'recorded',scope:'global',type:'user',summary:'所有项目仅初稿默认标记橄榄色',indexLine:'- [user] 所有项目仅初稿默认标记橄榄色 — 索引摘要',meaning:{kind:'preference',conditions:[{dimension:'document_kind',value:'draft'}]},expires:'2030-04-05',...patch})
|
|
50
|
+
test('transition context is separate from candidate identity and never displaces owner testimony',()=>{
|
|
51
|
+
const rows=[prior(),prior({id:'b'.repeat(64),scope:'project',summary:'PRIVATE_PROJECT_SENTINEL'})]
|
|
52
|
+
for(const bytes of [1024,2048,4096,24576]){
|
|
53
|
+
const before=prepareValidationPrompt([message],[candidate],bytes),after=prepareValidationPrompt([message],[candidate],bytes,8,rows),data=JSON.parse(after.text)
|
|
54
|
+
assert.deepEqual(after.messages,before.messages);assert.deepEqual(after.records,before.records);assert.ok(Buffer.byteLength(after.text)<=bytes)
|
|
55
|
+
assert.equal(data.currentMemorySummary.provided,true);assert.doesNotMatch(after.text,/PRIVATE_PROJECT_SENTINEL/)
|
|
56
|
+
assert.ok(data.currentMemory.length+data.currentMemorySummary.omittedContexts===after.records.length)
|
|
57
|
+
}
|
|
58
|
+
const data=JSON.parse(prepareValidationPrompt([message],[candidate],24576,8,rows).text)
|
|
59
|
+
assert.equal(data.currentMemory[0].records[0].expires,'2030-04-05');assert.equal(data.currentMemory[0].records[0].recordId,rows[0].id)
|
|
60
|
+
})
|
|
61
|
+
test('unknown context, explicitly empty context and omitted context have different representations',()=>{
|
|
62
|
+
const unknown=JSON.parse(prepared().text),empty=JSON.parse(prepareValidationPrompt([message],[candidate],24576,8,[]).text)
|
|
63
|
+
assert.equal(unknown.currentMemorySummary.provided,false);assert.equal(unknown.currentMemory.length,0)
|
|
64
|
+
assert.equal(empty.currentMemorySummary.provided,true);assert.equal(empty.currentMemory[0].omittedRecords,0);assert.equal(empty.currentMemory[0].records.length,0)
|
|
65
|
+
assert.throws(()=>prepareValidationPrompt([message],[candidate],24576,8,{}),/context-invalid/)
|
|
66
|
+
})
|
|
67
|
+
test('shown old interpretation is not admissible as new owner evidence or a rewritten candidate',()=>{
|
|
68
|
+
const row=prior(),p=prepareValidationPrompt([message],[candidate],24576,8,[row]),c=check()
|
|
69
|
+
assert.throws(()=>new ValidationSubmission(p).batch(JSON.stringify({checks:[{...c,evidence:[{messageId:row.id,quote:row.summary}]}]})),/invalid-envelope/)
|
|
70
|
+
assert.throws(()=>new ValidationSubmission(p).batch(JSON.stringify({checks:[{...c,currentMemory:[]}]})),/invalid-envelope/)
|
|
71
|
+
})
|
|
72
|
+
test('rejected dimensions are fixed field names and cannot carry rewritten instructions',()=>{
|
|
73
|
+
const c=check();c.fields.transition='unsupported';c.fields.wording='uncertain'
|
|
74
|
+
const v=parse({checks:[c]}).verdicts[0];assert.equal(v.status,'rejected');assert.deepEqual(v.unsupportedFields,['transition']);assert.deepEqual(v.uncertainFields,['wording'])
|
|
75
|
+
assert.equal(parse({checks:[check()]}).verdicts[0].unsupportedFields,undefined)
|
|
76
|
+
assert.throws(()=>parse({checks:[{...c,fields:{...c.fields,transition:'改写为另一条'}}]}),/invalid-envelope/)
|
|
77
|
+
})
|
|
78
|
+
test('a supported model vote cannot approve an explicitly unshown revision target',()=>{
|
|
79
|
+
const c={...candidate,supersedes:prior().indexLine},p=prepareValidationPrompt([message],[c],24576,8,[])
|
|
80
|
+
const v=new ValidationSubmission(p).batch(JSON.stringify({checks:[{...check(),candidateId:validationCandidateId(c)}]})).verdicts[0]
|
|
81
|
+
assert.equal(v.status,'uncertain');assert.deepEqual(v.uncertainFields,['transition'])
|
|
82
|
+
const shown=prepareValidationPrompt([message],[c],24576,8,[prior()])
|
|
83
|
+
assert.equal(new ValidationSubmission(shown).batch(JSON.stringify({checks:[{...check(),candidateId:validationCandidateId(c)}]})).verdicts[0].status,'approved')
|
|
84
|
+
})
|