piroboros 0.0.0-stage → 0.2.0
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 +43 -0
- package/LICENSE +21 -0
- package/NOTICE +39 -0
- package/README.md +140 -2
- package/agents/astrelia.md +31 -0
- package/agents/avaritia.md +31 -0
- package/agents/elaria.md +31 -0
- package/agents/nytheria.md +32 -0
- package/agents/raskreia.md +32 -0
- package/agents/samaela.md +40 -0
- package/agents/vaelia.md +35 -0
- package/agents/vesperia.md +45 -0
- package/bin/piroboros.mjs +17 -0
- package/dist/auth.js +105 -0
- package/dist/base.js +19 -0
- package/dist/chat/budget.js +87 -0
- package/dist/chat/compactloop.js +63 -0
- package/dist/chat/compactor.js +530 -0
- package/dist/chat/extension.js +36 -0
- package/dist/chat/hook.js +40 -0
- package/dist/chat/log.js +317 -0
- package/dist/chat/outbound.js +114 -0
- package/dist/chat/plan.js +64 -0
- package/dist/chat/prompt.js +115 -0
- package/dist/chat/status.js +37 -0
- package/dist/chat/stuck.js +83 -0
- package/dist/chat/tools.js +163 -0
- package/dist/chat/tree.js +73 -0
- package/dist/chat/turn.js +305 -0
- package/dist/chat/view.js +163 -0
- package/dist/conclave/agents.js +113 -0
- package/dist/conclave/pipeline.js +715 -0
- package/dist/conclave/report.js +43 -0
- package/dist/config.js +614 -0
- package/dist/durable.js +177 -0
- package/dist/guard.js +346 -0
- package/dist/lock.js +56 -0
- package/dist/main.js +348 -0
- package/dist/memory/akashic/api.js +121 -0
- package/dist/memory/akashic/confusables.js +41 -0
- package/dist/memory/akashic/scanner.js +67 -0
- package/dist/memory/akashic/snapshot.js +31 -0
- package/dist/memory/akashic/store.js +1254 -0
- package/dist/memory/akashic/tools.js +168 -0
- package/dist/memory/akashic/vault.js +984 -0
- package/dist/memory/host.js +124 -0
- package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
- package/dist/memory/mnemosia/adapters/contract.js +219 -0
- package/dist/memory/mnemosia/agents.js +387 -0
- package/dist/memory/mnemosia/brief.js +890 -0
- package/dist/memory/mnemosia/claims.js +609 -0
- package/dist/memory/mnemosia/conflicts.js +769 -0
- package/dist/memory/mnemosia/escalation.js +257 -0
- package/dist/memory/mnemosia/feedback.js +108 -0
- package/dist/memory/mnemosia/filters.js +248 -0
- package/dist/memory/mnemosia/intent.js +221 -0
- package/dist/memory/mnemosia/open.js +34 -0
- package/dist/memory/mnemosia/orchestrator.js +926 -0
- package/dist/memory/mnemosia/plan.js +266 -0
- package/dist/memory/mnemosia/policy.js +426 -0
- package/dist/memory/mnemosia/progressive.js +550 -0
- package/dist/memory/mnemosia/provenance.js +458 -0
- package/dist/memory/mnemosia/qualifiers.js +428 -0
- package/dist/memory/mnemosia/rank.js +525 -0
- package/dist/memory/mnemosia/relations.js +156 -0
- package/dist/memory/mnemosia/requirements.js +138 -0
- package/dist/memory/mnemosia/rerank.js +253 -0
- package/dist/memory/mnemosia/retention.js +174 -0
- package/dist/memory/mnemosia/rollback.js +337 -0
- package/dist/memory/mnemosia/select.js +607 -0
- package/dist/memory/mnemosia/similarity.js +164 -0
- package/dist/memory/mnemosia/situation.js +251 -0
- package/dist/memory/mnemosia/task.js +418 -0
- package/dist/memory/mnemosia/temporal.js +136 -0
- package/dist/memory/mnemosia/tokens.js +66 -0
- package/dist/memory/mnemosia/tools.js +160 -0
- package/dist/memory/mnemosia/trace.js +306 -0
- package/dist/memory/mnemosia/types.js +298 -0
- package/dist/models.js +360 -0
- package/dist/paths.js +103 -0
- package/dist/redact.js +79 -0
- package/dist/runtime.js +378 -0
- package/dist/search-format.js +102 -0
- package/dist/search.js +351 -0
- package/dist/setup.js +366 -0
- package/dist/shell.js +110 -0
- package/dist/skills.js +311 -0
- package/dist/telemetry.js +84 -0
- package/dist/tui/app.js +1011 -0
- package/dist/tui/commands.js +121 -0
- package/dist/tui/keys.js +83 -0
- package/dist/tui/pane.js +387 -0
- package/dist/tui/panel.js +60 -0
- package/dist/tui/picker.js +25 -0
- package/dist/tui/sanitize.js +59 -0
- package/dist/tui/settings.js +198 -0
- package/dist/tui/setup.js +256 -0
- package/dist/tui/theme.js +26 -0
- package/dist/tui/thinking/parse.js +1094 -0
- package/dist/tui/thinking/select.js +86 -0
- package/dist/tui/thinking/state.js +137 -0
- package/dist/tui/thinking/types.js +3 -0
- package/dist/tui/thinking/view.js +74 -0
- package/dist/tui/viewport.js +208 -0
- package/dist/undo.js +258 -0
- package/dist/web.js +933 -0
- package/docs/conclave.md +21 -0
- package/docs/configuration.md +48 -0
- package/docs/development.md +25 -0
- package/docs/interface.md +33 -0
- package/docs/memory.md +11 -0
- package/docs/privacy.md +13 -0
- package/docs/tools.md +20 -0
- package/docs/web.md +38 -0
- package/models.json.example +34 -0
- package/package.json +76 -4
- package/settings.json.example +29 -0
- package/skills/conclave/SKILL.md +76 -0
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
// Ported from mnemosia/task.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
/**
|
|
3
|
+
* Task analysis and scope authorization (spec §8 and §3, design §6, build-order step 7).
|
|
4
|
+
*
|
|
5
|
+
* Two functions, and the order between them is the point. Spec §3 says security authorization must
|
|
6
|
+
* occur before relevance ranking — "a highly relevant memory that is unauthorized remains
|
|
7
|
+
* unavailable" — so `authorizeScope` runs here, at state 3 of the machine, and produces the scope
|
|
8
|
+
* set that `plan.ts` may query and `filters.ts` enforces. Nothing downstream can widen it, because
|
|
9
|
+
* nothing downstream is given a way to.
|
|
10
|
+
*
|
|
11
|
+
* **Everything this module infers is labelled.** Spec §8 requires extracted information to be
|
|
12
|
+
* classified CONFIRMED / PROBABLE / SPECULATIVE / UNKNOWN and forbids silently converting
|
|
13
|
+
* speculation into retrieval fact. That is why every derived field is an `Extracted<T>` carrying a
|
|
14
|
+
* certainty and the basis for it, rather than a bare value: a keyword rule that fired on one weak
|
|
15
|
+
* match and a value the caller stated outright are different epistemic objects, and a briefing that
|
|
16
|
+
* cannot tell them apart is exactly the failure §8's last line names.
|
|
17
|
+
*
|
|
18
|
+
* The rules are keyword tables and regular expressions. They are not clever, and pretending
|
|
19
|
+
* otherwise by wrapping them in probabilistic language would misrepresent what they are; what they
|
|
20
|
+
* are is deterministic, inspectable, and measurable against the §16 gold set.
|
|
21
|
+
*/
|
|
22
|
+
import { resolve } from "node:path";
|
|
23
|
+
import { SCHEMA_VERSION, scopeKey } from "./types.js";
|
|
24
|
+
/* ------------------------------------------------------------------------------------------------
|
|
25
|
+
* Request
|
|
26
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
27
|
+
/** Design §16's four modes. Fast and Standard are `MVP_REQUIRED`; the other two are configured but unexercised in Phase 1. */
|
|
28
|
+
export const OPERATIONAL_MODES = ["fast", "standard", "deep", "high_assurance"];
|
|
29
|
+
/** The §12 keyword rules produce exactly these. */
|
|
30
|
+
export const TASK_TYPES = ["plan", "implement", "debug", "review", "research", "recall", "status"];
|
|
31
|
+
export const TEMPORAL_NEEDS = ["current_state", "recent", "historical", "any"];
|
|
32
|
+
function confirmed(value, basis) {
|
|
33
|
+
return { value, certainty: "CONFIRMED", basis };
|
|
34
|
+
}
|
|
35
|
+
/* ------------------------------------------------------------------------------------------------
|
|
36
|
+
* Task-type classification
|
|
37
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
38
|
+
/**
|
|
39
|
+
* Keyword rules, in precedence order for ties.
|
|
40
|
+
*
|
|
41
|
+
* `debug` sits above `implement` because "fix the failing test" is a debugging task that happens to
|
|
42
|
+
* involve editing code, and mis-filing it as implementation would cost it the known-failures
|
|
43
|
+
* section that is the most useful thing memory can offer a debugger. `recall` and `status` sit last
|
|
44
|
+
* because their keywords ("context", "summary", "progress") are common inside tasks that are really
|
|
45
|
+
* about something else.
|
|
46
|
+
*/
|
|
47
|
+
export const TASK_TYPE_KEYWORDS = [
|
|
48
|
+
{
|
|
49
|
+
type: "debug",
|
|
50
|
+
patterns: [/\bdebug\w*\b/iu, /\bbugs?\b/iu, /\berrors?\b/iu, /\bfail(?:s|ed|ing|ure)?\b/iu, /\bcrash\w*\b/iu, /\bbroken\b/iu, /\bregression\b/iu, /\bstack ?trace\b/iu, /\bexceptions?\b/iu, /\breproduce\b/iu, /\broot cause\b/iu, /\bfix(?:es|ed|ing)?\b/iu, /\bwhy (?:is|does|did|are)\b/iu],
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
type: "review",
|
|
54
|
+
patterns: [/\breview\w*\b/iu, /\baudit\w*\b/iu, /\bcritique\b/iu, /\bassess\w*\b/iu, /\bevaluat\w*\b/iu, /\bverif\w*\b/iu, /\bvalidat\w*\b/iu, /\binspect\w*\b/iu, /\bsecurity review\b/iu],
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
type: "plan",
|
|
58
|
+
patterns: [/\bplan\w*\b/iu, /\bdesign\w*\b/iu, /\barchitect\w*\b/iu, /\broadmap\b/iu, /\bstrateg\w*\b/iu, /\bapproach\b/iu, /\bpropos\w*\b/iu, /\boutline\b/iu, /\bdecompos\w*\b/iu, /\bshould we\b/iu],
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
type: "implement",
|
|
62
|
+
patterns: [/\bimplement\w*\b/iu, /\bbuild\w*\b/iu, /\bwrite\b/iu, /\brefactor\w*\b/iu, /\bmigrat\w*\b/iu, /\bwire (?:up|in)\b/iu, /\bship\b/iu, /\bintegrat\w*\b/iu, /\badd (?:a|an|the)\b/iu, /\bcreate (?:a|an|the)\b/iu],
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
type: "research",
|
|
66
|
+
patterns: [/\bresearch\w*\b/iu, /\binvestigat\w*\b/iu, /\bcompare\b/iu, /\bexplor\w*\b/iu, /\bfind out\b/iu, /\bsurvey\b/iu, /\bbenchmark\w*\b/iu, /\boptions\b/iu, /\bdocumentation\b/iu, /\bhow does\b/iu],
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
type: "recall",
|
|
70
|
+
patterns: [/\brecall\b/iu, /\bremember\b/iu, /\bremind\b/iu, /\bwhat did (?:we|i|you)\b/iu, /\bpreviously\b/iu, /\blast time\b/iu, /\bhistory\b/iu, /\bcatch me up\b/iu, /\bbrief me\b/iu, /\bprior (?:work|context|decisions?)\b/iu],
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
type: "status",
|
|
74
|
+
patterns: [/\bstatus\b/iu, /\bprogress\b/iu, /\bwhere (?:are|were) we\b/iu, /\bcurrent state\b/iu, /\bwhat(?:'s| is) left\b/iu, /\bdone so far\b/iu, /\bopen (?:loops|tasks|items)\b/iu, /\boutstanding\b/iu],
|
|
75
|
+
},
|
|
76
|
+
];
|
|
77
|
+
/**
|
|
78
|
+
* Highest keyword count wins; ties go to the earlier table entry.
|
|
79
|
+
*
|
|
80
|
+
* The certainty is the honest part. Two or more distinct rules firing is PROBABLE; a single rule is
|
|
81
|
+
* SPECULATIVE, because one keyword in a long sentence is genuinely weak evidence; nothing firing is
|
|
82
|
+
* UNKNOWN and falls back to `recall`, which is the least presumptuous reading of "an agent asked
|
|
83
|
+
* the memory orchestrator for a briefing and did not say why".
|
|
84
|
+
*/
|
|
85
|
+
export function classifyTaskType(task) {
|
|
86
|
+
let best = { type: "recall", hits: 0 };
|
|
87
|
+
for (const rule of TASK_TYPE_KEYWORDS) {
|
|
88
|
+
const hits = rule.patterns.filter((pattern) => pattern.test(task)).length;
|
|
89
|
+
if (hits > best.hits)
|
|
90
|
+
best = { type: rule.type, hits };
|
|
91
|
+
}
|
|
92
|
+
if (best.hits === 0)
|
|
93
|
+
return { value: "recall", certainty: "UNKNOWN", basis: "no task-type keyword matched; defaulted to recall" };
|
|
94
|
+
return {
|
|
95
|
+
value: best.type,
|
|
96
|
+
certainty: best.hits >= 2 ? "PROBABLE" : "SPECULATIVE",
|
|
97
|
+
basis: `${best.hits} ${best.type} keyword rule${best.hits === 1 ? "" : "s"} matched`,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/* ------------------------------------------------------------------------------------------------
|
|
101
|
+
* Entity extraction
|
|
102
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
103
|
+
export const ENTITY_KINDS = ["path", "identifier", "quoted", "hash"];
|
|
104
|
+
/**
|
|
105
|
+
* Ordered because a Windows absolute path must be matched before the dotted-identifier rule gets to
|
|
106
|
+
* chew on `store.ts`, and a backticked span must be matched before its contents are re-matched by
|
|
107
|
+
* everything else. Each pattern's first capture group, when present, is the entity text.
|
|
108
|
+
*/
|
|
109
|
+
const ENTITY_PATTERNS = [
|
|
110
|
+
{ kind: "quoted", pattern: /`([^`\n]{2,120})`/gu },
|
|
111
|
+
{ kind: "path", pattern: /\b([A-Za-z]:[\\/][^\s"'`,;)]+)/gu },
|
|
112
|
+
// The lookbehind keeps the scan linear: a match may start only at the beginning of a run of path characters.
|
|
113
|
+
{ kind: "path", pattern: /(?<![\w.@\/-])((?:\.{1,2}\/|\/)?(?:[\w.@-]+\/)+[\w.@-]+)/gu },
|
|
114
|
+
{ kind: "hash", pattern: /\b([0-9a-f]{7,40})\b/gu },
|
|
115
|
+
{ kind: "identifier", pattern: /\b([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]+)+)\b/gu },
|
|
116
|
+
{ kind: "identifier", pattern: /\b([a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)+)\b/gu },
|
|
117
|
+
{ kind: "identifier", pattern: /\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\b/gu },
|
|
118
|
+
{ kind: "identifier", pattern: /\b([a-z][a-z0-9]*(?:_[a-z0-9]+)+)\b/gu },
|
|
119
|
+
];
|
|
120
|
+
/** Upper bound on entities carried forward. Beyond this the tail is noise, and it is reported. */
|
|
121
|
+
export const MAX_ENTITIES = 24;
|
|
122
|
+
/**
|
|
123
|
+
* Path and identifier tokenization over the raw task text.
|
|
124
|
+
*
|
|
125
|
+
* Overlaps are resolved by claiming character spans: once a stretch of the task has been attributed
|
|
126
|
+
* to an entity, a later pattern cannot re-attribute it. Without that, `src/adapters/store.ts`
|
|
127
|
+
* would yield a path, a dotted identifier and a snake_case identifier for the same eleven
|
|
128
|
+
* characters, and the entity count — which feeds a ranking signal — would measure regex overlap
|
|
129
|
+
* instead of subject matter.
|
|
130
|
+
*/
|
|
131
|
+
export function extractEntities(task) {
|
|
132
|
+
const claimed = new Uint8Array(task.length);
|
|
133
|
+
const entities = [];
|
|
134
|
+
const seen = new Set();
|
|
135
|
+
for (const { kind, pattern } of ENTITY_PATTERNS) {
|
|
136
|
+
pattern.lastIndex = 0;
|
|
137
|
+
for (const match of task.matchAll(pattern)) {
|
|
138
|
+
const text = match[1] ?? match[0];
|
|
139
|
+
const start = match.index ?? 0;
|
|
140
|
+
const end = start + match[0].length;
|
|
141
|
+
if (claimed.subarray(start, end).some(Boolean))
|
|
142
|
+
continue;
|
|
143
|
+
claimed.fill(1, start, end);
|
|
144
|
+
const key = `${kind}:${text.toLowerCase()}`;
|
|
145
|
+
if (seen.has(key))
|
|
146
|
+
continue;
|
|
147
|
+
seen.add(key);
|
|
148
|
+
entities.push({ text, kind });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const value = entities.slice(0, MAX_ENTITIES);
|
|
152
|
+
if (value.length === 0)
|
|
153
|
+
return { value, certainty: "UNKNOWN", basis: "no path, identifier, quoted span or hash found in the task text" };
|
|
154
|
+
return {
|
|
155
|
+
value,
|
|
156
|
+
// A path or a backticked span is something the author typed deliberately; a bare camelCase
|
|
157
|
+
// word could be ordinary English with a capital in it. The distinction is worth the label.
|
|
158
|
+
certainty: value.some((entity) => entity.kind === "path" || entity.kind === "quoted" || entity.kind === "hash") ? "PROBABLE" : "SPECULATIVE",
|
|
159
|
+
basis: `${value.length} entit${value.length === 1 ? "y" : "ies"} from ${new Set(value.map((entity) => entity.kind)).size} pattern class(es)${entities.length > value.length ? `; ${entities.length - value.length} beyond MAX_ENTITIES dropped` : ""}`,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Removed before terms reach a query. AkashicForge's tokenizer keeps stopwords, and FTS5's default
|
|
164
|
+
* operator is AND, so leaving `the` in a term list turns the query into "documents containing every
|
|
165
|
+
* word of the sentence" — which on this corpus returns nothing at all. This list is deliberately
|
|
166
|
+
* short and structural (articles, auxiliaries, prepositions, and the imperative verbs that appear
|
|
167
|
+
* in nearly every task) rather than a general English stoplist, because a general stoplist would
|
|
168
|
+
* also swallow domain words like `state` and `key`.
|
|
169
|
+
*/
|
|
170
|
+
export const STOPWORDS = new Set([
|
|
171
|
+
"a", "about", "all", "an", "and", "any", "are", "as", "at", "be", "been", "but", "by", "can", "did", "do", "does", "for", "from", "get", "had", "has", "have", "how", "i", "if", "in", "into", "is", "it", "its", "just", "make", "me", "my", "need", "no", "not", "of", "on", "or", "our", "out", "over", "please", "should", "so", "some", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "to", "up", "us", "use", "very", "want", "was", "we", "were", "what", "when", "where", "which", "who", "why", "will", "with", "would", "you", "your",
|
|
172
|
+
]);
|
|
173
|
+
/** Store-side cap (`tokenizeSearch` slices to 32); mirrored so the analysis never claims more. */
|
|
174
|
+
export const MAX_TERMS = 32;
|
|
175
|
+
/** Tokens shorter than this are almost always noise from a split identifier. */
|
|
176
|
+
const MIN_TERM_LENGTH = 3;
|
|
177
|
+
/**
|
|
178
|
+
* The full content-term set for the task.
|
|
179
|
+
*
|
|
180
|
+
* This is *not* what goes into a query — `plan.ts` narrows it, because the store ANDs terms — but
|
|
181
|
+
* it is what design §9's relevance signal measures coverage against, so it stays wide here.
|
|
182
|
+
*/
|
|
183
|
+
export function extractTerms(task, tokenize) {
|
|
184
|
+
const raw = task.trim().length === 0 ? [] : tokenize(task);
|
|
185
|
+
const value = raw.filter((token) => token.length >= MIN_TERM_LENGTH && !STOPWORDS.has(token.toLowerCase())).slice(0, MAX_TERMS);
|
|
186
|
+
if (value.length === 0)
|
|
187
|
+
return { value, certainty: "UNKNOWN", basis: raw.length === 0 ? "the task tokenized to nothing" : `all ${raw.length} token(s) were stopwords or shorter than ${MIN_TERM_LENGTH} characters` };
|
|
188
|
+
return { value, certainty: "CONFIRMED", basis: `${value.length} content term(s) from ${raw.length} token(s) via the store's own tokenizer` };
|
|
189
|
+
}
|
|
190
|
+
/* ------------------------------------------------------------------------------------------------
|
|
191
|
+
* Temporal requirements
|
|
192
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
193
|
+
export const DAY_MS = 86_400_000;
|
|
194
|
+
/**
|
|
195
|
+
* Windows attached to each temporal need.
|
|
196
|
+
*
|
|
197
|
+
* They are short because the corpus is dense — 11,182 events over roughly a week of sessions — and
|
|
198
|
+
* because a bound that admits everything is not a bound. `historical` and `any` deliberately have
|
|
199
|
+
* no lower bound: "any" means the task gave no temporal signal, and inventing one would be exactly
|
|
200
|
+
* the silent speculation spec §8 prohibits.
|
|
201
|
+
*/
|
|
202
|
+
export const TEMPORAL_WINDOW_DAYS = {
|
|
203
|
+
current_state: 3,
|
|
204
|
+
recent: 14,
|
|
205
|
+
historical: null,
|
|
206
|
+
any: null,
|
|
207
|
+
};
|
|
208
|
+
const TEMPORAL_PATTERNS = [
|
|
209
|
+
{ need: "current_state", pattern: /\b(?:current(?:ly)?|latest|right now|as of now|today|present state|at the moment)\b/iu },
|
|
210
|
+
{ need: "recent", pattern: /\b(?:recent(?:ly)?|yesterday|this (?:week|session)|last (?:session|run|week)|just (?:now|did|finished))\b/iu },
|
|
211
|
+
{ need: "historical", pattern: /\b(?:origin(?:al|ally)|history|historical|ever|all time|first time|back (?:then|when)|why did we (?:originally|first))\b/iu },
|
|
212
|
+
];
|
|
213
|
+
export function classifyTemporalNeed(task) {
|
|
214
|
+
const matched = TEMPORAL_PATTERNS.filter((rule) => rule.pattern.test(task));
|
|
215
|
+
const first = matched[0];
|
|
216
|
+
if (first === undefined)
|
|
217
|
+
return { value: "any", certainty: "UNKNOWN", basis: "no temporal marker in the task text" };
|
|
218
|
+
// More than one marker means the task spans time rather than pointing at an instant; widening to
|
|
219
|
+
// `historical` is the safe reading, because a narrow window cannot be reopened later in the run.
|
|
220
|
+
if (matched.length > 1)
|
|
221
|
+
return { value: "historical", certainty: "SPECULATIVE", basis: `${matched.length} conflicting temporal markers; widened to historical` };
|
|
222
|
+
return { value: first.need, certainty: "PROBABLE", basis: `temporal marker matched ${first.need}` };
|
|
223
|
+
}
|
|
224
|
+
/* ------------------------------------------------------------------------------------------------
|
|
225
|
+
* Early-exit detection
|
|
226
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
227
|
+
/**
|
|
228
|
+
* Phrases that make "no memory required" a stated fact rather than an inference.
|
|
229
|
+
*/
|
|
230
|
+
const NO_MEMORY_MARKERS = /\b(?:no memory|without memory|no prior context|ignore (?:prior|previous) context|from scratch|self[- ]contained|standalone task)\b/iu;
|
|
231
|
+
/** Social turns and bare arithmetic: complete in themselves, and retrieval would only add noise. */
|
|
232
|
+
const TRIVIAL_TASK = /^\s*(?:hi|hello|hey|thanks|thank you|ok|okay|yes|no|sure)\b[\s!.?]*$/iu;
|
|
233
|
+
const PURE_ARITHMETIC = /^[\s\d+\-*/().^%=]+\??$/u;
|
|
234
|
+
/**
|
|
235
|
+
* A task built entirely out of referents and fillers — "that one again", "do the thing" — names
|
|
236
|
+
* nothing Mnemosia can retrieve on. The antecedent is in the caller's head, not in the request, and
|
|
237
|
+
* guessing at it from the most recent event would be exactly the kind of plausible wrong answer a
|
|
238
|
+
* memory orchestrator exists to avoid. The word list is closed and short on purpose: one content
|
|
239
|
+
* word anywhere in the task defeats it.
|
|
240
|
+
*/
|
|
241
|
+
const BARE_REFERENT = /^(?:\s*(?:that|this|it|its|them|they|those|these|the|a|an|same|again|one|ones|thing|things|stuff|please|do|it's|now|too|also)\b[\s.,;?!]*)+$/iu;
|
|
242
|
+
/** Below this a "task" is a fragment, not a request. Chosen to admit `fix the CI` (10) and reject `?`. */
|
|
243
|
+
export const MIN_TASK_CHARS = 8;
|
|
244
|
+
/* ------------------------------------------------------------------------------------------------
|
|
245
|
+
* Analysis
|
|
246
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
247
|
+
export const TASK_OUTCOMES = ["PROCEED", "NO_MEMORY_REQUIRED", "CLARIFICATION_REQUIRED"];
|
|
248
|
+
/**
|
|
249
|
+
* AkashicForge normalizes a project path as `resolve(trim(p))`, lowercased on win32
|
|
250
|
+
* (store.ts:367-370). That function is not exported, so it is mirrored here rather than injected —
|
|
251
|
+
* and mirrored exactly, because a scope string that differs by one character from the stored one
|
|
252
|
+
* silently matches no rows, which looks like an empty corpus rather than like a bug.
|
|
253
|
+
*
|
|
254
|
+
* `test/task.test.ts` pins the mirror against the project strings the live database actually holds.
|
|
255
|
+
*/
|
|
256
|
+
export function normalizeProjectPath(project) {
|
|
257
|
+
const normalized = resolve(project.trim());
|
|
258
|
+
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
|
|
259
|
+
}
|
|
260
|
+
export function analyzeTask(request, deps) {
|
|
261
|
+
const now = request.now ?? Date.now();
|
|
262
|
+
const objective = request.task.trim();
|
|
263
|
+
const mode = request.mode ?? "standard";
|
|
264
|
+
const taskType = request.taskTypeHint === undefined ? classifyTaskType(objective) : confirmed(request.taskTypeHint, "supplied by the requesting agent");
|
|
265
|
+
const entities = extractEntities(objective);
|
|
266
|
+
const terms = extractTerms(objective, deps.tokenize);
|
|
267
|
+
const temporalNeed = classifyTemporalNeed(objective);
|
|
268
|
+
const windowDays = TEMPORAL_WINDOW_DAYS[temporalNeed.value];
|
|
269
|
+
const project = request.project === null ? confirmed(null, "the caller reported no working project") : confirmed(normalizeProjectPath(request.project), "supplied by the caller, normalized as AkashicForge stores it");
|
|
270
|
+
const requestedProjects = confirmed([...new Set((request.requestedProjects ?? []).map(normalizeProjectPath))].sort(), (request.requestedProjects ?? []).length === 0 ? "the caller requested no additional project scope" : "explicitly requested by the caller");
|
|
271
|
+
// Both of these are derived from the task type rather than from separate keyword tables. A
|
|
272
|
+
// second table would be a second thing to keep consistent with the first, and there is no
|
|
273
|
+
// evidence in the corpus that it would classify better.
|
|
274
|
+
const historyMatters = {
|
|
275
|
+
value: taskType.value !== "implement" || temporalNeed.value === "historical",
|
|
276
|
+
certainty: taskType.certainty,
|
|
277
|
+
basis: `derived from taskType=${taskType.value}, temporalNeed=${temporalNeed.value}`,
|
|
278
|
+
};
|
|
279
|
+
const preferencesMatter = {
|
|
280
|
+
value: taskType.value !== "status",
|
|
281
|
+
certainty: taskType.certainty,
|
|
282
|
+
basis: `derived from taskType=${taskType.value}; only a pure status read ignores standing preferences`,
|
|
283
|
+
};
|
|
284
|
+
const reasons = [];
|
|
285
|
+
let outcome = "PROCEED";
|
|
286
|
+
if (objective.length === 0) {
|
|
287
|
+
outcome = "CLARIFICATION_REQUIRED";
|
|
288
|
+
reasons.push("the task is empty");
|
|
289
|
+
}
|
|
290
|
+
else if (NO_MEMORY_MARKERS.test(objective)) {
|
|
291
|
+
outcome = "NO_MEMORY_REQUIRED";
|
|
292
|
+
reasons.push("the task states that no prior context is to be used");
|
|
293
|
+
}
|
|
294
|
+
else if (TRIVIAL_TASK.test(objective) || PURE_ARITHMETIC.test(objective)) {
|
|
295
|
+
outcome = "NO_MEMORY_REQUIRED";
|
|
296
|
+
reasons.push("the task is self-contained (a social turn or a bare arithmetic expression); retrieval could only add noise");
|
|
297
|
+
}
|
|
298
|
+
else if (BARE_REFERENT.test(objective)) {
|
|
299
|
+
outcome = "CLARIFICATION_REQUIRED";
|
|
300
|
+
reasons.push("the task is a bare referent with no antecedent Mnemosia can resolve");
|
|
301
|
+
}
|
|
302
|
+
else if (objective.length < MIN_TASK_CHARS) {
|
|
303
|
+
outcome = "CLARIFICATION_REQUIRED";
|
|
304
|
+
reasons.push(`the task is ${objective.length} characters, below the ${MIN_TASK_CHARS}-character floor for a usable request`);
|
|
305
|
+
}
|
|
306
|
+
else if (terms.value.length === 0 && entities.value.length === 0) {
|
|
307
|
+
outcome = "CLARIFICATION_REQUIRED";
|
|
308
|
+
reasons.push("the task yielded no content terms and no entities, so there is nothing to retrieve on");
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
reasons.push(`taskType=${taskType.value} (${taskType.certainty}), ${terms.value.length} term(s), ${entities.value.length} entit(y|ies), temporal=${temporalNeed.value}`);
|
|
312
|
+
}
|
|
313
|
+
if (!Number.isInteger(request.contextBudget) || request.contextBudget <= 0) {
|
|
314
|
+
outcome = "CLARIFICATION_REQUIRED";
|
|
315
|
+
reasons.push(`contextBudget must be a positive integer; received ${String(request.contextBudget)}`);
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
schemaVersion: SCHEMA_VERSION.taskAnalysis,
|
|
319
|
+
runId: request.runId,
|
|
320
|
+
objective,
|
|
321
|
+
requestingAgent: request.requestingAgent,
|
|
322
|
+
taskType,
|
|
323
|
+
entities,
|
|
324
|
+
terms,
|
|
325
|
+
temporalNeed,
|
|
326
|
+
since: windowDays === null ? null : now - windowDays * DAY_MS,
|
|
327
|
+
until: null,
|
|
328
|
+
historyMatters,
|
|
329
|
+
preferencesMatter,
|
|
330
|
+
contextBudget: confirmed(request.contextBudget, "supplied by the caller; Pi exposes no live context occupancy to a tool"),
|
|
331
|
+
mode: request.mode === undefined ? { value: mode, certainty: "SPECULATIVE", basis: "no mode supplied; defaulted to standard" } : confirmed(mode, "supplied by the caller"),
|
|
332
|
+
assurance: mode === "high_assurance" ? confirmed("high", "high_assurance mode") : confirmed("standard", "derived from mode"),
|
|
333
|
+
project,
|
|
334
|
+
requestedProjects,
|
|
335
|
+
outcome,
|
|
336
|
+
reasons,
|
|
337
|
+
analyzedAt: now,
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
/* ------------------------------------------------------------------------------------------------
|
|
341
|
+
* Scope authorization
|
|
342
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
343
|
+
export const AUTHORIZATION_RULES = ["own_project", "global_scope", "explicitly_requested", "cross_project_not_requested", "unresolved_project_scope"];
|
|
344
|
+
/** A path entity long enough and absolute enough to be a project root rather than a file inside one. */
|
|
345
|
+
function looksLikeProjectRoot(text) {
|
|
346
|
+
return /^[A-Za-z]:[\\/]/u.test(text) || text.startsWith("/");
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Resolves the scopes this run may read (spec §3, design §12's first hard filter).
|
|
350
|
+
*
|
|
351
|
+
* The rules, in full:
|
|
352
|
+
*
|
|
353
|
+
* - **Global is always granted.** It is the user's own vault on a single-user machine; there is no
|
|
354
|
+
* second tenant it could leak to (design §2 drops tenancy for exactly this reason).
|
|
355
|
+
* - **The session's own project is granted.** That is the implicit authority of working in a repo.
|
|
356
|
+
* - **Any other project is granted only if the caller explicitly requested it.** A project path
|
|
357
|
+
* that merely *appears* in the task text is a mention — "the fix we made in D:\Threadweaver" —
|
|
358
|
+
* and reading that project's memory on the strength of a mention is precisely the cross-project
|
|
359
|
+
* leak spec §4 forbids.
|
|
360
|
+
* - **The run exits `INSUFFICIENT_AUTHORIZATION`** when something was refused and nothing
|
|
361
|
+
* project-scoped was granted: the task is about a project Mnemosia may not read, and answering
|
|
362
|
+
* from global memory alone would look like an answer while being about the wrong thing. Failing
|
|
363
|
+
* closed is the only honest option, and it is decided here, before anything is ranked.
|
|
364
|
+
*/
|
|
365
|
+
export function authorizeScope(analysis) {
|
|
366
|
+
const granted = [{ scope: { level: "global", project: null }, ruleId: "global_scope", detail: "global memory is the requesting user's own vault on a single-user machine" }];
|
|
367
|
+
const refused = [];
|
|
368
|
+
const reasons = [];
|
|
369
|
+
const own = analysis.project.value;
|
|
370
|
+
if (own !== null)
|
|
371
|
+
granted.push({ scope: { level: "project", project: own }, ruleId: "own_project", detail: `the session's working project (${own})` });
|
|
372
|
+
const requested = new Set(analysis.requestedProjects.value);
|
|
373
|
+
for (const project of analysis.requestedProjects.value) {
|
|
374
|
+
if (project === own)
|
|
375
|
+
continue;
|
|
376
|
+
granted.push({ scope: { level: "project", project }, ruleId: "explicitly_requested", detail: `explicitly requested cross-project read of ${project}` });
|
|
377
|
+
}
|
|
378
|
+
// Project paths the task text merely mentions.
|
|
379
|
+
const mentioned = new Set();
|
|
380
|
+
for (const entity of analysis.entities.value) {
|
|
381
|
+
if (entity.kind !== "path" || !looksLikeProjectRoot(entity.text))
|
|
382
|
+
continue;
|
|
383
|
+
mentioned.add(normalizeProjectPath(entity.text));
|
|
384
|
+
}
|
|
385
|
+
for (const project of [...mentioned].sort()) {
|
|
386
|
+
if (project === own || requested.has(project))
|
|
387
|
+
continue;
|
|
388
|
+
// A mentioned path is usually a *file* inside the session's own project, which is not a
|
|
389
|
+
// cross-project read at all and must not be reported as a refusal.
|
|
390
|
+
if (own !== null && project.startsWith(`${own}\\`))
|
|
391
|
+
continue;
|
|
392
|
+
if (own !== null && project.startsWith(`${own}/`))
|
|
393
|
+
continue;
|
|
394
|
+
refused.push({ scope: { level: "project", project }, ruleId: "cross_project_not_requested", detail: `${project} appears in the task text but was not explicitly requested` });
|
|
395
|
+
}
|
|
396
|
+
if (own === null && requested.size === 0 && analysis.taskType.value !== "recall" && mentioned.size > 0) {
|
|
397
|
+
reasons.push("no working project was supplied; only global scope is available");
|
|
398
|
+
}
|
|
399
|
+
const projectGrants = granted.filter((grant) => grant.scope.level === "project");
|
|
400
|
+
const outcome = refused.length > 0 && projectGrants.length === 0 ? "INSUFFICIENT_AUTHORIZATION" : "AUTHORIZED";
|
|
401
|
+
if (outcome === "INSUFFICIENT_AUTHORIZATION") {
|
|
402
|
+
reasons.push(`the task is scoped to ${refused.map((entry) => entry.scope.project).join(", ")}, which was not explicitly requested, and no project scope is authorized for this run`);
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
reasons.push(`${granted.length} scope(s) granted, ${refused.length} refused`);
|
|
406
|
+
}
|
|
407
|
+
return {
|
|
408
|
+
schemaVersion: SCHEMA_VERSION.scopeAuthorization,
|
|
409
|
+
runId: analysis.runId,
|
|
410
|
+
outcome,
|
|
411
|
+
granted,
|
|
412
|
+
refused,
|
|
413
|
+
// Built from the same `scopeKey` filters.ts tests membership with. Two definitions of scope
|
|
414
|
+
// identity would be two chances to disagree about what is authorized.
|
|
415
|
+
authorizedKeys: outcome === "AUTHORIZED" ? granted.map((grant) => scopeKey(grant.scope)) : [],
|
|
416
|
+
reasons,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Ported from mnemosia/temporal.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
/**
|
|
3
|
+
* Temporal validity (spec §12 `temporal_validity`, spec §14 "Consider: Effective time"; Phase 2).
|
|
4
|
+
*
|
|
5
|
+
* Phase 1 carried `effectiveAt` and `expiresAt` on every claim and enforced exactly one of them:
|
|
6
|
+
* `filters.ts` rejected a claim whose `expiresAt` had passed. That leaves the other half of the
|
|
7
|
+
* interval unenforced, and the two halves are not the same question:
|
|
8
|
+
*
|
|
9
|
+
* - **Freshness** asks *how old* a claim is, and answers with a decay curve. A six-month-old
|
|
10
|
+
* preference is stale-ish and still perfectly valid.
|
|
11
|
+
* - **Temporal validity** asks *whether the claim is in force at all*. A claim whose `effectiveAt`
|
|
12
|
+
* is next Tuesday is maximally fresh — age clamps to 0 in `freshnessSignal` — and is not yet true.
|
|
13
|
+
* A claim recorded a year ago with no expiry is unfresh and completely valid.
|
|
14
|
+
*
|
|
15
|
+
* Spec §12 lists them as two signals for that reason, and this module computes the second one.
|
|
16
|
+
*
|
|
17
|
+
* **It is deliberately not an eighth weighted signal.** Design §19 item 3 makes a `policy.ts` weight
|
|
18
|
+
* change a decision requiring human approval, and the honest way to add temporal reasoning without
|
|
19
|
+
* silently re-tuning six weights that were measured in Phase 1 is to use it where it is *categorical*
|
|
20
|
+
* rather than where it would be *marginal*:
|
|
21
|
+
*
|
|
22
|
+
* 1. **A gate.** A claim that is not in force may not enter a factual briefing section
|
|
23
|
+
* (`select.ts` routes it, `brief.ts` validates it). That is stronger than any weight could be —
|
|
24
|
+
* no amount of authority or relevance readmits it — and it is the same shape as the
|
|
25
|
+
* `SUPERSEDED`-in-`confirmed_facts` rule design §16 already gates at zero.
|
|
26
|
+
* 2. **A conflict input.** Spec §14's first consideration is effective time. `intervalRelation`
|
|
27
|
+
* below is what lets `conflicts.ts` say "these two never claimed to hold at the same moment", so
|
|
28
|
+
* a pair that merely *succeeded* one another is not reported as a contradiction.
|
|
29
|
+
* 3. **A recorded quantity.** `TemporalValidity` lands in `RankBasis` and in the trace, so a replay
|
|
30
|
+
* can see the value that was computed even though no weight multiplied it.
|
|
31
|
+
*
|
|
32
|
+
* The alternative — folding it into `freshness` — is the exact collapse spec §12 opens by
|
|
33
|
+
* prohibiting, and it would make a not-yet-effective claim indistinguishable from a very fresh one.
|
|
34
|
+
*/
|
|
35
|
+
/**
|
|
36
|
+
* Where `now` sits relative to `[effectiveAt, expiresAt)`.
|
|
37
|
+
*
|
|
38
|
+
* `unbounded` and `valid` are separated because they are different epistemic states: a claim with a
|
|
39
|
+
* stated expiry that has not yet arrived has been *given* a validity window by whoever recorded it,
|
|
40
|
+
* and a claim with no expiry has simply never been bounded. The first is a promise about the future;
|
|
41
|
+
* the second is an absence of one.
|
|
42
|
+
*/
|
|
43
|
+
export const TEMPORAL_STATUSES = ["not_yet_effective", "valid", "unbounded", "expired"];
|
|
44
|
+
function isoDay(at) {
|
|
45
|
+
return new Date(at).toISOString().slice(0, 10);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The claim's validity state at `now`.
|
|
49
|
+
*
|
|
50
|
+
* An `expiresAt` at or before `effectiveAt` is a degenerate interval — a claim that was never in
|
|
51
|
+
* force at any instant. It is reported as `expired` rather than as a schema error, because the two
|
|
52
|
+
* timestamps come from different columns of a governed row and a curator setting an expiry in the
|
|
53
|
+
* past is a real, recoverable data state; refusing to compute would turn it into a crash.
|
|
54
|
+
*/
|
|
55
|
+
export function temporalValidity(claim, now) {
|
|
56
|
+
const { effectiveAt, expiresAt } = claim;
|
|
57
|
+
const msUntilEffective = Math.max(0, effectiveAt - now);
|
|
58
|
+
const msUntilExpiry = expiresAt === null ? null : expiresAt - now;
|
|
59
|
+
if (expiresAt !== null && expiresAt <= now) {
|
|
60
|
+
return {
|
|
61
|
+
status: "expired",
|
|
62
|
+
effectiveAt,
|
|
63
|
+
expiresAt,
|
|
64
|
+
msUntilEffective,
|
|
65
|
+
msUntilExpiry,
|
|
66
|
+
inForce: false,
|
|
67
|
+
basis: `expired on ${isoDay(expiresAt)}`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (effectiveAt > now) {
|
|
71
|
+
return {
|
|
72
|
+
status: "not_yet_effective",
|
|
73
|
+
effectiveAt,
|
|
74
|
+
expiresAt,
|
|
75
|
+
msUntilEffective,
|
|
76
|
+
msUntilExpiry,
|
|
77
|
+
inForce: false,
|
|
78
|
+
basis: `not in force until ${isoDay(effectiveAt)}`,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
if (expiresAt === null) {
|
|
82
|
+
return { status: "unbounded", effectiveAt, expiresAt, msUntilEffective, msUntilExpiry, inForce: true, basis: `in force since ${isoDay(effectiveAt)}, with no stated expiry` };
|
|
83
|
+
}
|
|
84
|
+
return { status: "valid", effectiveAt, expiresAt, msUntilEffective, msUntilExpiry, inForce: true, basis: `in force from ${isoDay(effectiveAt)} until ${isoDay(expiresAt)}` };
|
|
85
|
+
}
|
|
86
|
+
/* ------------------------------------------------------------------------------------------------
|
|
87
|
+
* Interval reasoning for conflict resolution (spec §14)
|
|
88
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
89
|
+
/**
|
|
90
|
+
* How two validity intervals sit relative to one another.
|
|
91
|
+
*
|
|
92
|
+
* `disjoint` is the load-bearing case. Two statements that were each in force over intervals that
|
|
93
|
+
* never met cannot contradict one another: they are a sequence, not a disagreement, and spec §14's
|
|
94
|
+
* `TEMPORAL_SUCCESSION` is exactly the label for that. Reporting them as `DIRECT_CONTRADICTION`
|
|
95
|
+
* would put a resolved history in front of the reader as an open question.
|
|
96
|
+
*/
|
|
97
|
+
export const INTERVAL_RELATIONS = ["disjoint_a_before_b", "disjoint_b_before_a", "overlapping", "a_contains_b", "b_contains_a", "identical"];
|
|
98
|
+
const FOREVER = Number.POSITIVE_INFINITY;
|
|
99
|
+
export function intervalRelation(a, b) {
|
|
100
|
+
const aStart = a.effectiveAt;
|
|
101
|
+
const aEnd = a.expiresAt ?? FOREVER;
|
|
102
|
+
const bStart = b.effectiveAt;
|
|
103
|
+
const bEnd = b.expiresAt ?? FOREVER;
|
|
104
|
+
if (aStart === bStart && aEnd === bEnd)
|
|
105
|
+
return "identical";
|
|
106
|
+
// Half-open intervals: a claim that expires exactly when its successor takes effect is a clean
|
|
107
|
+
// handover, not an overlap. Recording it as an overlap would manufacture a contradiction out of
|
|
108
|
+
// two statements that were each true for their own stretch and never at the same instant.
|
|
109
|
+
if (aEnd <= bStart)
|
|
110
|
+
return "disjoint_a_before_b";
|
|
111
|
+
if (bEnd <= aStart)
|
|
112
|
+
return "disjoint_b_before_a";
|
|
113
|
+
if (aStart <= bStart && aEnd >= bEnd)
|
|
114
|
+
return "a_contains_b";
|
|
115
|
+
if (bStart <= aStart && bEnd >= aEnd)
|
|
116
|
+
return "b_contains_a";
|
|
117
|
+
return "overlapping";
|
|
118
|
+
}
|
|
119
|
+
/** True when the two claims never asserted themselves over a shared instant. */
|
|
120
|
+
export function temporallyDisjoint(a, b) {
|
|
121
|
+
const relation = intervalRelation(a, b);
|
|
122
|
+
return relation === "disjoint_a_before_b" || relation === "disjoint_b_before_a";
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Effective-time order with a total tie-break, for "which of these two is the newer statement".
|
|
126
|
+
*
|
|
127
|
+
* Returns a negative number when `a` is the newer one, so the array it sorts reads newest-first.
|
|
128
|
+
* The tie-break on `id` is not decoration: two claims extracted from one artifact share its
|
|
129
|
+
* `createdAt`, so "newer wins" is genuinely undecided for them, and without a second key the winner
|
|
130
|
+
* would depend on adapter return order — which the §16 determinism gate measures across three runs.
|
|
131
|
+
*/
|
|
132
|
+
export function newerFirst(a, b) {
|
|
133
|
+
if (a.effectiveAt !== b.effectiveAt)
|
|
134
|
+
return b.effectiveAt - a.effectiveAt;
|
|
135
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
136
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Ported from mnemosia/tokens.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
/**
|
|
3
|
+
* Token estimation and budget arithmetic.
|
|
4
|
+
*
|
|
5
|
+
* Design assumption 4 fixes the estimator at `ceil(chars / 4)`. That is deliberately not a
|
|
6
|
+
* tokenizer: Mnemosia budgets context for a caller whose model she does not know, so a
|
|
7
|
+
* model-specific count would be precise about the wrong model. What the budget actually needs is a
|
|
8
|
+
* function that is (a) monotonic in content length, (b) identical on every machine and every run,
|
|
9
|
+
* and (c) never optimistic enough to overflow a real context window by a factor that matters.
|
|
10
|
+
* `ceil(chars / 4)` is all three, and the §16 determinism gate depends on the second one.
|
|
11
|
+
*/
|
|
12
|
+
/** Characters per token. Changing this changes every recorded tokenEstimate; treat as a schema bump. */
|
|
13
|
+
export const CHARS_PER_TOKEN = 4;
|
|
14
|
+
/** Fraction of a budget held back for the briefing's own scaffolding (design §10). */
|
|
15
|
+
export const BUDGET_RESERVE_RATIO = 0.1;
|
|
16
|
+
/**
|
|
17
|
+
* `ceil(chars / 4)`, using UTF-16 code-unit length — the same `String.prototype.length` every other
|
|
18
|
+
* length check in both foundations uses, so a memory that fits AkashicForge's MAX_MEMORY_CHARS and
|
|
19
|
+
* a claim that fits a budget are measured on one ruler.
|
|
20
|
+
*
|
|
21
|
+
* The empty string costs 0 tokens rather than 1: a section that rendered nothing must not consume
|
|
22
|
+
* budget, or an empty briefing would price itself above zero.
|
|
23
|
+
*/
|
|
24
|
+
export function estimateTokens(text) {
|
|
25
|
+
if (text.length === 0)
|
|
26
|
+
return 0;
|
|
27
|
+
return Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
28
|
+
}
|
|
29
|
+
/** Sum of the parts, computed per part. Summing lengths first would round only once and under-count. */
|
|
30
|
+
export function estimateTokensOfAll(texts) {
|
|
31
|
+
let total = 0;
|
|
32
|
+
for (const text of texts)
|
|
33
|
+
total += estimateTokens(text);
|
|
34
|
+
return total;
|
|
35
|
+
}
|
|
36
|
+
export function createBudget(total, reserveRatio = BUDGET_RESERVE_RATIO) {
|
|
37
|
+
if (!Number.isInteger(total) || total < 0)
|
|
38
|
+
throw new Error("budget total must be a non-negative integer");
|
|
39
|
+
if (!(reserveRatio >= 0 && reserveRatio < 1))
|
|
40
|
+
throw new Error("reserveRatio must be in [0, 1)");
|
|
41
|
+
return { total, reserve: Math.ceil(reserveRatio * total), used: 0 };
|
|
42
|
+
}
|
|
43
|
+
/** What may still be spent by the MMR pool: the ceiling minus the reserve minus what is gone. */
|
|
44
|
+
export function selectableRemaining(budget) {
|
|
45
|
+
return Math.max(0, budget.total - budget.reserve - budget.used);
|
|
46
|
+
}
|
|
47
|
+
/** What may still be spent by a mandatory item, which is allowed to eat into the reserve. */
|
|
48
|
+
export function hardRemaining(budget) {
|
|
49
|
+
return Math.max(0, budget.total - budget.used);
|
|
50
|
+
}
|
|
51
|
+
/** Does `tokens` fit the selectable pool? Mandatory placement asks `fitsHard` instead. */
|
|
52
|
+
export function fits(budget, tokens) {
|
|
53
|
+
return tokens <= selectableRemaining(budget);
|
|
54
|
+
}
|
|
55
|
+
export function fitsHard(budget, tokens) {
|
|
56
|
+
return tokens <= hardRemaining(budget);
|
|
57
|
+
}
|
|
58
|
+
/** Spending past `total` is a programming error, not a value to clamp: the caller must test first. */
|
|
59
|
+
export function spend(budget, tokens) {
|
|
60
|
+
if (!Number.isInteger(tokens) || tokens < 0)
|
|
61
|
+
throw new Error("tokens must be a non-negative integer");
|
|
62
|
+
const used = budget.used + tokens;
|
|
63
|
+
if (used > budget.total)
|
|
64
|
+
throw new Error(`budget overflow: ${used} tokens used of ${budget.total}`);
|
|
65
|
+
return { total: budget.total, reserve: budget.reserve, used };
|
|
66
|
+
}
|