@yaks/persona 0.0.0-stage → 0.2.36

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 (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +401 -2
  3. package/_dist/comp.d.ts +13 -0
  4. package/_dist/comp.d.ts.map +1 -0
  5. package/_dist/effects.d.ts +22 -0
  6. package/_dist/effects.d.ts.map +1 -0
  7. package/_dist/mod.d.ts +40 -0
  8. package/_dist/mod.d.ts.map +1 -0
  9. package/_dist/name.d.ts +49 -0
  10. package/_dist/name.d.ts.map +1 -0
  11. package/_dist/owed.d.ts +56 -0
  12. package/_dist/owed.d.ts.map +1 -0
  13. package/_dist/part.d.ts +4 -0
  14. package/_dist/part.d.ts.map +1 -0
  15. package/_dist/shipped.d.ts +30 -0
  16. package/_dist/shipped.d.ts.map +1 -0
  17. package/_dist/skill-checkout.d.ts +6 -0
  18. package/_dist/skill-checkout.d.ts.map +1 -0
  19. package/_dist/skill-effects.d.ts +25 -0
  20. package/_dist/skill-effects.d.ts.map +1 -0
  21. package/_dist/skill-mirror-io.d.ts +7 -0
  22. package/_dist/skill-mirror-io.d.ts.map +1 -0
  23. package/_dist/skill-mirror.d.ts +15 -0
  24. package/_dist/skill-mirror.d.ts.map +1 -0
  25. package/_dist/skill-text.d.ts +28 -0
  26. package/_dist/skill-text.d.ts.map +1 -0
  27. package/_dist/skills.d.ts +22 -0
  28. package/_dist/skills.d.ts.map +1 -0
  29. package/_dist/tools.d.ts +9 -0
  30. package/_dist/tools.d.ts.map +1 -0
  31. package/_dist/ui.d.ts +6 -0
  32. package/_dist/ui.d.ts.map +1 -0
  33. package/_dist/views.d.ts +19 -0
  34. package/_dist/views.d.ts.map +1 -0
  35. package/_dist/vocab.d.ts +7 -0
  36. package/_dist/vocab.d.ts.map +1 -0
  37. package/_dist/voice.d.ts +47 -0
  38. package/_dist/voice.d.ts.map +1 -0
  39. package/_dist/worn.d.ts +55 -0
  40. package/_dist/worn.d.ts.map +1 -0
  41. package/carried.js +201 -0
  42. package/carried.js.map +1 -0
  43. package/carried.ts +269 -0
  44. package/comp.js +31 -0
  45. package/comp.js.map +1 -0
  46. package/comp.ts +38 -0
  47. package/deno.json +1 -0
  48. package/desk.js +201 -0
  49. package/desk.js.map +1 -0
  50. package/desk.ts +301 -0
  51. package/effects.js +106 -0
  52. package/effects.js.map +1 -0
  53. package/effects.ts +120 -0
  54. package/files.js +305 -0
  55. package/files.js.map +1 -0
  56. package/files.ts +319 -0
  57. package/inspect.js +66 -0
  58. package/inspect.js.map +1 -0
  59. package/inspect.ts +30 -0
  60. package/mod.js +40 -0
  61. package/mod.js.map +1 -0
  62. package/mod.ts +61 -0
  63. package/name.js +161 -0
  64. package/name.js.map +1 -0
  65. package/name.ts +184 -0
  66. package/owed.js +196 -0
  67. package/owed.js.map +1 -0
  68. package/owed.ts +256 -0
  69. package/package.json +83 -4
  70. package/part.js +4 -0
  71. package/part.js.map +1 -0
  72. package/part.ts +4 -0
  73. package/shipped.js +130 -0
  74. package/shipped.js.map +1 -0
  75. package/shipped.ts +131 -0
  76. package/skill-checkout.js +92 -0
  77. package/skill-checkout.js.map +1 -0
  78. package/skill-checkout.ts +121 -0
  79. package/skill-effects.js +244 -0
  80. package/skill-effects.js.map +1 -0
  81. package/skill-effects.ts +274 -0
  82. package/skill-mirror-io.js +193 -0
  83. package/skill-mirror-io.js.map +1 -0
  84. package/skill-mirror-io.ts +212 -0
  85. package/skill-mirror.js +659 -0
  86. package/skill-mirror.js.map +1 -0
  87. package/skill-mirror.ts +640 -0
  88. package/skill-text.js +158 -0
  89. package/skill-text.js.map +1 -0
  90. package/skill-text.ts +183 -0
  91. package/skills.js +238 -0
  92. package/skills.js.map +1 -0
  93. package/skills.ts +383 -0
  94. package/text.js +59 -0
  95. package/text.js.map +1 -0
  96. package/text.ts +60 -0
  97. package/tools.js +76 -0
  98. package/tools.js.map +1 -0
  99. package/tools.ts +91 -0
  100. package/ui.js +19 -0
  101. package/ui.js.map +1 -0
  102. package/ui.ts +34 -0
  103. package/views.js +27 -0
  104. package/views.js.map +1 -0
  105. package/views.ts +29 -0
  106. package/vocab.js +14 -0
  107. package/vocab.js.map +1 -0
  108. package/vocab.json +270 -0
  109. package/vocab.ts +16 -0
  110. package/voice.js +105 -0
  111. package/voice.js.map +1 -0
  112. package/voice.ts +133 -0
  113. package/worn.js +328 -0
  114. package/worn.js.map +1 -0
  115. package/worn.ts +336 -0
@@ -0,0 +1,244 @@
1
+ // The declared skill_files and skill_watch effects. Skills are a separate
2
+ // opt-in: persona files:true must never enable bidirectional repository writes.
3
+ // The pool owns these promises, including polling and shutdown cleanup. Imports
4
+ // and exports share a bounded queue and a per-pass lease; the watcher has its
5
+ // own lease so graph edits need not wait for the polling duty to finish. A
6
+ // poll stats the files a sync would read and syncs only when they moved. What a
7
+ // pass could not do is retried, so one a retry did not clear reaches the tracker.
8
+ import * as fs from "@yaks/file/io";
9
+ import { holding, sleep } from "@yaks/effects";
10
+ import { derivedEid } from "@yaks/graph/identity";
11
+ import { dirname, join, resolve } from 'node:path';
12
+ import { skillRoots, syncSkills } from "./skill-mirror.js";
13
+ import { stamp as stampOf } from "./skill-mirror-io.js";
14
+ /** Continuous polling is intentional: filesystem watches miss renames and
15
+ * index-only changes. Each pass reconciles the present, not a stale event.
16
+ * A poll is only stats: it compares each root's stamp with the one its last
17
+ * clean sync started from, and passes when any moved or never settled. */ export let skillEffects = (host, options = {}, runtime = {})=>{
18
+ if (!options.skills) return {};
19
+ let files = runtime.files ?? fs;
20
+ let roots = runtime.roots ?? skillRoots;
21
+ let sync = runtime.sync ?? syncSkills;
22
+ let stamp = runtime.stamp ?? stampOf;
23
+ let pause = runtime.pause ?? sleep;
24
+ let stopping = host.stopping ?? AbortSignal.abort();
25
+ let db = host.config?.db;
26
+ let persistent = db && db != ':memory:' ? join(dirname(resolve(db)), 'mirror', 'skills') : undefined;
27
+ let temporary;
28
+ let saved = new Map();
29
+ let names = new Map();
30
+ let memory = async (root)=>{
31
+ let name = names.get(root);
32
+ if (!name) names.set(root, name = `${derivedEid(`skills|${root}`)}.json`);
33
+ let dir = persistent ?? await (temporary ??= (async ()=>{
34
+ let dir = await files.makeTempDir({
35
+ prefix: 'yak-skills-'
36
+ });
37
+ try {
38
+ for (let [name, body] of saved){
39
+ await files.writeTextFile(join(dir, name), body);
40
+ }
41
+ return dir;
42
+ } catch (error) {
43
+ await files.remove(dir, {
44
+ recursive: true
45
+ });
46
+ throw error;
47
+ }
48
+ })());
49
+ return join(dir, name);
50
+ };
51
+ // A handler-only host has no awaited shutdown callback. Keep its agreement
52
+ // bytes, not an idle directory: clean inside the awaited handler and restore
53
+ // on its next pass. A watcher retains its directory until it ends (including
54
+ // failure), then uses the same route. No abort listener detaches I/O errors.
55
+ let clean = async (trailing = false)=>{
56
+ let owned = temporary;
57
+ if (!owned) return;
58
+ let retained = false;
59
+ try {
60
+ let dir = await owned;
61
+ try {
62
+ for (let name of names.values()){
63
+ try {
64
+ saved.set(name, await files.readTextFile(join(dir, name)));
65
+ } catch (error) {
66
+ if (!fs.isNotFound(error)) throw error;
67
+ saved.delete(name);
68
+ }
69
+ }
70
+ // An event during cleanup shares this batch. Keep its memo in place
71
+ // for the trailing pass; callers cannot observe completion yet.
72
+ retained = trailing && dirty && !host.stopping?.aborted;
73
+ } finally{
74
+ if (!retained) await files.remove(dir, {
75
+ recursive: true
76
+ });
77
+ }
78
+ } finally{
79
+ if (!retained) temporary = undefined;
80
+ }
81
+ };
82
+ // holding reports acquisition/renewal/release failures. Turn that report into
83
+ // the awaited effect's failure instead of detaching an exception from a timer.
84
+ let leased = async (name, signal, work)=>{
85
+ if (!host.me) return await work(signal);
86
+ let failed = false;
87
+ let error;
88
+ let interrupted = new AbortController();
89
+ await holding(host.graph, name, {
90
+ holder: host.me,
91
+ gone: host.gone,
92
+ signal: AbortSignal.any([
93
+ signal,
94
+ interrupted.signal
95
+ ]),
96
+ report: (e)=>{
97
+ if (!failed) error = e;
98
+ failed = true;
99
+ interrupted.abort();
100
+ }
101
+ }, work);
102
+ if (failed) throw error;
103
+ };
104
+ // The roots the last pass found, and the stamp each one's last clean sync
105
+ // started from. Graph edits arrive as skill_files passes, which refresh both.
106
+ let seen;
107
+ let settled = new Map();
108
+ let moved = async ()=>{
109
+ if (!seen) return true;
110
+ for (let root of seen){
111
+ let was = settled.get(root);
112
+ if (was == undefined || was != await stamp(root)) return true;
113
+ }
114
+ return false;
115
+ };
116
+ // What each root's last pass could not do, and whether it has been reported.
117
+ // A race clears on the next pass; one that survives a retry is a failure, told
118
+ // once however often it is retried, and told again if it clears and returns.
119
+ let unsettled = new Map();
120
+ let unresolved = async (root, reasons)=>{
121
+ let was = unsettled.get(root);
122
+ let now = new Map();
123
+ for (let reason of new Set(reasons)){
124
+ let told = was?.get(reason);
125
+ now.set(reason, told != undefined);
126
+ if (told == undefined) {
127
+ console.warn('@yaks/persona skills —', root, reason);
128
+ } else if (!told) {
129
+ await host.report?.(new Error(`skills at ${root}: ${reason}`), {
130
+ tags: {
131
+ step: 'skill_files',
132
+ root
133
+ }
134
+ });
135
+ }
136
+ }
137
+ if (now.size) unsettled.set(root, now);
138
+ else unsettled.delete(root);
139
+ };
140
+ let pass = async ()=>{
141
+ if (host.stopping?.aborted) return;
142
+ await leased('@yaks/persona/skill_files', host.stopping ?? new AbortController().signal, async (signal)=>{
143
+ seen = await roots(host.graph);
144
+ for (let root of settled.keys()){
145
+ if (!seen.includes(root)) settled.delete(root);
146
+ }
147
+ for (let root of unsettled.keys()){
148
+ if (!seen.includes(root)) unsettled.delete(root);
149
+ }
150
+ for (let root of seen){
151
+ if (signal.aborted) break;
152
+ settled.delete(root);
153
+ // Stamped before the sync reads, so a change during it moves it.
154
+ let before = await stamp(root);
155
+ let result = await sync(host.graph, root, await memory(root));
156
+ // Conflicts and refusals (a dirty checkout, a diverged main) may
157
+ // clear without touching these files, so they keep being retried.
158
+ if (!result.conflicts.length && !result.failed.length) {
159
+ settled.set(root, before);
160
+ }
161
+ await unresolved(root, [
162
+ ...result.conflicts.map((path)=>`conflict: ${path}`),
163
+ ...result.failed
164
+ ]);
165
+ }
166
+ });
167
+ };
168
+ let last = Promise.resolve();
169
+ let active;
170
+ let started = false;
171
+ let dirty = false;
172
+ let watching;
173
+ let watcher = false;
174
+ let reconcile = ()=>{
175
+ if (active) {
176
+ // Before the queued pass begins it already sees the latest graph. During
177
+ // a pass, any number of events owe only one trailing reconciliation.
178
+ if (started) dirty = true;
179
+ return active;
180
+ }
181
+ let done = last.then(async ()=>{
182
+ started = true;
183
+ try {
184
+ do {
185
+ dirty = false;
186
+ await pass();
187
+ // Cleanup yields to I/O too: events arriving there still owe the
188
+ // trailing pass before this shared batch promise can settle.
189
+ if (!watcher || stopping.aborted) await clean(true);
190
+ }while (dirty && !host.stopping?.aborted)
191
+ } finally{
192
+ try {
193
+ if (temporary && (!watcher || stopping.aborted)) await clean();
194
+ } finally{
195
+ // Clear before yielding again: an event after the last dirty check
196
+ // must enqueue a new batch, not join one that already finished.
197
+ started = false;
198
+ active = undefined;
199
+ }
200
+ }
201
+ });
202
+ active = done;
203
+ // Only the queue continuation recovers. Every caller receives the original
204
+ // rejection so the effects pool can report/retry unknown mirror failures.
205
+ last = done.then(()=>{}, ()=>{});
206
+ return done;
207
+ };
208
+ let watch = ()=>{
209
+ if (watching) return watching;
210
+ watcher = true;
211
+ watching = (async ()=>{
212
+ try {
213
+ await leased('@yaks/persona/skill_watch', stopping, async (signal)=>{
214
+ // A minimal one-shot host reconciles once. Live hosts poll until
215
+ // shutdown or loss of the singleton watcher lease. Every start
216
+ // reconciles, whatever an earlier watcher settled.
217
+ seen = undefined;
218
+ do {
219
+ if (await moved()) await reconcile();
220
+ if (signal.aborted) break;
221
+ await pause(runtime.poll ?? 2_000, signal);
222
+ }while (!signal.aborted)
223
+ });
224
+ } finally{
225
+ watcher = false;
226
+ // Serialize cleanup with graph-triggered passes too, including a pass
227
+ // still finishing when a poll or lease fails.
228
+ let cleanup = last.then(()=>clean());
229
+ last = cleanup.then(()=>{}, ()=>{});
230
+ try {
231
+ await cleanup;
232
+ } finally{
233
+ watching = undefined;
234
+ }
235
+ }
236
+ })();
237
+ return watching;
238
+ };
239
+ return {
240
+ skill_files: reconcile,
241
+ skill_watch: watch
242
+ };
243
+ };
244
+ //# sourceMappingURL=skill-effects.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skill-effects.js","sources":["./skill-effects.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,gFAAgF;AAChF,gFAAgF;AAChF,8EAA8E;AAC9E,2EAA2E;AAC3E,gFAAgF;AAChF,kFAAkF;AAElF,YAAY,6BAAkC;AAE9C,SAAwB,OAAO,EAAE,KAAK,6BAAkC;AAGxE,SAAS,UAAU,oCAAyC;AAC5D,SAAS,OAAO,EAAE,IAAI,EAAE,OAAO,QAAQ,YAAW;AAClD,SAAS,UAAU,EAAE,UAAU,4BAA2B;AAC1D,SAAS,SAAS,OAAO,+BAA8B;AA4BvD;;;wEAGwE,GACxE,OAAO,IAAI,eAAe,CACxB,MACA,UAAwB,CAAC,CAAC,EAC1B,UAAwB,CAAC,CAAC;EAE1B,IAAI,CAAC,QAAQ,MAAM,EAAE,OAAO,CAAC;EAC7B,IAAI,QAAQ,QAAQ,KAAK,IAAI;EAC7B,IAAI,QAAQ,QAAQ,KAAK,IAAI;EAC7B,IAAI,OAAO,QAAQ,IAAI,IAAI;EAC3B,IAAI,QAAQ,QAAQ,KAAK,IAAI;EAC7B,IAAI,QAAQ,QAAQ,KAAK,IAAI;EAC7B,IAAI,WAAW,KAAK,QAAQ,IAAI,YAAY,KAAK;EACjD,IAAI,KAAK,KAAK,MAAM,EAAE;EACtB,IAAI,aAAa,MAAM,MAAM,aACzB,KAAK,QAAQ,QAAQ,MAAM,UAAU,YACrC;EACJ,IAAI;EACJ,IAAI,QAAQ,IAAI;EAChB,IAAI,QAAQ,IAAI;EAChB,IAAI,SAAS,OAAO;IAClB,IAAI,OAAO,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AS,OAAO,EAAE,MAAM,MAAM;QAChD,QAAS,SAAS,CAAC,KAAK,QAAQ,EAAE,QAAQ;MAC5C,SAAU;QACR,IAAI;UACF,IAAI,aAAa,CAAC,CAAC,WAAW,SAAS,OAAO,GAAG,MAAM;QACzD,SAAU;UACR,mEAAmE;UACnE,gEAAgE;UAChE,UAAU;UACV,SAAS;QACX;MACF;IACF;IACA,SAAS;IACT,2EAA2E;IAC3E,0EAA0E;IAC1E,OAAO,KAAK,IAAI,CAAC,KAAO,GAAG,KAAO;IAClC,OAAO;EACT;EACA,IAAI,QAAQ;IACV,IAAI,UAAU,OAAO;IACrB,UAAU;IACV,WAAW,CAAC;MACV,IAAI;QACF,MAAM,OAAO,6BAA6B,UAAU,OAAO;UACzD,iEAAiE;UACjE,+DAA+D;UAC/D,mDAAmD;UACnD,OAAO;UACP,GAAG;YACD,IAAI,MAAM,SAAS,MAAM;YACzB,IAAI,OAAO,OAAO,EAAE;YACpB,MAAM,MAAM,QAAQ,IAAI,IAAI,OAAO;UACrC,QAAS,CAAC,OAAO,OAAO,CAAC;QAC3B;MACF,SAAU;QACR,UAAU;QACV,sEAAsE;QACtE,8CAA8C;QAC9C,IAAI,UAAU,KAAK,IAAI,CAAC,IAAM;QAC9B,OAAO,QAAQ,IAAI,CAAC,KAAO,GAAG,KAAO;QACrC,IAAI;UACF,MAAM;QACR,SAAU;UACR,WAAW;QACb;MACF;IACF,CAAC;IACD,OAAO;EACT;EACA,OAAO;IAAE,aAAa;IAAW,aAAa;EAAM;AACtD,EAAC"}
@@ -0,0 +1,274 @@
1
+ // The declared skill_files and skill_watch effects. Skills are a separate
2
+ // opt-in: persona files:true must never enable bidirectional repository writes.
3
+ // The pool owns these promises, including polling and shutdown cleanup. Imports
4
+ // and exports share a bounded queue and a per-pass lease; the watcher has its
5
+ // own lease so graph edits need not wait for the polling duty to finish. A
6
+ // poll stats the files a sync would read and syncs only when they moved. What a
7
+ // pass could not do is retried, so one a retry did not clear reaches the tracker.
8
+
9
+ import * as fs from '@yaks/file/io'
10
+
11
+ import { type Handlers, holding, sleep } from '@yaks/effects'
12
+ import type { Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
13
+ import type { Context } from 'jsr:@yaks/tracker@0.2.36/report'
14
+ import { derivedEid } from '@yaks/graph/identity'
15
+ import { dirname, join, resolve } from 'node:path'
16
+ import { skillRoots, syncSkills } from './skill-mirror.js'
17
+ import { stamp as stampOf } from './skill-mirror-io.js'
18
+
19
+ /** The explicit bidirectional mirror opt-in in the plugin config. */
20
+ export type SkillOptions = { skills?: boolean }
21
+
22
+ /** Only the host capabilities this facet uses; fixtures need no server. */
23
+ export type SkillHost = {
24
+ graph: Graph
25
+ config?: { db?: string }
26
+ stopping?: AbortSignal
27
+ me?: Eid
28
+ gone?: (holder: Eid) => Promise<boolean>
29
+ report?: (error: unknown, context?: Partial<Context>) => void | Promise<void>
30
+ }
31
+
32
+ /** Injectable boundaries for tests; production uses the mirror and timers. */
33
+ export type SkillRuntime = {
34
+ roots?: typeof skillRoots
35
+ sync?: typeof syncSkills
36
+ stamp?: typeof stampOf
37
+ pause?: typeof sleep
38
+ poll?: number
39
+ files?: Pick<
40
+ typeof fs,
41
+ 'makeTempDir' | 'readTextFile' | 'writeTextFile' | 'remove'
42
+ >
43
+ }
44
+
45
+ /** Continuous polling is intentional: filesystem watches miss renames and
46
+ * index-only changes. Each pass reconciles the present, not a stale event.
47
+ * A poll is only stats: it compares each root's stamp with the one its last
48
+ * clean sync started from, and passes when any moved or never settled. */
49
+ export let skillEffects = (
50
+ host: SkillHost,
51
+ options: SkillOptions = {},
52
+ runtime: SkillRuntime = {},
53
+ ): Handlers => {
54
+ if (!options.skills) return {}
55
+ let files = runtime.files ?? fs
56
+ let roots = runtime.roots ?? skillRoots
57
+ let sync = runtime.sync ?? syncSkills
58
+ let stamp = runtime.stamp ?? stampOf
59
+ let pause = runtime.pause ?? sleep
60
+ let stopping = host.stopping ?? AbortSignal.abort()
61
+ let db = host.config?.db
62
+ let persistent = db && db != ':memory:'
63
+ ? join(dirname(resolve(db)), 'mirror', 'skills')
64
+ : undefined
65
+ let temporary: Promise<string> | undefined
66
+ let saved = new Map<string, string>()
67
+ let names = new Map<string, string>()
68
+ let memory = async (root: string): Promise<string> => {
69
+ let name = names.get(root)
70
+ if (!name) names.set(root, name = `${derivedEid(`skills|${root}`)}.json`)
71
+ let dir = persistent ?? await (temporary ??= (async () => {
72
+ let dir = await files.makeTempDir({ prefix: 'yak-skills-' })
73
+ try {
74
+ for (let [name, body] of saved) {
75
+ await files.writeTextFile(join(dir, name), body)
76
+ }
77
+ return dir
78
+ } catch (error) {
79
+ await files.remove(dir, { recursive: true })
80
+ throw error
81
+ }
82
+ })())
83
+ return join(dir, name)
84
+ }
85
+ // A handler-only host has no awaited shutdown callback. Keep its agreement
86
+ // bytes, not an idle directory: clean inside the awaited handler and restore
87
+ // on its next pass. A watcher retains its directory until it ends (including
88
+ // failure), then uses the same route. No abort listener detaches I/O errors.
89
+ let clean = async (trailing = false): Promise<void> => {
90
+ let owned = temporary
91
+ if (!owned) return
92
+ let retained = false
93
+ try {
94
+ let dir = await owned
95
+ try {
96
+ for (let name of names.values()) {
97
+ try {
98
+ saved.set(name, await files.readTextFile(join(dir, name)))
99
+ } catch (error) {
100
+ if (!fs.isNotFound(error)) throw error
101
+ saved.delete(name)
102
+ }
103
+ }
104
+ // An event during cleanup shares this batch. Keep its memo in place
105
+ // for the trailing pass; callers cannot observe completion yet.
106
+ retained = trailing && dirty && !host.stopping?.aborted
107
+ } finally {
108
+ if (!retained) await files.remove(dir, { recursive: true })
109
+ }
110
+ } finally {
111
+ if (!retained) temporary = undefined
112
+ }
113
+ }
114
+ // holding reports acquisition/renewal/release failures. Turn that report into
115
+ // the awaited effect's failure instead of detaching an exception from a timer.
116
+ let leased = async (
117
+ name: string,
118
+ signal: AbortSignal,
119
+ work: (signal: AbortSignal) => Promise<void>,
120
+ ): Promise<void> => {
121
+ if (!host.me) return await work(signal)
122
+ let failed = false
123
+ let error: unknown
124
+ let interrupted = new AbortController()
125
+ await holding(host.graph, name, {
126
+ holder: host.me,
127
+ gone: host.gone,
128
+ signal: AbortSignal.any([signal, interrupted.signal]),
129
+ report: (e) => {
130
+ if (!failed) error = e
131
+ failed = true
132
+ interrupted.abort()
133
+ },
134
+ }, work)
135
+ if (failed) throw error
136
+ }
137
+ // The roots the last pass found, and the stamp each one's last clean sync
138
+ // started from. Graph edits arrive as skill_files passes, which refresh both.
139
+ let seen: string[] | undefined
140
+ let settled = new Map<string, string>()
141
+ let moved = async (): Promise<boolean> => {
142
+ if (!seen) return true
143
+ for (let root of seen) {
144
+ let was = settled.get(root)
145
+ if (was == undefined || was != await stamp(root)) return true
146
+ }
147
+ return false
148
+ }
149
+ // What each root's last pass could not do, and whether it has been reported.
150
+ // A race clears on the next pass; one that survives a retry is a failure, told
151
+ // once however often it is retried, and told again if it clears and returns.
152
+ let unsettled = new Map<string, Map<string, boolean>>()
153
+ let unresolved = async (root: string, reasons: string[]): Promise<void> => {
154
+ let was = unsettled.get(root)
155
+ let now = new Map<string, boolean>()
156
+ for (let reason of new Set(reasons)) {
157
+ let told = was?.get(reason)
158
+ now.set(reason, told != undefined)
159
+ if (told == undefined) {
160
+ console.warn('@yaks/persona skills —', root, reason)
161
+ } else if (!told) {
162
+ await host.report?.(new Error(`skills at ${root}: ${reason}`), {
163
+ tags: { step: 'skill_files', root },
164
+ })
165
+ }
166
+ }
167
+ if (now.size) unsettled.set(root, now)
168
+ else unsettled.delete(root)
169
+ }
170
+ let pass = async (): Promise<void> => {
171
+ if (host.stopping?.aborted) return
172
+ await leased(
173
+ '@yaks/persona/skill_files',
174
+ host.stopping ?? new AbortController().signal,
175
+ async (signal) => {
176
+ seen = await roots(host.graph)
177
+ for (let root of settled.keys()) {
178
+ if (!seen.includes(root)) settled.delete(root)
179
+ }
180
+ for (let root of unsettled.keys()) {
181
+ if (!seen.includes(root)) unsettled.delete(root)
182
+ }
183
+ for (let root of seen) {
184
+ if (signal.aborted) break
185
+ settled.delete(root)
186
+ // Stamped before the sync reads, so a change during it moves it.
187
+ let before = await stamp(root)
188
+ let result = await sync(host.graph, root, await memory(root))
189
+ // Conflicts and refusals (a dirty checkout, a diverged main) may
190
+ // clear without touching these files, so they keep being retried.
191
+ if (!result.conflicts.length && !result.failed.length) {
192
+ settled.set(root, before)
193
+ }
194
+ await unresolved(root, [
195
+ ...result.conflicts.map((path) => `conflict: ${path}`),
196
+ ...result.failed,
197
+ ])
198
+ }
199
+ },
200
+ )
201
+ }
202
+ let last = Promise.resolve()
203
+ let active: Promise<void> | undefined
204
+ let started = false
205
+ let dirty = false
206
+ let watching: Promise<void> | undefined
207
+ let watcher = false
208
+ let reconcile = (): Promise<void> => {
209
+ if (active) {
210
+ // Before the queued pass begins it already sees the latest graph. During
211
+ // a pass, any number of events owe only one trailing reconciliation.
212
+ if (started) dirty = true
213
+ return active
214
+ }
215
+ let done = last.then(async () => {
216
+ started = true
217
+ try {
218
+ do {
219
+ dirty = false
220
+ await pass()
221
+ // Cleanup yields to I/O too: events arriving there still owe the
222
+ // trailing pass before this shared batch promise can settle.
223
+ if (!watcher || stopping.aborted) await clean(true)
224
+ } while (dirty && !host.stopping?.aborted)
225
+ } finally {
226
+ try {
227
+ if (temporary && (!watcher || stopping.aborted)) await clean()
228
+ } finally {
229
+ // Clear before yielding again: an event after the last dirty check
230
+ // must enqueue a new batch, not join one that already finished.
231
+ started = false
232
+ active = undefined
233
+ }
234
+ }
235
+ })
236
+ active = done
237
+ // Only the queue continuation recovers. Every caller receives the original
238
+ // rejection so the effects pool can report/retry unknown mirror failures.
239
+ last = done.then(() => {}, () => {})
240
+ return done
241
+ }
242
+ let watch = (): Promise<void> => {
243
+ if (watching) return watching
244
+ watcher = true
245
+ watching = (async () => {
246
+ try {
247
+ await leased('@yaks/persona/skill_watch', stopping, async (signal) => {
248
+ // A minimal one-shot host reconciles once. Live hosts poll until
249
+ // shutdown or loss of the singleton watcher lease. Every start
250
+ // reconciles, whatever an earlier watcher settled.
251
+ seen = undefined
252
+ do {
253
+ if (await moved()) await reconcile()
254
+ if (signal.aborted) break
255
+ await pause(runtime.poll ?? 2_000, signal)
256
+ } while (!signal.aborted)
257
+ })
258
+ } finally {
259
+ watcher = false
260
+ // Serialize cleanup with graph-triggered passes too, including a pass
261
+ // still finishing when a poll or lease fails.
262
+ let cleanup = last.then(() => clean())
263
+ last = cleanup.then(() => {}, () => {})
264
+ try {
265
+ await cleanup
266
+ } finally {
267
+ watching = undefined
268
+ }
269
+ }
270
+ })()
271
+ return watching
272
+ }
273
+ return { skill_files: reconcile, skill_watch: watch }
274
+ }