@homeostat/core 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.
Files changed (110) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +6 -2
  3. package/dist/src/automation.d.ts +68 -0
  4. package/dist/src/automation.js +21 -0
  5. package/dist/src/automerge.d.ts +27 -0
  6. package/dist/src/automerge.js +51 -0
  7. package/dist/src/body.d.ts +16 -0
  8. package/dist/src/body.js +74 -0
  9. package/dist/src/check.d.ts +17 -0
  10. package/dist/src/check.js +55 -0
  11. package/dist/src/claude-code.d.ts +36 -0
  12. package/dist/src/claude-code.js +100 -0
  13. package/dist/src/claude.d.ts +29 -0
  14. package/dist/src/claude.js +48 -0
  15. package/dist/src/cloud.d.ts +36 -0
  16. package/dist/src/cloud.js +85 -0
  17. package/dist/src/codeowners.d.ts +14 -0
  18. package/dist/src/codeowners.js +63 -0
  19. package/dist/src/confidence.d.ts +39 -0
  20. package/dist/src/confidence.js +101 -0
  21. package/dist/src/config.d.ts +199 -0
  22. package/dist/src/config.js +328 -0
  23. package/dist/src/conflicts.d.ts +23 -0
  24. package/dist/src/conflicts.js +132 -0
  25. package/dist/src/cron.d.ts +12 -0
  26. package/dist/src/cron.js +65 -0
  27. package/dist/src/curator/curate.d.ts +67 -0
  28. package/dist/src/curator/curate.js +273 -0
  29. package/dist/src/curator/doc-patcher.d.ts +42 -0
  30. package/dist/src/curator/doc-patcher.js +57 -0
  31. package/dist/src/curator/draft.d.ts +33 -0
  32. package/dist/src/curator/draft.js +59 -0
  33. package/dist/src/curator/threads.d.ts +16 -0
  34. package/dist/src/curator/threads.js +41 -0
  35. package/dist/src/curator/urls.d.ts +15 -0
  36. package/dist/src/curator/urls.js +32 -0
  37. package/dist/src/deepdive.d.ts +68 -0
  38. package/dist/src/deepdive.js +200 -0
  39. package/dist/src/describe.d.ts +14 -0
  40. package/dist/src/describe.js +72 -0
  41. package/dist/src/digest.d.ts +18 -0
  42. package/dist/src/digest.js +54 -0
  43. package/dist/src/doc-context.d.ts +29 -0
  44. package/dist/src/doc-context.js +62 -0
  45. package/dist/src/doc-convert.d.ts +19 -0
  46. package/dist/src/doc-convert.js +102 -0
  47. package/dist/src/doc-patch.d.ts +30 -0
  48. package/dist/src/doc-patch.js +95 -0
  49. package/dist/src/doc.d.ts +56 -0
  50. package/dist/src/doc.js +220 -0
  51. package/dist/src/entry.d.ts +19 -0
  52. package/dist/src/entry.js +80 -0
  53. package/dist/src/events.d.ts +24 -0
  54. package/dist/src/events.js +134 -0
  55. package/dist/src/export-block.d.ts +7 -0
  56. package/dist/src/export-block.js +20 -0
  57. package/dist/src/export.d.ts +28 -0
  58. package/dist/src/export.js +148 -0
  59. package/dist/src/files.d.ts +24 -0
  60. package/dist/src/files.js +65 -0
  61. package/dist/src/fix.d.ts +6 -0
  62. package/dist/src/fix.js +21 -0
  63. package/dist/src/flag.d.ts +14 -0
  64. package/dist/src/flag.js +16 -0
  65. package/dist/src/index.d.ts +46 -0
  66. package/dist/src/index.js +46 -0
  67. package/dist/src/issues.d.ts +19 -0
  68. package/dist/src/issues.js +7 -0
  69. package/dist/src/json-schema.d.ts +114 -0
  70. package/dist/src/json-schema.js +10 -0
  71. package/dist/src/providers/bitbucket.d.ts +25 -0
  72. package/dist/src/providers/bitbucket.js +123 -0
  73. package/dist/src/providers/github.d.ts +28 -0
  74. package/dist/src/providers/github.js +139 -0
  75. package/dist/src/providers/http.d.ts +16 -0
  76. package/dist/src/providers/http.js +47 -0
  77. package/dist/src/providers/index.d.ts +5 -0
  78. package/dist/src/providers/index.js +4 -0
  79. package/dist/src/providers/types.d.ts +76 -0
  80. package/dist/src/providers/types.js +2 -0
  81. package/dist/src/risk.d.ts +15 -0
  82. package/dist/src/risk.js +73 -0
  83. package/dist/src/schema.d.ts +76 -0
  84. package/dist/src/schema.js +70 -0
  85. package/dist/src/score.d.ts +21 -0
  86. package/dist/src/score.js +39 -0
  87. package/dist/src/search.d.ts +21 -0
  88. package/dist/src/search.js +66 -0
  89. package/dist/src/secrets.d.ts +20 -0
  90. package/dist/src/secrets.js +79 -0
  91. package/dist/src/section-usage.d.ts +22 -0
  92. package/dist/src/section-usage.js +49 -0
  93. package/dist/src/seed.d.ts +63 -0
  94. package/dist/src/seed.js +122 -0
  95. package/dist/src/select.d.ts +35 -0
  96. package/dist/src/select.js +94 -0
  97. package/dist/src/slug.d.ts +2 -0
  98. package/dist/src/slug.js +12 -0
  99. package/dist/src/tokens.d.ts +5 -0
  100. package/dist/src/tokens.js +13 -0
  101. package/dist/src/validate.d.ts +32 -0
  102. package/dist/src/validate.js +185 -0
  103. package/dist/src/version.d.ts +2 -0
  104. package/dist/src/version.js +2 -0
  105. package/dist/src/visibility.d.ts +19 -0
  106. package/dist/src/visibility.js +17 -0
  107. package/dist/src/zod-issues.d.ts +8 -0
  108. package/dist/src/zod-issues.js +17 -0
  109. package/package.json +64 -3
  110. package/schema/entry.schema.json +155 -0
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,7 @@
1
- # Temporary Holding Version
1
+ # @homeostat/core
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
+ The library behind [homeostat](https://www.npmjs.com/package/homeostat): the entry and config schemas, validation, scoring, selection, the secret and risky-content scanners, the curator and deep dive, and the GitHub and Bitbucket providers.
4
+
5
+ Most people want the `homeostat` command instead. This package is published for it and for tools built on the same knowledge-base format; its API follows the CLI's version and may change before 1.0.
6
+
7
+ Apache-2.0. Source: <https://github.com/ysugarmen/homeostat>.
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Shared names for the automated daily flow (local pending lessons → one daily PR per developer
3
+ * → a decision by confidence score). Laptops and the daily run talk only through git refs on the
4
+ * KB repo's origin, so nothing needs a service:
5
+ *
6
+ * - `candidates/<member>`: the base branch plus that developer's pending lessons and a heartbeat,
7
+ * force-pushed by the developer's sync. Transport only; never merged.
8
+ * - `homeostat/state`: written by the daily run: each developer's decisions, collected heartbeats
9
+ * and one report per run. Laptops read their decisions from it; the dashboard reads all of it.
10
+ */
11
+ export declare const STATE_BRANCH = "homeostat/state";
12
+ export declare const candidatesBranch: (member: string) => string;
13
+ export declare const HEARTBEAT_PATH = ".homeostat-sync/heartbeat.json";
14
+ export declare const decisionsPath: (member: string) => string;
15
+ /** Identifies one version of a lesson file, so a decision applies to exactly what was submitted. */
16
+ export declare const lessonHash: (text: string) => string;
17
+ export type Decision = "merged" | "declined" | "review";
18
+ export interface DecisionRecord {
19
+ path: string;
20
+ id: string;
21
+ hash: string;
22
+ decision: Decision;
23
+ /** Why: the score breakdown summary, or the reviewer's action. */
24
+ reason: string;
25
+ confidence?: number;
26
+ pr?: string;
27
+ at: string;
28
+ }
29
+ export interface DecisionsFile {
30
+ member: string;
31
+ decided: DecisionRecord[];
32
+ }
33
+ export interface Heartbeat {
34
+ member: string;
35
+ at: string;
36
+ /** The base-branch commit the developer's clone was on after the sync. */
37
+ kbCommit: string | null;
38
+ /** Commits the clone could not fast-forward (local edits in the way), 0 when current. */
39
+ behind: number;
40
+ pending: number;
41
+ version: string;
42
+ }
43
+ /** One daily run, written to `runs/<date>.json` on the state branch. */
44
+ export interface RunReport {
45
+ at: string;
46
+ members: {
47
+ member: string;
48
+ merged: number;
49
+ declined: number;
50
+ review: number;
51
+ dailyPr?: string;
52
+ reviewPr?: string;
53
+ mergeError?: string;
54
+ }[];
55
+ /** Review PRs from earlier runs that a reviewer merged or closed since. */
56
+ settled: number;
57
+ lessons: {
58
+ member: string;
59
+ id: string;
60
+ decision: Decision;
61
+ confidence?: number;
62
+ reason: string;
63
+ }[];
64
+ }
65
+ /** Review items older than this are repeated in the morning notice and marked on the dashboard. */
66
+ export declare const REVIEW_REMINDER_DAYS = 2;
67
+ /** A developer whose sync has not reported for this long is shown as not syncing. */
68
+ export declare const STALE_HEARTBEAT_HOURS = 48;
@@ -0,0 +1,21 @@
1
+ import { createHash } from "node:crypto";
2
+ /**
3
+ * Shared names for the automated daily flow (local pending lessons → one daily PR per developer
4
+ * → a decision by confidence score). Laptops and the daily run talk only through git refs on the
5
+ * KB repo's origin, so nothing needs a service:
6
+ *
7
+ * - `candidates/<member>`: the base branch plus that developer's pending lessons and a heartbeat,
8
+ * force-pushed by the developer's sync. Transport only; never merged.
9
+ * - `homeostat/state`: written by the daily run: each developer's decisions, collected heartbeats
10
+ * and one report per run. Laptops read their decisions from it; the dashboard reads all of it.
11
+ */
12
+ export const STATE_BRANCH = "homeostat/state";
13
+ export const candidatesBranch = (member) => `candidates/${member}`;
14
+ export const HEARTBEAT_PATH = ".homeostat-sync/heartbeat.json";
15
+ export const decisionsPath = (member) => `decisions/${member}.json`;
16
+ /** Identifies one version of a lesson file, so a decision applies to exactly what was submitted. */
17
+ export const lessonHash = (text) => createHash("sha256").update(text).digest("hex").slice(0, 16);
18
+ /** Review items older than this are repeated in the morning notice and marked on the dashboard. */
19
+ export const REVIEW_REMINDER_DAYS = 2;
20
+ /** A developer whose sync has not reported for this long is shown as not syncing. */
21
+ export const STALE_HEARTBEAT_HOURS = 48;
@@ -0,0 +1,27 @@
1
+ import type { Config } from "./config.ts";
2
+ import type { Frontmatter } from "./schema.ts";
3
+ /** What the auto-merge gates look at: an entry plus its risky-content findings. */
4
+ export interface MergeCandidate {
5
+ frontmatter: Frontmatter;
6
+ risks: readonly string[];
7
+ }
8
+ export type AutoMergeDecision = {
9
+ auto: true;
10
+ } | {
11
+ auto: false;
12
+ reason: string;
13
+ };
14
+ /**
15
+ * Whether one entry may merge without a reviewer (security plan T1). The score says a lesson is
16
+ * genuine (a member's review comment led to a code change); the other gates check what the rule
17
+ * says and who wrote it. Any failed gate sends the entry to a human.
18
+ */
19
+ export declare function autoMergeDecision(c: MergeCandidate, config: Config): AutoMergeDecision;
20
+ /** Splits a run's entries into those that auto-merge (at most `maxPerRun`) and the rest. */
21
+ export declare function splitAutoMerge<T extends MergeCandidate>(entries: readonly T[], config: Config): {
22
+ auto: T[];
23
+ review: {
24
+ entry: T;
25
+ reason: string;
26
+ }[];
27
+ };
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Whether one entry may merge without a reviewer (security plan T1). The score says a lesson is
3
+ * genuine (a member's review comment led to a code change); the other gates check what the rule
4
+ * says and who wrote it. Any failed gate sends the entry to a human.
5
+ */
6
+ export function autoMergeDecision(c, config) {
7
+ const gate = config.scoring.autoMerge;
8
+ const fm = c.frontmatter;
9
+ const no = (reason) => ({ auto: false, reason });
10
+ if (!gate.enabled)
11
+ return no("auto-merge is off");
12
+ if (fm.status !== "accepted" || fm.score < config.scoring.autoMergeThreshold) {
13
+ return no(`score ${fm.score} is below the threshold (${config.scoring.autoMergeThreshold})`);
14
+ }
15
+ if (fm.source.type !== "pr-feedback")
16
+ return no("only review feedback from a member auto-merges");
17
+ if (fm.source.changedCode !== true)
18
+ return no("no code change followed the comment");
19
+ if (!config.team.members.some((m) => m.id === fm.source.author)) {
20
+ return no(`${fm.source.author} is not a team member`);
21
+ }
22
+ if (c.risks.length > 0)
23
+ return no("flagged by the risky-content check");
24
+ if (fm.flags?.length)
25
+ return no("flagged by a member");
26
+ if (gate.excludeAreas.includes(fm.area))
27
+ return no(`area ${fm.area} always needs a reviewer`);
28
+ if (gate.areas.length > 0 && !gate.areas.includes(fm.area)) {
29
+ return no(`area ${fm.area} is not in scoring.autoMerge.areas`);
30
+ }
31
+ return { auto: true };
32
+ }
33
+ /** Splits a run's entries into those that auto-merge (at most `maxPerRun`) and the rest. */
34
+ export function splitAutoMerge(entries, config) {
35
+ const auto = [];
36
+ const review = [];
37
+ for (const entry of entries) {
38
+ const d = autoMergeDecision(entry, config);
39
+ if (!d.auto)
40
+ review.push({ entry, reason: d.reason });
41
+ else if (auto.length >= config.scoring.autoMerge.maxPerRun) {
42
+ review.push({
43
+ entry,
44
+ reason: `over the per-run cap (${config.scoring.autoMerge.maxPerRun})`,
45
+ });
46
+ }
47
+ else
48
+ auto.push(entry);
49
+ }
50
+ return { auto, review };
51
+ }
@@ -0,0 +1,16 @@
1
+ import { type Issue } from "./issues.ts";
2
+ export declare const RULE_MAX_WORDS = 60;
3
+ export declare const WHY_MAX_WORDS = 100;
4
+ export interface BodySections {
5
+ rule?: string;
6
+ why?: string;
7
+ example?: string;
8
+ }
9
+ /**
10
+ * Splits an entry body into its fixed `## Rule`, `## Why` and `## Example` sections and checks
11
+ * the structural rules. Headings inside fenced code blocks are content, not sections.
12
+ */
13
+ export declare function parseBody(body: string): {
14
+ sections: BodySections;
15
+ issues: Issue[];
16
+ };
@@ -0,0 +1,74 @@
1
+ import { error } from "./issues.js";
2
+ export const RULE_MAX_WORDS = 60;
3
+ export const WHY_MAX_WORDS = 100;
4
+ const SECTIONS = { rule: "Rule", why: "Why", example: "Example" };
5
+ const isSectionKey = (name) => Object.hasOwn(SECTIONS, name);
6
+ const countWords = (text) => text.split(/\s+/).filter(Boolean).length;
7
+ /**
8
+ * Splits an entry body into its fixed `## Rule`, `## Why` and `## Example` sections and checks
9
+ * the structural rules. Headings inside fenced code blocks are content, not sections.
10
+ */
11
+ export function parseBody(body) {
12
+ const issues = [];
13
+ const raw = {};
14
+ const preamble = [];
15
+ let current;
16
+ let fence;
17
+ for (const line of body.split(/\r?\n/)) {
18
+ const fenceMatch = /^\s*(```|~~~)/.exec(line);
19
+ if (fenceMatch) {
20
+ if (!fence)
21
+ fence = fenceMatch[1];
22
+ else if (line.trim().startsWith(fence))
23
+ fence = undefined;
24
+ }
25
+ const heading = fence || fenceMatch ? undefined : /^##\s+(.+?)\s*#*\s*$/.exec(line);
26
+ if (!heading?.[1]) {
27
+ (current ?? preamble).push(line);
28
+ continue;
29
+ }
30
+ const name = heading[1].toLowerCase();
31
+ if (!isSectionKey(name)) {
32
+ issues.push(error("body.section.unknown", `unknown section "## ${heading[1]}"; allowed: Rule, Why, Example`));
33
+ current = [];
34
+ }
35
+ else if (raw[name]) {
36
+ issues.push(error("body.section.duplicate", `section "## ${SECTIONS[name]}" appears twice`));
37
+ current = [];
38
+ }
39
+ else {
40
+ current = raw[name] = [];
41
+ }
42
+ }
43
+ if (preamble.join("").trim()) {
44
+ issues.unshift(error("body.preamble", "text before the first section; start the body with ## Rule"));
45
+ }
46
+ const sections = {};
47
+ for (const key of Object.keys(SECTIONS)) {
48
+ const text = raw[key]?.join("\n").trim();
49
+ if (text)
50
+ sections[key] = text;
51
+ }
52
+ if (!sections.rule) {
53
+ issues.push(error("body.rule.missing", "missing or empty ## Rule section"));
54
+ }
55
+ else {
56
+ if (/\n\s*\n/.test(sections.rule)) {
57
+ issues.push(error("body.rule.multiParagraph", "## Rule must be a single paragraph"));
58
+ }
59
+ const n = countWords(sections.rule);
60
+ if (n > RULE_MAX_WORDS) {
61
+ issues.push(error("body.rule.tooLong", `## Rule has ${n} words; max ${RULE_MAX_WORDS}`));
62
+ }
63
+ }
64
+ if (!sections.why) {
65
+ issues.push(error("body.why.missing", "missing or empty ## Why section"));
66
+ }
67
+ else {
68
+ const n = countWords(sections.why);
69
+ if (n > WHY_MAX_WORDS) {
70
+ issues.push(error("body.why.tooLong", `## Why has ${n} words; max ${WHY_MAX_WORDS}`));
71
+ }
72
+ }
73
+ return { sections, issues };
74
+ }
@@ -0,0 +1,17 @@
1
+ import type { Entry } from "./entry.ts";
2
+ import { type Issue } from "./issues.ts";
3
+ /** The `core` area always exists and holds team-wide entries. */
4
+ export declare const CORE_AREA = "core";
5
+ export interface CheckContext {
6
+ /** Path of the entry file relative to the KB root, e.g. `knowledge/core/my-rule.md`. */
7
+ path: string;
8
+ /** Area names from the config's `areas` key. */
9
+ areas: readonly string[];
10
+ autoMergeThreshold: number;
11
+ /** Member ids from the config's `team`. When omitted, member references are not checked. */
12
+ members?: readonly string[];
13
+ /** The computed score, when known; the threshold check uses it instead of the stored one. */
14
+ score?: number;
15
+ }
16
+ /** Checks one parsed entry against its location and the KB config. Pure; no I/O. */
17
+ export declare function checkEntry(entry: Entry, ctx: CheckContext): Issue[];
@@ -0,0 +1,55 @@
1
+ import { error } from "./issues.js";
2
+ import { countTokens } from "./tokens.js";
3
+ /** The `core` area always exists and holds team-wide entries. */
4
+ export const CORE_AREA = "core";
5
+ /** Checks one parsed entry against its location and the KB config. Pure; no I/O. */
6
+ export function checkEntry(entry, ctx) {
7
+ const fm = entry.frontmatter;
8
+ const file = ctx.path;
9
+ const issues = [];
10
+ const parts = ctx.path.replaceAll("\\", "/").split("/");
11
+ const filename = parts.at(-1) ?? "";
12
+ if (filename !== `${fm.id}.md`) {
13
+ issues.push(error("path.filename", `filename must be "${fm.id}.md" to match id`, { path: "id", file }));
14
+ }
15
+ if (parts.length !== 3 || parts[0] !== "knowledge") {
16
+ issues.push(error("path.root", `entry must live at knowledge/<area>/${fm.id}.md`, { file }));
17
+ }
18
+ else if (parts[1] !== fm.area) {
19
+ issues.push(error("path.folder", `folder "${parts[1]}" does not match area "${fm.area}"`, {
20
+ path: "area",
21
+ file,
22
+ }));
23
+ }
24
+ if (fm.area !== CORE_AREA && !ctx.areas.includes(fm.area)) {
25
+ issues.push(error("area.unknown", `area "${fm.area}" is not in the config's areas (${[CORE_AREA, ...ctx.areas].join(", ")})`, { path: "area", file }));
26
+ }
27
+ if (ctx.members) {
28
+ const refs = [
29
+ ["owner", fm.owner],
30
+ ["source.author", fm.source.author],
31
+ ["approvedBy", fm.approvedBy],
32
+ ...(fm.flags ?? []).map((f, i) => [`flags.${i}.by`, f.by]),
33
+ ];
34
+ for (const [path, member] of refs) {
35
+ if (member !== undefined && !ctx.members.includes(member)) {
36
+ issues.push(error("member.unknown", `${path}: "${member}" is not a team member`, { path, file }));
37
+ }
38
+ }
39
+ }
40
+ // No approval field is required: a rule is accepted by the merge that put it on the base
41
+ // branch, decided by the daily run's confidence score or a reviewer (branch protection makes
42
+ // sure nothing else can merge).
43
+ const tokens = countTokens(entry.body);
44
+ if (fm.tokens !== tokens) {
45
+ issues.push({
46
+ code: "tokens.mismatch",
47
+ severity: "warning",
48
+ message: `tokens is ${fm.tokens}, body counts ${tokens}; run with --fix to update`,
49
+ path: "tokens",
50
+ file,
51
+ fix: { field: "tokens", value: tokens },
52
+ });
53
+ }
54
+ return issues;
55
+ }
@@ -0,0 +1,36 @@
1
+ import { type Asker, type Effort } from "./claude.ts";
2
+ export interface RunResult {
3
+ code: number | null;
4
+ stdout: string;
5
+ stderr: string;
6
+ }
7
+ /** Runs a command with `input` on stdin; rejects with an ENOENT error when it is not installed. */
8
+ export type CommandRunner = (command: string, args: readonly string[], input: string, env: NodeJS.ProcessEnv) => Promise<RunResult>;
9
+ export interface ClaudeCodeAskerOptions {
10
+ model: string;
11
+ effort: Effort;
12
+ /** The Claude Code binary; defaults to `claude` on the PATH. */
13
+ command?: string;
14
+ /** Injected for tests. */
15
+ run?: CommandRunner;
16
+ env?: NodeJS.ProcessEnv;
17
+ }
18
+ /** Set on the child so the homeostat plugin's own hooks never fire inside an agent call. */
19
+ export declare const AGENT_ENV = "HOMEOSTAT_AGENT";
20
+ /**
21
+ * Flags for a bare structured call: our system prompt instead of Claude Code's, no tools, no MCP
22
+ * servers, no skills, no user/project settings (so no plugins or hooks). That keeps a call at
23
+ * about a thousand input tokens instead of the full interactive context.
24
+ */
25
+ export declare function claudeCodeArgs(opts: {
26
+ model: string;
27
+ effort: Effort;
28
+ }, system: string, jsonSchema: object): string[];
29
+ /**
30
+ * The Claude Code runtime: runs `claude -p`, which uses whatever Claude Code is logged in with:
31
+ * an interactive login, a `claude setup-token` token as CLAUDE_CODE_OAUTH_TOKEN, or an API key.
32
+ * Anthropic's terms limit a personal Free/Pro/Max subscription to the subscriber's own,
33
+ * non-commercial use and forbid sharing its token, so a team KB should use the API runtime or a
34
+ * Team/Enterprise plan instead (see docs/execution-plan.md, decisions log).
35
+ */
36
+ export declare function claudeCodeAsker(opts: ClaudeCodeAskerOptions): Asker;