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,164 @@
|
|
|
1
|
+
// Ported from mnemosia/similarity.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
/**
|
|
3
|
+
* Shingle similarity, token similarity and blocked pair enumeration (design §10, §11; Phase 2).
|
|
4
|
+
*
|
|
5
|
+
* `shingles` and `jaccard` lived in `select.ts` through Phase 1 because selection was their only
|
|
6
|
+
* consumer. Phase 2's conflict taxonomy needs a neighbourhood test — design §11 defines
|
|
7
|
+
* `PLAN_VERSUS_FACT`, `PREFERENCE_CHANGE`, `BRANCH_DIFFERENCE` and the deterministic
|
|
8
|
+
* `DIRECT_CONTRADICTION` subset over "near-duplicate" pairs — and `select.ts` already imports
|
|
9
|
+
* `conflicts.ts`, so conflicts cannot import back from select without a cycle. They move here, once,
|
|
10
|
+
* and `select.ts` re-exports them so nothing that already imported them has to change.
|
|
11
|
+
*
|
|
12
|
+
* ## CORRECTED IN PHASE 2 — jaccard₃ alone cannot express design §11's own canonical example.
|
|
13
|
+
*
|
|
14
|
+
* Design §11 writes the neighbourhood as `jaccard₃ ≥ 0.6` (stated for `PLAN_VERSUS_FACT`, and the
|
|
15
|
+
* obvious reading for the "near-dup" and "neighborhood match" wording of the other three). Applied
|
|
16
|
+
* to the deterministic `DIRECT_CONTRADICTION` detector the design specifies in the same table —
|
|
17
|
+
* "exactly one side carries a negation marker" — that threshold is unsatisfiable, and the reason is
|
|
18
|
+
* arithmetic rather than empirical:
|
|
19
|
+
*
|
|
20
|
+
* A one-token edit destroys **three** 3-grams on each side. For a claim of `n` tokens, negating it
|
|
21
|
+
* leaves `jaccard₃ ≈ (n−5)/(n+1)`, which reaches 0.6 only at `n ≥ 14`. Measured on the exact pair
|
|
22
|
+
* the design describes:
|
|
23
|
+
*
|
|
24
|
+
* ```
|
|
25
|
+
* "The compaction hook writes a summary into the ledger on every turn." J₃ 0.467 J₁ 0.714
|
|
26
|
+
* "The compaction hook does not write a summary into the ledger on every turn."
|
|
27
|
+
* "…retries: 3 for the pipeline." / "…retries: 5 for the pipeline." J₃ 0.571 J₁ 0.846
|
|
28
|
+
* "…runs on main…" / "…runs on the release branch…" J₃ 0.385 J₁ 0.750
|
|
29
|
+
* "Deploy from main after the smoke test passes." J₃ 0.000 J₁ 0.364
|
|
30
|
+
* / "Deploy from the release branch, never from main." ← genuinely different statements
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* So a `jaccard₃ ≥ 0.6` neighbourhood makes the negation detector, the `key: value` detector and the
|
|
34
|
+
* branch detector unreachable by construction, while the pairs that *should* be excluded sit far
|
|
35
|
+
* below on both metrics. The two measures are answering different questions: 3-grams measure
|
|
36
|
+
* **phrasing** overlap, which is what redundancy (design §10's MMR penalty) is about, and unigrams
|
|
37
|
+
* measure **subject** overlap, which is what "same core" in design §11 is about.
|
|
38
|
+
*
|
|
39
|
+
* The correction adds the second leg and **introduces no new constant**: the neighbourhood is
|
|
40
|
+
* `jaccard₃ ≥ 0.6 OR jaccard₁ ≥ 0.6`, reusing the number design §11 already fixed. The token leg is
|
|
41
|
+
* not tuned to the examples above — it is set to the design's own threshold, which happens to sit in
|
|
42
|
+
* the wide gap those numbers show (true near-duplicates 0.71–0.85, different statements ≤ 0.36).
|
|
43
|
+
* Design §10's redundancy penalty is untouched and still uses 3-grams alone, because phrasing
|
|
44
|
+
* overlap is the right question there.
|
|
45
|
+
*
|
|
46
|
+
* **The pair enumeration is blocked, not quadratic.** A detector that compares every claim to every
|
|
47
|
+
* other is O(n²) on a set that `deep` mode caps at 1,500. `candidatePairs` builds an inverted index
|
|
48
|
+
* from feature to claim and only proposes pairs that share at least one feature. That is exact, not
|
|
49
|
+
* approximate: a positive Jaccard on either metric *means* a non-empty intersection, so every pair
|
|
50
|
+
* either threshold would accept shares a feature and is proposed.
|
|
51
|
+
*/
|
|
52
|
+
/**
|
|
53
|
+
* The n-token shingle set of a text, over an already-normalized string.
|
|
54
|
+
*
|
|
55
|
+
* Callers pass `normalizeClaimText(text)` output — normalizing here would make this module import
|
|
56
|
+
* `claims.ts` for one function and would hide from the caller that two differently-punctuated
|
|
57
|
+
* renderings of one sentence are meant to shingle identically.
|
|
58
|
+
*
|
|
59
|
+
* A text shorter than the window yields one shingle of its whole token list rather than none, so a
|
|
60
|
+
* two-word claim is still comparable instead of being scored as maximally novel against everything.
|
|
61
|
+
*/
|
|
62
|
+
export function shingleSet(normalized, size) {
|
|
63
|
+
const tokens = normalized.split(" ").filter((token) => token.length > 0);
|
|
64
|
+
const result = new Set();
|
|
65
|
+
if (tokens.length === 0)
|
|
66
|
+
return result;
|
|
67
|
+
if (tokens.length < size) {
|
|
68
|
+
result.add(tokens.join(" "));
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
for (let index = 0; index + size <= tokens.length; index += 1)
|
|
72
|
+
result.add(tokens.slice(index, index + size).join(" "));
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
export function tokenSet(normalized) {
|
|
76
|
+
return new Set(normalized.split(" ").filter((token) => token.length > 0));
|
|
77
|
+
}
|
|
78
|
+
export function profileOf(normalized, shingleSize) {
|
|
79
|
+
return { shingles: shingleSet(normalized, shingleSize), tokens: tokenSet(normalized) };
|
|
80
|
+
}
|
|
81
|
+
export function jaccard(a, b) {
|
|
82
|
+
if (a.size === 0 || b.size === 0)
|
|
83
|
+
return 0;
|
|
84
|
+
let intersection = 0;
|
|
85
|
+
const [small, large] = a.size <= b.size ? [a, b] : [b, a];
|
|
86
|
+
for (const entry of small) {
|
|
87
|
+
if (large.has(entry))
|
|
88
|
+
intersection += 1;
|
|
89
|
+
}
|
|
90
|
+
const union = a.size + b.size - intersection;
|
|
91
|
+
return union === 0 ? 0 : intersection / union;
|
|
92
|
+
}
|
|
93
|
+
/** Design §11's threshold. One number, applied to both legs of the neighbourhood test. */
|
|
94
|
+
export const NEIGHBOURHOOD_THRESHOLD = 0.6;
|
|
95
|
+
export function neighbourhoodScore(a, b, threshold = NEIGHBOURHOOD_THRESHOLD) {
|
|
96
|
+
const shingle = jaccard(a.shingles, b.shingles);
|
|
97
|
+
const token = jaccard(a.tokens, b.tokens);
|
|
98
|
+
return { shingle, token, inNeighbourhood: shingle >= threshold || token >= threshold };
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Every pair of entries inside the neighbourhood, in a total order.
|
|
102
|
+
*
|
|
103
|
+
* `keyOf` supplies the stable identity used for ordering, so the returned pairs are always
|
|
104
|
+
* `(lower key, higher key)` and the list is sorted `(similarity desc, a key asc, b key asc)`. The
|
|
105
|
+
* §16 determinism gate reads conflict records byte for byte, and a pair order that depended on the
|
|
106
|
+
* iteration order of a `Map` would fail it on a corpus where two pairs tie.
|
|
107
|
+
*
|
|
108
|
+
* A feature that occurs on more than `maxPostings` entries is skipped as a blocking key. That is not
|
|
109
|
+
* a correctness compromise for the pairs it drops — every pair it drops is proposed by any *other*
|
|
110
|
+
* feature the two share, and two texts inside the neighbourhood share a great many — it is a bound
|
|
111
|
+
* on the pathological case where one boilerplate token appears on 400 claims and would alone propose
|
|
112
|
+
* 80,000 pairs.
|
|
113
|
+
*/
|
|
114
|
+
export function candidatePairs(entries, profile, keyOf, threshold = NEIGHBOURHOOD_THRESHOLD, maxPostings = 64) {
|
|
115
|
+
const postings = new Map();
|
|
116
|
+
entries.forEach((entry, index) => {
|
|
117
|
+
const own = profile(entry);
|
|
118
|
+
for (const feature of own.shingles)
|
|
119
|
+
push(postings, `3${feature}`, index);
|
|
120
|
+
for (const feature of own.tokens)
|
|
121
|
+
push(postings, `1${feature}`, index);
|
|
122
|
+
});
|
|
123
|
+
const seen = new Set();
|
|
124
|
+
const pairs = [];
|
|
125
|
+
for (const bucket of postings.values()) {
|
|
126
|
+
if (bucket.length < 2 || bucket.length > maxPostings)
|
|
127
|
+
continue;
|
|
128
|
+
for (let i = 0; i < bucket.length; i += 1) {
|
|
129
|
+
for (let j = i + 1; j < bucket.length; j += 1) {
|
|
130
|
+
const left = bucket[i];
|
|
131
|
+
const right = bucket[j];
|
|
132
|
+
if (left === undefined || right === undefined)
|
|
133
|
+
continue;
|
|
134
|
+
const key = `${left}:${right}`;
|
|
135
|
+
if (seen.has(key))
|
|
136
|
+
continue;
|
|
137
|
+
seen.add(key);
|
|
138
|
+
const a = entries[left];
|
|
139
|
+
const b = entries[right];
|
|
140
|
+
if (a === undefined || b === undefined)
|
|
141
|
+
continue;
|
|
142
|
+
const score = neighbourhoodScore(profile(a), profile(b), threshold);
|
|
143
|
+
if (!score.inNeighbourhood)
|
|
144
|
+
continue;
|
|
145
|
+
const similarity = Math.max(score.shingle, score.token);
|
|
146
|
+
pairs.push(keyOf(a) <= keyOf(b)
|
|
147
|
+
? { a, b, similarity, shingleSimilarity: score.shingle, tokenSimilarity: score.token }
|
|
148
|
+
: { a: b, b: a, similarity, shingleSimilarity: score.shingle, tokenSimilarity: score.token });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
pairs.sort((x, y) => y.similarity - x.similarity || compareKeys(keyOf(x.a), keyOf(y.a)) || compareKeys(keyOf(x.b), keyOf(y.b)));
|
|
153
|
+
return pairs;
|
|
154
|
+
}
|
|
155
|
+
function push(index, key, value) {
|
|
156
|
+
const bucket = index.get(key);
|
|
157
|
+
if (bucket === undefined)
|
|
158
|
+
index.set(key, [value]);
|
|
159
|
+
else
|
|
160
|
+
bucket.push(value);
|
|
161
|
+
}
|
|
162
|
+
function compareKeys(a, b) {
|
|
163
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
164
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// Ported from mnemosia/situation.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
/**
|
|
3
|
+
* Phase B stage 1 — situation-aware analysis (spec "Stage 2: Situation-Aware Retrieval").
|
|
4
|
+
*
|
|
5
|
+
* The task text is the *objective*, not the *situation*. "Continue implementing Phase 5" names an
|
|
6
|
+
* objective; the situation it lives in — which project, which branch, what the phase definition
|
|
7
|
+
* says, how the previous phase ended — is inferred, and every inference can be wrong in a way that
|
|
8
|
+
* changes what gets retrieved. So this module does one thing: it separates what the task *states*
|
|
9
|
+
* from what it *implies*, from what it merely *suggests*, from what is genuinely *unknown*, and from
|
|
10
|
+
* what should go back to the caller as a clarification — and for everything beyond `explicit` it
|
|
11
|
+
* records the four fields spec requires: confidence, supporting signals, the retrieval consequence of
|
|
12
|
+
* believing it, and the fallback if it is wrong.
|
|
13
|
+
*
|
|
14
|
+
* Classification is **deterministic**: a fixed rule table over the task text and the caller-supplied
|
|
15
|
+
* project context. Model-assisted enrichment is a future seam (`SituationEnricher`, interface only —
|
|
16
|
+
* no LLM call exists anywhere in this file), and when it arrives its output passes through the same
|
|
17
|
+
* validator and the same bounds, treated as proposals rather than decisions (spec §21).
|
|
18
|
+
*
|
|
19
|
+
* The guardrail at the bottom of the spec section is structural here: this module *never rewrites*
|
|
20
|
+
* the task. It only produces candidate context with named consequences; whether retrieval acts on a
|
|
21
|
+
* consequence is decided downstream, where the token budget lives.
|
|
22
|
+
*/
|
|
23
|
+
import { SCHEMA_VERSION } from "./types.js";
|
|
24
|
+
import { extractEntities } from "./task.js";
|
|
25
|
+
/* ------------------------------------------------------------------------------------------------
|
|
26
|
+
* Taxonomy
|
|
27
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
28
|
+
/** Spec's five-way distinction, in descending order of belief. */
|
|
29
|
+
export const CONTEXT_TIERS = ["explicit", "implied", "inferred", "unknown", "needs_clarification"];
|
|
30
|
+
/** Hard bound on items per analysis; the tail beyond this is noise by construction. */
|
|
31
|
+
export const MAX_SITUATION_ITEMS = 24;
|
|
32
|
+
/** Tier anchor points. A rule may refine within ±0.1 but never cross a neighbouring tier's band. */
|
|
33
|
+
export const CONFIDENCE_BY_TIER = {
|
|
34
|
+
explicit: 1,
|
|
35
|
+
implied: 0.8,
|
|
36
|
+
inferred: 0.45,
|
|
37
|
+
unknown: 0.1,
|
|
38
|
+
needs_clarification: 0.25,
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Deterministic rules over lowercased task text. Order matters only for stability of output order —
|
|
42
|
+
* ids are unique and every match emits exactly one item, so no precedence logic exists to get wrong.
|
|
43
|
+
*/
|
|
44
|
+
const SITUATION_RULES = [
|
|
45
|
+
{
|
|
46
|
+
id: "resume-open-work",
|
|
47
|
+
inference: "there is unfinished work in the current project whose state must be recovered before continuing",
|
|
48
|
+
tier: "implied",
|
|
49
|
+
pattern: /\b(continue|resume|pick ?up|carry ?on|finish|complete|unfinished)\b/iu,
|
|
50
|
+
signal: "continuation verb",
|
|
51
|
+
retrievalConsequence: "read project-scoped memories for open TODOs and last observed state",
|
|
52
|
+
fallbackIfWrong: "treat the task as fresh work; the cost is some redundant retrieval, not a wrong edit",
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: "active-milestone-definition",
|
|
56
|
+
inference: "the task names a milestone or phase whose definition governs what the work includes",
|
|
57
|
+
tier: "implied",
|
|
58
|
+
pattern: /\b(phase|milestone|stage)\b/iu,
|
|
59
|
+
signal: "milestone noun",
|
|
60
|
+
retrievalConsequence: "retrieve the milestone/phase definition and its acceptance criteria before planning",
|
|
61
|
+
fallbackIfWrong: "fall back to the objective's literal wording as the scope boundary",
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
id: "previous-phase-outcome",
|
|
65
|
+
inference: "a prior milestone or phase reached an outcome that conditions this one",
|
|
66
|
+
tier: "implied",
|
|
67
|
+
pattern: /\b(phase|milestone|stage)\b/iu,
|
|
68
|
+
signal: "milestone noun with continuation framing",
|
|
69
|
+
retrievalConsequence: "check curated memory for the previous milestone's recorded outcome or release decision",
|
|
70
|
+
fallbackIfWrong: "proceed without predecessor context; scope checks lose one corroborating signal",
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
id: "known-failures",
|
|
74
|
+
inference: "known failures or recorded blockers about this subject exist in memory",
|
|
75
|
+
tier: "inferred",
|
|
76
|
+
pattern: /\b(fix|repair|correct|bug|broken|failing|failure|crash|error)\b/iu,
|
|
77
|
+
signal: "defect vocabulary",
|
|
78
|
+
retrievalConsequence: "query curated memory for known failures before diagnosing from scratch",
|
|
79
|
+
fallbackIfWrong: "an empty result costs one query; diagnosis proceeds normally",
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
id: "coding-conventions",
|
|
83
|
+
inference: "the work should follow conventions already recorded for this codebase",
|
|
84
|
+
tier: "inferred",
|
|
85
|
+
pattern: /\b(implement|build|write|create|add|extend|refactor)\b/iu,
|
|
86
|
+
signal: "authoring verb",
|
|
87
|
+
retrievalConsequence: "include convention/preference memories in the candidate pool",
|
|
88
|
+
fallbackIfWrong: "conventions are advisory; their absence degrades style consistency, not correctness",
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: "recency-sensitivity",
|
|
92
|
+
inference: "the answer depends on current state rather than historical narrative",
|
|
93
|
+
tier: "inferred",
|
|
94
|
+
pattern: /\b(latest|current|now|today|recent|still)\b/iu,
|
|
95
|
+
signal: "present-tense marker",
|
|
96
|
+
retrievalConsequence: "prefer freshness-weighted sources and tighten the temporal window",
|
|
97
|
+
fallbackIfWrong: "older evidence is still usable; ranking demotes rather than drops it",
|
|
98
|
+
},
|
|
99
|
+
];
|
|
100
|
+
/* ------------------------------------------------------------------------------------------------
|
|
101
|
+
* Analysis
|
|
102
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
103
|
+
function entityItems(entities) {
|
|
104
|
+
return entities.slice(0, 6).map((entity) => ({
|
|
105
|
+
id: `explicit-entity-${entity.kind}-${entity.text.toLowerCase().replace(/[^a-z0-9_-]+/gu, "-").slice(0, 40)}`,
|
|
106
|
+
inference: `the task explicitly names the ${entity.kind} "${entity.text}"`,
|
|
107
|
+
tier: "explicit",
|
|
108
|
+
confidence: CONFIDENCE_BY_TIER.explicit,
|
|
109
|
+
supportingSignals: [`literal ${entity.kind} in task text`],
|
|
110
|
+
retrievalConsequence: "the entity's own tokens join the query vocabulary",
|
|
111
|
+
fallbackIfWrong: "an entity that retrieves nothing simply contributes zero results",
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
114
|
+
function vagueReferentItem(task, entities) {
|
|
115
|
+
const hasSubjectEntity = entities.some((entity) => entity.kind !== "identifier");
|
|
116
|
+
if (!/\b(it|that|this|them|those|the issue|the problem)\b/iu.test(task) || hasSubjectEntity)
|
|
117
|
+
return null;
|
|
118
|
+
return {
|
|
119
|
+
id: "vague-referent",
|
|
120
|
+
inference: "the task's subject may be under-specified (a pronoun stands where a named subject would)",
|
|
121
|
+
tier: "needs_clarification",
|
|
122
|
+
confidence: CONFIDENCE_BY_TIER.needs_clarification,
|
|
123
|
+
supportingSignals: ["unresolved pronoun or bare referent"],
|
|
124
|
+
retrievalConsequence: "retrieval would guess the subject; the intent layer decides whether to clarify instead",
|
|
125
|
+
fallbackIfWrong: "if the referent is clear from session context, retrieval on the surrounding terms still applies",
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Analyses the operational situation behind a task. Pure and deterministic: same inputs, same
|
|
130
|
+
* output, byte for byte (spec §16's determinism gate applies here like everywhere else).
|
|
131
|
+
*/
|
|
132
|
+
export function analyseSituation(task, requestingAgent, projectContext) {
|
|
133
|
+
const trimmed = task.trim();
|
|
134
|
+
const entities = extractEntities(trimmed).value;
|
|
135
|
+
const items = [];
|
|
136
|
+
if (projectContext?.project != null && projectContext.project !== "") {
|
|
137
|
+
items.push({
|
|
138
|
+
id: "explicit-project",
|
|
139
|
+
inference: `the task runs in the project ${projectContext.project}`,
|
|
140
|
+
tier: "explicit",
|
|
141
|
+
confidence: CONFIDENCE_BY_TIER.explicit,
|
|
142
|
+
supportingSignals: ["caller-supplied project context"],
|
|
143
|
+
retrievalConsequence: "scope retrieval to this project (plus global)",
|
|
144
|
+
fallbackIfWrong: "the caller asked for this project; mis-scoping would be a caller error, not an inference",
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
if (projectContext?.requestedProjects && projectContext.requestedProjects.length > 0) {
|
|
148
|
+
items.push({
|
|
149
|
+
id: "explicit-requested-projects",
|
|
150
|
+
inference: `the caller explicitly asked to read ${projectContext.requestedProjects.length} additional project(s)`,
|
|
151
|
+
tier: "explicit",
|
|
152
|
+
confidence: CONFIDENCE_BY_TIER.explicit,
|
|
153
|
+
supportingSignals: ["requestedProjects supplied by caller"],
|
|
154
|
+
retrievalConsequence: "those projects become authorized scopes",
|
|
155
|
+
fallbackIfWrong: "not an inference; nothing to fall back from",
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (projectContext?.project != null && projectContext.project !== "") {
|
|
159
|
+
items.push({
|
|
160
|
+
id: "current-repository-state",
|
|
161
|
+
inference: `there is a working repository${projectContext.branch ? ` on branch ${projectContext.branch}` : ""} whose current state matters`,
|
|
162
|
+
tier: "implied",
|
|
163
|
+
confidence: CONFIDENCE_BY_TIER.implied - 0.05,
|
|
164
|
+
supportingSignals: ["a live project implies a repository and worktree"],
|
|
165
|
+
retrievalConsequence: "recent project memories enter the candidate pool",
|
|
166
|
+
fallbackIfWrong: "global-only retrieval; project filter dropped",
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
for (const rule of SITUATION_RULES) {
|
|
170
|
+
if (!rule.pattern.test(trimmed))
|
|
171
|
+
continue;
|
|
172
|
+
items.push({
|
|
173
|
+
id: rule.id,
|
|
174
|
+
inference: rule.inference,
|
|
175
|
+
tier: rule.tier,
|
|
176
|
+
confidence: CONFIDENCE_BY_TIER[rule.tier],
|
|
177
|
+
supportingSignals: [rule.signal],
|
|
178
|
+
retrievalConsequence: rule.retrievalConsequence,
|
|
179
|
+
fallbackIfWrong: rule.fallbackIfWrong,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
// Cross-rule strengthening: "continue implementing Phase 5" makes the predecessor-outcome
|
|
183
|
+
// inference stronger than the milestone noun alone would. One bump, capped inside the tier band.
|
|
184
|
+
if (/resume-open-work/u.test(items.map((item) => item.id).join(",")) && items.some((item) => item.id === "previous-phase-outcome")) {
|
|
185
|
+
const outcome = items.find((item) => item.id === "previous-phase-outcome");
|
|
186
|
+
if (outcome) {
|
|
187
|
+
outcome.confidence = Math.min(CONFIDENCE_BY_TIER.implied + 0.1, outcome.confidence + 0.1);
|
|
188
|
+
outcome.supportingSignals = [...outcome.supportingSignals, "continuation verb present"];
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const vague = vagueReferentItem(trimmed, entities);
|
|
192
|
+
if (vague)
|
|
193
|
+
items.push(vague);
|
|
194
|
+
items.push(...entityItems(entities));
|
|
195
|
+
// Unknowns are recorded honestly rather than omitted: they name what this analysis could not
|
|
196
|
+
// establish, so a reader of the trace sees the holes and not just the hits.
|
|
197
|
+
for (const unknown of [
|
|
198
|
+
{ id: "prior-discussions", inference: "whether prior conversations already cover this subject is unknown", consequence: "would justify a broad recall query only if stronger signals fail", fallback: "proceed without them" },
|
|
199
|
+
{ id: "outstanding-validation", inference: "what validation remains outstanding for this work is unknown", consequence: "none until a source establishes it", fallback: "the caller's own validation loop governs" },
|
|
200
|
+
]) {
|
|
201
|
+
items.push({ id: unknown.id, inference: unknown.inference, tier: "unknown", confidence: CONFIDENCE_BY_TIER.unknown, supportingSignals: [], retrievalConsequence: unknown.consequence, fallbackIfWrong: unknown.fallback });
|
|
202
|
+
}
|
|
203
|
+
return validateSituationContext({
|
|
204
|
+
schemaVersion: SCHEMA_VERSION.situationContext,
|
|
205
|
+
task: trimmed,
|
|
206
|
+
requestingAgent,
|
|
207
|
+
project: projectContext?.project ?? null,
|
|
208
|
+
items,
|
|
209
|
+
counts: { explicit: 0, implied: 0, inferred: 0, unknown: 0, needs_clarification: 0 },
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/* ------------------------------------------------------------------------------------------------
|
|
213
|
+
* Validation (deterministic policy over any item set, including future model-assisted proposals)
|
|
214
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
215
|
+
const ID_PATTERN = /^[a-z0-9][a-z0-9:_-]{0,79}$/u;
|
|
216
|
+
/**
|
|
217
|
+
* Schema-validates and bounds a situation context. Invalid items are *dropped* (with the count
|
|
218
|
+
* recomputed) rather than thrown: a bad proposal must degrade the analysis, never crash the run.
|
|
219
|
+
*/
|
|
220
|
+
export function validateSituationContext(value) {
|
|
221
|
+
const seen = new Set();
|
|
222
|
+
const items = [];
|
|
223
|
+
for (const item of value.items) {
|
|
224
|
+
if (items.length >= MAX_SITUATION_ITEMS)
|
|
225
|
+
break;
|
|
226
|
+
if (!CONTEXT_TIERS.includes(item.tier))
|
|
227
|
+
continue;
|
|
228
|
+
if (typeof item.confidence !== "number" || !Number.isFinite(item.confidence))
|
|
229
|
+
continue;
|
|
230
|
+
if (typeof item.inference !== "string" || item.inference.length === 0)
|
|
231
|
+
continue;
|
|
232
|
+
if (typeof item.id !== "string" || !ID_PATTERN.test(item.id) || seen.has(item.id))
|
|
233
|
+
continue;
|
|
234
|
+
if (!Array.isArray(item.supportingSignals))
|
|
235
|
+
continue;
|
|
236
|
+
if (typeof item.retrievalConsequence !== "string" || typeof item.fallbackIfWrong !== "string")
|
|
237
|
+
continue;
|
|
238
|
+
seen.add(item.id);
|
|
239
|
+
items.push({
|
|
240
|
+
...item,
|
|
241
|
+
confidence: Math.min(1, Math.max(0, item.confidence)),
|
|
242
|
+
supportingSignals: item.supportingSignals.filter((signal) => typeof signal === "string").slice(0, 8),
|
|
243
|
+
retrievalConsequence: String(item.retrievalConsequence ?? ""),
|
|
244
|
+
fallbackIfWrong: String(item.fallbackIfWrong ?? ""),
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
const counts = { explicit: 0, implied: 0, inferred: 0, unknown: 0, needs_clarification: 0 };
|
|
248
|
+
for (const item of items)
|
|
249
|
+
counts[item.tier] += 1;
|
|
250
|
+
return { ...value, items, counts };
|
|
251
|
+
}
|