@dsh-cc/command-learn 0.7.1-rc.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm check:readme --write
5
+ README.md: 1b09e8788d5be0f275066f700ee633e50a0dd848
6
+ README.zh.md: c83a9ac6ca5c4c1c3855d91afaafb55405eef735
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # @dsh-cc/command-learn
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ User-facing `/learn` command: distills recurring failure→success corrections from the durable session transcripts into workspace memory, so the same mistakes stop recurring across sessions. Analysis lives in the pure library [`@dsh-cc/session-forensics`](../session-forensics/README.md); this package mounts it as a session-scoped slash command with settings and a memory write path.
6
+
7
+ ## Command contract
8
+
9
+ | Input | Result |
10
+ |---|---|
11
+ | `/learn` | Dry-run: scan the session store (current project by default, last 14 days), render the ranked findings and the proposed managed memory block. Writes nothing. |
12
+ | `/learn apply` | Write the `session-learnings` memory topic file and upsert the `MEMORY.md` pointer through the real `@dsh-cc/memory` writeback helpers. Empty findings leave existing memory untouched. |
13
+ | `/learn all` | Scan every project's sessions instead of the current project only. |
14
+ | `/learn days=N` | Override the recency window for this run. |
15
+ | `/learn help` | Usage text via the shared `helpable()` helper. |
16
+
17
+ Memory writes are wholesale-regenerated per run inside a marker-delimited managed block (`<!-- dsh-cc:learn:start -->` … `end`) owned entirely by `/learn`; the topic-file description stays stable so the pointer line does not churn between runs.
18
+
19
+ ## Composition
20
+
21
+ The plugin injects `commands`, `fs`, and `settings`. A custom app mounts its owner plus this plugin:
22
+
23
+ ```yaml
24
+ - id: command-learn
25
+ name: '@dsh-cc/command-learn'
26
+ ```
27
+
28
+ ## Settings
29
+
30
+ Namespace `cc-learn` (kebab-case, tolerant absence-preserving schema): `enabled` (default `true` — the command is on-demand, nothing runs unprompted; `false` prints a notice and exits), `days` (default `14`), `min-occurrences` (default `2` — only repeated corrections are written).
31
+
32
+ ## Model Experience
33
+
34
+ The slash input and command output do not consume model tokens. Dry-run output is presentation-only; `apply` writes workspace memory files, which surface to the model only through the normal memory recall surfaces in later sessions.
35
+
36
+ ## Known Limitations and Deferred Work
37
+
38
+ - Precision of the deterministic analyzers is unvalidated on real data — a manual 20-finding spot check is the dogfooding gate before trusting `apply` output.
39
+ - No LLM summarization pass in v1; findings land verbatim with evidence anchors.
package/README.zh.md ADDED
@@ -0,0 +1,39 @@
1
+ # @dsh-cc/command-learn
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 面向用户的 `/learn` 命令:从持久化会话转录中蒸馏反复出现的 失败→成功 修正并写入工作区记忆,让同样的错误不再跨会话重演。分析逻辑位于纯库 [`@dsh-cc/session-forensics`](../session-forensics/README.md);本包把它挂载为带设置与记忆写入路径的会话级斜杠命令。
6
+
7
+ ## 命令约定
8
+
9
+ | 输入 | 结果 |
10
+ |---|---|
11
+ | `/learn` | 干跑:扫描会话存储(默认当前项目、最近 14 天),渲染排序后的 findings 与拟写入的记忆块。不写任何内容。 |
12
+ | `/learn apply` | 通过真实的 `@dsh-cc/memory` writeback 辅助函数写入 `session-learnings` 记忆主题文件并 upsert `MEMORY.md` 指针。空 findings 时保持现有记忆不变。 |
13
+ | `/learn all` | 扫描所有项目的会话,而非仅当前项目。 |
14
+ | `/learn days=N` | 为本次运行覆盖新近度窗口。 |
15
+ | `/learn help` | 经共享 `helpable()` 辅助函数输出用法文本。 |
16
+
17
+ 记忆写入在标记限定的托管块(`<!-- dsh-cc:learn:start -->` … `end`)内按运行整体再生成,该块完全由 `/learn` 拥有;主题文件的 description 保持稳定,指针行不会在运行间抖动。
18
+
19
+ ## 组合
20
+
21
+ 该插件注入 `commands`、`fs` 与 `settings`。自定义应用会挂载它的拥有者与此插件:
22
+
23
+ ```yaml
24
+ - id: command-learn
25
+ name: '@dsh-cc/command-learn'
26
+ ```
27
+
28
+ ## 设置
29
+
30
+ 命名空间 `cc-learn`(kebab-case、容忍缺省的 schema):`enabled`(默认 `true` —— 命令按需触发,不会有任何未提示的运行;`false` 时打印提示并退出)、`days`(默认 `14`)、`min-occurrences`(默认 `2` —— 只写重复出现的修正)。
31
+
32
+ ## 模型体验
33
+
34
+ 斜杠输入与命令输出不消耗模型 token。干跑输出仅用于呈现;`apply` 写入工作区记忆文件,这些文件仅在后续会话中通过常规记忆 recall 面呈现给模型。
35
+
36
+ ## 已知限制与暂缓事项
37
+
38
+ - 确定性分析器在真实数据上的精度尚未验证 —— 信任 `apply` 输出前的 dogfood 门是 20 条 findings 的人工抽查。
39
+ - v1 无 LLM 摘要 pass;findings 连同证据锚点原样落盘。
package/lib/index.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Human-facing `/learn` command: distills recurring session failure patterns
3
+ * into the memory system. Dry-run by default; `apply` writes through the
4
+ * real `@dsh-cc/memory` writeback path. Zero writes unless asked.
5
+ * @module @dsh-cc/command-learn
6
+ */
7
+ import type { Context } from '@deepseek-ai/cordis';
8
+ import type { SettingsNamespace } from '@deepseek-ai/dsh-settings';
9
+ import z from '@deepseek-ai/schemastery';
10
+ import { type ForensicsResult } from '@dsh-cc/session-forensics';
11
+ export { LEARNING_DESCRIPTION, TOPIC_NAME, TOPIC_TYPE, renderBlock } from './render.ts';
12
+ export { applyLearnings } from './write.ts';
13
+ export declare const name = "command-learn";
14
+ export declare const inject: string[];
15
+ /** Settings namespace carrying the `/learn` section (kebab-case). */
16
+ export declare const LEARN_SETTINGS_NAMESPACE: SettingsNamespace;
17
+ /** Raw (unresolved) settings section: tolerant, unknown siblings pass through. */
18
+ export type LearnSection = {
19
+ enabled?: unknown;
20
+ days?: unknown;
21
+ 'min-occurrences'?: unknown;
22
+ [key: string]: unknown;
23
+ };
24
+ /** Defaults; used verbatim as the composition entry and when a key is absent. */
25
+ export declare const LEARN_DEFAULTS: {
26
+ readonly enabled: true;
27
+ readonly days: 14;
28
+ readonly 'min-occurrences': 2;
29
+ };
30
+ /** Tolerant schema: every key `z.any()`; missing section resolves to defaults. */
31
+ export declare const LEARN_SECTION_SCHEMA: z<LearnSection>;
32
+ /** Default recency window (days) when neither settings nor CLI override it. */
33
+ export declare const DEFAULT_DAYS = 14;
34
+ /** Default minimum occurrence threshold. */
35
+ export declare const DEFAULT_MIN_OCCURRENCES = 2;
36
+ /** One parsed `/learn` invocation. */
37
+ export interface LearnRequest {
38
+ /** `apply` — write the topic file (default is a dry run). */
39
+ readonly apply: boolean;
40
+ /** `all` — scan every project instead of the current one. */
41
+ readonly all: boolean;
42
+ /** `days=N` recency override. */
43
+ readonly days: number | undefined;
44
+ /** Non-empty when a token was unrecognized or `days=` malformed. */
45
+ readonly invalid: string | undefined;
46
+ }
47
+ /**
48
+ * Parse `/learn` argument tokens: `apply`, `all`, `days=N`.
49
+ * @param rawInput - exact text following the command name.
50
+ */
51
+ export declare function parseLearn(rawInput: string): LearnRequest;
52
+ /**
53
+ * Resolve effective forensics options from the settings section and CLI
54
+ * overrides (CLI wins). Pure; exported for unit tests.
55
+ */
56
+ export declare function resolveOptions(section: LearnSection | undefined, request: LearnRequest): {
57
+ days: number;
58
+ minOccurrences: number;
59
+ };
60
+ /** Harness-style sessions-store project key: `--<slug>--` around memory's ported slug. */
61
+ export declare function sessionsProjectKey(cwd: string): string;
62
+ /** Human-readable ranked findings + the proposed block (dry-run output). */
63
+ export declare function renderDryRun(result: ForensicsResult): string;
64
+ /**
65
+ * Register the `/learn` command and (optionally) the `cc-learn` settings
66
+ * section. The settings section is optional: a host without a settings
67
+ * provider leaves the command on its built-in defaults.
68
+ * @param ctx - context carrying the command registry and filesystem service.
69
+ */
70
+ export declare function apply(ctx: Context): void;
71
+ //# sourceMappingURL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C,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;IACjC,oEAAoE;IACpE,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAA;CACrC;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,YAAY,CAazD;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,YAAY,GAAG,SAAS,EACjC,OAAO,EAAE,YAAY,GACpB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,CAO1C;AAeD,0FAA0F;AAC1F,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,4EAA4E;AAC5E,wBAAgB,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAY5D;AA6BD;;;;;GAKG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CA6BxC"}
package/lib/index.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Human-facing `/learn` command: distills recurring session failure patterns
3
+ * into the memory system. Dry-run by default; `apply` writes through the
4
+ * real `@dsh-cc/memory` writeback path. Zero writes unless asked.
5
+ * @module @dsh-cc/command-learn
6
+ */
7
+ import { join, resolve } from 'node:path';
8
+ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths';
9
+ import z from '@deepseek-ai/schemastery';
10
+ import { helpable } from '@dsh-cc/command-usage';
11
+ import { projectSlug } from '@dsh-cc/memory';
12
+ import { runForensics } from '@dsh-cc/session-forensics';
13
+ import { renderBlock } from "./render.js";
14
+ import { applyLearnings } from "./write.js";
15
+ export { LEARNING_DESCRIPTION, TOPIC_NAME, TOPIC_TYPE, renderBlock } from "./render.js";
16
+ export { applyLearnings } from "./write.js";
17
+ export const name = 'command-learn';
18
+ export const inject = ['commands', 'fs'];
19
+ /** Settings namespace carrying the `/learn` section (kebab-case). */
20
+ export const LEARN_SETTINGS_NAMESPACE = 'cc-learn';
21
+ /** Defaults; used verbatim as the composition entry and when a key is absent. */
22
+ export const LEARN_DEFAULTS = { enabled: true, days: 14, 'min-occurrences': 2 };
23
+ /** Tolerant schema: every key `z.any()`; missing section resolves to defaults. */
24
+ export const LEARN_SECTION_SCHEMA = z.object({
25
+ enabled: z.any(),
26
+ days: z.any(),
27
+ 'min-occurrences': z.any(),
28
+ });
29
+ /** Default recency window (days) when neither settings nor CLI override it. */
30
+ export const DEFAULT_DAYS = 14;
31
+ /** Default minimum occurrence threshold. */
32
+ export const DEFAULT_MIN_OCCURRENCES = 2;
33
+ /**
34
+ * Parse `/learn` argument tokens: `apply`, `all`, `days=N`.
35
+ * @param rawInput - exact text following the command name.
36
+ */
37
+ export function parseLearn(rawInput) {
38
+ const tokens = rawInput.trim().split(/\s+/u).filter(token => token.length > 0);
39
+ let apply = false;
40
+ let all = false;
41
+ let days;
42
+ let invalid;
43
+ for (const token of tokens) {
44
+ if (token === 'apply')
45
+ apply = true;
46
+ else if (token === 'all')
47
+ all = true;
48
+ else if (/^days=\d+$/u.test(token))
49
+ days = Number(token.slice(5));
50
+ else
51
+ invalid = token;
52
+ }
53
+ return { apply, all, days, invalid };
54
+ }
55
+ /**
56
+ * Resolve effective forensics options from the settings section and CLI
57
+ * overrides (CLI wins). Pure; exported for unit tests.
58
+ */
59
+ export function resolveOptions(section, request) {
60
+ const days = request.days
61
+ ?? (typeof section?.days === 'number' && section.days > 0 ? section.days : DEFAULT_DAYS);
62
+ const minOccurrences = typeof section?.['min-occurrences'] === 'number' && section['min-occurrences'] > 0
63
+ ? section['min-occurrences']
64
+ : DEFAULT_MIN_OCCURRENCES;
65
+ return { days, minOccurrences };
66
+ }
67
+ /**
68
+ * Read the live `cc-learn` section. Returns undefined when no settings
69
+ * provider is attached — callers fall back to the defaults.
70
+ */
71
+ function readSection(ctx) {
72
+ if (sectionSource !== undefined)
73
+ return sectionSource();
74
+ const settings = ctx.get('settings');
75
+ return settings?.get(LEARN_SETTINGS_NAMESPACE);
76
+ }
77
+ /** Live settings-source thunk, wired by installSection; undefined without a provider. */
78
+ let sectionSource;
79
+ /** Harness-style sessions-store project key: `--<slug>--` around memory's ported slug. */
80
+ export function sessionsProjectKey(cwd) {
81
+ return `--${projectSlug(resolve(cwd))}--`;
82
+ }
83
+ /** Human-readable ranked findings + the proposed block (dry-run output). */
84
+ export function renderDryRun(result) {
85
+ const s = result.stats;
86
+ const head = `Scanned ${s.sessionsScanned} session(s) (${s.linesParsed} lines, ` +
87
+ `${s.corruptLinesSkipped} corrupt skipped, ${s.truncatedTails} truncated tails).`;
88
+ if (result.findings.length === 0) {
89
+ return `${head}\nNo findings above the occurrence threshold — nothing to apply.`;
90
+ }
91
+ const listed = result.findings
92
+ .map((f, i) => `${i + 1}. ${f.title} (${f.occurrences} occurrences) — ${f.detail}`)
93
+ .join('\n');
94
+ return `${head}\n${result.findings.length} finding(s):\n${listed}\n\nProposed session-learnings.md block:\n\n${renderBlock(result, new Date().toISOString().slice(0, 10))}`;
95
+ }
96
+ /** Execute `/learn`: dry-run renders findings + proposed block; apply writes. */
97
+ async function executeLearn(ctx, request) {
98
+ const section = readSection(ctx);
99
+ if (section?.enabled === false) {
100
+ return { kind: 'success', text: '/learn is disabled (`cc-learn.enabled` is false in settings).' };
101
+ }
102
+ if (request.invalid !== undefined) {
103
+ return { kind: 'error', text: `Unknown argument "${request.invalid}". Usage: /learn [apply] [all] [days=N]` };
104
+ }
105
+ const { days, minOccurrences } = resolveOptions(section, request);
106
+ const home = resolveDshHome();
107
+ const result = await runForensics(join(home, 'sessions'), {
108
+ days,
109
+ minOccurrences,
110
+ ...(request.all ? {} : { project: sessionsProjectKey(process.cwd()) }),
111
+ });
112
+ if (!request.apply)
113
+ return { kind: 'success', text: renderDryRun(result) };
114
+ if (result.findings.length === 0) {
115
+ return { kind: 'success', text: 'no findings — existing session-learnings.md left untouched' };
116
+ }
117
+ const outcome = await applyLearnings(ctx.fs, join(home, 'memory'), process.cwd(), result);
118
+ return {
119
+ kind: 'success',
120
+ text: `Wrote ${outcome.findings} learning(s) to ${outcome.file} and updated MEMORY.md.`,
121
+ };
122
+ }
123
+ /**
124
+ * Register the `/learn` command and (optionally) the `cc-learn` settings
125
+ * section. The settings section is optional: a host without a settings
126
+ * provider leaves the command on its built-in defaults.
127
+ * @param ctx - context carrying the command registry and filesystem service.
128
+ */
129
+ export function apply(ctx) {
130
+ // Optional settings inject: absent provider → defaults only (same fallback
131
+ // contract as the onboarding section).
132
+ ctx.inject(['settings'], (sctx) => {
133
+ const settings = sctx.settings;
134
+ if (typeof settings?.installSection !== 'function')
135
+ return;
136
+ settings.installSection(ctx, LEARN_SETTINGS_NAMESPACE, LEARN_SECTION_SCHEMA, { ...LEARN_DEFAULTS }, {
137
+ setSource: (current) => { sectionSource = current; },
138
+ onChange: () => { },
139
+ });
140
+ });
141
+ ctx.commands.register(helpable({
142
+ name: 'learn',
143
+ description: 'distill recurring session failure patterns into memory (dry-run by default)',
144
+ input: { hint: '[apply] [all] [days=N]' },
145
+ handler: (invocation) => executeLearn(ctx, parseLearn(invocation.rawInput)),
146
+ }, {
147
+ subcommands: [
148
+ { word: 'apply', summary: 'write the session-learnings.md memory topic (default is a dry run)' },
149
+ { word: 'all', summary: 'scan every project, not just the current workspace' },
150
+ { word: 'days=N', summary: `recency window override (default ${DEFAULT_DAYS})` },
151
+ ],
152
+ notes: [
153
+ 'Writes only with `apply`; empty findings never touch existing memory.',
154
+ 'Tuned via the `cc-learn` settings namespace (enabled, days, min-occurrences).',
155
+ ],
156
+ }));
157
+ }
158
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAIzC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAE5D,OAAO,CAA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AChF;KACF,CAAC,CAAC,CAAA;AACL,CAAC"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Marker-delimited managed block for the `/learn` memory topic: rendering is
3
+ * pure and deterministic so `apply` is idempotent and unit-testable.
4
+ * @module @dsh-cc/command-learn/render
5
+ */
6
+ import type { Finding, ForensicsResult } from '@dsh-cc/session-forensics';
7
+ /** Memory topic slug owned by `/learn` (the file is `<name>.md`). */
8
+ export declare const TOPIC_NAME = "session-learnings";
9
+ /** Memory frontmatter type for the learnings topic. */
10
+ export declare const TOPIC_TYPE: "project";
11
+ /**
12
+ * STABLE one-line description for the MEMORY.md pointer. Deliberately free of
13
+ * finding counts or run dates: any per-run variance would churn the pointer
14
+ * line on every apply (critic MUST-FIX). The run date lives in the body only.
15
+ */
16
+ export declare const LEARNING_DESCRIPTION = "auto-distilled session failure corrections from /learn";
17
+ /** Managed block opening marker. */
18
+ export declare const BLOCK_START = "<!-- dsh-cc:learn:start -->";
19
+ /** Managed block closing marker. */
20
+ export declare const BLOCK_END = "<!-- dsh-cc:learn:end -->";
21
+ /** ISO date (YYYY-MM-DD) for the body header. */
22
+ export declare function isoDate(now?: Date): string;
23
+ /** Render one finding as deterministic markdown lines. */
24
+ export declare function renderFinding(finding: Finding): string[];
25
+ /**
26
+ * Render the managed block for a forensics result. Deterministic for a given
27
+ * result + date: the run date appears in the body header only, never in the
28
+ * MEMORY.md pointer description.
29
+ */
30
+ export declare function renderBlock(result: ForensicsResult, today: string): string;
31
+ //# sourceMappingURL=render.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAEzE,qEAAqE;AACrE,eAAO,MAAM,UAAU,sBAAsB,CAAA;AAE7C,uDAAuD;AACvD,eAAO,MAAM,UAAU,EAAG,SAAkB,CAAA;AAE5C;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,2DACyB,CAAA;AAE1D,oCAAoC;AACpC,eAAO,MAAM,WAAW,gCAAgC,CAAA;AACxD,oCAAoC;AACpC,eAAO,MAAM,SAAS,8BAA8B,CAAA;AAEpD,iDAAiD;AACjD,wBAAgB,OAAO,CAAC,GAAG,GAAE,IAAiB,GAAG,MAAM,CAEtD;AAED,0DAA0D;AAC1D,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,EAAE,CAOxD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAY1E"}
package/lib/render.js ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Marker-delimited managed block for the `/learn` memory topic: rendering is
3
+ * pure and deterministic so `apply` is idempotent and unit-testable.
4
+ * @module @dsh-cc/command-learn/render
5
+ */
6
+ /** Memory topic slug owned by `/learn` (the file is `<name>.md`). */
7
+ export const TOPIC_NAME = 'session-learnings';
8
+ /** Memory frontmatter type for the learnings topic. */
9
+ export const TOPIC_TYPE = 'project';
10
+ /**
11
+ * STABLE one-line description for the MEMORY.md pointer. Deliberately free of
12
+ * finding counts or run dates: any per-run variance would churn the pointer
13
+ * line on every apply (critic MUST-FIX). The run date lives in the body only.
14
+ */
15
+ export const LEARNING_DESCRIPTION = 'auto-distilled session failure corrections from /learn';
16
+ /** Managed block opening marker. */
17
+ export const BLOCK_START = '<!-- dsh-cc:learn:start -->';
18
+ /** Managed block closing marker. */
19
+ export const BLOCK_END = '<!-- dsh-cc:learn:end -->';
20
+ /** ISO date (YYYY-MM-DD) for the body header. */
21
+ export function isoDate(now = new Date()) {
22
+ return now.toISOString().slice(0, 10);
23
+ }
24
+ /** Render one finding as deterministic markdown lines. */
25
+ export function renderFinding(finding) {
26
+ const lines = [`- **${finding.title}** (${finding.occurrences} occurrences)`];
27
+ if (finding.detail.length > 0)
28
+ lines.push(` ${finding.detail}`);
29
+ if (finding.evidence.length > 0) {
30
+ lines.push(` evidence: ${finding.evidence.slice(0, 3).join(', ')}`);
31
+ }
32
+ return lines;
33
+ }
34
+ /**
35
+ * Render the managed block for a forensics result. Deterministic for a given
36
+ * result + date: the run date appears in the body header only, never in the
37
+ * MEMORY.md pointer description.
38
+ */
39
+ export function renderBlock(result, today) {
40
+ const lines = [
41
+ BLOCK_START,
42
+ '## Session Learnings',
43
+ '*Auto-generated by /learn — do not edit manually*',
44
+ '',
45
+ `_Last run: ${today} — ${result.stats.sessionsScanned} session(s) scanned._`,
46
+ '',
47
+ ...result.findings.flatMap(renderFinding),
48
+ BLOCK_END,
49
+ ];
50
+ return `${lines.join('\n')}\n`;
51
+ }
52
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,qEAAqE;AACrE,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAA;AAE7C,uDAAuD;AACvD,MAAM,CAAC,MAAM,UAAU,GAAG,SAAkB,CAAA;AAE5C;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAC/B,wDAAwD,CAAA;AAE1D,oCAAoC;AACpC,MAAM,CAAC,MAAM,WAAW,GAAG,6BAA6B,CAAA;AACxD,oCAAoC;AACpC,MAAM,CAAC,MAAM,SAAS,GAAG,2BAA2B,CAAA;AAEpD,iDAAiD;AACjD,MAAM,UAAU,OAAO,CAAC,MAAY,IAAI,IAAI,EAAE;IAC5C,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;AACvC,CAAC;AAED,0DAA0D;AAC1D,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,MAAM,KAAK,GAAG,CAAC,OAAO,OAAO,CAAC,KAAK,OAAO,OAAO,CAAC,WAAW,eAAe,CAAC,CAAA;IAC7E,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;QAAE,KAAK,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;IAChE,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChC,KAAK,CAAC,IAAI,CAAC,eAAe,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IACtE,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,MAAuB,EAAE,KAAa;IAChE,MAAM,KAAK,GAAG;QACZ,WAAW;QACX,sBAAsB;QACtB,mDAAmD;QACnD,EAAE;QACF,cAAc,KAAK,MAAM,MAAM,CAAC,KAAK,CAAC,eAAe,uBAAuB;QAC5E,EAAE;QACF,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC;QACzC,SAAS;KACV,CAAA;IACD,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;AAChC,CAAC"}
package/lib/write.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `/learn apply` write path: composes the topic file + MEMORY.md pointer
3
+ * through the REAL `@dsh-cc/memory` helpers (renderTopicFile, upsertPointer,
4
+ * validateMemoryWrites, writeMemoryFiles) — the same composition the
5
+ * `memory_save` tool uses; no reimplementation here.
6
+ * @module @dsh-cc/command-learn/write
7
+ */
8
+ import type { FileSystem } from '@deepseek-ai/dsh-fs';
9
+ import type { ForensicsResult } from '@dsh-cc/session-forensics';
10
+ /** Result of one `apply` (or deliberate no-op). */
11
+ export interface ApplyOutcome {
12
+ /** False when findings were empty and nothing was written. */
13
+ wrote: boolean;
14
+ /** Number of findings applied (0 when not written). */
15
+ findings: number;
16
+ /** Absolute topic-file path, set only when written. */
17
+ file?: string;
18
+ }
19
+ /**
20
+ * Write the learnings topic file and MEMORY.md pointer into the workspace
21
+ * memory directory.
22
+ *
23
+ * `/learn` owns the WHOLE topic file (`session-learnings.md`), so apply is a
24
+ * wholesale regenerate of that file — no managed-block surgery on partial
25
+ * content. The MEMORY.md pointer is upserted (appended when absent) through
26
+ * the shared writeback path, which confines writes to the memory directory.
27
+ *
28
+ * Empty findings are a hard no-op: never auto-delete memory on a weak run
29
+ * (critic MUST-FIX).
30
+ */
31
+ export declare function applyLearnings(fs: FileSystem, home: string, cwd: string, result: ForensicsResult): Promise<ApplyOutcome>;
32
+ //# sourceMappingURL=write.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../src/write.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AASrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAGhE,mDAAmD;AACnD,MAAM,WAAW,YAAY;IAC3B,8DAA8D;IAC9D,KAAK,EAAE,OAAO,CAAA;IACd,uDAAuD;IACvD,QAAQ,EAAE,MAAM,CAAA;IAChB,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAClC,EAAE,EAAE,UAAU,EACd,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAAe,GACtB,OAAO,CAAC,YAAY,CAAC,CAuBvB"}
package/lib/write.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `/learn apply` write path: composes the topic file + MEMORY.md pointer
3
+ * through the REAL `@dsh-cc/memory` helpers (renderTopicFile, upsertPointer,
4
+ * validateMemoryWrites, writeMemoryFiles) — the same composition the
5
+ * `memory_save` tool uses; no reimplementation here.
6
+ * @module @dsh-cc/command-learn/write
7
+ */
8
+ import { join } from 'node:path';
9
+ import { resolveWorkspaceMemoryDir, renderTopicFile, upsertPointer, validateMemoryWrites, writeMemoryFiles, } from '@dsh-cc/memory';
10
+ import { LEARNING_DESCRIPTION, TOPIC_NAME, TOPIC_TYPE, isoDate, renderBlock } from "./render.js";
11
+ /**
12
+ * Write the learnings topic file and MEMORY.md pointer into the workspace
13
+ * memory directory.
14
+ *
15
+ * `/learn` owns the WHOLE topic file (`session-learnings.md`), so apply is a
16
+ * wholesale regenerate of that file — no managed-block surgery on partial
17
+ * content. The MEMORY.md pointer is upserted (appended when absent) through
18
+ * the shared writeback path, which confines writes to the memory directory.
19
+ *
20
+ * Empty findings are a hard no-op: never auto-delete memory on a weak run
21
+ * (critic MUST-FIX).
22
+ */
23
+ export async function applyLearnings(fs, home, cwd, result) {
24
+ if (result.findings.length === 0)
25
+ return { wrote: false, findings: 0 };
26
+ const dir = resolveWorkspaceMemoryDir(home, cwd);
27
+ const args = {
28
+ name: TOPIC_NAME,
29
+ type: TOPIC_TYPE,
30
+ description: LEARNING_DESCRIPTION,
31
+ body: renderBlock(result, isoDate()),
32
+ };
33
+ // Upsert the pointer from the CURRENT entrypoint body (empty when the
34
+ // index does not exist yet), then write both files in one batch.
35
+ let entrypoint = '';
36
+ try {
37
+ entrypoint = await fs.readText(await fs.resolve(join(dir, 'MEMORY.md')));
38
+ }
39
+ catch {
40
+ // No index yet — upsert starts from an empty body.
41
+ }
42
+ const writes = [
43
+ { path: `${TOPIC_NAME}.md`, content: renderTopicFile(args) },
44
+ { path: 'MEMORY.md', content: upsertPointer(entrypoint, args) },
45
+ ];
46
+ await writeMemoryFiles(fs, dir, validateMemoryWrites({ writes }));
47
+ return { wrote: true, findings: result.findings.length, file: join(dir, `${TOPIC_NAME}.md`) };
48
+ }
49
+ //# sourceMappingURL=write.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.js","sourceRoot":"","sources":["../src/write.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,IAAI,EAAE,MA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E,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAA;IACjE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,UAAU,KAAK,CAAC,EAAE,CAAA;AAC/F,CAAC"}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@dsh-cc/command-learn",
3
+ "description": "Human-facing slash command distilling session failure patterns into memory (/learn)",
4
+ "version": "0.7.1-rc.1",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/dsh-cc/dsh-cc.git",
8
+ "directory": "packages/session/command-learn"
9
+ },
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./render": {
17
+ "types": "./lib/render.d.ts",
18
+ "default": "./lib/render.js"
19
+ },
20
+ "./src/*": "./src/*",
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "lib"
25
+ ],
26
+ "license": "Apache-2.0",
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "dependencies": {
31
+ "@dsh-cc/session-forensics": "^0.7.1-rc.1",
32
+ "@dsh-cc/command-usage": "^0.7.1-rc.1",
33
+ "@dsh-cc/memory": "^0.7.1-rc.1"
34
+ },
35
+ "peerDependencies": {
36
+ "@deepseek-ai/cordis": ">=0.1.5-rc.1",
37
+ "@deepseek-ai/dsh-commands": ">=0.1.5-rc.1",
38
+ "@deepseek-ai/dsh-fs": ">=0.1.5-rc.1",
39
+ "@deepseek-ai/dsh-home-paths": ">=0.1.5-rc.1",
40
+ "@deepseek-ai/dsh-settings": ">=0.1.5-rc.1",
41
+ "@deepseek-ai/schemastery": "^3.18.1"
42
+ },
43
+ "devDependencies": {
44
+ "@deepseek-ai/cordis": "link:../../../../deepseek-harness/vendor/cordis",
45
+ "@deepseek-ai/cordis-plugin-loader": "link:../../../../deepseek-harness/vendor/loader",
46
+ "@deepseek-ai/dsh-agent": "link:../../../../deepseek-harness/packages/core/agent",
47
+ "@deepseek-ai/dsh-commands": "link:../../../../deepseek-harness/packages/interaction/commands",
48
+ "@deepseek-ai/dsh-fs": "link:../../../../deepseek-harness/packages/fs/fs",
49
+ "@deepseek-ai/dsh-fs-local": "link:../../../../deepseek-harness/packages/fs/fs-local",
50
+ "@deepseek-ai/dsh-home-paths": "link:../../../../deepseek-harness/packages/util/home-paths",
51
+ "@deepseek-ai/dsh-llm": "link:../../../../deepseek-harness/packages/llm/llm",
52
+ "@deepseek-ai/dsh-session": "link:../../../../deepseek-harness/packages/core/session",
53
+ "@deepseek-ai/dsh-settings": "link:../../../../deepseek-harness/packages/settings/settings",
54
+ "@deepseek-ai/schemastery": "link:../../../../deepseek-harness/vendor/schemastery"
55
+ }
56
+ }