taskflow-core 0.1.5 → 0.1.7

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 (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -30
  3. package/dist/agents.d.ts +20 -0
  4. package/dist/agents.d.ts.map +1 -1
  5. package/dist/agents.js +51 -2
  6. package/dist/agents.js.map +1 -1
  7. package/dist/deterministic.d.ts +33 -0
  8. package/dist/deterministic.d.ts.map +1 -0
  9. package/dist/deterministic.js +56 -0
  10. package/dist/deterministic.js.map +1 -0
  11. package/dist/flowir/translate.d.ts.map +1 -1
  12. package/dist/flowir/translate.js +25 -7
  13. package/dist/flowir/translate.js.map +1 -1
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +7 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/interpolate.d.ts +18 -0
  19. package/dist/interpolate.d.ts.map +1 -1
  20. package/dist/interpolate.js +45 -0
  21. package/dist/interpolate.js.map +1 -1
  22. package/dist/jsonc.d.ts +30 -0
  23. package/dist/jsonc.d.ts.map +1 -0
  24. package/dist/jsonc.js +108 -0
  25. package/dist/jsonc.js.map +1 -0
  26. package/dist/library/meta.d.ts +31 -0
  27. package/dist/library/meta.d.ts.map +1 -0
  28. package/dist/library/meta.js +154 -0
  29. package/dist/library/meta.js.map +1 -0
  30. package/dist/library/search.d.ts +33 -0
  31. package/dist/library/search.d.ts.map +1 -0
  32. package/dist/library/search.js +299 -0
  33. package/dist/library/search.js.map +1 -0
  34. package/dist/library/types.d.ts +121 -0
  35. package/dist/library/types.d.ts.map +1 -0
  36. package/dist/library/types.js +18 -0
  37. package/dist/library/types.js.map +1 -0
  38. package/dist/replay.d.ts +75 -0
  39. package/dist/replay.d.ts.map +1 -0
  40. package/dist/replay.js +25 -0
  41. package/dist/replay.js.map +1 -0
  42. package/dist/runner-core.d.ts +54 -4
  43. package/dist/runner-core.d.ts.map +1 -1
  44. package/dist/runner-core.js +237 -10
  45. package/dist/runner-core.js.map +1 -1
  46. package/dist/runtime.d.ts +8 -11
  47. package/dist/runtime.d.ts.map +1 -1
  48. package/dist/runtime.js +170 -43
  49. package/dist/runtime.js.map +1 -1
  50. package/dist/schema.d.ts.map +1 -1
  51. package/dist/schema.js +13 -0
  52. package/dist/schema.js.map +1 -1
  53. package/dist/scorers.d.ts +11 -3
  54. package/dist/scorers.d.ts.map +1 -1
  55. package/dist/scorers.js +38 -7
  56. package/dist/scorers.js.map +1 -1
  57. package/dist/store.d.ts +80 -0
  58. package/dist/store.d.ts.map +1 -1
  59. package/dist/store.js +249 -39
  60. package/dist/store.js.map +1 -1
  61. package/dist/trace.d.ts +150 -0
  62. package/dist/trace.d.ts.map +1 -0
  63. package/dist/trace.js +191 -0
  64. package/dist/trace.js.map +1 -0
  65. package/package.json +6 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"meta.js","sourceRoot":"","sources":["../../src/library/meta.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG1C;;8BAE8B;AAC9B,MAAM,UAAU,qBAAqB,CAAC,GAAa;IAClD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACrE,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,MAAM;SACX,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SAC7D,IAAI,CAAC,GAAG,CAAC,CAAC;AACb,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,GAAa;IAC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I;QACf,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,cAAc,EAAE,qBAAqB,CAAC,GAAG,CAAC;QAC1C,UAAU,EAAE,WAAW,CAAC,GAAG,CAAC;QAC5B,UAAU,EAAE,iBAAiB,CAAC,GAAG,CAAC;QAClC,UAAU,EAAE,iBAAiB,CAAC,GAAG,CAAC;QAClC,UAAU,EAAE,IAAI,EAAE,UAAU,IAAI,CAAC;QACjC,UAAU,EAAE,IAAI,EAAE,UAAU,IAAI,IAAI;QACpC,SAAS,EAAE,IAAI,EAAE,SAAS,IAAI,GAAG;QACjC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACpC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,SAAS,EAAE,IAAI,EAAE,SAAS,IAAI,IAAI;QAClC,cAAc,EAAE,IAAI,EAAE,cAAc;QACpC,YAAY,EAAE,IAAI,EAAE,YAAY;QAChC,UAAU,EAAE,IAAI,EAAE,UAAU,IAAI,IAAI;KACpC,CAAC;AACH,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Library — search ranking (structural + keyword; Phase 1).
3
+ *
4
+ * Phase 2 adds the embedding/cosine path; the seam (LibraryDeps.embedder) is
5
+ * already in place but left unused here. When no embedder is configured OR
6
+ * structureOnly is set, search degrades to keyword + structural ranking.
7
+ *
8
+ * Refs: docs/rfc-library-reuse.md §5.2 (blend), §5.2.1 (structScore),
9
+ * §5.2.2 (staleness), §5.3 (why/reuseHint templates).
10
+ */
11
+ import { getFlow } from "../store.ts";
12
+ import type { Taskflow } from "../schema.ts";
13
+ import type { FlowMeta } from "./types.ts";
14
+ import type { LibraryDeps, ResolvedCandidate, SearchInput, SearchResponse } from "./types.ts";
15
+ /** Standard Levenshtein edit distance (insert/delete/replace cost 1).
16
+ * O(m·n) DP; signature strings are short (<50 chars) so cost is negligible. */
17
+ export declare function levenshtein(a: string, b: string): number;
18
+ /** Resolve a saved flow + its sidecar into a candidate whose structural fields
19
+ * are ALWAYS freshly derived from the current def, and whose embedding is only
20
+ * trusted when the sidecar's phaseSignature matches the fresh one. */
21
+ export declare function resolveCandidate(def: Taskflow, scope: "user" | "project", name: string, sidecar: FlowMeta | undefined): ResolvedCandidate;
22
+ /** Search the library. Returns ranked top-N. Degrades to structural/keyword
23
+ * when no embedder is configured or structureOnly is requested. */
24
+ export declare function searchLibrary(deps: LibraryDeps, input: SearchInput): Promise<SearchResponse>;
25
+ /** Pure cosine similarity. Zero-dep. Accepts non-normalized vectors. */
26
+ export declare function cosine(a: number[], b: number[]): number;
27
+ /** Bump reuseCount for a flow by name (RFC §6 reuse flywheel).
28
+ * Phase 1: structural-only; the caller (tool handler) decides whether to
29
+ * bump based on a `reusedFromSearch` flag. Returns the new count or null if
30
+ * the flow has no sidecar yet. The actual sidecar write is done by
31
+ * `bumpReuseInSidecar` in store.ts under withLock. */
32
+ export { getFlow };
33
+ //# sourceMappingURL=search.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/library/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,OAAO,EAAuB,MAAM,aAAa,CAAC;AAC3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAO3C,OAAO,KAAK,EACX,WAAW,EACX,iBAAiB,EACjB,WAAW,EACX,cAAc,EAEd,MAAM,YAAY,CAAC;AAMpB;gFACgF;AAChF,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAmBxD;AAMD;;uEAEuE;AACvE,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,QAAQ,EACb,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,QAAQ,GAAG,SAAS,GAC3B,iBAAiB,CAwCnB;AAiHD;oEACoE;AACpE,wBAAsB,aAAa,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,cAAc,CAAC,CAqFlG;AAED,wEAAwE;AACxE,wBAAgB,MAAM,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAgBvD;AAED;;;;uDAIuD;AACvD,OAAO,EAAE,OAAO,EAAE,CAAC"}
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Library — search ranking (structural + keyword; Phase 1).
3
+ *
4
+ * Phase 2 adds the embedding/cosine path; the seam (LibraryDeps.embedder) is
5
+ * already in place but left unused here. When no embedder is configured OR
6
+ * structureOnly is set, search degrades to keyword + structural ranking.
7
+ *
8
+ * Refs: docs/rfc-library-reuse.md §5.2 (blend), §5.2.1 (structScore),
9
+ * §5.2.2 (staleness), §5.3 (why/reuseHint templates).
10
+ */
11
+ import { getFlow, listFlows, readMeta } from "../store.js";
12
+ import { computeGenerality, computePhaseSignature, countPhases, extractAgentUsage, } from "./meta.js";
13
+ // ---------------------------------------------------------------------------
14
+ // Levenshtein (RFC §5.2.1)
15
+ // ---------------------------------------------------------------------------
16
+ /** Standard Levenshtein edit distance (insert/delete/replace cost 1).
17
+ * O(m·n) DP; signature strings are short (<50 chars) so cost is negligible. */
18
+ export function levenshtein(a, b) {
19
+ if (a === b)
20
+ return 0;
21
+ if (a.length === 0)
22
+ return b.length;
23
+ if (b.length === 0)
24
+ return a.length;
25
+ const m = a.length;
26
+ const n = b.length;
27
+ // Two rolling rows; allocate fresh each call (signatures are tiny).
28
+ let prev = new Array(n + 1);
29
+ for (let j = 0; j <= n; j++)
30
+ prev[j] = j;
31
+ for (let i = 1; i <= m; i++) {
32
+ const curr = new Array(n + 1);
33
+ curr[0] = i;
34
+ for (let j = 1; j <= n; j++) {
35
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
36
+ curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
37
+ }
38
+ prev = curr;
39
+ }
40
+ return prev[n];
41
+ }
42
+ // ---------------------------------------------------------------------------
43
+ // Candidate resolution (RFC §5.2.2 staleness detection)
44
+ // ---------------------------------------------------------------------------
45
+ /** Resolve a saved flow + its sidecar into a candidate whose structural fields
46
+ * are ALWAYS freshly derived from the current def, and whose embedding is only
47
+ * trusted when the sidecar's phaseSignature matches the fresh one. */
48
+ export function resolveCandidate(def, scope, name, sidecar) {
49
+ const freshSig = computePhaseSignature(def);
50
+ const freshGen = computeGenerality(def);
51
+ const freshAgents = extractAgentUsage(def);
52
+ const freshCount = countPhases(def);
53
+ if (!sidecar) {
54
+ return {
55
+ name,
56
+ scope,
57
+ def,
58
+ phaseSignature: freshSig,
59
+ phaseCount: freshCount,
60
+ agentUsage: freshAgents,
61
+ generality: freshGen,
62
+ reuseCount: 0,
63
+ version: 1,
64
+ embedding: null,
65
+ embeddingStale: true,
66
+ };
67
+ }
68
+ const sigMatch = sidecar.phaseSignature === freshSig;
69
+ return {
70
+ name,
71
+ scope,
72
+ def,
73
+ phaseSignature: freshSig,
74
+ phaseCount: freshCount,
75
+ agentUsage: freshAgents,
76
+ generality: freshGen,
77
+ purpose: sidecar.purpose,
78
+ tags: sidecar.tags,
79
+ notes: sidecar.notes,
80
+ reuseCount: sidecar.reuseCount ?? 0,
81
+ version: sidecar.version ?? 1,
82
+ derivedFrom: sidecar.derivedFrom,
83
+ embedding: sigMatch ? sidecar.embedding ?? null : null,
84
+ embeddingStale: !sigMatch,
85
+ };
86
+ }
87
+ // ---------------------------------------------------------------------------
88
+ // Scoring
89
+ // ---------------------------------------------------------------------------
90
+ /** structScore ∈ [0,1]. RFC §5.2.1: 0.7*sigSim + 0.3*countPenalty. */
91
+ function computeStructScore(query, cand) {
92
+ let sigSim = 0;
93
+ if (cand.phaseSignature && query.phaseSignature) {
94
+ const d = levenshtein(query.phaseSignature, cand.phaseSignature);
95
+ const denom = Math.max(query.phaseSignature.length, cand.phaseSignature.length, 1);
96
+ sigSim = 1 - d / denom;
97
+ if (sigSim < 0)
98
+ sigSim = 0;
99
+ }
100
+ let countPenalty = 0;
101
+ if (query.phaseCount > 0 && cand.phaseCount > 0) {
102
+ const diff = Math.abs(query.phaseCount - cand.phaseCount);
103
+ countPenalty = 1 - Math.min(1, diff / Math.max(query.phaseCount, cand.phaseCount));
104
+ }
105
+ return 0.7 * sigSim + 0.3 * countPenalty;
106
+ }
107
+ /** textScore ∈ [0,1]. Token-overlap between query and the flow's text fields
108
+ * (name + purpose + tags + phase task text). CJK-aware: queries tokenized on
109
+ * whitespace AND matched as substrings, so a Chinese query token like "鉴权"
110
+ * still matches a purpose containing "...缺少鉴权检查..." (which whitespace
111
+ * alone would never split out). */
112
+ function computeTextScore(queryTokens, cand) {
113
+ if (queryTokens.length === 0)
114
+ return 0;
115
+ const fieldText = ((cand.name ?? "") +
116
+ " " +
117
+ (cand.purpose ?? "") +
118
+ " " +
119
+ (cand.tags ?? []).join(" ") +
120
+ " " +
121
+ cand.phaseTaskText).toLowerCase();
122
+ if (!fieldText.trim())
123
+ return 0;
124
+ // Substring match per query token (CJK-friendly). Longer tokens weigh more
125
+ // (they carry more signal) so e.g. a 2-char Chinese term counts more than a
126
+ // 2-char English one only marginally; this keeps the [0,1] shape intuitive.
127
+ let hits = 0;
128
+ for (const t of queryTokens) {
129
+ if (!t)
130
+ continue;
131
+ if (fieldText.includes(t))
132
+ hits++;
133
+ }
134
+ return hits / queryTokens.length;
135
+ }
136
+ function tokenize(query) {
137
+ return query
138
+ .toLowerCase()
139
+ .split(/[^\p{L}\p{N}]+/u)
140
+ .filter((t) => t.length > 1);
141
+ }
142
+ function phaseTaskText(def) {
143
+ if (!Array.isArray(def.phases))
144
+ return "";
145
+ const parts = [];
146
+ for (const p of def.phases) {
147
+ if (typeof p.task === "string")
148
+ parts.push(p.task);
149
+ if (Array.isArray(p.branches)) {
150
+ for (const b of p.branches ?? []) {
151
+ if (b?.task)
152
+ parts.push(b.task);
153
+ }
154
+ }
155
+ }
156
+ return parts.join(" ");
157
+ }
158
+ // ---------------------------------------------------------------------------
159
+ // why / reuseHint templates (RFC §5.3, Tier 1, zero-token)
160
+ // ---------------------------------------------------------------------------
161
+ function buildWhy(s) {
162
+ const hits = [];
163
+ if ((s.searchMode === "semantic" || s.searchMode === "mixed") && s.semScore != null && s.semScore > 0.7) {
164
+ hits.push(`语义命中(sem=${s.semScore.toFixed(2)})`);
165
+ }
166
+ if (s.structScore > 0.8)
167
+ hits.push(`结构一致(struct=${s.structScore.toFixed(2)})`);
168
+ if (s.textScore > 0.3)
169
+ hits.push(`关键词匹配(text=${s.textScore.toFixed(2)})`);
170
+ return hits.length > 0 ? hits.join(" + ") : "低分命中,建议检查";
171
+ }
172
+ function buildReuseHint(r) {
173
+ if (r.score >= 0.8)
174
+ return `直接复用${r.argCount > 0 ? `,注意 ${r.argCount} 个 args 参数` : ""}`;
175
+ if (r.score >= 0.5)
176
+ return `结构相似,建议 copy + 泛化后使用`;
177
+ return `低相关度,建议从头编写或大幅改写`;
178
+ }
179
+ // ---------------------------------------------------------------------------
180
+ // searchLibrary
181
+ // ---------------------------------------------------------------------------
182
+ function argCountOf(def) {
183
+ return def.args && typeof def.args === "object" ? Object.keys(def.args).length : 0;
184
+ }
185
+ /** Search the library. Returns ranked top-N. Degrades to structural/keyword
186
+ * when no embedder is configured or structureOnly is requested. */
187
+ export async function searchLibrary(deps, input) {
188
+ const limit = Math.min(20, Math.max(1, input.limit ?? 5));
189
+ const minScore = input.minScore ?? 0;
190
+ const scope = input.scope ?? deps.settings.scope ?? "both";
191
+ // gather candidates
192
+ const flows = listFlows(deps.cwd).filter((f) => {
193
+ if (scope === "both")
194
+ return true;
195
+ return f.scope === scope;
196
+ });
197
+ const queryTokens = tokenize(input.query);
198
+ // embed the query if an embedder is available and not structureOnly
199
+ let queryVec = null;
200
+ const hasEmbedder = !!deps.embedder && !input.structureOnly;
201
+ if (hasEmbedder && deps.embedder) {
202
+ try {
203
+ queryVec = await deps.embedder.embed(input.query);
204
+ }
205
+ catch {
206
+ queryVec = null; // degrade
207
+ }
208
+ }
209
+ const scored = [];
210
+ for (const f of flows) {
211
+ const sidecarR = readMeta(deps.cwd, f.name);
212
+ const sidecar = sidecarR.ok ? sidecarR.value : undefined;
213
+ const cand = resolveCandidate(f.def, f.scope, f.name, sidecar);
214
+ const qShape = {
215
+ phaseSignature: input.phaseSignatureHint ?? "",
216
+ phaseCount: input.phaseCountHint ?? 0,
217
+ };
218
+ const structScore = computeStructScore(qShape, cand);
219
+ const textScore = computeTextScore(queryTokens, {
220
+ name: cand.name,
221
+ purpose: cand.purpose,
222
+ tags: cand.tags,
223
+ phaseTaskText: phaseTaskText(cand.def),
224
+ });
225
+ let score;
226
+ let semScore;
227
+ const hasVectors = queryVec != null && cand.embedding != null && !cand.embeddingStale;
228
+ if (hasVectors && queryVec && cand.embedding) {
229
+ semScore = cosine(queryVec, cand.embedding);
230
+ score = 0.6 * semScore + 0.25 * structScore + 0.15 * textScore;
231
+ }
232
+ else {
233
+ score = 0.6 * textScore + 0.4 * structScore;
234
+ }
235
+ if (score < minScore)
236
+ continue;
237
+ if (score <= 0)
238
+ continue; // zero-relevance results are noise; don't surface them
239
+ scored.push({ cand, score: Math.round(score * 100) / 100, semScore, structScore, textScore });
240
+ }
241
+ scored.sort((a, b) => b.score - a.score);
242
+ const top = scored.slice(0, limit);
243
+ const withVectors = top.filter((s) => s.cand.embedding != null && !s.cand.embeddingStale).length;
244
+ let searchMode;
245
+ if (input.structureOnly || !deps.embedder || withVectors === 0)
246
+ searchMode = "structural";
247
+ else if (withVectors === top.length)
248
+ searchMode = "semantic";
249
+ else
250
+ searchMode = "mixed";
251
+ const results = top.map((s) => ({
252
+ name: s.cand.name,
253
+ scope: s.cand.scope,
254
+ purpose: s.cand.purpose,
255
+ tags: s.cand.tags,
256
+ phaseSignature: s.cand.phaseSignature,
257
+ phaseCount: s.cand.phaseCount,
258
+ generality: s.cand.generality,
259
+ reuseCount: s.cand.reuseCount,
260
+ version: s.cand.version,
261
+ score: s.score,
262
+ why: buildWhy({ semScore: s.semScore, structScore: s.structScore, textScore: s.textScore, searchMode }),
263
+ reuseHint: buildReuseHint({ score: s.score, argCount: argCountOf(s.cand.def) }),
264
+ }));
265
+ return {
266
+ results,
267
+ searchMode,
268
+ embedder: deps.embedder?.model,
269
+ counts: { scanned: flows.length, withVectors },
270
+ };
271
+ }
272
+ /** Pure cosine similarity. Zero-dep. Accepts non-normalized vectors. */
273
+ export function cosine(a, b) {
274
+ const n = Math.min(a.length, b.length);
275
+ if (n === 0)
276
+ return 0;
277
+ let dot = 0;
278
+ let normA = 0;
279
+ let normB = 0;
280
+ for (let i = 0; i < n; i++) {
281
+ const x = a[i];
282
+ const y = b[i];
283
+ if (!Number.isFinite(x) || !Number.isFinite(y))
284
+ continue;
285
+ dot += x * y;
286
+ normA += x * x;
287
+ normB += y * y;
288
+ }
289
+ if (normA === 0 || normB === 0)
290
+ return 0;
291
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
292
+ }
293
+ /** Bump reuseCount for a flow by name (RFC §6 reuse flywheel).
294
+ * Phase 1: structural-only; the caller (tool handler) decides whether to
295
+ * bump based on a `reusedFromSearch` flag. Returns the new count or null if
296
+ * the flow has no sidecar yet. The actual sidecar write is done by
297
+ * `bumpReuseInSidecar` in store.ts under withLock. */
298
+ export { getFlow };
299
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.js","sourceRoot":"","sources":["../../src/library/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG3D,OAAO,EACN,iBAAiB,EACjB,qBAAqB,EACrB,WAAW,EACX,iBAAiB,GACjB,MAAM,WAAW,CAAC;AASnB,8EAA8E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@
1
+ /**
2
+ * Library — reusable-flow asset layer types.
3
+ *
4
+ * The library lets taskflow accumulate, retrieve, and iteratively generalize
5
+ * saved flows. Phase 1 (this module) defines the data shapes and the
6
+ * host-neutral interfaces; the runtime logic (meta derivation, search ranking)
7
+ * lives in `meta.ts` / `search.ts`, and persistence (sidecar `.meta.json`)
8
+ * lives in `store.ts`.
9
+ *
10
+ * Design refs: docs/rfc-library-reuse.md (§3 data format, §4 embedder, §5
11
+ * search). Embedding support is Phase 2 — Phase 1 ships with structural /
12
+ * keyword search only and every embedding field is optional.
13
+ */
14
+ import type { Taskflow } from "../schema.ts";
15
+ /** Library-side settings, nested under `settings.json → taskflow.library`. */
16
+ export interface LibrarySettings {
17
+ /** Master switch. Default true. When false, search/save-meta are no-ops. */
18
+ enabled: boolean;
19
+ /** Which scopes to search: "project" | "user" | "both" (default both). */
20
+ scope: "project" | "user" | "both";
21
+ /** Optional blend weights for mixed search ranking (Phase 2). */
22
+ searchWeights?: {
23
+ semantic: number;
24
+ structural: number;
25
+ textual: number;
26
+ };
27
+ /** Optional Phase-3 auto-prune threshold. */
28
+ maxFlows?: number;
29
+ }
30
+ export declare const DEFAULT_LIBRARY_SETTINGS: LibrarySettings;
31
+ /** The sidecar `.meta.json` record. Persisted next to a flow file. */
32
+ export interface FlowMeta {
33
+ schemaVersion: 1;
34
+ /** Agent-provided (optional). */
35
+ purpose?: string;
36
+ tags?: string[];
37
+ notes?: string;
38
+ /** Auto-derived at save time. */
39
+ phaseSignature: string;
40
+ phaseCount: number;
41
+ agentUsage: string[];
42
+ generality: number;
43
+ argShape?: Record<string, string>;
44
+ /** Reuse flywheel. */
45
+ reuseCount: number;
46
+ lastUsedAt: number | null;
47
+ createdAt: number;
48
+ version: number;
49
+ derivedFrom?: string;
50
+ /** Embedding (Phase 2; always optional / may be null). */
51
+ embeddingModel?: string;
52
+ embeddingDim?: number;
53
+ embedding?: number[] | null;
54
+ embeddedAt?: number | null;
55
+ }
56
+ /** A candidate resolved for search: live-derived structural fields + trusted
57
+ * sidecar fields (purpose/tags/...) + embedding gated on signature match.
58
+ * (RFC §5.2.2 staleness detection.) */
59
+ export interface ResolvedCandidate {
60
+ name: string;
61
+ scope: "user" | "project";
62
+ def: Taskflow;
63
+ phaseSignature: string;
64
+ phaseCount: number;
65
+ agentUsage: string[];
66
+ generality: number;
67
+ purpose?: string;
68
+ tags?: string[];
69
+ notes?: string;
70
+ reuseCount: number;
71
+ version: number;
72
+ derivedFrom?: string;
73
+ embedding: number[] | null;
74
+ embeddingStale: boolean;
75
+ }
76
+ export interface SearchResult {
77
+ name: string;
78
+ scope: "user" | "project";
79
+ purpose?: string;
80
+ tags?: string[];
81
+ phaseSignature: string;
82
+ phaseCount: number;
83
+ generality: number;
84
+ reuseCount: number;
85
+ version: number;
86
+ score: number;
87
+ why: string;
88
+ reuseHint: string;
89
+ }
90
+ export interface SearchResponse {
91
+ results: SearchResult[];
92
+ searchMode: "semantic" | "structural" | "mixed";
93
+ embedder?: string;
94
+ counts: {
95
+ scanned: number;
96
+ withVectors: number;
97
+ };
98
+ }
99
+ /** Input to searchLibrary(). */
100
+ export interface SearchInput {
101
+ query: string;
102
+ limit?: number;
103
+ structureOnly?: boolean;
104
+ minScore?: number;
105
+ scope?: "project" | "user" | "both";
106
+ phaseSignatureHint?: string;
107
+ phaseCountHint?: number;
108
+ }
109
+ /** The minimal host-neutral dependency the library functions need.
110
+ * Embedder is Phase 2; Phase 1 leaves it undefined and search degrades to
111
+ * structural/keyword (RFC §4.3, A2: stays OUT of RuntimeDeps). */
112
+ export interface LibraryDeps {
113
+ embedder?: {
114
+ embed(text: string): Promise<number[]>;
115
+ readonly model: string;
116
+ readonly dim: number;
117
+ };
118
+ settings: LibrarySettings;
119
+ cwd: string;
120
+ }
121
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/library/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG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AAA;KAAE,CAAC;CACjD;AAED,gCAAgC;AAChC,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;IACpC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;mEAEmE;AACnE,MAAM,WAAW,WAAW;IAC3B,QAAQ,CAAC,EAAE;QACV,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QACvC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QACvB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;KACrB,CAAC;IACF,QAAQ,EAAE,eAAe,CAAC;IAC1B,GAAG,EAAE,MAAM,CAAC;CACZ"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Library — reusable-flow asset layer types.
3
+ *
4
+ * The library lets taskflow accumulate, retrieve, and iteratively generalize
5
+ * saved flows. Phase 1 (this module) defines the data shapes and the
6
+ * host-neutral interfaces; the runtime logic (meta derivation, search ranking)
7
+ * lives in `meta.ts` / `search.ts`, and persistence (sidecar `.meta.json`)
8
+ * lives in `store.ts`.
9
+ *
10
+ * Design refs: docs/rfc-library-reuse.md (§3 data format, §4 embedder, §5
11
+ * search). Embedding support is Phase 2 — Phase 1 ships with structural /
12
+ * keyword search only and every embedding field is optional.
13
+ */
14
+ export const DEFAULT_LIBRARY_SETTINGS = {
15
+ enabled: true,
16
+ scope: "both",
17
+ };
18
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/library/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAgBH,MAAM,CAAC,MAAM,wBAAwB,GAAoB;IACxD,OAAO,EAAE,IAAI;IACb,KAAK,EAAE,MAAM;CACb,CAAC"}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Deterministic replay — **type stub + design contract (0.1.7)**.
3
+ *
4
+ * Replay re-evaluates a recorded run against changed **decision knobs** (gate
5
+ * thresholds, budget caps, model route) by reading the event trace
6
+ * (`trace.ts`) and re-applying deterministic decision logic — **never calling
7
+ * `runTask`**. Zero tokens, offline. Because the DAG and its verdicts are data,
8
+ * you can re-adjudicate them against recorded evidence.
9
+ *
10
+ * **0.1.7 ships the trace foundation + this type only.** The pure `replayRun()`
11
+ * function and the `replay` action land in 0.2.0. The `ReplayDecision` type is
12
+ * defined now so the trace schema and the diff-report contract are fixed before
13
+ * any events are emitted — avoiding a breaking migration later.
14
+ *
15
+ * The 0.2.0 `replayRun()` will import ONLY from pure modules:
16
+ * `trace.ts` (read), `schema.ts` (topo sort/desugar),
17
+ * `interpolate.ts` (condition re-eval), `deterministic.ts` (parseGateVerdict,
18
+ * overBudget), `scorers.ts` (pure scorer re-run).
19
+ * It must NOT import `runtime.ts` (which drags in the process-spawning runner)
20
+ * — the "replay never spends a token" invariant is enforced structurally by the
21
+ * import graph.
22
+ */
23
+ /**
24
+ * Per-phase outcome of a replay. Distinct from `RecomputeDecision` (which
25
+ * describes a *live* recompute): only `"reused"` overlaps. Overloading
26
+ * `RecomputeDecision.outcome` with replay-specific values would be a semantic
27
+ * lie — replay and recompute are different operations (recorded vs. live).
28
+ */
29
+ export interface ReplayDecision {
30
+ readonly phaseId: string;
31
+ readonly outcome:
32
+ /** Recorded output valid → reused verbatim (zero tokens). */
33
+ "reused"
34
+ /** A gate verdict flipped under the new threshold/scorers. */
35
+ | "verdict-flipped"
36
+ /** The phase would now BLOCK the flow (e.g. gate under a stricter threshold). */
37
+ | "would-block"
38
+ /** The phase would be skipped by a tighter budget cap. */
39
+ | "would-exceed-budget"
40
+ /** Replay cannot decide — a fresh model call is required. Conservative. */
41
+ | "needs-live-rerun"
42
+ /** A `when` guard now skips a phase that previously ran (or vice-versa). */
43
+ | "would-skip"
44
+ /** A score threshold changed (verdict may or may not have flipped). */
45
+ | "threshold-changed"
46
+ /** The phase failed in the recorded run; replay does not retry. */
47
+ | "failed";
48
+ readonly reason: string;
49
+ /** The phase's outcome in the recorded run. */
50
+ readonly priorOutcome?: string;
51
+ /** The phase's outcome under the replayed knobs. */
52
+ readonly replayedOutcome?: string;
53
+ /** Upstream phases whose change caused this outcome, when applicable. */
54
+ readonly causedBy?: readonly string[];
55
+ }
56
+ /**
57
+ * Knobs a replay may override on a *copy* of the recorded definition (never the
58
+ * stored run). v1 (0.2.0) supports the deterministic subset; anything that
59
+ * would require re-generation (a changed task prompt) routes to
60
+ * `needs-live-rerun`.
61
+ */
62
+ export interface ReplayOverrides {
63
+ /** `budget.maxUSD` / `budget.maxTokens` — re-tally recorded usage. */
64
+ budgetMaxUSD?: number;
65
+ budgetMaxTokens?: number;
66
+ /** `phases.<id>.score.threshold` — re-run scorers against recorded target. */
67
+ thresholds?: Record<string, number>;
68
+ /** `phases.<id>.model` — report a cost delta only (cannot replay quality). */
69
+ models?: Record<string, string>;
70
+ /** `args.*` — only affects interpolation; changed-text phases → needs-live-rerun. */
71
+ args?: Record<string, unknown>;
72
+ }
73
+ /** Sentinel: this module exports types only in 0.1.7. Implemented in 0.2.0. */
74
+ export declare const REPLAY_NOT_YET_IMPLEMENTED = "replayRun() lands in 0.2.0; 0.1.7 ships the trace foundation + this type contract.";
75
+ //# sourceMappingURL=replay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay.d.ts","sourceRoot":"","sources":["../src/replay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO;IACf,6DAA6D;IAC3D,QAAQ;IACV,8DAA8D;OAC5D,iBAAiB;IACnB,iFAAiF;OAC/E,aAAa;IACf,0DAA0D;OACxD,qBAAqB;IACvB,2EAA2E;OACzE,kBAAkB;IACpB,4EAA4E;OAC1E,YAAY;IACd,uEAAuE;OACrE,mBAAmB;IACrB,mEAAmE;OACjE,QAAQ,CAAC;IACZ,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,+CAA+C;IAC/C,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,oDAAoD;IACpD,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,yEAAyE;IACzE,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC;AAED;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC/B,sEAAsE;IACtE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,8EAA8E;IAC9E,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,8EAA8E;IAC9E,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,qFAAqF;IACrF,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC/B;AAED,+EAA+E;AAC/E,eAAO,MAAM,0BAA0B,uFAC8C,CAAC"}
package/dist/replay.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Deterministic replay — **type stub + design contract (0.1.7)**.
3
+ *
4
+ * Replay re-evaluates a recorded run against changed **decision knobs** (gate
5
+ * thresholds, budget caps, model route) by reading the event trace
6
+ * (`trace.ts`) and re-applying deterministic decision logic — **never calling
7
+ * `runTask`**. Zero tokens, offline. Because the DAG and its verdicts are data,
8
+ * you can re-adjudicate them against recorded evidence.
9
+ *
10
+ * **0.1.7 ships the trace foundation + this type only.** The pure `replayRun()`
11
+ * function and the `replay` action land in 0.2.0. The `ReplayDecision` type is
12
+ * defined now so the trace schema and the diff-report contract are fixed before
13
+ * any events are emitted — avoiding a breaking migration later.
14
+ *
15
+ * The 0.2.0 `replayRun()` will import ONLY from pure modules:
16
+ * `trace.ts` (read), `schema.ts` (topo sort/desugar),
17
+ * `interpolate.ts` (condition re-eval), `deterministic.ts` (parseGateVerdict,
18
+ * overBudget), `scorers.ts` (pure scorer re-run).
19
+ * It must NOT import `runtime.ts` (which drags in the process-spawning runner)
20
+ * — the "replay never spends a token" invariant is enforced structurally by the
21
+ * import graph.
22
+ */
23
+ /** Sentinel: this module exports types only in 0.1.7. Implemented in 0.2.0. */
24
+ export const REPLAY_NOT_YET_IMPLEMENTED = "replayRun() lands in 0.2.0; 0.1.7 ships the trace foundation + this type contract.";
25
+ //# sourceMappingURL=replay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay.js","sourceRoot":"","sources":["../src/replay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAsDH,+EAA+E;AAC/E,MAAM,CAAC,MAAM,0BAA0B,GACtC,oFAAoF,CAAC"}