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.
Files changed (152) hide show
  1. package/CHANGELOG.md +453 -0
  2. package/COMPATIBILITY.md +155 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +62 -0
  5. package/README.md +105 -2
  6. package/RELEASE.md +43 -0
  7. package/SECURITY.md +73 -0
  8. package/accept.mjs +18 -0
  9. package/belief-revision.mjs +48 -0
  10. package/candidates.mjs +355 -0
  11. package/capture-diagnostics.mjs +77 -0
  12. package/capture-evidence.mjs +49 -0
  13. package/capture-inputs.mjs +171 -0
  14. package/capture-jobs.mjs +195 -0
  15. package/capture-llm.mjs +299 -0
  16. package/capture-projections.mjs +7 -0
  17. package/capture-revision.mjs +13 -0
  18. package/capture-source-aliases.mjs +20 -0
  19. package/capture-submission.mjs +75 -0
  20. package/capture-validation-contract.mjs +30 -0
  21. package/capture-validation-job.mjs +43 -0
  22. package/capture-validation.mjs +112 -0
  23. package/capture.mjs +109 -0
  24. package/context-history.mjs +123 -0
  25. package/control-schema.mjs +18 -0
  26. package/cordis.patch.yml +3 -0
  27. package/corpus/capture-contract-v25.json +59 -0
  28. package/corpus/external-labeled.json +187 -0
  29. package/corpus/holdout-v2.json +217 -0
  30. package/corpus/holdout-v3.json +145 -0
  31. package/corpus/injections.json +699 -0
  32. package/corpus/legacy-self-excluding-dev36.json +7 -0
  33. package/corpus/legacy-summary-v15.json +12 -0
  34. package/episodes.mjs +130 -0
  35. package/eval/mechanical-table.mjs +470 -0
  36. package/eval/paired-analysis.mjs +47 -0
  37. package/eval/run-eval.mjs +493 -0
  38. package/field-lineage.mjs +62 -0
  39. package/fixture-host.mjs +96 -0
  40. package/host-services.mjs +8 -0
  41. package/icon.svg +1 -0
  42. package/index.mjs +2931 -0
  43. package/locale/en.json +6 -0
  44. package/locale/zh.json +6 -0
  45. package/managed-access.mjs +182 -0
  46. package/managed-activation.mjs +36 -0
  47. package/managed-hooks.mjs +110 -0
  48. package/managed-logs.mjs +34 -0
  49. package/managed-policy.mjs +296 -0
  50. package/meaning.mjs +117 -0
  51. package/memory-policy.mjs +18 -0
  52. package/memory-protocol.mjs +21 -0
  53. package/memory-rule-policy.mjs +11 -0
  54. package/memory-scope-policy.mjs +7 -0
  55. package/native-write-validation.mjs +45 -0
  56. package/package.json +206 -4
  57. package/plugin-config.mjs +34 -0
  58. package/project-stores.mjs +222 -0
  59. package/publication.mjs +92 -0
  60. package/restoration-lock.mjs +9 -0
  61. package/restore.mjs +173 -0
  62. package/retrieval.mjs +43 -0
  63. package/revision-admission.mjs +6 -0
  64. package/runtime-startup.mjs +36 -0
  65. package/scripts/backup.mjs +15 -0
  66. package/scripts/candidates.mjs +46 -0
  67. package/scripts/capture-jobs.mjs +41 -0
  68. package/scripts/control.mjs +25 -0
  69. package/scripts/patch.mjs +152 -0
  70. package/scripts/probe-env.mjs +8 -0
  71. package/scripts/probe-load.mjs +88 -0
  72. package/scripts/probe-package.mjs +104 -0
  73. package/scripts/projects.mjs +19 -0
  74. package/scripts/verify.mjs +81 -0
  75. package/security.mjs +489 -0
  76. package/service-readiness.mjs +34 -0
  77. package/snapshots.mjs +76 -0
  78. package/source-identity.mjs +29 -0
  79. package/source-record.mjs +59 -0
  80. package/source-retirement.mjs +76 -0
  81. package/store-lock-guard.mjs +4 -0
  82. package/test-adversarial.mjs +331 -0
  83. package/test-belief-revision.mjs +166 -0
  84. package/test-candidates.mjs +147 -0
  85. package/test-capture-diagnostics.mjs +98 -0
  86. package/test-capture-field-lineage.mjs +63 -0
  87. package/test-capture-inputs.mjs +271 -0
  88. package/test-capture-jobs.mjs +301 -0
  89. package/test-capture-projections.mjs +78 -0
  90. package/test-capture-revision.mjs +77 -0
  91. package/test-capture-submission.mjs +68 -0
  92. package/test-capture-validation-flow.mjs +47 -0
  93. package/test-capture-validation-job.mjs +76 -0
  94. package/test-capture-validation-lineage.mjs +40 -0
  95. package/test-capture-validation.mjs +84 -0
  96. package/test-capture.mjs +808 -0
  97. package/test-compaction-compat.mjs +307 -0
  98. package/test-compat.mjs +126 -0
  99. package/test-concurrency.mjs +204 -0
  100. package/test-conflict.mjs +133 -0
  101. package/test-context-history.mjs +105 -0
  102. package/test-control-schema.mjs +26 -0
  103. package/test-episodes.mjs +157 -0
  104. package/test-explicit-memory.mjs +43 -0
  105. package/test-field-lineage.mjs +105 -0
  106. package/test-history.mjs +305 -0
  107. package/test-inline-summary.mjs +52 -0
  108. package/test-legacy-source-identity.mjs +46 -0
  109. package/test-links.mjs +245 -0
  110. package/test-managed-access.mjs +114 -0
  111. package/test-managed-activation.mjs +93 -0
  112. package/test-meaning.mjs +178 -0
  113. package/test-native-service-lifecycle.mjs +25 -0
  114. package/test-native-write-validation.mjs +154 -0
  115. package/test-packaging.mjs +102 -0
  116. package/test-paired-analysis.mjs +26 -0
  117. package/test-patch.mjs +218 -0
  118. package/test-plugin-contract.mjs +118 -0
  119. package/test-project-stores.mjs +228 -0
  120. package/test-publication.mjs +145 -0
  121. package/test-restore.mjs +127 -0
  122. package/test-retrieval.mjs +75 -0
  123. package/test-revision-admission.mjs +23 -0
  124. package/test-rule-admission.mjs +52 -0
  125. package/test-runtime-startup.mjs +68 -0
  126. package/test-schema.mjs +187 -0
  127. package/test-security.mjs +448 -0
  128. package/test-service-readiness.mjs +50 -0
  129. package/test-smell.mjs +201 -0
  130. package/test-snapshots.mjs +58 -0
  131. package/test-source-completeness.mjs +44 -0
  132. package/test-source-key.mjs +17 -0
  133. package/test-source-retirement.mjs +83 -0
  134. package/test-status-both.mjs +42 -0
  135. package/test-supersede.mjs +216 -0
  136. package/test-text-admission.mjs +82 -0
  137. package/test-tool-inputs.mjs +13 -0
  138. package/test-tool-observations.mjs +124 -0
  139. package/test-tool-write-guard.mjs +23 -0
  140. package/test-tool-write-lifecycle.mjs +52 -0
  141. package/test-usability.mjs +588 -0
  142. package/test-validation-source-refs.mjs +27 -0
  143. package/test-validation-transition-context.mjs +41 -0
  144. package/test-withdrawal-archives.mjs +156 -0
  145. package/test-withdrawal.mjs +167 -0
  146. package/test.mjs +515 -0
  147. package/tool-inputs.mjs +68 -0
  148. package/tool-observations.mjs +115 -0
  149. package/validation-transition-context.mjs +30 -0
  150. package/version.mjs +5 -0
  151. package/withdrawal.mjs +155 -0
  152. package/worker-write.mjs +13 -0
