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,154 @@
|
|
|
1
|
+
/** Synthetic, scripted transport tests; no claim of real-model semantic quality. */
|
|
2
|
+
import test from 'node:test'
|
|
3
|
+
import assert from 'node:assert/strict'
|
|
4
|
+
import {mkdtempSync,realpathSync,mkdirSync,rmSync,readFileSync,existsSync} from 'node:fs'
|
|
5
|
+
import {tmpdir} from 'node:os'
|
|
6
|
+
import {join} from 'node:path'
|
|
7
|
+
import {apply,storeDirFor,searchStore,withdrawManagedSource} from './index.mjs'
|
|
8
|
+
import {candidateSnapshot} from './candidates.mjs'
|
|
9
|
+
import {VALIDATION_FIELDS} from './capture-validation-contract.mjs'
|
|
10
|
+
import {writeFixtureMemory} from './fixture-host.mjs'
|
|
11
|
+
const proposal={type:'user',scope:'global',summary:'长期反馈先列两处问题再给办法',meaning:{kind:'preference',conditions:[{dimension:'task',value:'review'}]}}
|
|
12
|
+
const text='跨我的所有项目,长期反馈都先列两处问题再给修改办法。'
|
|
13
|
+
async function box(options,run){
|
|
14
|
+
if(typeof options==='function'){run=options;options={}}
|
|
15
|
+
const base=realpathSync(mkdtempSync(join(tmpdir(),'native-validator-'))),home=join(base,'home'),old=process.env.DSH_HOME
|
|
16
|
+
mkdirSync(home);process.env.DSH_HOME=home
|
|
17
|
+
const root=join(home,'memory'),handlers=[],tools=[],effects=[],requests=[],session={id:'synthetic-native-validator'}
|
|
18
|
+
let seq=0,turn=0,cwd=join(base,'project-a'),f;mkdirSync(cwd)
|
|
19
|
+
const llm={async prepareCall(config){await options.beforePrepare?.(f);return{config,async*stream(req){
|
|
20
|
+
requests.push(req);assert.equal(req.purpose,'memory-validation');const input=JSON.parse(req.messages[0].content[0].text)
|
|
21
|
+
await options.duringStream?.(f,input)
|
|
22
|
+
const state=options.state??'supported',checks=input.candidates.map(r=>({candidateId:r.candidateId,fields:Object.fromEntries(VALIDATION_FIELDS.map(k=>[k,options.fields?.[k]??state])),evidence:state==='uncertain'?[]:options.evidence?options.evidence(input):r.value.evidence.map(({messageId,quote})=>({messageId,quote}))}))
|
|
23
|
+
if(options.rewrite)checks[0].summary='伪造改写'
|
|
24
|
+
yield{type:'text-delta',text:JSON.stringify({checks})};yield{type:'finish',reason:{kind:'stop'}}
|
|
25
|
+
}}}}
|
|
26
|
+
const ctx={...options.offline?{}:{llm},systemPrompt:{context(){}},workingDirectory:{get:()=>cwd},tools:{register:t=>tools.push(t)},on:(name,fn)=>handlers.push([name,fn]),effect:fn=>{const dispose=fn();if(typeof dispose==='function')effects.push(dispose)}}
|
|
27
|
+
const agent={session,options:{provider:'fixture',model:'fixture'}},emit=(name,...args)=>{for(const[event,fn]of handlers)if(event===name)fn(...args)}
|
|
28
|
+
apply(ctx,{autoCapture:{enabled:false,timeoutMs:options.timeoutMs??2000}})
|
|
29
|
+
const tool=tools.find(t=>t.name==='memory_write')
|
|
30
|
+
f={base,root,session,agent,ctx,requests,tool,effects,emit,
|
|
31
|
+
cwd(value){if(value===undefined)return cwd;cwd=value;mkdirSync(cwd,{recursive:true})},
|
|
32
|
+
owner(value=text,{queued=false}={}){const message={id:'owner-'+(++seq),role:'user',source:{kind:'user'},content:[{type:'text',text:value}]};if(!queued)emit('agent/pre-step',{agent,turn:++turn,step:1,messages:[message]},()=>{});emit('session/event',session,{type:'user/message',seq,data:message});return session.id+':'+seq},
|
|
33
|
+
call(id='native-'+(++seq)){emit('session/event',session,{type:'tool/call',seq:++seq,data:{callId:id,name:'memory_write',arguments:'{}',turn,step:1}});return{agent,callId:id}},
|
|
34
|
+
records:()=>candidateSnapshot(root,'global').records,
|
|
35
|
+
rendered:value=>tool.output.render({},value).map(b=>b.text).join('\n')}
|
|
36
|
+
try{return await run(f)}finally{for(const dispose of effects)dispose();if(old===undefined)delete process.env.DSH_HOME;else process.env.DSH_HOME=old;rmSync(base,{recursive:true,force:true})}
|
|
37
|
+
}
|
|
38
|
+
test('native approval publishes the unchanged typed candidate; exact replay is an explicit no-op',()=>box(async f=>{
|
|
39
|
+
f.owner();const exec=f.call(),result=await f.tool.execute(proposal,exec)
|
|
40
|
+
assert.equal(result.status,'recorded');assert.equal(f.records()[0].summary,proposal.summary);assert.equal(f.requests.length,1)
|
|
41
|
+
assert.equal((await f.tool.execute(proposal,exec)).status,'duplicate');assert.equal(f.requests.length,1)
|
|
42
|
+
}))
|
|
43
|
+
test('definite rejection leaves no current or pending memory and does not render success',()=>box({state:'unsupported'},async f=>{
|
|
44
|
+
f.owner();const result=await f.tool.execute(proposal,f.call());assert.equal(result.status,'rejected');assert.equal(f.records().length,0);assert.doesNotMatch(f.rendered(result),/已写入/);assert.equal(searchStore(f.root,'长期反馈').hits.length,0)
|
|
45
|
+
}))
|
|
46
|
+
for(const mode of ['uncertain','offline','rewrite'])test(mode+' retains only a non-injected fresh pending candidate',()=>box({state:mode==='uncertain'?'uncertain':'supported',offline:mode==='offline',rewrite:mode==='rewrite'},async f=>{
|
|
47
|
+
f.owner();const result=await f.tool.execute(proposal,f.call());assert.equal(result.status,'pending-review');assert.equal(f.records()[0].status,'pending');assert.equal(f.records()[0].summary,proposal.summary);assert.equal(searchStore(f.root,'长期反馈').hits.length,0);assert.doesNotMatch(f.rendered(result),/已写入/)
|
|
48
|
+
}))
|
|
49
|
+
test('a real short owner source uses minimumQuoteLength=1 without weakening the pending inbox',()=>box(async f=>{
|
|
50
|
+
f.owner('记住红色');const result=await f.tool.execute({...proposal,summary:'长期偏好红色',meaning:{kind:'preference'}},f.call());assert.equal(result.status,'recorded');assert.equal(f.records()[0].evidence[0].quote,'记住红色');assert.equal(JSON.parse(f.requests[0].messages[0].content[0].text).minimumQuoteLength,1)
|
|
51
|
+
}))
|
|
52
|
+
test('offline short sources cannot become source-free or schema-weakened pending memory',()=>box({offline:true},async f=>{
|
|
53
|
+
f.owner('记住红色');const result=await f.tool.execute(proposal,f.call());assert.equal(result.status,'not-applied');assert.equal(result.reason,'pending-source-too-short');assert.equal(f.records().length,0)
|
|
54
|
+
}))
|
|
55
|
+
test('all additional same-project owner citations remain roots of a native accepted memory',()=>box({evidence:input=>input.ownerMessages.map(m=>({messageId:m.id,quote:m.text}))},async f=>{
|
|
56
|
+
const older=f.owner('反馈顺序是先两处问题,再说修改办法。');f.owner('这个顺序是跨项目的长期约定。');await f.tool.execute(proposal,f.call())
|
|
57
|
+
const record=f.records().find(r=>r.status==='recorded');assert.equal(record.evidence.length,2);assert.ok(record.evidence.some(e=>e.messageId===older))
|
|
58
|
+
const plan=withdrawManagedSource(f.root,f.session.id,older);withdrawManagedSource(f.root,f.session.id,older,{apply:true,controlReview:plan.controlReview});assert.equal(searchStore(f.root,'长期反馈').hits.length,0)
|
|
59
|
+
}))
|
|
60
|
+
test('another project, queued input, and later input are excluded from native validation history',()=>box(async f=>{
|
|
61
|
+
f.owner('Earlier project-specific owner source must stay in project A.');f.cwd(join(f.base,'project-b'))
|
|
62
|
+
f.owner('This queued input has not been admitted to the agent.',{queued:true});const current=f.owner();const exec=f.call();f.owner('This later input cannot support the earlier call.',{queued:true})
|
|
63
|
+
await f.tool.execute(proposal,exec);const input=JSON.parse(f.requests[0].messages[0].content[0].text);assert.deepEqual(input.ownerMessages.map(m=>m.id),[current])
|
|
64
|
+
}))
|
|
65
|
+
test('a claimed native call cannot resend validation by changing candidate arguments',()=>box({state:'uncertain'},async f=>{
|
|
66
|
+
f.owner();const exec=f.call();await f.tool.execute(proposal,exec);const next=await f.tool.execute({...proposal,summary:'改变候选参数也不能重发同一调用'},exec);assert.equal(next.status,'pending-review');assert.equal(next.reason,'previous-invocation');assert.equal(f.requests.length,1);assert.equal(f.records().some(r=>r.status==='recorded'),false)
|
|
67
|
+
}))
|
|
68
|
+
for(const mode of ['cwd','route','dispose','withdraw','index'])test(mode+' changing during native validation cannot publish or stage stale content',()=>box({duringStream(f){
|
|
69
|
+
if(mode==='cwd')f.cwd(join(f.base,'project-b'))
|
|
70
|
+
if(mode==='route')f.agent.options.model='changed-model'
|
|
71
|
+
if(mode==='dispose')f.emit('session/disposed',f.session)
|
|
72
|
+
if(mode==='withdraw'){const plan=withdrawManagedSource(f.root,f.session.id,f.ownerId);withdrawManagedSource(f.root,f.session.id,f.ownerId,{apply:true,controlReview:plan.controlReview})}
|
|
73
|
+
if(mode==='index')storeDirFor('project',f.cwd()) // Project registration changes the managed control revision.
|
|
74
|
+
}},async f=>{
|
|
75
|
+
f.ownerId=f.owner();const exec=f.call();await assert.rejects(()=>f.tool.execute(proposal,exec));assert.equal(f.records().some(r=>['pending','recorded'].includes(r.status)),false)
|
|
76
|
+
}))
|
|
77
|
+
test('unload during prepare aborts before a native validation stream is dispatched',()=>box({beforePrepare(f){for(const dispose of f.effects)dispose()}},async f=>{
|
|
78
|
+
f.owner();await assert.rejects(()=>f.tool.execute(proposal,f.call()));assert.equal(f.requests.length,0);assert.equal(f.records().length,0)
|
|
79
|
+
}))
|
|
80
|
+
test('long owner messages cannot silently lose a trailing exception at the 2000-character bound',()=>box(async f=>{
|
|
81
|
+
f.owner('甲'.repeat(2001)+'但是仅本项目适用。');await assert.rejects(()=>f.tool.execute(proposal,f.call()),/source-incomplete/);assert.equal(f.requests.length,0);assert.equal(f.records().length,0)
|
|
82
|
+
}))
|
|
83
|
+
test('an unapproved replacement keeps its target intact instead of staging a targetless append',()=>box({state:'uncertain'},async f=>{
|
|
84
|
+
const old=writeFixtureMemory({dir:f.root,type:'user',scope:'global',summary:'之前长期反馈先列一处问题',meaning:{kind:'preference'}})
|
|
85
|
+
f.owner();const result=await f.tool.execute({...proposal,supersedes:old.indexLine,revisionMode:'replace'},f.call());assert.equal(result.status,'not-applied');assert.equal(f.requests.length,1);assert.equal(f.records().filter(r=>r.status==='pending').length,0);assert.equal(searchStore(f.root,'之前长期反馈',{mode:'exact'}).hits.length,1)
|
|
86
|
+
}))
|
|
87
|
+
test('a missing native route never picks the first configured account',()=>box(async f=>{
|
|
88
|
+
delete f.agent.options.provider;f.owner();const result=await f.tool.execute(proposal,f.call());assert.equal(result.status,'pending-review');assert.equal(f.requests.length,0)
|
|
89
|
+
}))
|
|
90
|
+
|
|
91
|
+
const draftMeaning={kind:'preference',conditions:[{dimension:'document_kind',value:'draft'}]}
|
|
92
|
+
function seedDraft(f,expires){writeFixtureMemory({dir:f.root,type:'user',scope:'global',summary:'所有项目仅初稿默认标记为橄榄色',meaning:draftMeaning,expires});return f.records().find(r=>r.status==='recorded')}
|
|
93
|
+
function revoke(f,record){const plan=withdrawManagedSource(f.root,record.sessionId,record.evidence[0].messageId);withdrawManagedSource(f.root,record.sessionId,record.evidence[0].messageId,{apply:true,controlReview:plan.controlReview})}
|
|
94
|
+
test('native current-state context shows target conditions and expiry without old owner evidence',()=>box(async f=>{
|
|
95
|
+
const old=seedDraft(f,'2030-04-05');f.owner('重新完整约定:跨所有项目、所有阶段默认标记为青色,不再限定初稿,仍只保留到2030年4月5日。')
|
|
96
|
+
const r=await f.tool.execute({type:'user',scope:'global',summary:'所有项目所有阶段默认标记为青色',meaning:{kind:'preference'},expires:'2030-04-05',supersedes:old.indexLine,revisionMode:'replace'},f.call())
|
|
97
|
+
assert.equal(r.status,'recorded');const input=JSON.parse(f.requests[0].messages[0].content[0].text),context=input.currentMemory[0]
|
|
98
|
+
assert.equal(context.targetShown,true);assert.equal(context.records[0].recordId,old.id);assert.equal(context.records[0].expires,old.expires);assert.deepEqual(context.records[0].meaning.conditions,old.meaning.conditions)
|
|
99
|
+
assert.equal(context.records[0].evidence,undefined);assert.equal(input.ownerMessages.some(m=>m.id===old.evidence[0].messageId),false)
|
|
100
|
+
}))
|
|
101
|
+
test('scripted transition rejection of targetless append leaves old rule current and provides safe feedback',()=>box({fields:{transition:'unsupported'}},async f=>{
|
|
102
|
+
const old=seedDraft(f);f.owner('同一项长期约定,颜色改为青色。')
|
|
103
|
+
const r=await f.tool.execute({type:'user',scope:'global',summary:'所有项目仅初稿默认标记改为青色',meaning:draftMeaning},f.call())
|
|
104
|
+
assert.equal(r.status,'rejected');assert.equal(r.reason,'revision-intent-unsupported');assert.deepEqual(r.reviewIssues,{unsupported:['transition'],uncertain:[]})
|
|
105
|
+
const input=JSON.parse(f.requests[0].messages[0].content[0].text);assert.equal(input.currentMemory[0].records[0].recordId,old.id)
|
|
106
|
+
assert.equal(f.records().length,1);assert.equal(f.records()[0].id,old.id);assert.match(f.rendered(r),/transition/);assert.doesNotMatch(f.rendered(r),/已写入/)
|
|
107
|
+
}))
|
|
108
|
+
test('native value-only revision binds prior metadata before validation and drops obsolete intermediate roots',()=>box(async f=>{
|
|
109
|
+
const old=seedDraft(f);f.owner('同一项长期约定,颜色改为青色。');
|
|
110
|
+
let r=await f.tool.execute({type:'user',scope:'global',summary:'所有项目仅初稿默认标记改为青色',meaning:{kind:'preference'},supersedes:old.indexLine},f.call());assert.equal(r.status,'recorded');
|
|
111
|
+
const middle=f.records().find(r=>r.status==='recorded'),v=JSON.parse(f.requests[0].messages[0].content[0].text).candidates[0].value;
|
|
112
|
+
assert.equal(v.revisionMode,'value');assert.equal(v.inheritedMetadata.parentId,old.id);assert.deepEqual(v.meaning.conditions,old.meaning.conditions);
|
|
113
|
+
assert.equal(middle.evidence.length,1);assert.notEqual(middle.sessionId,old.sessionId);assert.equal(middle.sources.length,2);
|
|
114
|
+
f.owner('同一项长期约定,再改为紫色。');r=await f.tool.execute({type:'user',scope:'global',summary:'所有项目仅初稿默认标记改为紫色',meaning:{kind:'preference'},supersedes:middle.indexLine},f.call());assert.equal(r.status,'recorded');
|
|
115
|
+
const latest=f.records().find(r=>r.status==='recorded');assert.equal(latest.sources.length,2);assert.ok(latest.sources.includes(old.sources[0]));assert.equal(latest.sources.some(root=>middle.sources.includes(root)&&!old.sources.includes(root)),false);
|
|
116
|
+
revoke(f,middle);assert.ok(searchStore(f.root,'紫色',{context:{document_kind:'draft'}}).hits.length);assert.equal(searchStore(f.root,'紫色',{context:{document_kind:'final'}}).hits.length,0);
|
|
117
|
+
revoke(f,old);assert.equal(searchStore(f.root,'紫色').hits.length,0);
|
|
118
|
+
}))
|
|
119
|
+
test('native complete restatement carries its own roots and no inherited field certificate',()=>box(async f=>{
|
|
120
|
+
const old=seedDraft(f);f.owner('重新完整约定:跨所有项目,所有阶段默认标记均为青色,不再限定初稿。');
|
|
121
|
+
const r=await f.tool.execute({type:'user',scope:'global',summary:'跨所有项目所有阶段默认标记为青色',meaning:{kind:'preference'},supersedes:old.indexLine,revisionMode:'replace'},f.call());assert.equal(r.status,'recorded');
|
|
122
|
+
const next=f.records().find(r=>r.status==='recorded'),v=JSON.parse(f.requests[0].messages[0].content[0].text).candidates[0].value;
|
|
123
|
+
assert.equal(v.inheritedMetadata,undefined);assert.equal(next.fieldLineage,undefined);assert.deepEqual(next.meaning.conditions,[]);assert.equal(next.sources.length,1);revoke(f,old);assert.ok(searchStore(f.root,'青色',{context:{document_kind:'final'}}).hits.length);
|
|
124
|
+
}))
|
|
125
|
+
test('native value-only change retains expiry in line, validation and field certificate',()=>box(async f=>{
|
|
126
|
+
const old=seedDraft(f,'2030-04-05');f.owner('同一项长期约定,颜色改为青色。');const r=await f.tool.execute({type:'user',scope:'global',summary:'所有项目仅初稿默认标记改为青色',meaning:{kind:'preference'},supersedes:old.indexLine},f.call());
|
|
127
|
+
assert.equal(r.status,'recorded');assert.match(r.indexLine,/exp:2030-04-05/);const next=f.records().find(r=>r.status==='recorded');assert.equal(next.expires,old.expires);
|
|
128
|
+
const v=JSON.parse(f.requests[0].messages[0].content[0].text).candidates[0].value;assert.equal(v.expires,old.expires);assert.equal(v.inheritedMetadata.expires,old.expires);
|
|
129
|
+
}))
|
|
130
|
+
for(const state of ['unsupported','uncertain'])test('native '+state+' value revision never replaces or stages without its target',()=>box({state},async f=>{
|
|
131
|
+
const old=seedDraft(f);f.owner('同一项长期约定,颜色改为青色。');const r=await f.tool.execute({type:'user',scope:'global',summary:'所有项目仅初稿默认标记改为青色',meaning:{kind:'preference'},supersedes:old.indexLine},f.call());
|
|
132
|
+
assert.equal(r.status,state==='unsupported'?'rejected':'not-applied');assert.equal(f.records().length,1);assert.ok(searchStore(f.root,'橄榄色').hits.length);
|
|
133
|
+
}))
|
|
134
|
+
test('native value mode cannot silently change a condition or be used without a target',()=>box(async f=>{
|
|
135
|
+
const old=seedDraft(f);f.owner('请把正式稿的颜色改为青色。');
|
|
136
|
+
await assert.rejects(()=>f.tool.execute({type:'user',scope:'global',summary:'正式稿改为青色',meaning:{kind:'preference',conditions:[{dimension:'document_kind',value:'final'}]},supersedes:old.indexLine},f.call()),/meaning-change-needs-complete-replacement/);
|
|
137
|
+
await assert.rejects(()=>f.tool.execute({...proposal,revisionMode:'replace'},f.call()),/mode-needs-target/);assert.equal(f.requests.length,0);
|
|
138
|
+
}))
|
|
139
|
+
test('withdrawing inherited condition source during native validation blocks publication',()=>box({duringStream(f){revoke(f,f.parent)}},async f=>{
|
|
140
|
+
f.parent=seedDraft(f);f.owner('同一项长期约定,颜色改为青色。');
|
|
141
|
+
await assert.rejects(()=>f.tool.execute({type:'user',scope:'global',summary:'所有项目仅初稿默认标记改为青色',meaning:{kind:'preference'},supersedes:f.parent.indexLine},f.call()));assert.equal(f.records().some(r=>r.status==='recorded'),false);
|
|
142
|
+
}))
|
|
143
|
+
test('extra accepted current sources cannot displace an inherited source to fit the root bound',()=>box({evidence:input=>input.ownerMessages.map(m=>({messageId:m.id,quote:m.text}))},async f=>{
|
|
144
|
+
const old=seedDraft(f);f.owner('这是一条用于校对的额外真实用户说明甲。');f.owner('这是一条用于校对的额外真实用户说明乙。');f.owner('同一项长期约定,颜色改为青色。');
|
|
145
|
+
await assert.rejects(()=>f.tool.execute({type:'user',scope:'global',summary:'所有项目仅初稿默认标记改为青色',meaning:{kind:'preference'},supersedes:old.indexLine},f.call()),/source-overflow/);assert.equal(f.records().filter(r=>r.status==='recorded').length,1);assert.ok(searchStore(f.root,'橄榄色').hits.length);
|
|
146
|
+
}))
|
|
147
|
+
|
|
148
|
+
test('native self-excluding candidate is refused before any model stream or ledger write',()=>box(async f=>{
|
|
149
|
+
f.owner();await assert.rejects(()=>f.tool.execute({...proposal,meaning:{kind:'preference',conditions:[{dimension:'task',value:'review'}],except:[{dimension:'task',value:'review'}]}},f.call()),/contradictory-conditions/);assert.equal(f.requests.length,0);assert.equal(f.records().length,0)
|
|
150
|
+
}))
|
|
151
|
+
|
|
152
|
+
test('native validation cannot silently omit a clipped earlier owner exception',()=>box(async f=>{
|
|
153
|
+
f.owner('甲'.repeat(2000)+'但这条约定只适用于初稿,不要忽略末尾例外。');f.owner();await assert.rejects(()=>f.tool.execute(proposal,f.call()),/source-incomplete/);assert.equal(f.requests.length,0);assert.equal(f.records().length,0)
|
|
154
|
+
}))
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 打包完整性。跑法:node --test ~/.dsh/plugins/memory/test-packaging.mjs
|
|
3
|
+
*
|
|
4
|
+
* 发布前最容易漏的四件事:版本两处不一致、manifest 字段缺失、files 漏了运行时文件、
|
|
5
|
+
* 文档里指向不存在的文件。这些都是机械可查的,不该靠人记得。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { test } from 'node:test'
|
|
9
|
+
import assert from 'node:assert/strict'
|
|
10
|
+
import { existsSync, readFileSync, mkdtempSync, mkdirSync, rmSync } from 'node:fs'
|
|
11
|
+
import { join, dirname } from 'node:path'
|
|
12
|
+
import { fileURLToPath } from 'node:url'
|
|
13
|
+
import { tmpdir } from 'node:os'
|
|
14
|
+
import { spawnSync } from 'node:child_process'
|
|
15
|
+
import { probeEnvironment } from './scripts/probe-env.mjs'
|
|
16
|
+
|
|
17
|
+
import { VERSION } from './version.mjs'
|
|
18
|
+
|
|
19
|
+
const HERE = dirname(fileURLToPath(import.meta.url))
|
|
20
|
+
const pkg = JSON.parse(readFileSync(join(HERE, 'package.json'), 'utf8'))
|
|
21
|
+
|
|
22
|
+
test('版本单点:package.json 与 version.mjs 一致', () => {
|
|
23
|
+
assert.equal(pkg.version, VERSION)
|
|
24
|
+
assert.match(VERSION, /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
test('manifest:官方 bundle 配置层和宿主版本约束均存在', () => {
|
|
28
|
+
assert.equal(pkg.dsh?.bundle?.patch, './cordis.patch.yml')
|
|
29
|
+
assert.ok(existsSync(join(HERE, pkg.dsh.bundle.patch)))
|
|
30
|
+
assert.equal(typeof pkg.engines?.dsh, 'string')
|
|
31
|
+
assert.match(pkg.engines.dsh, /[<>]=?\s*\d+\.\d+/)
|
|
32
|
+
assert.match(pkg.engines.node, />=24/)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
test('入口文件存在且是 ESM', () => {
|
|
36
|
+
assert.equal(pkg.type, 'module')
|
|
37
|
+
assert.ok(existsSync(join(HERE, pkg.main)))
|
|
38
|
+
for (const entry of Object.values(pkg.exports)) {
|
|
39
|
+
assert.ok(existsSync(join(HERE, entry)), `exports 指向不存在的文件:${entry}`)
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test('files 覆盖运行时必需文件', () => {
|
|
44
|
+
const files = pkg.files ?? []
|
|
45
|
+
for (const required of ['field-lineage.mjs', 'source-record.mjs', 'index.mjs', 'security.mjs', 'version.mjs', 'tool-inputs.mjs', 'source-retirement.mjs', 'belief-revision.mjs', 'tool-observations.mjs', 'capture-diagnostics.mjs', 'snapshots.mjs', 'restore.mjs', 'restoration-lock.mjs', 'scripts/backup.mjs', 'runtime-startup.mjs', 'managed-activation.mjs', 'scripts/control.mjs', 'managed-access.mjs', 'managed-policy.mjs', 'managed-hooks.mjs', 'store-lock-guard.mjs', 'capture-llm.mjs', 'capture-evidence.mjs', 'capture-jobs.mjs', 'capture-inputs.mjs', 'context-history.mjs', 'retrieval.mjs', 'candidates.mjs', 'publication.mjs', 'withdrawal.mjs', 'managed-logs.mjs', 'plugin-config.mjs', 'host-services.mjs', 'project-stores.mjs', 'service-readiness.mjs', 'scripts/projects.mjs', 'cordis.patch.yml', 'README.md', 'SECURITY.md', 'LICENSE', 'COMPATIBILITY.md', 'scripts/']) {
|
|
46
|
+
assert.ok(files.some(entry => entry === required || entry.endsWith('/') && required.startsWith(entry)), `files 漏了 ${required}`)
|
|
47
|
+
assert.ok(existsSync(join(HERE, required)), `发布目录缺少 ${required}`)
|
|
48
|
+
}
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
test('文档齐全且不提不存在的东西', () => {
|
|
52
|
+
for (const doc of ['README.md', 'SECURITY.md', 'CHANGELOG.md', 'LICENSE']) {
|
|
53
|
+
assert.ok(existsSync(join(HERE, doc)), `缺 ${doc}`)
|
|
54
|
+
}
|
|
55
|
+
const readme = readFileSync(join(HERE, 'README.md'), 'utf8')
|
|
56
|
+
assert.match(readme, /SECURITY\.md/)
|
|
57
|
+
assert.match(readme, /scripts\/verify\.mjs/, 'README 应给出可执行的门禁命令')
|
|
58
|
+
const security = readFileSync(join(HERE, 'SECURITY.md'), 'utf8')
|
|
59
|
+
assert.match(security, /不.*防护|不防护|明确/, '安全文档必须写清不防什么')
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('没有绝对路径泄漏进 package.json', () => {
|
|
63
|
+
const text = readFileSync(join(HERE, 'package.json'), 'utf8')
|
|
64
|
+
assert.doesNotMatch(text, /\/Users\//)
|
|
65
|
+
assert.doesNotMatch(text, /file:\/\//)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
test('npm scripts 指向真实存在的测试文件', () => {
|
|
69
|
+
const script = pkg.scripts?.test ?? ''
|
|
70
|
+
const files = script.split(/\s+/).filter((token) => token.endsWith('.mjs'))
|
|
71
|
+
assert.ok(files.length >= 8, `test 脚本只覆盖 ${files.length} 个文件`)
|
|
72
|
+
for (const file of files) assert.ok(existsSync(join(HERE, file)), `脚本引用了不存在的 ${file}`)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
test('LICENSE 与 package.json 的 license 字段一致', () => {
|
|
76
|
+
assert.equal(pkg.license, 'MIT')
|
|
77
|
+
assert.match(readFileSync(join(HERE, 'LICENSE'), 'utf8'), /MIT License/)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
test('宿主/安装包探针环境只取 PATH,父环境中的凭据、代理和加载钩子不继承', () => {
|
|
81
|
+
const parent = { PATH: process.env.PATH, HOME: '/unrelated-home', DSH_HOME: '/unrelated-dsh',
|
|
82
|
+
OPENAI_API_KEY: 'synthetic-key', DEEPSEEK_API_KEY: 'synthetic-key', AWS_ACCESS_KEY_ID: 'synthetic-key',
|
|
83
|
+
HTTP_PROXY: 'http://invalid', NODE_OPTIONS: '--require=/missing-hook', ELECTRON_RUN_AS_NODE:'0',
|
|
84
|
+
NPM_CONFIG_USERCONFIG:'/unrelated-npmrc', UNRECOGNIZED_PROVIDER_SECRET:'synthetic-key' }
|
|
85
|
+
const env = probeEnvironment('/isolated-probe', parent)
|
|
86
|
+
assert.deepEqual(Object.keys(env).sort(), ['PATH','HOME','USERPROFILE','DSH_HOME','TMPDIR','TMP','TEMP','ELECTRON_RUN_AS_NODE','NO_COLOR'].sort())
|
|
87
|
+
assert.equal(env.PATH,parent.PATH);assert.equal(env.HOME,'/isolated-probe/home')
|
|
88
|
+
assert.equal(env.ELECTRON_RUN_AS_NODE,'1');assert.equal(parent.ELECTRON_RUN_AS_NODE,'0')
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
test('真实探针子进程看不到合成凭据或 NODE_OPTIONS,home/tmp 均定位到私有根', () => {
|
|
92
|
+
const root=mkdtempSync(join(tmpdir(),'dsh-probe-env-'))
|
|
93
|
+
try {
|
|
94
|
+
const env=probeEnvironment(root,{...process.env,OPENAI_API_KEY:'synthetic-key',HTTP_PROXY:'http://invalid',NODE_OPTIONS:'--require=/missing-hook',UNRECOGNIZED_PROVIDER_SECRET:'synthetic-key'})
|
|
95
|
+
mkdirSync(env.HOME);mkdirSync(env.TMPDIR)
|
|
96
|
+
const child=spawnSync(process.execPath,['--input-type=module','-e',`console.log(JSON.stringify({keys:Object.keys(process.env),home:process.env.HOME,tmp:process.env.TMPDIR}))`],{env,encoding:'utf8',timeout:5000})
|
|
97
|
+
assert.equal(child.status,0,child.stderr);const seen=JSON.parse(child.stdout)
|
|
98
|
+
for(const key of ['OPENAI_API_KEY','HTTP_PROXY','NODE_OPTIONS','UNRECOGNIZED_PROVIDER_SECRET'])assert.equal(seen.keys.includes(key),false)
|
|
99
|
+
assert.equal(seen.home,env.HOME);assert.equal(seen.tmp,env.TMPDIR)
|
|
100
|
+
assert.doesNotMatch(child.stdout,/synthetic-key/)
|
|
101
|
+
} finally {rmSync(root,{recursive:true,force:true})}
|
|
102
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { analyzePairs, signTail } from './eval/paired-analysis.mjs'
|
|
4
|
+
|
|
5
|
+
test('配对精确检验:已知二项尾概率', () => {
|
|
6
|
+
assert.equal(signTail(0, 0), 1)
|
|
7
|
+
assert.ok(Math.abs(signTail(5, 0) - 1 / 32) < 1e-12)
|
|
8
|
+
assert.ok(Math.abs(signTail(2, 2) - 11 / 16) < 1e-12)
|
|
9
|
+
assert.ok(signTail(1000, 0) < 1e-100)
|
|
10
|
+
})
|
|
11
|
+
test('配对检验:重复运行不能伪装独立样本', () => {
|
|
12
|
+
const report = analyzePairs([{ id: 'one', ours: Array(100).fill(true), baseline: Array(100).fill(false) }])
|
|
13
|
+
assert.equal(report.scenarios, 1)
|
|
14
|
+
assert.ok(Math.abs(report.oneSidedSignP - 0.5) < 1e-12)
|
|
15
|
+
})
|
|
16
|
+
test('配对检验:相同与反向结果不产生胜出结论', () => {
|
|
17
|
+
const rows = Array.from({ length: 10 }, (_, i) => ({ id: `${i}`, ours: [false], baseline: [true] }))
|
|
18
|
+
assert.equal(analyzePairs(rows).oneSidedSignP, 1)
|
|
19
|
+
assert.match(analyzePairs(rows).conclusion, /statistics-only/)
|
|
20
|
+
})
|
|
21
|
+
test('配对检验:失败、缺失、重复编号不能静默从分母删除', () => {
|
|
22
|
+
const row = { id: 'a', ours: [true], baseline: [false] }
|
|
23
|
+
assert.throws(() => analyzePairs([row, row]), /duplicate/)
|
|
24
|
+
assert.throws(() => analyzePairs([{ ...row, baseline: [] }]), /unpaired/)
|
|
25
|
+
assert.throws(() => analyzePairs([{ ...row, ours: [null] }]), /boolean/)
|
|
26
|
+
})
|
package/test-patch.mjs
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 安装/卸载脚本。跑法:node --test ~/.dsh/plugins/memory/test-patch.mjs
|
|
3
|
+
*
|
|
4
|
+
* 这类脚本最容易在"用户的文件"上出事:删多了、重复插、覆盖掉别人的配置。
|
|
5
|
+
* 所以测试重点不是"能不能装上",而是"只动自己那几行"。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { test } from 'node:test'
|
|
9
|
+
import assert from 'node:assert/strict'
|
|
10
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, copyFileSync, realpathSync } from 'node:fs'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
14
|
+
import { spawnSync } from 'node:child_process'
|
|
15
|
+
|
|
16
|
+
import { run } from './scripts/patch.mjs'
|
|
17
|
+
|
|
18
|
+
const OTHER = `# 用户自己的配置
|
|
19
|
+
- id: locale
|
|
20
|
+
name: "@deepseek-ai/dsh-client-locale"
|
|
21
|
+
config:
|
|
22
|
+
preference: zh
|
|
23
|
+
- insert:
|
|
24
|
+
- id: mcp-godot
|
|
25
|
+
name: "@deepseek-ai/dsh-mcp-client"
|
|
26
|
+
`
|
|
27
|
+
|
|
28
|
+
function sandbox(patch = OTHER) {
|
|
29
|
+
const root = mkdtempSync(join(tmpdir(), 'dsh-mem-patch-'))
|
|
30
|
+
const profile = join(root, 'profile')
|
|
31
|
+
mkdirSync(profile, { recursive: true })
|
|
32
|
+
const file = join(profile, 'cordis.patch.yml')
|
|
33
|
+
writeFileSync(file, patch, 'utf8')
|
|
34
|
+
return {
|
|
35
|
+
root,
|
|
36
|
+
profile,
|
|
37
|
+
file,
|
|
38
|
+
cleanup: () => rmSync(root, { recursive: true, force: true }),
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
test('插件路径不存在时拒绝安装,且不改动文件', () => {
|
|
43
|
+
const box = sandbox()
|
|
44
|
+
try {
|
|
45
|
+
const before = readFileSync(box.file, 'utf8')
|
|
46
|
+
assert.throws(
|
|
47
|
+
() => run(['install', '--profile', box.profile, '--plugin', '/tmp/does-not-exist/index.mjs']),
|
|
48
|
+
/插件文件不存在/,
|
|
49
|
+
)
|
|
50
|
+
assert.equal(readFileSync(box.file, 'utf8'), before)
|
|
51
|
+
assert.equal(readdirSync(box.profile).filter((n) => n.includes('.bak-')).length, 0)
|
|
52
|
+
} finally {
|
|
53
|
+
box.cleanup()
|
|
54
|
+
}
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
test('安装:真实路径下写入块,且原有条目一行不少', () => {
|
|
58
|
+
const box = sandbox()
|
|
59
|
+
try {
|
|
60
|
+
const plugin = fileURLToPath(new URL('./index.mjs', import.meta.url))
|
|
61
|
+
const result = run(['install', '--profile', box.profile, '--plugin', plugin])
|
|
62
|
+
assert.equal(result.changed, true)
|
|
63
|
+
|
|
64
|
+
const text = readFileSync(box.file, 'utf8')
|
|
65
|
+
for (const line of OTHER.split('\n')) {
|
|
66
|
+
if (line.trim().length === 0) continue
|
|
67
|
+
assert.ok(text.includes(line), `丢了用户配置:${line}`)
|
|
68
|
+
}
|
|
69
|
+
assert.match(text, /# >>> dsh-memory/)
|
|
70
|
+
assert.match(text, /- id: memory/)
|
|
71
|
+
assert.match(text, /file:\/\/.*index\.mjs/)
|
|
72
|
+
const backups = readdirSync(box.profile).filter((name) => name.includes('.bak-dsh-memory-'))
|
|
73
|
+
assert.equal(backups.length, 1, '应留一份备份')
|
|
74
|
+
} finally {
|
|
75
|
+
box.cleanup()
|
|
76
|
+
}
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
test('幂等:装两次不产生第二个块', () => {
|
|
80
|
+
const box = sandbox()
|
|
81
|
+
try {
|
|
82
|
+
const plugin = fileURLToPath(new URL('./index.mjs', import.meta.url))
|
|
83
|
+
run(['install', '--profile', box.profile, '--plugin', plugin])
|
|
84
|
+
const first = readFileSync(box.file, 'utf8')
|
|
85
|
+
|
|
86
|
+
const second = run(['install', '--profile', box.profile, '--plugin', plugin])
|
|
87
|
+
assert.equal(second.changed, false)
|
|
88
|
+
assert.equal(readFileSync(box.file, 'utf8'), first)
|
|
89
|
+
assert.equal((first.match(/# >>> dsh-memory/g) ?? []).length, 1)
|
|
90
|
+
} finally {
|
|
91
|
+
box.cleanup()
|
|
92
|
+
}
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('卸载:只删自己的块,用户配置逐字保留', () => {
|
|
96
|
+
const box = sandbox()
|
|
97
|
+
try {
|
|
98
|
+
const plugin = fileURLToPath(new URL('./index.mjs', import.meta.url))
|
|
99
|
+
run(['install', '--profile', box.profile, '--plugin', plugin])
|
|
100
|
+
const result = run(['uninstall', '--profile', box.profile])
|
|
101
|
+
assert.equal(result.changed, true)
|
|
102
|
+
|
|
103
|
+
const after = readFileSync(box.file, 'utf8')
|
|
104
|
+
assert.doesNotMatch(after, /dsh-memory/)
|
|
105
|
+
// 用户原始内容完整回来(允许尾部空行差异)
|
|
106
|
+
assert.equal(after.trimEnd(), OTHER.trimEnd())
|
|
107
|
+
} finally {
|
|
108
|
+
box.cleanup()
|
|
109
|
+
}
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
test('卸载:没装过时不动文件', () => {
|
|
113
|
+
const box = sandbox()
|
|
114
|
+
try {
|
|
115
|
+
const before = readFileSync(box.file, 'utf8')
|
|
116
|
+
const result = run(['uninstall', '--profile', box.profile])
|
|
117
|
+
assert.equal(result.changed, false)
|
|
118
|
+
assert.equal(readFileSync(box.file, 'utf8'), before)
|
|
119
|
+
} finally {
|
|
120
|
+
box.cleanup()
|
|
121
|
+
}
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
test('dry-run 不落盘', () => {
|
|
125
|
+
const box = sandbox()
|
|
126
|
+
try {
|
|
127
|
+
const plugin = fileURLToPath(new URL('./index.mjs', import.meta.url))
|
|
128
|
+
const before = readFileSync(box.file, 'utf8')
|
|
129
|
+
const result = run(['install', '--profile', box.profile, '--plugin', plugin, '--dry-run'])
|
|
130
|
+
assert.equal(result.dryRun, true)
|
|
131
|
+
assert.equal(readFileSync(box.file, 'utf8'), before)
|
|
132
|
+
assert.equal(readdirSync(box.profile).filter((n) => n.includes('.bak-')).length, 0)
|
|
133
|
+
} finally {
|
|
134
|
+
box.cleanup()
|
|
135
|
+
}
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
test('标记不成对时拒绝操作(不猜)', () => {
|
|
139
|
+
const box = sandbox(`${OTHER}# >>> dsh-memory\n- insert:\n`)
|
|
140
|
+
try {
|
|
141
|
+
assert.throws(() => run(['install', '--profile', box.profile, '--plugin', fileURLToPath(new URL('./index.mjs', import.meta.url))]), /标记不成对/)
|
|
142
|
+
assert.throws(() => run(['uninstall', '--profile', box.profile]), /标记不成对/)
|
|
143
|
+
} finally {
|
|
144
|
+
box.cleanup()
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
test('缺少 --profile 时报错而不是猜默认值', () => {
|
|
149
|
+
assert.throws(() => run(['install', '--plugin', '/tmp/x']), /缺少 --profile/)
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
test('已有未托管的 memory 条目时拒绝安装(不制造副本)', () => {
|
|
153
|
+
const manual = `${OTHER}- insert:
|
|
154
|
+
- id: memory
|
|
155
|
+
name: "file:///somewhere/index.mjs"
|
|
156
|
+
`
|
|
157
|
+
const box = sandbox(manual)
|
|
158
|
+
try {
|
|
159
|
+
const before = readFileSync(box.file, 'utf8')
|
|
160
|
+
assert.throws(
|
|
161
|
+
() => run(['install', '--profile', box.profile, '--plugin', fileURLToPath(new URL('./index.mjs', import.meta.url))]),
|
|
162
|
+
/未托管的 memory 条目/,
|
|
163
|
+
)
|
|
164
|
+
assert.equal(readFileSync(box.file, 'utf8'), before, '拒绝时不应改动文件')
|
|
165
|
+
} finally {
|
|
166
|
+
box.cleanup()
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
test('全新空列表配置可安装,卸载逐字恢复注释与空白', () => {
|
|
171
|
+
const original = '# clean profile\n [] # intentional empty\n\n'
|
|
172
|
+
const box = sandbox(original)
|
|
173
|
+
try {
|
|
174
|
+
run(['install', '--profile', box.profile, '--plugin', fileURLToPath(new URL('./index.mjs', import.meta.url))])
|
|
175
|
+
const installed = readFileSync(box.file, 'utf8')
|
|
176
|
+
assert.doesNotMatch(installed, /^\s*\[\]/m)
|
|
177
|
+
assert.match(installed, /^- insert:/m)
|
|
178
|
+
run(['uninstall', '--profile', box.profile])
|
|
179
|
+
assert.equal(readFileSync(box.file, 'utf8'), original)
|
|
180
|
+
} finally { box.cleanup() }
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
test('恢复空列表时保留托管块以外的新注释,损坏恢复标记则拒绝', () => {
|
|
184
|
+
const box = sandbox('[]\n')
|
|
185
|
+
try {
|
|
186
|
+
run(['install', '--profile', box.profile, '--plugin', fileURLToPath(new URL('./index.mjs', import.meta.url))])
|
|
187
|
+
const installed = readFileSync(box.file, 'utf8')
|
|
188
|
+
writeFileSync(box.file, '# newer outside comment\n' + installed)
|
|
189
|
+
run(['uninstall', '--profile', box.profile])
|
|
190
|
+
assert.equal(readFileSync(box.file, 'utf8'), '# newer outside comment\n[]\n')
|
|
191
|
+
writeFileSync(box.file, installed.replace(/# dsh-memory-original-empty:[^\n]+/, '# dsh-memory-original-empty:aW52YWxpZA=='))
|
|
192
|
+
const broken = readFileSync(box.file, 'utf8')
|
|
193
|
+
assert.throws(() => run(['uninstall', '--profile', box.profile]), /恢复标记损坏/)
|
|
194
|
+
assert.equal(readFileSync(box.file, 'utf8'), broken)
|
|
195
|
+
} finally { box.cleanup() }
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
test('插件路径中的空格、中文与井号使用有效 file URL', () => {
|
|
199
|
+
const box = sandbox()
|
|
200
|
+
try {
|
|
201
|
+
const plugin = join(box.root, '含 空格#?.mjs'); writeFileSync(plugin, 'export const name="fixture"')
|
|
202
|
+
run(['install', '--profile', box.profile, '--plugin', plugin])
|
|
203
|
+
const line = readFileSync(box.file, 'utf8').split('\n').find((line) => line.trim().startsWith('name:'))
|
|
204
|
+
const names = readFileSync(box.file, 'utf8').split('\n').filter((line) => line.trim().startsWith('name:'))
|
|
205
|
+
const href = JSON.parse(names.at(-1).split('name:')[1].trim())
|
|
206
|
+
assert.equal(fileURLToPath(href), plugin)
|
|
207
|
+
assert.ok(href.includes('%23')); assert.ok(href.includes('%20')); assert.ok(line)
|
|
208
|
+
} finally { box.cleanup() }
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
test('default plugin path installs correctly from a Unicode directory with spaces and URL metacharacters',()=>{
|
|
213
|
+
const box=sandbox()
|
|
214
|
+
try{
|
|
215
|
+
const local=join(box.root,'插件 空间#'),scripts=join(local,'scripts');mkdirSync(scripts,{recursive:true});writeFileSync(join(local,'index.mjs'),'export function apply() {}\n');const file=join(scripts,'patch.mjs');copyFileSync(fileURLToPath(new URL('./scripts/patch.mjs',import.meta.url)),file)
|
|
216
|
+
const result=spawnSync(process.execPath,[file,'install','--profile',box.profile],{encoding:'utf8'});assert.equal(result.status,0,result.stderr);const body=readFileSync(box.file,'utf8'),href=JSON.parse(body.split('\n').filter(line=>line.trim().startsWith('name:')).at(-1).split('name:')[1].trim());assert.equal(realpathSync(fileURLToPath(href)),realpathSync(join(local,'index.mjs')));assert.ok(href.includes('%20')&&href.includes('%23'));assert.ok(body.includes('id: mcp-godot'))
|
|
217
|
+
}finally{box.cleanup()}
|
|
218
|
+
})
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import {realpathSync} from 'node:fs'
|
|
2
|
+
import { test } from 'node:test'
|
|
3
|
+
import assert from 'node:assert/strict'
|
|
4
|
+
import { mkdtempSync, mkdirSync, readFileSync, existsSync, rmSync } from 'node:fs'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { Config, normalizePluginConfig, DEFAULT_AUTO_CAPTURE } from './plugin-config.mjs'
|
|
8
|
+
import { optionalService } from './host-services.mjs'
|
|
9
|
+
import { extractWithLlm } from './capture-llm.mjs'
|
|
10
|
+
import { apply,storeDirFor } from './index.mjs'
|
|
11
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
|
12
|
+
async function until(check) { for (let i = 0; i < 200; i++) { if (check()) return; await sleep(5) } throw Error('fixture deadline') }
|
|
13
|
+
|
|
14
|
+
test('Cordis Config implements synchronous Standard Schema V1 and returns independent defaults', () => {
|
|
15
|
+
assert.equal(Config['~standard'].version, 1)
|
|
16
|
+
assert.equal(typeof Config['~standard'].vendor, 'string')
|
|
17
|
+
const a = Config['~standard'].validate({}), b = normalizePluginConfig({})
|
|
18
|
+
assert.deepEqual(a.value.autoCapture, DEFAULT_AUTO_CAPTURE)
|
|
19
|
+
assert.deepEqual(Config['~standard'].validate(undefined).value.autoCapture, DEFAULT_AUTO_CAPTURE)
|
|
20
|
+
a.value.autoCapture.enabled = false
|
|
21
|
+
assert.equal(b.autoCapture.enabled, true)
|
|
22
|
+
assert.equal(normalizePluginConfig({ autoCapture: { everyTurns: undefined } }).autoCapture.everyTurns, 4)
|
|
23
|
+
})
|
|
24
|
+
for (const [key, values] of Object.entries({ enabled: [0, 'false'], everyTurns: [0, 1.5, 1001], maxEntries: [0, 11], maxTokens: [0, 8193], maxInputBytes: [1023, 65537], timeoutMs: [0, 120001] })) {
|
|
25
|
+
test(`invalid ${key} fails load-time validation rather than entering capture`, () => {
|
|
26
|
+
for (const value of values) {
|
|
27
|
+
const result = Config['~standard'].validate({ autoCapture: { [key]: value } })
|
|
28
|
+
assert.ok(result.issues.length)
|
|
29
|
+
assert.throws(() => normalizePluginConfig({ autoCapture: { [key]: value } }), /memory-invalid-config/)
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
test('unknown fields, nonobjects and incomplete routes are rejected without echoing configured values', () => {
|
|
34
|
+
for (const value of [null, [], true, { unknown: 'synthetic-private-value' }, { autoCapture: null }, { autoCapture: { timeout: 'synthetic-private-value' } }, { autoCapture: { provider: 'only-provider' } }, { autoCapture: { provider: ' ', model: 'model' } }]) {
|
|
35
|
+
assert.throws(() => normalizePluginConfig(value), /memory-invalid-config/)
|
|
36
|
+
assert.doesNotMatch(JSON.stringify(Config['~standard'].validate(value)), /synthetic-private-value|only-provider/)
|
|
37
|
+
}
|
|
38
|
+
assert.deepEqual(normalizePluginConfig({ autoCapture: { provider: ' p ', model: ' m ' } }).autoCapture, { ...DEFAULT_AUTO_CAPTURE, provider: 'p', model: 'm' })
|
|
39
|
+
})
|
|
40
|
+
test('invalid configuration registers no tools or prompt contributions', () => {
|
|
41
|
+
let calls = 0
|
|
42
|
+
const ctx = { systemPrompt: { context: () => calls++ }, tools: { register: () => calls++ }, workingDirectory: { get: () => '' } }
|
|
43
|
+
assert.throws(() => apply(ctx, { autoCapture: { everyTurns: 0 } }), /memory-invalid-config/)
|
|
44
|
+
assert.equal(calls, 0)
|
|
45
|
+
})
|
|
46
|
+
test('optional service lookup prefers public active lookup and never revives an absent provider', () => {
|
|
47
|
+
const active = { marker: 'active' }
|
|
48
|
+
assert.equal(optionalService({ get: name => name === 'llm' ? active : undefined }, 'llm'), active)
|
|
49
|
+
assert.equal(optionalService({ get: () => undefined, reflect: { get: () => active }, llm: active }, 'llm'), undefined)
|
|
50
|
+
assert.equal(optionalService({ get: () => { throw Error('not permitted') }, llm: active }, 'llm'), undefined)
|
|
51
|
+
assert.equal(optionalService({ reflect: { get: () => active } }, 'llm'), active)
|
|
52
|
+
assert.equal(optionalService({ llm: active }, 'llm'), active)
|
|
53
|
+
})
|
|
54
|
+
const options = { messages: [], indexLines: [], route: { provider: 'fixture', model: 'fixture' }, timeoutMs: 5000 }
|
|
55
|
+
test('pre-cancelled capture never prepares or sends a model call', async () => {
|
|
56
|
+
const controller = new AbortController(); controller.abort()
|
|
57
|
+
let prepared = 0
|
|
58
|
+
await assert.rejects(extractWithLlm({ ...options, signal: controller.signal, llm: { prepareCall: () => { prepared++; throw Error('must not run') } } }), /capture-cancelled/)
|
|
59
|
+
assert.equal(prepared, 0)
|
|
60
|
+
})
|
|
61
|
+
test('unload during preparation stops waiting and rejects late dispatch even if provider ignores cancellation', async () => {
|
|
62
|
+
const controller = new AbortController()
|
|
63
|
+
let finish, dispatched = 0
|
|
64
|
+
const pending = extractWithLlm({ ...options, signal: controller.signal, llm: { prepareCall: () => new Promise(resolve => finish = resolve) } })
|
|
65
|
+
controller.abort()
|
|
66
|
+
await assert.rejects(pending, /capture-cancelled/)
|
|
67
|
+
finish({ config: {}, stream: () => { dispatched++; throw Error('must not dispatch') } })
|
|
68
|
+
await sleep(10)
|
|
69
|
+
assert.equal(dispatched, 0)
|
|
70
|
+
})
|
|
71
|
+
test('unload during an uncooperative stream stops waiting and propagates abort without accepting late text', async () => {
|
|
72
|
+
const controller = new AbortController()
|
|
73
|
+
let received, finish, started = false
|
|
74
|
+
const pending = extractWithLlm({ ...options, signal: controller.signal, llm: { async prepareCall(config, signal) {
|
|
75
|
+
received = signal
|
|
76
|
+
return { config, stream: async function* () { started = true; await new Promise(resolve => finish = resolve); yield { type: 'text-delta', text: '[]' } } }
|
|
77
|
+
} } })
|
|
78
|
+
await until(() => started)
|
|
79
|
+
controller.abort()
|
|
80
|
+
await assert.rejects(pending, /capture-cancelled/)
|
|
81
|
+
assert.equal(received.aborted, true)
|
|
82
|
+
finish()
|
|
83
|
+
await sleep(10)
|
|
84
|
+
})
|
|
85
|
+
test('plugin disposal prevents pending capture from adopting a valid late candidate', async () => {
|
|
86
|
+
const root = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-plugin-dispose-'))), previous = process.env.DSH_HOME
|
|
87
|
+
const cwd = join(root, 'project'), store = join(root, 'memory')
|
|
88
|
+
mkdirSync(cwd); process.env.DSH_HOME = root
|
|
89
|
+
const disposers = [], handlers = new Map()
|
|
90
|
+
let release, streamStarted = false, requestSignal
|
|
91
|
+
const llm = { listProviders: () => [{ provider: 'fixture', model: 'fixture' }], async prepareCall(config, signal) {
|
|
92
|
+
requestSignal = signal
|
|
93
|
+
return { config, stream: async function* () { streamStarted = true; await new Promise(resolve => release = resolve); yield { type: 'text-delta', text: JSON.stringify([{ type: 'user', summary: '合成项目使用低反差画面', scope: 'project', meaning:{kind:'claim'},basis: 'explicit', evidence: [{ messageId: 'dispose-session:event-0', quote: '合成项目使用低反差画面' }] }]) } } }
|
|
94
|
+
} }
|
|
95
|
+
const ctx = { get: name => name === 'llm' ? llm : undefined, systemPrompt: { context() {} }, tools: { register() {} }, workingDirectory: { get: () => cwd },
|
|
96
|
+
effect: callback => disposers.push(callback()), on: (name, fn) => handlers.set(name, fn) }
|
|
97
|
+
try {
|
|
98
|
+
apply(ctx, { autoCapture: { everyTurns: 1 } })
|
|
99
|
+
const session = { id: 'dispose-session' }, emit = handlers.get('session/event')
|
|
100
|
+
emit(session, { type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '合成项目使用低反差画面,其他项目另定。' }] } })
|
|
101
|
+
emit(session, { type: 'step/end' })
|
|
102
|
+
await until(() => streamStarted)
|
|
103
|
+
for (const dispose of disposers.reverse()) dispose?.()
|
|
104
|
+
await until(() => JSON.parse(readFileSync(join(store, '.capture-state.json'))).lastError === 'capture-cancelled')
|
|
105
|
+
assert.equal(requestSignal.aborted, true)
|
|
106
|
+
release()
|
|
107
|
+
await sleep(20)
|
|
108
|
+
const project=storeDirFor('project',cwd)
|
|
109
|
+
assert.equal(existsSync(join(project,'.managed-policy.json')),true)
|
|
110
|
+
assert.equal(existsSync(join(project,'MEMORY.md')),false)
|
|
111
|
+
assert.equal(existsSync(join(project,'.candidates.json')),false)
|
|
112
|
+
assert.equal(existsSync(join(store, 'MEMORY.md')), false)
|
|
113
|
+
} finally {
|
|
114
|
+
release?.()
|
|
115
|
+
if (previous === undefined) delete process.env.DSH_HOME; else process.env.DSH_HOME = previous
|
|
116
|
+
rmSync(root, { recursive: true, force: true })
|
|
117
|
+
}
|
|
118
|
+
})
|