@sonettogu14/dsh-te-facts 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @sonettogu14/dsh-te-facts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Learns per-repository shell repairs from what actually happened — this command
4
+ form failed here and that one worked, or this command needs that environment
5
+ variable — and injects at most one short reminder, only while the wasted
6
+ attempts are still recurring.
7
+
8
+ ```sh
9
+ dsh plugin --profile <profile> add @sonettogu14/dsh-te-facts
10
+ ```
11
+
12
+ - A repair is promoted only after three separate sessions confirm it, and
13
+ injected only while it is still paying for itself.
14
+ - Budget is fixed: one message, at most 4 facts, at most 600 characters, and
15
+ nothing at all when no fact qualifies.
16
+ - Stores command forms and variable *names*; never output text or file contents.
17
+ - `/te-facts` lists what it knows, with state, score and firing rate.
18
+
19
+ Part of [dsh-tokeneconomizer](https://github.com/SonettoGu14/dsh-tokeneconomizer) — install
20
+ `@sonettogu14/dsh-te` for all three components. Thresholds and configuration are
21
+ documented there.
22
+ Licensed Apache-2.0.
@@ -0,0 +1,5 @@
1
+ # te-facts: inserts this component into a DSH profile roster.
2
+ # Install: dsh plugin --profile <name> add link:<repo>/packages/facts
3
+ - insert:
4
+ - id: te-facts
5
+ name: '@sonettogu14/dsh-te-facts'
package/lib/index.d.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Repository facts, learned mechanically and spent sparingly.
3
+ *
4
+ * The component watches shell calls in a session, and when a session dies it
5
+ * turns "this form failed here, that form worked" into a fact. Facts are scoped
6
+ * to one repository (git origin remote, else the working directory) and are
7
+ * only injected once they have been confirmed by three separate sessions *and*
8
+ * the waste they warn about is still happening. That second gate is the point:
9
+ * a fact the model has already absorbed stops costing tokens.
10
+ *
11
+ * Injection rides the logged pre-step channel: one extra user-role message at
12
+ * the first step of a session, and nothing at all when no fact qualifies.
13
+ *
14
+ * @module @sonettogu14/dsh-te-facts
15
+ */
16
+ import { Service, type Context } from '@deepseek-ai/cordis';
17
+ import z from '@deepseek-ai/schemastery';
18
+ import type { Session } from '@deepseek-ai/dsh-session';
19
+ declare module '@deepseek-ai/dsh-llm' {
20
+ interface MessageSourceMap {
21
+ 'dsh-te-facts': {
22
+ kind: 'dsh-te-facts';
23
+ form: 'notice';
24
+ };
25
+ }
26
+ }
27
+ /** Settings for the facts component. */
28
+ export interface Config {
29
+ /** Watch and inject. Off means the component does nothing at all. */
30
+ enabled: boolean;
31
+ /** Never inject more than this many facts at once (TokenEconomizer used 4). */
32
+ maxFacts: number;
33
+ /** Hard cap on the injected text; ~150 tokens at 4 chars/token. */
34
+ maxChars: number;
35
+ }
36
+ export declare const name = "dsh-te-facts";
37
+ export declare const Config: z<Config>;
38
+ /**
39
+ * Per-repository fact store and per-session watcher.
40
+ * Exposed on the context as `teFacts`.
41
+ */
42
+ export declare class Facts extends Service {
43
+ private readonly config;
44
+ static inject: string[];
45
+ private readonly watching;
46
+ /** Settles in flight, awaited by the `session/flush` durability checkpoint. */
47
+ private readonly pending;
48
+ private readonly repos;
49
+ constructor(ctx: Context, config: Config);
50
+ protected [Service.init](): Promise<void>;
51
+ /** Record one shell call. */
52
+ private observe;
53
+ /** The watcher for one session. */
54
+ private watchOf;
55
+ /** Load (and cache) the facts of the session's repository. */
56
+ private repoOf;
57
+ /** Facts worth injecting now, best first. */
58
+ private worthInjecting;
59
+ /** The user-role message to admit, or undefined to leave the step alone. */
60
+ private injectedMessage;
61
+ /** Count the injected text as this component's own overhead, when a ledger is present. */
62
+ private bill;
63
+ /**
64
+ * Fold a finished session into the repository's facts.
65
+ * @param session - the session that just ended.
66
+ */
67
+ settle(session: Session): Promise<void>;
68
+ /** Replace one fact in place. */
69
+ private replace;
70
+ /** Human-readable listing for `/te-facts`. */
71
+ report(session: Session): string;
72
+ /** Whether any session is currently being watched (used by tests). */
73
+ get watchingCount(): number;
74
+ }
75
+ declare module '@deepseek-ai/cordis' {
76
+ interface Context {
77
+ teFacts: Facts;
78
+ }
79
+ }
80
+ /** Mount the component. */
81
+ export declare function apply(ctx: Context, config: Config): void;
82
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAC3D,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAIxC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAA;AAEvD,OAAO,QAAQ,sBAAsB,CAAC;IACpC,UAAU,gBAAgB;QACxB,cAAc,EAAE;YAAE,IAAI,EAAE,cAAc,CAAC;YAAC,IAAI,EAAE,QAAQ,CAAA;SAAE,CAAA;KACzD;CACF;AAuBD,wCAAwC;AACxC,MAAM,WAAW,MAAM;IACrB,qEAAqE;IACrE,OAAO,EAAE,OAAO,CAAA;IAChB,+EAA+E;IAC/E,QAAQ,EAAE,MAAM,CAAA;IAChB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,eAAO,MAAM,IAAI,iBAAiB,CAAA;AAElC,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAI3B,CAAA;AA+FF;;;GAGG;AACH,qBAAa,KAAM,SAAQ,OAAO;IAUN,OAAO,CAAC,QAAQ,CAAC,MAAM;IATjD,MAAM,CAAC,MAAM,WAAe;IAE5B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAkC;IAE3D,+EAA+E;IAC/E,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAmC;IAE3D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA+B;gBAEzC,GAAG,EAAE,OAAO,EAAmB,MAAM,EAAE,MAAM;cAIzC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;IA+C/C,6BAA6B;IAC7B,OAAO,CAAC,OAAO;IASf,mCAAmC;IACnC,OAAO,CAAC,OAAO;IAQf,8DAA8D;YAChD,MAAM;IAapB,6CAA6C;IAC7C,OAAO,CAAC,cAAc;IAQtB,4EAA4E;YAC9D,eAAe;IAkB7B,0FAA0F;IAC1F,OAAO,CAAC,IAAI;IAKZ;;;OAGG;IACG,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IA6D7C,iCAAiC;IACjC,OAAO,CAAC,OAAO;IAKf,8CAA8C;IAC9C,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM;IAgBhC,sEAAsE;IACtE,IAAI,aAAa,IAAI,MAAM,CAE1B;CACF;AAED,OAAO,QAAQ,qBAAqB,CAAC;IACnC,UAAU,OAAO;QACf,OAAO,EAAE,KAAK,CAAA;KACf;CACF;AAED,2BAA2B;AAC3B,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAGxD"}
package/lib/index.js ADDED
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Repository facts, learned mechanically and spent sparingly.
3
+ *
4
+ * The component watches shell calls in a session, and when a session dies it
5
+ * turns "this form failed here, that form worked" into a fact. Facts are scoped
6
+ * to one repository (git origin remote, else the working directory) and are
7
+ * only injected once they have been confirmed by three separate sessions *and*
8
+ * the waste they warn about is still happening. That second gate is the point:
9
+ * a fact the model has already absorbed stops costing tokens.
10
+ *
11
+ * Injection rides the logged pre-step channel: one extra user-role message at
12
+ * the first step of a session, and nothing at all when no fact qualifies.
13
+ *
14
+ * @module @sonettogu14/dsh-te-facts
15
+ */
16
+ import { Service } from '@deepseek-ai/cordis';
17
+ import z from '@deepseek-ai/schemastery';
18
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
19
+ import { NEW_LIFECYCLE, confirm, contradict, contradicted, exercised, extractFacts, injectable, readJson, recordExercise, repoKeyDirName, resolveRepoKey, score, stateRoot, wasteRecurred, writeJsonAtomic, } from '@sonettogu14/dsh-te-core';
20
+ import { join } from 'node:path';
21
+ export const name = 'dsh-te-facts';
22
+ export const Config = z.object({
23
+ enabled: z.boolean().default(true),
24
+ maxFacts: z.number().min(0).default(4),
25
+ maxChars: z.number().min(0).default(600),
26
+ });
27
+ /** How many facts one repository may keep; lowest-value facts go first. */
28
+ const FACT_CAP = 200;
29
+ /**
30
+ * Whether one stored entry still has the shape this version understands.
31
+ *
32
+ * A hand-edited, truncated or older file must degrade to "that entry is gone",
33
+ * not to a throw on the step-1 hot path.
34
+ */
35
+ function isStoredFact(value) {
36
+ if (value === null || typeof value !== 'object')
37
+ return false;
38
+ const fact = value;
39
+ return (typeof fact.key === 'string' &&
40
+ typeof fact.text === 'string' &&
41
+ (fact.family === 'form-repair' || fact.family === 'env-value') &&
42
+ (fact.state === 'candidate' || fact.state === 'active' || fact.state === 'retired') &&
43
+ Array.isArray(fact.confirms) &&
44
+ Array.isArray(fact.contradicts) &&
45
+ typeof fact.fired === 'number' &&
46
+ typeof fact.firedWaste === 'number');
47
+ }
48
+ /** Whether this session is a subagent child rather than a top-level task. */
49
+ function isSubagent(session) {
50
+ return session.header?.origin === 'subagent';
51
+ }
52
+ function textOf(result) {
53
+ return result.content
54
+ .map((block) => (block.type === 'text' ? block.text : ''))
55
+ .join('\n');
56
+ }
57
+ /** Trim output to what the extractors actually read. */
58
+ function relevant(output) {
59
+ return output.length <= 4_000 ? output : `${output.slice(0, 2_000)}\n${output.slice(-2_000)}`;
60
+ }
61
+ /** The shell command a tool call carried, when it carried one. */
62
+ function commandOf(exec) {
63
+ if (exec.name !== 'bash' && exec.name !== 'bash_persistent')
64
+ return undefined;
65
+ const args = exec.arguments;
66
+ if (typeof args !== 'object' || args === null)
67
+ return undefined;
68
+ const command = args.command;
69
+ return typeof command === 'string' ? command : undefined;
70
+ }
71
+ /** Where one repository's facts live. */
72
+ function repoFactsPath(key) {
73
+ return join(stateRoot(), 'repos', repoKeyDirName(key), 'facts.json');
74
+ }
75
+ /** Render the injected block for a set of facts. */
76
+ function render(facts, maxChars) {
77
+ if (facts.length === 0 || maxChars <= 0)
78
+ return undefined;
79
+ const header = 'Facts learned from earlier sessions in this repository (verify before relying):';
80
+ const lines = [header];
81
+ let used = header.length;
82
+ for (const fact of facts) {
83
+ const line = `- ${fact.text}`;
84
+ if (used + line.length + 1 > maxChars)
85
+ break;
86
+ lines.push(line);
87
+ used += line.length + 1;
88
+ }
89
+ return lines.length > 1 ? lines.join('\n') : undefined;
90
+ }
91
+ /**
92
+ * Per-repository fact store and per-session watcher.
93
+ * Exposed on the context as `teFacts`.
94
+ */
95
+ export class Facts extends Service {
96
+ config;
97
+ static inject = ['commands'];
98
+ watching = new Map();
99
+ /** Settles in flight, awaited by the `session/flush` durability checkpoint. */
100
+ pending = new Map();
101
+ repos = new Map();
102
+ constructor(ctx, config) {
103
+ super(ctx, 'teFacts');
104
+ this.config = config;
105
+ }
106
+ async [Service.init]() {
107
+ this.ctx.on('tools/result', (exec, result) => {
108
+ this.observe(exec, result);
109
+ });
110
+ this.ctx.on('agent/pre-step', async (payload, next) => {
111
+ const decision = await next();
112
+ if (decision.kind !== 'enter')
113
+ return decision;
114
+ if (isSubagent(payload.agent.session))
115
+ return decision;
116
+ let message;
117
+ try {
118
+ message = await this.injectedMessage(payload.agent, payload.turn, payload.step);
119
+ }
120
+ catch (error) {
121
+ // Injection is an optimization: a damaged state file must never stop a
122
+ // session from starting.
123
+ this.ctx.logger('dsh-te-facts').warn('facts not injected: %s', String(error));
124
+ return decision;
125
+ }
126
+ if (message === undefined)
127
+ return decision;
128
+ // Spread the decision: it may carry `startsRequestSeries`, and dropping it
129
+ // would move the prefix-cache boundary for every listener after us.
130
+ return { ...decision, messages: [...decision.messages, message] };
131
+ });
132
+ this.ctx.on('session/disposed', (session) => {
133
+ // Teardown does not await listeners, so the write is drained by the
134
+ // awaited `session/flush` checkpoint instead of racing the process exit.
135
+ this.pending.set(session.id, this.settle(session)
136
+ .catch((error) => {
137
+ // A learning pass must never take the session down with it.
138
+ this.ctx.logger('dsh-te-facts').warn('facts not settled: %s', String(error));
139
+ })
140
+ .finally(() => this.pending.delete(session.id)));
141
+ });
142
+ this.ctx.on('session/flush', async () => {
143
+ await Promise.all([...this.pending.values()]);
144
+ });
145
+ this.ctx.effect(() => this.ctx.commands.register({
146
+ name: 'te-facts',
147
+ description: 'List repository facts learned by dsh-te-facts',
148
+ handler: (invocation) => ({ kind: 'success', text: this.report(invocation.agent.session) }),
149
+ }));
150
+ }
151
+ /** Record one shell call. */
152
+ observe(exec, result) {
153
+ const session = exec.agent?.session;
154
+ const command = commandOf(exec);
155
+ if (session === undefined || command === undefined)
156
+ return;
157
+ const watch = this.watchOf(session);
158
+ if (watch.calls.length >= 200)
159
+ watch.calls.shift();
160
+ watch.calls.push({ command, ok: result.isError !== true, output: relevant(textOf(result)) });
161
+ }
162
+ /** The watcher for one session. */
163
+ watchOf(session) {
164
+ const existing = this.watching.get(session.id);
165
+ if (existing !== undefined)
166
+ return existing;
167
+ const created = { calls: [] };
168
+ this.watching.set(session.id, created);
169
+ return created;
170
+ }
171
+ /** Load (and cache) the facts of the session's repository. */
172
+ async repoOf(session) {
173
+ const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key;
174
+ const cached = this.repos.get(key);
175
+ if (cached !== undefined)
176
+ return cached;
177
+ const stored = await readJson(repoFactsPath(key));
178
+ const repo = stored !== undefined && stored.version === 1 && Array.isArray(stored.facts)
179
+ ? { ...stored, key, facts: stored.facts.filter(isStoredFact) }
180
+ : { version: 1, key, tasks: 0, facts: [] };
181
+ this.repos.set(key, repo);
182
+ return repo;
183
+ }
184
+ /** Facts worth injecting now, best first. */
185
+ worthInjecting(repo) {
186
+ const ordinal = repo.tasks;
187
+ return repo.facts
188
+ .filter((fact) => injectable(fact, ordinal))
189
+ .sort((left, right) => score(right, ordinal) - score(left, ordinal))
190
+ .slice(0, this.config.maxFacts);
191
+ }
192
+ /** The user-role message to admit, or undefined to leave the step alone. */
193
+ async injectedMessage(agent, turn, step) {
194
+ if (turn !== 1 || step !== 1)
195
+ return undefined;
196
+ const session = agent.session;
197
+ const watch = this.watchOf(session);
198
+ if (watch.injected !== undefined)
199
+ return undefined;
200
+ watch.injected = [];
201
+ const repo = await this.repoOf(session);
202
+ const facts = this.worthInjecting(repo);
203
+ const text = render(facts, this.config.maxChars);
204
+ if (text === undefined)
205
+ return undefined;
206
+ watch.injected = facts.map((fact) => fact.key);
207
+ this.bill(session, text);
208
+ return createUserMessage({
209
+ content: [{ type: 'text', text }],
210
+ source: { kind: 'dsh-te-facts', form: 'notice' },
211
+ });
212
+ }
213
+ /** Count the injected text as this component's own overhead, when a ledger is present. */
214
+ bill(session, text) {
215
+ const ledger = this.ctx.get('teCost');
216
+ ledger?.recordOverhead?.(session, 'facts', Math.ceil(text.length / 4));
217
+ }
218
+ /**
219
+ * Fold a finished session into the repository's facts.
220
+ * @param session - the session that just ended.
221
+ */
222
+ async settle(session) {
223
+ const watch = this.watching.get(session.id);
224
+ this.watching.delete(session.id);
225
+ // A subagent child is a delegation of the session that already counts:
226
+ // folding it in would inflate the task ordinal that promotions are keyed on.
227
+ if (isSubagent(session))
228
+ return;
229
+ const repo = await this.repoOf(session);
230
+ const ordinal = repo.tasks + 1;
231
+ const calls = watch?.calls ?? [];
232
+ const learned = new Map(extractFacts(calls).map((candidate) => [candidate.key, candidate]));
233
+ for (const fact of [...repo.facts]) {
234
+ if (fact.state === 'retired')
235
+ continue;
236
+ const arose = exercised(calls, fact.key);
237
+ const waste = wasteRecurred(calls, fact.key);
238
+ let next = { ...fact, ...recordExercise(fact, arose, waste) };
239
+ if (contradicted(calls, fact.key)) {
240
+ // The claim was false here: fail toward retirement, never toward
241
+ // re-injection of something the repository has already disproved.
242
+ next = { ...next, ...contradict(next, ordinal) };
243
+ }
244
+ else if (learned.has(fact.key) || waste) {
245
+ next = { ...next, ...confirm(next, ordinal) };
246
+ }
247
+ this.replace(repo, next);
248
+ }
249
+ for (const candidate of learned.values()) {
250
+ const known = repo.facts.find((fact) => fact.key === candidate.key);
251
+ if (known !== undefined && known.state !== 'retired')
252
+ continue;
253
+ if (known !== undefined) {
254
+ // Retired is not permanent: a repository can change (tooling added, env
255
+ // fixed, then broken again). Re-learn from scratch rather than resurrect
256
+ // the old record, so the promotion and firing evidence starts clean.
257
+ repo.facts.splice(repo.facts.indexOf(known), 1);
258
+ }
259
+ // The session that taught us the fact exercised it too: it saw both the
260
+ // failure and the repair, so it is the first entry in the firing record.
261
+ repo.facts.push({
262
+ ...recordExercise(NEW_LIFECYCLE, true, true),
263
+ ...candidate,
264
+ confirms: [ordinal],
265
+ });
266
+ }
267
+ if (repo.facts.length > FACT_CAP) {
268
+ // Keep what is provably useful longest: retired entries go first, then the
269
+ // lowest-scoring candidates.
270
+ const ranked = [...repo.facts].sort((left, right) => {
271
+ const retiredLeft = left.state === 'retired' ? 0 : 1;
272
+ const retiredRight = right.state === 'retired' ? 0 : 1;
273
+ if (retiredLeft !== retiredRight)
274
+ return retiredLeft - retiredRight;
275
+ return score(left, ordinal) - score(right, ordinal);
276
+ });
277
+ repo.facts = ranked.slice(ranked.length - FACT_CAP);
278
+ }
279
+ repo.tasks = ordinal;
280
+ this.repos.set(repo.key, repo);
281
+ await writeJsonAtomic(repoFactsPath(repo.key), repo);
282
+ }
283
+ /** Replace one fact in place. */
284
+ replace(repo, fact) {
285
+ const index = repo.facts.findIndex((entry) => entry.key === fact.key);
286
+ if (index >= 0)
287
+ repo.facts[index] = fact;
288
+ }
289
+ /** Human-readable listing for `/te-facts`. */
290
+ report(session) {
291
+ const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key;
292
+ const repo = this.repos.get(key);
293
+ if (repo === undefined)
294
+ return `No facts learned yet for ${key}.`;
295
+ if (repo.facts.length === 0)
296
+ return `No facts learned yet for ${key} (${repo.tasks} sessions).`;
297
+ const ordinal = repo.tasks;
298
+ const lines = repo.facts
299
+ .slice()
300
+ .sort((left, right) => score(right, ordinal) - score(left, ordinal))
301
+ .map((fact) => {
302
+ const rate = fact.fired === 0 ? '—' : `${Math.round((fact.firedWaste / fact.fired) * 100)}%`;
303
+ return `${fact.state.padEnd(9)} score ${score(fact, ordinal).toFixed(2).padStart(5)} fired ${rate.padStart(4)} ${fact.text}`;
304
+ });
305
+ return [`Facts for ${key} (${repo.tasks} sessions)`, ...lines].join('\n');
306
+ }
307
+ /** Whether any session is currently being watched (used by tests). */
308
+ get watchingCount() {
309
+ return this.watching.size;
310
+ }
311
+ }
312
+ /** Mount the component. */
313
+ export function apply(ctx, config) {
314
+ if (!config.enabled)
315
+ return;
316
+ ctx.plugin(Facts, config);
317
+ }
318
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,OAAO,EAAgB,MAAM,qBAAqB,CAAA;AAC3D,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAGxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AASxD,OAAO,EACL,aAAa,EACb,OAAO,EACP,UAAU,EACV,YAAY,EACZ,SAAS,EACT,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,cAAc,EACd,cAAc,EACd,cAAc,EACd,KAAK,EACL,SAAS,EACT,aAAa,EACb,eAAe,GAGhB,MAAM,0BAA0B,CAAA;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAYhC,MAAM,CAAC,MAAM,IAAI,GAAG,cAAc,CAAA;AAElC,MAAM,CAAC,MAAM,MAAM,GAAc,CAAC,CAAC,MAAM,CAAC;IACxC,OAAO,EAAE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CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,GAAG,CAAA;YAC5F,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,UAAU,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,WAAW,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAA;QAChI,CAAC,CAAC,CAAA;QACJ,OAAO,CAAC,aAAa,GAAG,KAAK,IAAI,CAAC,KAAK,YAAY,EAAE,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC3E,CAAC;IAED,sEAAsE;IACtE,IAAI,aAAa;QACf,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAA;IAC3B,CAAC;;AASH,2BAA2B;AAC3B,MAAM,UAAU,KAAK,CAAC,GAAY,EAAE,MAAc;IAChD,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAM;IAC3B,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;AAC3B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@sonettogu14/dsh-te-facts",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Repository-scoped learned facts injected into the system prompt.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "lib/index.js",
8
+ "types": "lib/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./lib/index.d.ts",
12
+ "import": "./lib/index.js"
13
+ },
14
+ "./cordis.patch.yml": "./cordis.patch.yml",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "lib",
19
+ "src",
20
+ "cordis.patch.yml"
21
+ ],
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/SonettoGu14/dsh-tokeneconomizer.git",
25
+ "directory": "packages/facts"
26
+ },
27
+ "engines": {
28
+ "node": ">=24.9.0",
29
+ "dsh": ">=0.2.2-rc.3 <0.3.0"
30
+ },
31
+ "dsh": {
32
+ "bundle": {
33
+ "patch": "./cordis.patch.yml"
34
+ }
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@sonettogu14/dsh-te-core": "0.1.1",
41
+ "@deepseek-ai/schemastery": "^3.19.0"
42
+ },
43
+ "peerDependencies": {
44
+ "@deepseek-ai/dsh": ">=0.2.2-rc.3 <0.3.0",
45
+ "@deepseek-ai/cordis": "^4.1.0",
46
+ "@deepseek-ai/dsh-session": ">=0.2.2-rc.3 <0.3.0",
47
+ "@deepseek-ai/dsh-agent": ">=0.2.2-rc.3 <0.3.0",
48
+ "@deepseek-ai/dsh-tools": ">=0.2.2-rc.3 <0.3.0",
49
+ "@deepseek-ai/dsh-commands": ">=0.2.2-rc.3 <0.3.0",
50
+ "@deepseek-ai/dsh-llm": ">=0.2.2-rc.3 <0.3.0"
51
+ },
52
+ "devDependencies": {
53
+ "@deepseek-ai/cordis": "^4.1.0",
54
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.3",
55
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
56
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3",
57
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.3",
58
+ "@deepseek-ai/dsh-commands": "0.2.2-rc.3"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "@deepseek-ai/cordis": {
62
+ "optional": false
63
+ },
64
+ "@deepseek-ai/dsh-session": {
65
+ "optional": false
66
+ },
67
+ "@deepseek-ai/dsh-agent": {
68
+ "optional": false
69
+ },
70
+ "@deepseek-ai/dsh-tools": {
71
+ "optional": false
72
+ },
73
+ "@deepseek-ai/dsh-commands": {
74
+ "optional": false
75
+ }
76
+ },
77
+ "homepage": "https://github.com/SonettoGu14/dsh-tokeneconomizer/tree/master/packages/facts#readme",
78
+ "bugs": {
79
+ "url": "https://github.com/SonettoGu14/dsh-tokeneconomizer/issues"
80
+ },
81
+ "scripts": {}
6
82
  }