@@ -0,0 +1,52 @@
1
+ /** Synthetic regression cases, including bytes produced by the frozen old writer. */
2
+ import test from 'node:test'
3
+ import assert from 'node:assert/strict'
4
+ import {mkdtempSync,realpathSync,readFileSync,writeFileSync,existsSync,rmSync} from 'node:fs'
5
+ import {join} from 'node:path'
6
+ import {tmpdir} from 'node:os'
7
+ import {assertMeaningSatisfiable,normalizeMeaning,applicability} from './meaning.mjs'
8
+ import {assessCandidate} from './capture-evidence.mjs'
9
+ import {writeFixtureMemory} from './fixture-host.mjs'
10
+ import {candidateSnapshot,stageCandidate} from './candidates.mjs'
11
+ import {adoptCandidate,storeRevision} from './index.mjs'
12
+ import {prepareValidationPrompt,ValidationSubmission} from './capture-validation.mjs'
13
+ import {VALIDATION_FIELDS} from './capture-validation-contract.mjs'
14
+ const contradictory={kind:'preference',conditions:[{dimension:'document_kind',value:'exploratory_draft'}],except:[{dimension:'document_kind',value:'exploratory_draft'}]}
15
+ const valid={...contradictory,except:[{dimension:'document_kind',value:'final'}]}
16
+ const owner={id:'synthetic-owner',role:'user',hash:'a'.repeat(64),text:'长期处理探索性草稿时先确认试验目标。'}
17
+ const candidate={type:'user',scope:'global',basis:'explicit',summary:'探索性草稿先确认试验目标',meaning:contradictory,evidence:[{messageId:owner.id,quote:owner.text}]}
18
+ function box(run){const dir=realpathSync(mkdtempSync(join(tmpdir(),'rule-admission-')));try{return run(dir)}finally{rmSync(dir,{recursive:true,force:true})}}
19
+ test('new admission rejects canonical equality between a required and excluded term',()=>{
20
+ assert.throws(()=>assertMeaningSatisfiable(contradictory),{code:'memory-meaning-contradictory-conditions'})
21
+ assert.throws(()=>assertMeaningSatisfiable({...contradictory,conditions:[{dimension:'document_kind',value:' exploratory_draft '}]}),/contradictory-conditions/)
22
+ assert.equal(assessCandidate(candidate,[owner],false).reason,'invalid-meaning')
23
+ })
24
+ test('different excluded values and independent exclusions still allow useful contexts',()=>{
25
+ const meaning=assertMeaningSatisfiable(valid)
26
+ assert.equal(applicability(meaning,{document_kind:'exploratory_draft'}).state,'applicable')
27
+ assert.equal(applicability(assertMeaningSatisfiable({...valid,except:[{dimension:'audience',value:'adults'}]}),{document_kind:'exploratory_draft',audience:'children'}).state,'applicable')
28
+ assert.equal(assessCandidate({...candidate,meaning:valid},[owner],false).status,'eligible')
29
+ })
30
+ test('direct publication rejects impossible meaning before creating a data directory',()=>box(dir=>{
31
+ const target=join(dir,'not-created');assert.throws(()=>writeFixtureMemory({dir:target,type:'user',scope:'global',summary:candidate.summary,meaning:contradictory}),/contradictory-conditions/)
32
+ assert.equal(existsSync(target),false)
33
+ }))
34
+ test('reviewed adoption cannot publish an impossible pending candidate or change its ledger',()=>box(dir=>{
35
+ const pending=stageCandidate(dir,{...candidate,sessionId:'synthetic-review',indexRevision:storeRevision(dir),evidence:[{messageId:owner.id,hash:owner.hash,quote:owner.text}]})
36
+ const preview=adoptCandidate(dir,pending.id,{scope:'global'}),before=readFileSync(join(dir,'.candidates.json'),'utf8')
37
+ assert.throws(()=>adoptCandidate(dir,pending.id,{apply:true,scope:'global',reviewedIndex:preview.reviewedIndex,candidateRevision:preview.candidateRevision}),/contradictory-conditions/)
38
+ assert.equal(readFileSync(join(dir,'.candidates.json'),'utf8'),before);assert.equal(existsSync(join(dir,'MEMORY.md')),false)
39
+ }))
40
+ test('old effective self-excluding records retain their identities and remain readable without rewriting',()=>box(dir=>{
41
+ const fixture=JSON.parse(readFileSync(new URL('./corpus/legacy-self-excluding-dev36.json',import.meta.url)))
42
+ for(const[name,content]of Object.entries(fixture.files))writeFileSync(join(dir,name),content)
43
+ const records=candidateSnapshot(dir,'global').records;assert.equal(records.length,1);assert.equal(records[0].status,'recorded')
44
+ assert.deepEqual(normalizeMeaning(records[0].meaning),normalizeMeaning(contradictory))
45
+ assert.equal(applicability(records[0].meaning,{document_kind:'exploratory_draft'}).state,'not-applicable')
46
+ for(const[name,content]of Object.entries(fixture.files))assert.equal(readFileSync(join(dir,name),'utf8'),content)
47
+ }))
48
+ test('a scripted all-supported model vote cannot certify structurally impossible applicability',()=>{
49
+ const prepared=prepareValidationPrompt([owner],[candidate]),r=prepared.records[0]
50
+ const batch=new ValidationSubmission(prepared).batch(JSON.stringify({checks:[{candidateId:r.candidateId,fields:Object.fromEntries(VALIDATION_FIELDS.map(k=>[k,'supported'])),evidence:candidate.evidence}]}))
51
+ assert.equal(batch.verdicts[0].status,'rejected');assert.deepEqual(batch.verdicts[0].unsupportedFields,['applicability'])
52
+ })
@@ -0,0 +1,68 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,rmSync,realpathSync,existsSync,symlinkSync} from 'node:fs'
4
+ import {join} from 'node:path'
5
+ import {tmpdir} from 'node:os'
6
+ import {createHash} from 'node:crypto'
7
+ import {apply,managedMemoryStatus,writeMemory,indexLine,withdrawManagedSource,storeDirFor,searchStore} from './index.mjs'
8
+ import {projectIdentity} from './project-stores.mjs'
9
+ const hash=value=>createHash('sha256').update(value).digest('hex')
10
+ async function box(run){const root=realpathSync(mkdtempSync(join(tmpdir(),'memory-startup-'))),home=join(root,'home'),cwd=join(root,'work'),data=join(home,'memory'),previous=process.env.DSH_HOME;mkdirSync(home);mkdirSync(cwd);process.env.DSH_HOME=home;const effects=[]
11
+ try{return await run({root,home,cwd,data,effects})}finally{for(const effect of effects.reverse())effect?.();if(previous===undefined)delete process.env.DSH_HOME;else process.env.DSH_HOME=previous;rmSync(root,{recursive:true,force:true})}}
12
+ function mount(f,llm,config={autoCapture:{enabled:false}}){const tools=[],handlers=[],captured={},ctx={systemPrompt:{context:entry=>captured.provider=entry},workingDirectory:{get:()=>f.cwd},tools:{register:tool=>tools.push(tool)},llm,on(name,fn){handlers.push([name,fn])},effect(fn){const dispose=fn();if(typeof dispose==='function')f.effects.push(dispose)}};apply(ctx,config);return{tools,handlers,provider:captured.provider,emit(name,...args){for(const [event,fn]of handlers)if(event===name)fn(...args)}}}
13
+ function write(dir,scope='global',fresh=false){const summary=fresh?'Independent delivery cobalt7654':'Synthetic private palette jade9876';return writeMemory({dir,scope,type:'user',summary,detail:summary,line:indexLine('user',summary,undefined,true),provenance:{basis:'tool-context',sessionId:fresh?'fresh-owner':'withdrawn-owner',callHash:hash(summary),evidence:[{messageId:'root',hash:hash('synthetic source'),quote:summary}]}})}
14
+ const rendered=h=>h.provider.text({agent:{session:{id:'synthetic-agent'}}})
15
+ test('fresh default load creates source control and cold reload preserves the same installation',()=>box(async f=>{
16
+ const first=mount(f);assert.equal(managedMemoryStatus(f.data).registered,true);const id=managedMemoryStatus(f.data).installationId
17
+ assert.equal(JSON.parse(readFileSync(join(f.data,'.loaded.json'))).sourceControl.state,'managed');assert.doesNotThrow(()=>rendered(first));assert.equal(managedMemoryStatus(f.data).stores.length,2)
18
+ const second=mount(f);assert.equal(managedMemoryStatus(f.data).installationId,id);const status=await second.tools.find(tool=>tool.name==='memory_status').execute({scope:'global'});assert.equal(status.sourceControl.state,'managed');assert.ok(status.index)
19
+ }))
20
+ test('old data and queued metadata require upgrade: no body injection, writes or capture calls',()=>box(async f=>{
21
+ mkdirSync(f.data);const old='- [user] Synthetic private old jade9876 — 索引摘要\n',queue='synthetic old queue must remain byte-identical';writeFileSync(join(f.data,'MEMORY.md'),old);writeFileSync(join(f.data,'.capture-inputs.json'),queue);let calls=0
22
+ const host=mount(f,{listProviders:()=>[{provider:'fixture',model:'fixture'}],prepareCall(){calls++;throw Error('must not call')}},{autoCapture:{everyTurns:1}}),text=rendered(host);assert.match(text,/需要升级/);assert.doesNotMatch(text,/jade9876/)
23
+ const status=await host.tools.find(tool=>tool.name==='memory_status').execute({scope:'global'});assert.equal(status.sourceControl.state,'migration-required');assert.equal(status.index,undefined)
24
+ for(const name of ['memory_search','memory_write','memory_prune','memory_forget','memory_links'])await assert.rejects(host.tools.find(tool=>tool.name===name).execute({scope:'global'}),/upgrade-required/)
25
+ const session={id:'old-owner'};host.emit('session/event',session,{type:'user/message',data:{source:{kind:'user'},content:[{type:'text',text:'Synthetic fresh long term request'}]}});host.emit('session/event',session,{type:'step/end'});await new Promise(resolve=>setTimeout(resolve,30));assert.equal(calls,0)
26
+ assert.equal(readFileSync(join(f.data,'MEMORY.md'),'utf8'),old);assert.equal(readFileSync(join(f.data,'.capture-inputs.json'),'utf8'),queue);assert.equal(existsSync(f.data+'.control'),false);assert.equal(JSON.parse(readFileSync(join(f.data,'.loaded.json'))).autoCapture.enabled,false)
27
+ }))
28
+ test('an interrupted old publication is diagnosed before upgrade without rewriting its journal',()=>box(async f=>{
29
+ mkdirSync(f.data);writeFileSync(join(f.data,'.publication.json'),'synthetic interrupted journal');writeFileSync(join(f.data,'MEMORY.md'),'- [user] Synthetic half-published jade9876\n');const host=mount(f),text=rendered(host)
30
+ assert.match(text,/中断发布/);assert.doesNotMatch(text,/jade9876/);assert.equal(readFileSync(join(f.data,'.publication.json'),'utf8'),'synthetic interrupted journal');assert.equal(existsSync(f.data+'.control'),false);assert.equal((await host.tools.find(tool=>tool.name==='memory_status').execute({scope:'global'})).sourceControl.code,'managed-memory-publication-needs-recovery')
31
+ }))
32
+ test('a missing independent ledger after healthy startup produces unavailable status and is never recreated',()=>box(async f=>{
33
+ const host=mount(f);write(f.data);rmSync(f.data+'.control',{recursive:true});assert.doesNotMatch(rendered(host),/jade9876/);assert.match(rendered(host),/暂不可用/)
34
+ const status=await host.tools.find(tool=>tool.name==='memory_status').execute({scope:'global'});assert.equal(status.sourceControl.state,'unavailable');await assert.rejects(host.tools.find(tool=>tool.name==='memory_search').execute({scope:'global',query:'jade9876'}),/control-missing/);assert.equal(existsSync(f.data+'.control'),false)
35
+ const next=mount(f);assert.equal(JSON.parse(readFileSync(join(f.data,'.loaded.json'))).sourceControl.state,'unavailable');assert.doesNotMatch(rendered(next),/jade9876/);assert.equal(existsSync(f.data+'.control'),false)
36
+ }))
37
+ test('removing every ownership marker after startup cannot downgrade a context read to raw data',()=>box(async f=>{
38
+ const host=mount(f);write(f.data);
39
+ rmSync(f.data+'.control',{recursive:true});rmSync(f.data+'.control-binding.json');rmSync(join(f.data,'.managed-policy.json'));
40
+ const text=rendered(host);assert.match(text,/暂不可用/);assert.doesNotMatch(text,/jade9876/);assert.equal(existsSync(f.data+'.control'),false);
41
+ }))
42
+ test('first use of a fresh project inherits every existing source barrier before ordinary access',()=>box(async f=>{
43
+ const host=mount(f);write(f.data);const view=withdrawManagedSource(f.data,'withdrawn-owner','root'),op=withdrawManagedSource(f.data,'withdrawn-owner','root',{apply:true,controlReview:view.controlReview})
44
+ assert.equal(managedMemoryStatus(f.data).stores.length,1);rendered(host);const project=storeDirFor('project',f.cwd),status=managedMemoryStatus(f.data);assert.equal(status.stores.length,2);assert.equal(status.operations[0].pending,1)
45
+ assert.throws(()=>write(project,'project'),/source-revoked/);write(project,'project',true);assert.ok(searchStore(project,'cobalt7654').hits.length>0);assert.equal(withdrawManagedSource(f.data,'withdrawn-owner','root',{operationId:op.id,apply:true}).cleanupComplete,true)
46
+ }))
47
+ test('an existing nonempty project target requires review without registering or injecting its old contents',()=>box(async f=>{
48
+ const host=mount(f),project=join(f.data,'projects/v2-'+projectIdentity(f.cwd));mkdirSync(project,{recursive:true});const old='- [project] Synthetic unknown old project jade9876 — 索引摘要\n';writeFileSync(join(project,'MEMORY.md'),old)
49
+ assert.match(rendered(host),/需要升级/);assert.doesNotMatch(rendered(host),/jade9876/);assert.equal(managedMemoryStatus(f.data).stores.length,1);assert.equal(readFileSync(join(project,'MEMORY.md'),'utf8'),old);assert.equal(existsSync(join(project,'.managed-policy.json')),false)
50
+ const status=await host.tools.find(tool=>tool.name==='memory_status').execute({}, {agent:{session:{}}});assert.equal(status.sourceControl.state,'unavailable');assert.equal(status.index,undefined)
51
+ }))
52
+ test('a linked root is unavailable and cannot be turned into a fresh managed installation',()=>box(async f=>{
53
+ const outside=join(f.root,'outside');mkdirSync(outside);writeFileSync(join(outside,'sentinel'),'Synthetic unchanged');symlinkSync(outside,f.data);const host=mount(f);assert.match(rendered(host),/暂不可用/);assert.equal(existsSync(join(outside,'.managed-policy.json')),false);assert.equal(readFileSync(join(outside,'sentinel'),'utf8'),'Synthetic unchanged');assert.equal(existsSync(f.data+'.control'),false)
54
+ }))
55
+ test('capture deduplication input excludes withdrawn index text even while the old projection remains on disk',()=>box(async f=>{
56
+ const fresh=mount(f);write(f.data);const view=withdrawManagedSource(f.data,'withdrawn-owner','root');withdrawManagedSource(f.data,'withdrawn-owner','root',{apply:true,controlReview:view.controlReview,cleanup:false});let requestText,calls=0
57
+ const llm={listProviders:()=>[{provider:'fixture',model:'fixture'}],async prepareCall(){calls++;return{config:{},async *stream(request){requestText=JSON.stringify(request.messages);yield{type:'text-delta',text:'[]'}}}}},host=mount(f,llm,{autoCapture:{everyTurns:1}}),session={id:'independent-capture-session'}
58
+ host.emit('session/event',session,{type:'user/message',data:{source:{kind:'user'},content:[{type:'text',text:'Synthetic independent lasting delivery preference cobalt7654'}]}});host.emit('session/event',session,{type:'step/end'})
59
+ const until=Date.now()+4000;while(!requestText&&Date.now()<until)await new Promise(resolve=>setTimeout(resolve,10));assert.equal(calls,1);assert.equal(typeof requestText,'string');assert.doesNotMatch(requestText,/jade9876/);assert.match(readFileSync(join(f.data,'MEMORY.md'),'utf8'),/jade9876/);assert.equal(searchStore(f.data,'jade9876').hits.length,0)
60
+ }))
61
+ for(const id of ['synthetic-fallback-owner','synthetic-\u200bfallback-owner'])test('fallback capture checks revoked owner roots before preparation; canonical identity '+JSON.stringify(id),()=>box(async f=>{
62
+ let calls=0,streams=0,body;const llm={listProviders:()=>[{provider:'fixture',model:'fixture'}],async prepareCall(){calls++;return{config:{},async *stream(request){streams++;body=JSON.stringify(request.messages);yield{type:'text-delta',text:'[]'}}}}},host=mount(f,llm,{autoCapture:{everyTurns:1}}),session={id}
63
+ const emit=(who,seq,text)=>host.emit('session/event',who,{type:'user/message',seq,data:{source:{kind:'user'},content:[{type:'text',text}]}})
64
+ emit(session,1,'Synthetic revoked original quotation jade9876');const view=withdrawManagedSource(f.data,id,id+':1');withdrawManagedSource(f.data,id,id+':1',{apply:true,controlReview:view.controlReview,cleanup:false});host.emit('session/event',session,{type:'step/end',seq:2})
65
+ const state=join(f.data,'.capture-state.json'),wait=async who=>{const until=Date.now()+4000;while(Date.now()<until){if(existsSync(state)){const value=JSON.parse(readFileSync(state));if(value.sessionId===who&&!value.running&&value.lastCaptureAt)return value}await new Promise(resolve=>setTimeout(resolve,10))}throw Error('synthetic-capture-deadline')}
66
+ const stopped=await wait(id);assert.equal(stopped.lastError,'capture-input-source-withdrawn');assert.equal(calls,0);assert.equal(streams,0);assert.equal(existsSync(join(f.data,'MEMORY.md')),false)
67
+ const independent={id:'synthetic-independent-'+id};emit(independent,1,'Synthetic valid independent quotation cobalt7654');host.emit('session/event',independent,{type:'step/end',seq:2});await wait(independent.id);assert.equal(calls,1);assert.equal(streams,1);assert.doesNotMatch(body,/jade9876/)
68
+ }))
@@ -0,0 +1,187 @@
1
+ import {realpathSync} from 'node:fs'
2
+ import {applyWithOwnerFixture as apply} from './fixture-host.mjs'
3
+ /**
4
+ * 工具 schema 的静态校验。跑法:node --test ~/.dsh/plugins/memory/test-schema.mjs
5
+ *
6
+ * 为什么需要它:宿主在**注册时**校验 output schema,不合格会让整个插件加载失败;
7
+ * 而单元测试直接调 tool.execute(),完全绕过那道校验。
8
+ * 2026-10-28 就是这样:`additionalProperties: {type:'integer'}` 让插件静默不加载,
9
+ * 272 个测试却全绿。这个文件把宿主的三条硬规则搬进测试。
10
+ *
11
+ * 规则(来自宿主 JsonSchemaError 的实际报错):
12
+ * 1. additionalProperties 必须是布尔值,不能是 schema 对象
13
+ * 2. 每个 schema 节点必须有 type(或 oneOf/anyOf)
14
+ * 3. required 里的字段必须在 properties 里
15
+ */
16
+
17
+ import { test } from 'node:test'
18
+ import assert from 'node:assert/strict'
19
+
20
+ import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'
21
+ import { join } from 'node:path'
22
+ import { tmpdir } from 'node:os'
23
+
24
+ function tools() {
25
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-mem-schema-')))
26
+ const home = join(root, 'home')
27
+ const cwd = join(root, 'proj')
28
+ mkdirSync(home, { recursive: true })
29
+ mkdirSync(cwd, { recursive: true })
30
+ const prev = process.env.DSH_HOME
31
+ process.env.DSH_HOME = home
32
+ const captured = { tools: [] }
33
+ apply({
34
+ systemPrompt: { context() {} },
35
+ workingDirectory: { get: () => cwd },
36
+ tools: { register: (definition) => captured.tools.push(definition) },
37
+ on() {},
38
+ })
39
+ return {
40
+ list: captured.tools,
41
+ cleanup() {
42
+ if (prev === undefined) delete process.env.DSH_HOME
43
+ else process.env.DSH_HOME = prev
44
+ rmSync(root, { recursive: true, force: true })
45
+ },
46
+ }
47
+ }
48
+
49
+ function walk(node, path, problems) {
50
+ if (node === null || typeof node !== 'object') return
51
+ if (Array.isArray(node)) {
52
+ node.forEach((item, i) => walk(item, `${path}[${i}]`, problems))
53
+ return
54
+ }
55
+ // Installed DSH output-schema contract rejects unsupported constraint
56
+ // keywords instead of merely ignoring them. Keep value bounds in validators.
57
+ const supported=new Set(['type','oneOf','anyOf','properties','required','additionalProperties','items','enum','const','description','title','default','examples'])
58
+ for(const key of Object.keys(node))if(!supported.has(key))problems.push(`${path}.${key} 不是已核对的宿主schema关键字`)
59
+ if ('additionalProperties' in node && typeof node.additionalProperties !== 'boolean') {
60
+ problems.push(`${path}.additionalProperties 必须是布尔值`)
61
+ }
62
+ if ('type' in node) {
63
+ if (node.type === 'object' && node.properties !== undefined) {
64
+ for (const key of node.required ?? []) {
65
+ if (node.properties[key] === undefined) problems.push(`${path}.required 里的 ${key} 不在 properties`)
66
+ }
67
+ }
68
+ }
69
+ for (const [key, value] of Object.entries(node)) {
70
+ if (key === 'properties') {
71
+ for (const [prop, schema] of Object.entries(value)) walk(schema, `${path}.properties.${prop}`, problems)
72
+ } else if (['oneOf','anyOf','items'].includes(key)) {
73
+ walk(value, `${path}.${key}`, problems)
74
+ }
75
+ }
76
+ }
77
+
78
+ test('所有工具的 parameters 与 output.schema 都过宿主的 schema 规则', () => {
79
+ const { list, cleanup } = tools()
80
+ try {
81
+ assert.equal(list.length, 6)
82
+ for (const tool of list) {
83
+ const problems = []
84
+ walk(tool.parameters, `${tool.name}.parameters`, problems)
85
+ walk(tool.output.schema, `${tool.name}.output`, problems)
86
+ assert.deepEqual(problems, [], `${tool.name}:\n${problems.join('\n')}`)
87
+ }
88
+ } finally {
89
+ cleanup()
90
+ }
91
+ })
92
+
93
+ test('每个工具都有 name / description / execute / render', () => {
94
+ const { list, cleanup } = tools()
95
+ try {
96
+ for (const tool of list) {
97
+ assert.equal(typeof tool.name, 'string')
98
+ assert.ok(tool.description.length > 0)
99
+ assert.equal(typeof tool.execute, 'function')
100
+ assert.equal(typeof tool.output.render, 'function')
101
+ assert.equal(typeof tool.output.schema, 'object')
102
+ }
103
+ } finally {
104
+ cleanup()
105
+ }
106
+ })
107
+
108
+ function lossless(value) {
109
+ assert.deepEqual(value, JSON.parse(JSON.stringify(value)), '工具结果必须原样往返 JSON,不能携带 undefined')
110
+ }
111
+
112
+ test('原生工具输出:首次写入省略未填写的可选字段', async () => {
113
+ const box = tools()
114
+ try {
115
+ const value = await box.list.find(t => t.name === 'memory_write').execute({type:'user',scope:'global',summary:'固定使用紫罗兰色的画板'}, {})
116
+ lossless(value)
117
+ assert.equal(Object.hasOwn(value, 'detailPath'), false)
118
+ assert.equal(Object.hasOwn(value, 'superseded'), false)
119
+ assert.equal(value.duplicate, false)
120
+ } finally { box.cleanup() }
121
+ })
122
+
123
+ test('原生工具输出:重复写入仍是有效 JSON 且不重复落盘', async () => {
124
+ const box = tools()
125
+ try {
126
+ const tool = box.list.find(t => t.name === 'memory_write')
127
+ const args = {type:'user',scope:'global',summary:'固定使用紫罗兰色的画板'}
128
+ await tool.execute(args, {})
129
+ const value = await tool.execute(args, {})
130
+ lossless(value)
131
+ assert.equal(value.duplicate, true)
132
+ const status = await box.list.find(t => t.name === 'memory_status').execute({scope:'global'}, {})
133
+ assert.equal(status.index.lines, 1)
134
+ } finally { box.cleanup() }
135
+ })
136
+
137
+ test('原生工具输出:填写细节时保留有效 detailPath', async () => {
138
+ const box = tools()
139
+ try {
140
+ const value = await box.list.find(t => t.name === 'memory_write').execute({type:'user',scope:'global',summary:'固定使用紫罗兰色的画板',detail:'用于后续绘画项目的稳定偏好。'}, {})
141
+ lossless(value)
142
+ assert.equal(typeof value.detailPath, 'string')
143
+ assert.equal(Object.hasOwn(value, 'superseded'), false)
144
+ } finally { box.cleanup() }
145
+ })
146
+
147
+ test('原生工具输出:取代与双向版本查询保留关系并可往返 JSON', async () => {
148
+ const box = tools()
149
+ try {
150
+ const write = box.list.find(t => t.name === 'memory_write')
151
+ const links = box.list.find(t => t.name === 'memory_links')
152
+ const old = await write.execute({type:'user',scope:'global',summary:'固定使用紫罗兰色的画板'}, {})
153
+ const value = await write.execute({type:'user',scope:'global',summary:'固定使用深绿色的画板',supersedes:'紫罗兰色'}, {})
154
+ lossless(value)
155
+ assert.equal(typeof value.superseded, 'string')
156
+ const older = await links.execute({scope:'global',id:old.id}, {})
157
+ const newer = await links.execute({scope:'global',id:value.id}, {})
158
+ lossless(older);lossless(newer)
159
+ assert.equal(older.found, false)
160
+ assert.equal(newer.supersedesLine, old.indexLine)
161
+ } finally { box.cleanup() }
162
+ })
163
+
164
+ test('原生工具输出:无版本链或未找到的 links 不带未定义属性', async () => {
165
+ const box = tools()
166
+ try {
167
+ const value = await box.list.find(t => t.name === 'memory_write').execute({type:'user',scope:'global',summary:'固定使用紫罗兰色的画板'}, {})
168
+ const tool = box.list.find(t => t.name === 'memory_links')
169
+ lossless(await tool.execute({scope:'global',id:value.id}, {}))
170
+ const missing = await tool.execute({scope:'global',match:'不存在的风琴'}, {})
171
+ lossless(missing);assert.equal(missing.found, false)
172
+ } finally { box.cleanup() }
173
+ })
174
+
175
+ test('原生工具输出:六工具完整生命周期均保持 JSON 结果契约', async () => {
176
+ const box = tools()
177
+ try {
178
+ const call = async (name,args) => {const value=await box.list.find(t => t.name === name).execute({scope:'global',...args}, {});lossless(value);return value}
179
+ await call('memory_write',{type:'user',summary:'固定使用紫罗兰色的画板'})
180
+ assert.ok((await call('memory_search',{query:'紫罗兰色'})).hits.length)
181
+ assert.equal((await call('memory_links',{match:'紫罗兰色'})).found, true)
182
+ assert.equal((await call('memory_status',{})).index.lines, 1)
183
+ assert.equal((await call('memory_prune',{})).applied, false)
184
+ assert.equal((await call('memory_forget',{match:'紫罗兰色'})).removed, 1)
185
+ assert.equal((await call('memory_status',{})).index.lines, 0)
186
+ } finally { box.cleanup() }
187
+ })