package/src/index.ts ADDED
@@ -0,0 +1,397 @@
1
+ /**
2
+ * Repository facts, learned mechanically and spent sparingly.
3
+ *
4
+ * The component watches shell calls in a session, and when a session dies it
5
+ * turns "this form failed here, that form worked" into a fact. Facts are scoped
6
+ * to one repository (git origin remote, else the working directory) and are
7
+ * only injected once they have been confirmed by three separate sessions *and*
8
+ * the waste they warn about is still happening. That second gate is the point:
9
+ * a fact the model has already absorbed stops costing tokens.
10
+ *
11
+ * Injection rides the logged pre-step channel: one extra user-role message at
12
+ * the first step of a session, and nothing at all when no fact qualifies.
13
+ *
14
+ * @module @sonettogu14/dsh-te-facts
15
+ */
16
+ import { Service, type Context } from '@deepseek-ai/cordis'
17
+ import z from '@deepseek-ai/schemastery'
18
+ import type {} from '@deepseek-ai/dsh-commands'
19
+ import type { Agent } from '@deepseek-ai/dsh-agent'
20
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
21
+ import type { Session } from '@deepseek-ai/dsh-session'
22
+
23
+ declare module '@deepseek-ai/dsh-llm' {
24
+ interface MessageSourceMap {
25
+ 'dsh-te-facts': { kind: 'dsh-te-facts'; form: 'notice' }
26
+ }
27
+ }
28
+ import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
29
+ import {
30
+ NEW_LIFECYCLE,
31
+ confirm,
32
+ contradict,
33
+ contradicted,
34
+ exercised,
35
+ extractFacts,
36
+ injectable,
37
+ readJson,
38
+ recordExercise,
39
+ repoKeyDirName,
40
+ resolveRepoKey,
41
+ score,
42
+ stateRoot,
43
+ wasteRecurred,
44
+ writeJsonAtomic,
45
+ type FactLifecycle,
46
+ type ShellCall,
47
+ } from '@sonettogu14/dsh-te-core'
48
+ import { join } from 'node:path'
49
+
50
+ /** Settings for the facts component. */
51
+ export interface Config {
52
+ /** Watch and inject. Off means the component does nothing at all. */
53
+ enabled: boolean
54
+ /** Never inject more than this many facts at once (TokenEconomizer used 4). */
55
+ maxFacts: number
56
+ /** Hard cap on the injected text; ~150 tokens at 4 chars/token. */
57
+ maxChars: number
58
+ }
59
+
60
+ export const name = 'dsh-te-facts'
61
+
62
+ export const Config: z<Config> = z.object({
63
+ enabled: z.boolean().default(true),
64
+ maxFacts: z.number().min(0).default(4),
65
+ maxChars: z.number().min(0).default(600),
66
+ })
67
+
68
+ /** One stored fact: what it claims plus how it has fared. */
69
+ interface StoredFact extends FactLifecycle {
70
+ readonly key: string
71
+ readonly family: 'form-repair' | 'env-value'
72
+ readonly intent: string
73
+ readonly text: string
74
+ }
75
+
76
+ /** The learned state of one repository. */
77
+ interface RepoFacts {
78
+ version: 1
79
+ key: string
80
+ /** Sessions that ended in this repository; the lifecycle clock. */
81
+ tasks: number
82
+ facts: StoredFact[]
83
+ }
84
+
85
+ /** What one live session has shown us so far. */
86
+ interface SessionWatch {
87
+ calls: ShellCall[]
88
+ /** Fact keys injected into this session, or undefined before the decision. */
89
+ injected?: string[]
90
+ }
91
+
92
+ /** How many facts one repository may keep; lowest-value facts go first. */
93
+ const FACT_CAP = 200
94
+
95
+ /**
96
+ * Whether one stored entry still has the shape this version understands.
97
+ *
98
+ * A hand-edited, truncated or older file must degrade to "that entry is gone",
99
+ * not to a throw on the step-1 hot path.
100
+ */
101
+ function isStoredFact(value: unknown): value is StoredFact {
102
+ if (value === null || typeof value !== 'object') return false
103
+ const fact = value as Partial<StoredFact>
104
+ return (
105
+ typeof fact.key === 'string' &&
106
+ typeof fact.text === 'string' &&
107
+ (fact.family === 'form-repair' || fact.family === 'env-value') &&
108
+ (fact.state === 'candidate' || fact.state === 'active' || fact.state === 'retired') &&
109
+ Array.isArray(fact.confirms) &&
110
+ Array.isArray(fact.contradicts) &&
111
+ typeof fact.fired === 'number' &&
112
+ typeof fact.firedWaste === 'number'
113
+ )
114
+ }
115
+
116
+ /** Whether this session is a subagent child rather than a top-level task. */
117
+ function isSubagent(session: Session): boolean {
118
+ return session.header?.origin === 'subagent'
119
+ }
120
+
121
+ function textOf(result: ToolExecutionResult): string {
122
+ return result.content
123
+ .map((block) => (block.type === 'text' ? block.text : ''))
124
+ .join('\n')
125
+ }
126
+
127
+ /** Trim output to what the extractors actually read. */
128
+ function relevant(output: string): string {
129
+ return output.length <= 4_000 ? output : `${output.slice(0, 2_000)}\n${output.slice(-2_000)}`
130
+ }
131
+
132
+ /** The shell command a tool call carried, when it carried one. */
133
+ function commandOf(exec: ToolExecution): string | undefined {
134
+ if (exec.name !== 'bash' && exec.name !== 'bash_persistent') return undefined
135
+ const args = exec.arguments
136
+ if (typeof args !== 'object' || args === null) return undefined
137
+ const command = (args as { command?: unknown }).command
138
+ return typeof command === 'string' ? command : undefined
139
+ }
140
+
141
+ /** Where one repository's facts live. */
142
+ function repoFactsPath(key: string): string {
143
+ return join(stateRoot(), 'repos', repoKeyDirName(key), 'facts.json')
144
+ }
145
+
146
+ /** Render the injected block for a set of facts. */
147
+ function render(facts: readonly StoredFact[], maxChars: number): string | undefined {
148
+ if (facts.length === 0 || maxChars <= 0) return undefined
149
+ const header = 'Facts learned from earlier sessions in this repository (verify before relying):'
150
+ const lines: string[] = [header]
151
+ let used = header.length
152
+ for (const fact of facts) {
153
+ const line = `- ${fact.text}`
154
+ if (used + line.length + 1 > maxChars) break
155
+ lines.push(line)
156
+ used += line.length + 1
157
+ }
158
+ return lines.length > 1 ? lines.join('\n') : undefined
159
+ }
160
+
161
+ /**
162
+ * Per-repository fact store and per-session watcher.
163
+ * Exposed on the context as `teFacts`.
164
+ */
165
+ export class Facts extends Service {
166
+ static inject = ['commands']
167
+
168
+ private readonly watching = new Map<string, SessionWatch>()
169
+
170
+ /** Settles in flight, awaited by the `session/flush` durability checkpoint. */
171
+ private readonly pending = new Map<string, Promise<void>>()
172
+
173
+ private readonly repos = new Map<string, RepoFacts>()
174
+
175
+ constructor(ctx: Context, private readonly config: Config) {
176
+ super(ctx, 'teFacts')
177
+ }
178
+
179
+ protected async [Service.init](): Promise<void> {
180
+ this.ctx.on('tools/result', (exec, result) => {
181
+ this.observe(exec, result)
182
+ })
183
+ this.ctx.on('agent/pre-step', async (payload, next) => {
184
+ const decision = await next()
185
+ if (decision.kind !== 'enter') return decision
186
+ if (isSubagent(payload.agent.session)) return decision
187
+ let message: ReturnType<typeof createUserMessage> | undefined
188
+ try {
189
+ message = await this.injectedMessage(payload.agent, payload.turn, payload.step)
190
+ } catch (error) {
191
+ // Injection is an optimization: a damaged state file must never stop a
192
+ // session from starting.
193
+ this.ctx.logger('dsh-te-facts').warn('facts not injected: %s', String(error))
194
+ return decision
195
+ }
196
+ if (message === undefined) return decision
197
+ // Spread the decision: it may carry `startsRequestSeries`, and dropping it
198
+ // would move the prefix-cache boundary for every listener after us.
199
+ return { ...decision, messages: [...decision.messages, message] }
200
+ })
201
+ this.ctx.on('session/disposed', (session) => {
202
+ // Teardown does not await listeners, so the write is drained by the
203
+ // awaited `session/flush` checkpoint instead of racing the process exit.
204
+ this.pending.set(
205
+ session.id,
206
+ this.settle(session)
207
+ .catch((error: unknown) => {
208
+ // A learning pass must never take the session down with it.
209
+ this.ctx.logger('dsh-te-facts').warn('facts not settled: %s', String(error))
210
+ })
211
+ .finally(() => this.pending.delete(session.id)),
212
+ )
213
+ })
214
+ this.ctx.on('session/flush', async () => {
215
+ await Promise.all([...this.pending.values()])
216
+ })
217
+ this.ctx.effect(() =>
218
+ this.ctx.commands.register({
219
+ name: 'te-facts',
220
+ description: 'List repository facts learned by dsh-te-facts',
221
+ handler: (invocation) => ({ kind: 'success', text: this.report(invocation.agent.session) }),
222
+ }),
223
+ )
224
+ }
225
+
226
+ /** Record one shell call. */
227
+ private observe(exec: ToolExecution, result: ToolExecutionResult): void {
228
+ const session = exec.agent?.session
229
+ const command = commandOf(exec)
230
+ if (session === undefined || command === undefined) return
231
+ const watch = this.watchOf(session)
232
+ if (watch.calls.length >= 200) watch.calls.shift()
233
+ watch.calls.push({ command, ok: result.isError !== true, output: relevant(textOf(result)) })
234
+ }
235
+
236
+ /** The watcher for one session. */
237
+ private watchOf(session: Session): SessionWatch {
238
+ const existing = this.watching.get(session.id)
239
+ if (existing !== undefined) return existing
240
+ const created: SessionWatch = { calls: [] }
241
+ this.watching.set(session.id, created)
242
+ return created
243
+ }
244
+
245
+ /** Load (and cache) the facts of the session's repository. */
246
+ private async repoOf(session: Session): Promise<RepoFacts> {
247
+ const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key
248
+ const cached = this.repos.get(key)
249
+ if (cached !== undefined) return cached
250
+ const stored = await readJson<RepoFacts>(repoFactsPath(key))
251
+ const repo: RepoFacts =
252
+ stored !== undefined && stored.version === 1 && Array.isArray(stored.facts)
253
+ ? { ...stored, key, facts: stored.facts.filter(isStoredFact) }
254
+ : { version: 1, key, tasks: 0, facts: [] }
255
+ this.repos.set(key, repo)
256
+ return repo
257
+ }
258
+
259
+ /** Facts worth injecting now, best first. */
260
+ private worthInjecting(repo: RepoFacts): StoredFact[] {
261
+ const ordinal = repo.tasks
262
+ return repo.facts
263
+ .filter((fact) => injectable(fact, ordinal))
264
+ .sort((left, right) => score(right, ordinal) - score(left, ordinal))
265
+ .slice(0, this.config.maxFacts)
266
+ }
267
+
268
+ /** The user-role message to admit, or undefined to leave the step alone. */
269
+ private async injectedMessage(agent: Agent, turn: number, step: number): Promise<ReturnType<typeof createUserMessage> | undefined> {
270
+ if (turn !== 1 || step !== 1) return undefined
271
+ const session = agent.session
272
+ const watch = this.watchOf(session)
273
+ if (watch.injected !== undefined) return undefined
274
+ watch.injected = []
275
+ const repo = await this.repoOf(session)
276
+ const facts = this.worthInjecting(repo)
277
+ const text = render(facts, this.config.maxChars)
278
+ if (text === undefined) return undefined
279
+ watch.injected = facts.map((fact) => fact.key)
280
+ this.bill(session, text)
281
+ return createUserMessage({
282
+ content: [{ type: 'text', text }],
283
+ source: { kind: 'dsh-te-facts', form: 'notice' },
284
+ })
285
+ }
286
+
287
+ /** Count the injected text as this component's own overhead, when a ledger is present. */
288
+ private bill(session: Session, text: string): void {
289
+ const ledger = this.ctx.get('teCost') as { recordOverhead?: (target: Session, label: string, tokens: number) => void } | undefined
290
+ ledger?.recordOverhead?.(session, 'facts', Math.ceil(text.length / 4))
291
+ }
292
+
293
+ /**
294
+ * Fold a finished session into the repository's facts.
295
+ * @param session - the session that just ended.
296
+ */
297
+ async settle(session: Session): Promise<void> {
298
+ const watch = this.watching.get(session.id)
299
+ this.watching.delete(session.id)
300
+ // A subagent child is a delegation of the session that already counts:
301
+ // folding it in would inflate the task ordinal that promotions are keyed on.
302
+ if (isSubagent(session)) return
303
+ const repo = await this.repoOf(session)
304
+ const ordinal = repo.tasks + 1
305
+ const calls = watch?.calls ?? []
306
+ const learned = new Map(extractFacts(calls).map((candidate) => [candidate.key, candidate]))
307
+
308
+ for (const fact of [...repo.facts]) {
309
+ if (fact.state === 'retired') continue
310
+ const arose = exercised(calls, fact.key)
311
+ const waste = wasteRecurred(calls, fact.key)
312
+ let next: StoredFact = { ...fact, ...recordExercise(fact, arose, waste) }
313
+ if (contradicted(calls, fact.key)) {
314
+ // The claim was false here: fail toward retirement, never toward
315
+ // re-injection of something the repository has already disproved.
316
+ next = { ...next, ...contradict(next, ordinal) }
317
+ } else if (learned.has(fact.key) || waste) {
318
+ next = { ...next, ...confirm(next, ordinal) }
319
+ }
320
+ this.replace(repo, next)
321
+ }
322
+
323
+ for (const candidate of learned.values()) {
324
+ const known = repo.facts.find((fact) => fact.key === candidate.key)
325
+ if (known !== undefined && known.state !== 'retired') continue
326
+ if (known !== undefined) {
327
+ // Retired is not permanent: a repository can change (tooling added, env
328
+ // fixed, then broken again). Re-learn from scratch rather than resurrect
329
+ // the old record, so the promotion and firing evidence starts clean.
330
+ repo.facts.splice(repo.facts.indexOf(known), 1)
331
+ }
332
+ // The session that taught us the fact exercised it too: it saw both the
333
+ // failure and the repair, so it is the first entry in the firing record.
334
+ repo.facts.push({
335
+ ...recordExercise(NEW_LIFECYCLE, true, true),
336
+ ...candidate,
337
+ confirms: [ordinal],
338
+ })
339
+ }
340
+
341
+ if (repo.facts.length > FACT_CAP) {
342
+ // Keep what is provably useful longest: retired entries go first, then the
343
+ // lowest-scoring candidates.
344
+ const ranked = [...repo.facts].sort((left, right) => {
345
+ const retiredLeft = left.state === 'retired' ? 0 : 1
346
+ const retiredRight = right.state === 'retired' ? 0 : 1
347
+ if (retiredLeft !== retiredRight) return retiredLeft - retiredRight
348
+ return score(left, ordinal) - score(right, ordinal)
349
+ })
350
+ repo.facts = ranked.slice(ranked.length - FACT_CAP)
351
+ }
352
+
353
+ repo.tasks = ordinal
354
+ this.repos.set(repo.key, repo)
355
+ await writeJsonAtomic(repoFactsPath(repo.key), repo)
356
+ }
357
+
358
+ /** Replace one fact in place. */
359
+ private replace(repo: RepoFacts, fact: StoredFact): void {
360
+ const index = repo.facts.findIndex((entry) => entry.key === fact.key)
361
+ if (index >= 0) repo.facts[index] = fact
362
+ }
363
+
364
+ /** Human-readable listing for `/te-facts`. */
365
+ report(session: Session): string {
366
+ const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key
367
+ const repo = this.repos.get(key)
368
+ if (repo === undefined) return `No facts learned yet for ${key}.`
369
+ if (repo.facts.length === 0) return `No facts learned yet for ${key} (${repo.tasks} sessions).`
370
+ const ordinal = repo.tasks
371
+ const lines = repo.facts
372
+ .slice()
373
+ .sort((left, right) => score(right, ordinal) - score(left, ordinal))
374
+ .map((fact) => {
375
+ const rate = fact.fired === 0 ? '—' : `${Math.round((fact.firedWaste / fact.fired) * 100)}%`
376
+ return `${fact.state.padEnd(9)} score ${score(fact, ordinal).toFixed(2).padStart(5)} fired ${rate.padStart(4)} ${fact.text}`
377
+ })
378
+ return [`Facts for ${key} (${repo.tasks} sessions)`, ...lines].join('\n')
379
+ }
380
+
381
+ /** Whether any session is currently being watched (used by tests). */
382
+ get watchingCount(): number {
383
+ return this.watching.size
384
+ }
385
+ }
386
+
387
+ declare module '@deepseek-ai/cordis' {
388
+ interface Context {
389
+ teFacts: Facts
390
+ }
391
+ }
392
+
393
+ /** Mount the component. */
394
+ export function apply(ctx: Context, config: Config): void {
395
+ if (!config.enabled) return
396
+ ctx.plugin(Facts, config)
397
+ }