wyrm-mcp 7.3.2 → 7.3.3

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 (184) hide show
  1. package/README.md +8 -14
  2. package/dist/activation.js +59 -1
  3. package/dist/agent-daemon.js +281 -4
  4. package/dist/agent-loop.js +332 -7
  5. package/dist/analytics.js +236 -13
  6. package/dist/attribution.js +49 -1
  7. package/dist/audit.js +457 -2
  8. package/dist/auto-capture.js +138 -3
  9. package/dist/auto-orchestrator.js +325 -1
  10. package/dist/autoconfig.d.ts +50 -0
  11. package/dist/autoconfig.d.ts.map +1 -1
  12. package/dist/autoconfig.js +1115 -39
  13. package/dist/autoconfig.js.map +1 -1
  14. package/dist/buddy-runner.js +109 -1
  15. package/dist/buddy.js +564 -14
  16. package/dist/build-flags.js +15 -1
  17. package/dist/capabilities.js +183 -3
  18. package/dist/capture.js +56 -1
  19. package/dist/causality.js +148 -8
  20. package/dist/cli.js +281 -20
  21. package/dist/cloud/cli.js +541 -5
  22. package/dist/cloud/client.js +221 -1
  23. package/dist/cloud/crypto.js +85 -1
  24. package/dist/cloud/machine-id.js +113 -2
  25. package/dist/cloud/recovery.js +60 -1
  26. package/dist/cloud/sync-engine.js +543 -7
  27. package/dist/cloud-backup.js +579 -5
  28. package/dist/cloud-profile.js +138 -1
  29. package/dist/cloud-sync-entrypoint.js +47 -1
  30. package/dist/cloud-sync.js +309 -2
  31. package/dist/connectors/bridge-source.d.ts +46 -0
  32. package/dist/connectors/bridge-source.d.ts.map +1 -0
  33. package/dist/connectors/bridge-source.js +77 -0
  34. package/dist/connectors/bridge-source.js.map +1 -0
  35. package/dist/connectors/index.d.ts +24 -0
  36. package/dist/connectors/index.d.ts.map +1 -0
  37. package/dist/connectors/index.js +69 -0
  38. package/dist/connectors/index.js.map +1 -0
  39. package/dist/connectors/ingest.d.ts +16 -0
  40. package/dist/connectors/ingest.d.ts.map +1 -0
  41. package/dist/connectors/ingest.js +116 -0
  42. package/dist/connectors/ingest.js.map +1 -0
  43. package/dist/connectors/types.d.ts +99 -0
  44. package/dist/connectors/types.d.ts.map +1 -0
  45. package/dist/connectors/types.js +17 -0
  46. package/dist/connectors/types.js.map +1 -0
  47. package/dist/constellation.js +168 -12
  48. package/dist/content-signature.js +45 -1
  49. package/dist/context-build-budgeted.js +144 -4
  50. package/dist/context-ranking.js +69 -1
  51. package/dist/crypto.js +179 -1
  52. package/dist/daemon-write-endpoint.js +290 -1
  53. package/dist/daemon-writer.js +406 -2
  54. package/dist/database.js +1278 -53
  55. package/dist/deprecations.js +162 -2
  56. package/dist/design.js +141 -13
  57. package/dist/event-replication.js +112 -1
  58. package/dist/events-sse.js +43 -7
  59. package/dist/events.js +238 -6
  60. package/dist/failure-patterns.d.ts +107 -0
  61. package/dist/failure-patterns.d.ts.map +1 -1
  62. package/dist/failure-patterns.js +924 -43
  63. package/dist/failure-patterns.js.map +1 -1
  64. package/dist/federation.js +236 -12
  65. package/dist/goals.js +101 -13
  66. package/dist/golden.js +355 -3
  67. package/dist/handlers/agent.js +165 -4
  68. package/dist/handlers/alias-adapters.js +129 -1
  69. package/dist/handlers/aliases.js +171 -1
  70. package/dist/handlers/audit.js +87 -1
  71. package/dist/handlers/boundary.js +221 -1
  72. package/dist/handlers/capture.js +1114 -73
  73. package/dist/handlers/causality.js +119 -9
  74. package/dist/handlers/cloud.js +382 -85
  75. package/dist/handlers/companion.js +459 -28
  76. package/dist/handlers/datalake.js +187 -7
  77. package/dist/handlers/dispatch-context.js +22 -0
  78. package/dist/handlers/entity.js +256 -25
  79. package/dist/handlers/events.js +335 -16
  80. package/dist/handlers/failure.d.ts.map +1 -1
  81. package/dist/handlers/failure.js +408 -13
  82. package/dist/handlers/failure.js.map +1 -1
  83. package/dist/handlers/goals.js +296 -4
  84. package/dist/handlers/intelligence.js +681 -126
  85. package/dist/handlers/invoicing.js +70 -1
  86. package/dist/handlers/mcpclient.js +137 -6
  87. package/dist/handlers/orchestration.js +125 -40
  88. package/dist/handlers/output-schemas.js +24 -1
  89. package/dist/handlers/presence.js +99 -3
  90. package/dist/handlers/project.js +182 -28
  91. package/dist/handlers/prompts.js +157 -6
  92. package/dist/handlers/quest.js +224 -4
  93. package/dist/handlers/recall.js +237 -13
  94. package/dist/handlers/registry.js +167 -1
  95. package/dist/handlers/resources.js +288 -1
  96. package/dist/handlers/review.js +74 -11
  97. package/dist/handlers/run.js +498 -16
  98. package/dist/handlers/search.js +338 -15
  99. package/dist/handlers/session.js +643 -31
  100. package/dist/handlers/share.js +184 -8
  101. package/dist/handlers/shims.js +464 -1
  102. package/dist/handlers/skill.js +449 -67
  103. package/dist/handlers/survivors.js +120 -1
  104. package/dist/handlers/symbols.js +109 -8
  105. package/dist/handlers/syncops.js +302 -4
  106. package/dist/handlers/types.js +27 -1
  107. package/dist/harvest.js +191 -5
  108. package/dist/hours.js +156 -7
  109. package/dist/http-auth.js +321 -3
  110. package/dist/http-fast.js +1302 -22
  111. package/dist/icons.js +47 -1
  112. package/dist/importers.js +268 -1
  113. package/dist/index.js +840 -2
  114. package/dist/indexer.js +145 -4
  115. package/dist/intelligence.js +261 -31
  116. package/dist/internal-dispatch.js +212 -3
  117. package/dist/keyset.js +110 -1
  118. package/dist/knowledge-graph.js +176 -12
  119. package/dist/license.js +441 -2
  120. package/dist/logger.js +199 -2
  121. package/dist/maintenance.js +148 -2
  122. package/dist/mcp-client.js +262 -6
  123. package/dist/memory-artifacts.js +596 -32
  124. package/dist/migrate-prompt.js +124 -2
  125. package/dist/migrations.d.ts.map +1 -1
  126. package/dist/migrations.js +799 -42
  127. package/dist/migrations.js.map +1 -1
  128. package/dist/performance.js +228 -1
  129. package/dist/presence.js +140 -11
  130. package/dist/priority-embed.js +164 -5
  131. package/dist/providers/embedding-provider.js +196 -1
  132. package/dist/readonly-gate.js +29 -1
  133. package/dist/receipt.js +43 -1
  134. package/dist/rehydration.js +157 -9
  135. package/dist/reindex.js +88 -1
  136. package/dist/render-target.js +544 -21
  137. package/dist/render.js +280 -4
  138. package/dist/repl-guard.js +173 -1
  139. package/dist/replication-daemon-entrypoint.js +31 -1
  140. package/dist/replication-daemon.js +262 -2
  141. package/dist/rerank.js +142 -1
  142. package/dist/resilience.js +591 -1
  143. package/dist/reverse-bridge.js +360 -5
  144. package/dist/security.js +244 -1
  145. package/dist/session-seen.js +51 -3
  146. package/dist/setup.js +260 -1
  147. package/dist/skill-author.js +168 -5
  148. package/dist/spec-kit.js +191 -1
  149. package/dist/sqlite-busy.js +154 -1
  150. package/dist/statusline.js +315 -11
  151. package/dist/sub-agent.js +262 -13
  152. package/dist/summarizer.js +139 -13
  153. package/dist/symbols.js +283 -7
  154. package/dist/sync.js +359 -5
  155. package/dist/tasks-dispatch.js +84 -1
  156. package/dist/tasks.js +282 -1
  157. package/dist/token-budget.js +143 -1
  158. package/dist/tool-analytics.js +129 -7
  159. package/dist/tool-annotations.js +365 -1
  160. package/dist/tool-manifest-v2.json +1 -1
  161. package/dist/tool-manifest.json +1 -1
  162. package/dist/tool-profiles.js +75 -1
  163. package/dist/trace-harvest.js +244 -6
  164. package/dist/types.js +30 -1
  165. package/dist/ui-dashboard.js +50 -41
  166. package/dist/ulid.js +81 -1
  167. package/dist/usage-tracker.js +66 -1
  168. package/dist/validate.js +129 -1
  169. package/dist/vault.js +534 -1
  170. package/dist/vector-init.js +67 -1
  171. package/dist/vectors.js +184 -3
  172. package/dist/version-check.js +136 -4
  173. package/dist/visibility.js +155 -19
  174. package/dist/wyrm-cli.js +2845 -101
  175. package/dist/wyrm-cli.js.map +1 -1
  176. package/dist/wyrm-guard.d.ts.map +1 -1
  177. package/dist/wyrm-guard.js +475 -14
  178. package/dist/wyrm-guard.js.map +1 -1
  179. package/dist/wyrm-loop.js +150 -3
  180. package/dist/wyrm-manifest.json +1 -1
  181. package/dist/wyrm-statusline-daemon.js +11 -1
  182. package/dist/wyrm-statusline.js +56 -4
  183. package/dist/wyrm-ui.js +77 -9
  184. package/package.json +1 -1
package/dist/harvest.js CHANGED
@@ -1,5 +1,191 @@
1
- import{execFileSync as m}from"child_process";import{readFileSync as h,existsSync as g}from"fs";import{join as p}from"path";import{createHash as x}from"crypto";const $=["README.md","CLAUDE.md","AGENTS.md","ARCHITECTURE.md"],k=40,u=o=>x("sha1").update(o).digest("hex").slice(0,8);function y(o){const s=[];for(const c of $){const e=p(o,c);if(!g(e))continue;let n;try{n=h(e,"utf-8")}catch{continue}for(const t of n.split(/\n(?=#{1,4}\s)/)){const i=t.match(/^#{1,4}\s+(.+)/);if(!i)continue;const d=/[\x00-\x1f\x7f]/g,r=i[1].replace(/[#*`]/g,"").replace(d,"").trim(),l=t.slice(i[0].length).split(`
2
- `).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#")&&!a.startsWith("|")&&!a.startsWith("```")).slice(0,3).join(" ").replace(d,"").replace(/\s+/g," ");if(!r||l.length<24)continue;const f=`${r}: ${l}`.slice(0,600);if(s.push({kind:"lesson",text:f,source:`doc:${c}`,sig:`doc:${c}:${u(f)}`,tags:["harvest","doc",c],confidence:.6}),s.length>=k)return s}}return s}const C=/^(merge|wip|typo|fixup|squash|amend|\.+|chore: lint|format)\b/i;function S(o,s=30){if(!g(p(o,".git")))return[];let c;try{c=m("git",["-C",o,"log",`-n${Math.max(1,Math.min(s,200))}`,"--no-merges","--pretty=%h%x09%s"],{encoding:"utf-8",timeout:5e3})}catch{return[]}const e=[];for(const n of c.split(`
3
- `)){const t=n.trim();if(!t)continue;const i=t.indexOf(" ");if(i<0)continue;const d=t.slice(0,i),r=t.slice(i+1).trim();r.length<8||C.test(r)||e.push({kind:"pattern",text:r.slice(0,300),source:"git",sig:`git:${d}`,tags:["harvest","git",`sha:${d}`],confidence:.45})}return e}function v(o){const s=[],c=p(o,"package.json");if(g(c))try{const e=JSON.parse(h(c,"utf-8")),n=Object.keys({...e.dependencies,...e.devDependencies}).slice(0,16),t=Object.keys(e.scripts??{}).slice(0,10);if(n.length||t.length){const i=`Stack (package.json): ${n.join(", ")||"\u2014"}${t.length?` \xB7 scripts: ${t.join(", ")}`:""}`.slice(0,600);s.push({kind:"lesson",text:i,source:"code:package.json",sig:`code:pkg:${u(i)}`,tags:["harvest","code","stack"],confidence:.6})}}catch{}for(const e of["Cargo.toml","composer.json","requirements.txt","pyproject.toml","go.mod","wrangler.toml"]){const n=p(o,e);if(g(n))try{const t=h(n,"utf-8").split(`
4
- `).map(i=>i.trim()).filter(Boolean).slice(0,6).join(" ").replace(/\s+/g," ").slice(0,400);t&&s.push({kind:"lesson",text:`Stack (${e}): ${t}`,source:`code:${e}`,sig:`code:${e}:${u(t)}`,tags:["harvest","code","stack"],confidence:.55})}catch{}}if(g(p(o,".git")))try{const e=m("git",["-C",o,"grep","-nIE","\\b(TODO|FIXME|HACK|XXX)\\b","--","*.ts","*.tsx","*.js","*.py","*.rs","*.go","*.php","*.rb"],{encoding:"utf-8",timeout:6e3,maxBuffer:4194304}),n=/[\x00-\x1f\x7f]/g;let t=0;for(const i of e.split(`
5
- `)){if(t>=25)break;const d=i.trim();if(!d)continue;const r=d.match(/^([^:]+):(\d+):(.*)$/);if(!r)continue;const l=r[3].trim().replace(n,"").slice(0,200);if(l.length<8)continue;const f=`${r[1]}:${r[2]} \u2014 ${l}`;s.push({kind:"anti_pattern",text:f,source:"code:todo",sig:`code:todo:${r[1]}:${r[2]}:${u(l)}`,tags:["harvest","code","todo"],confidence:.4}),t++}}catch{}return s}function b(o,s,c={}){const e=y(s.path),n=S(s.path,c.gitLimit??30),t=c.includeCode?v(s.path):[],i=[...e,...n,...t];let d=0,r=0;const l=[],f=new Set;for(const a of i){if(f.has(a.sig)||o.existsBySig(s.id,a.sig)){r++;continue}f.add(a.sig),c.dryRun||o.addCandidate(s.id,a),d++,l.length<5&&l.push(`[${a.source}] ${a.text.slice(0,80)}`)}return{project:s.name,docFacts:e.length,commits:n.length,codeSignals:t.length,added:d,skipped:r,sample:l}}function R(o,s,c={}){const e=s.map(n=>b(o,n,c));return{reports:e,totalAdded:e.reduce((n,t)=>n+t.added,0),totalSkipped:e.reduce((n,t)=>n+t.skipped,0)}}export{v as harvestCodeSignals,y as harvestDocFacts,S as harvestGitCommits,b as harvestProject,R as harvestProjects};
1
+ /**
2
+ * Wyrm Harvest auto-populate memory from artifacts you ALREADY produce.
3
+ *
4
+ * The corpus is thin because population is manual. Harvest fixes that without a
5
+ * daemon and without noise: it walks a project, pulls durable facts from its
6
+ * docs (README/CLAUDE/AGENTS/ARCHITECTURE) and recent commit subjects from
7
+ * `git log`, and drops them into the REVIEW QUEUE (needs_review = 1) where the
8
+ * operator approves or rejects. Nothing is auto-trusted.
9
+ *
10
+ * Idempotent: every candidate carries a deterministic dedup signature in its
11
+ * tags, so re-running harvest skips what's already there.
12
+ *
13
+ * Pure-ish: I/O is git + fs, but DB access is injected (`HarvestDeps`) so the
14
+ * extraction logic is unit-testable without a database.
15
+ *
16
+ * @copyright 2026 Ghost Protocol (Pvt) Ltd.
17
+ * @license Proprietary — (c) 2026 Ghost Protocol (Pvt) Ltd. All rights reserved. See LICENSE.
18
+ */
19
+ import { execFileSync } from 'child_process';
20
+ import { readFileSync, existsSync } from 'fs';
21
+ import { join } from 'path';
22
+ import { createHash } from 'crypto';
23
+ const DOC_FILES = ['README.md', 'CLAUDE.md', 'AGENTS.md', 'ARCHITECTURE.md'];
24
+ const MAX_DOC_FACTS = 40; // per project — don't flood the review queue
25
+ const hash8 = (s) => createHash('sha1').update(s).digest('hex').slice(0, 8);
26
+ /** Extract durable facts from a project's docs: each heading + its lead paragraph. */
27
+ export function harvestDocFacts(projectPath) {
28
+ const out = [];
29
+ for (const f of DOC_FILES) {
30
+ const p = join(projectPath, f);
31
+ if (!existsSync(p))
32
+ continue;
33
+ let content;
34
+ try {
35
+ content = readFileSync(p, 'utf-8');
36
+ }
37
+ catch {
38
+ continue;
39
+ }
40
+ // Split on markdown headings; keep heading + first ~3 non-empty lines (the fact).
41
+ for (const sec of content.split(/\n(?=#{1,4}\s)/)) {
42
+ const m = sec.match(/^#{1,4}\s+(.+)/);
43
+ if (!m)
44
+ continue;
45
+ // Strip control chars too (an ANSI/BEL byte in a heading shouldn't reach the
46
+ // review queue or a TUI). eslint-disable-next-line no-control-regex
47
+ const ctrl = /[\x00-\x1f\x7f]/g;
48
+ const heading = m[1].replace(/[#*`]/g, '').replace(ctrl, '').trim();
49
+ const body = sec.slice(m[0].length).split('\n').map((l) => l.trim())
50
+ .filter((l) => l && !l.startsWith('#') && !l.startsWith('|') && !l.startsWith('```'))
51
+ .slice(0, 3).join(' ').replace(ctrl, '').replace(/\s+/g, ' ');
52
+ if (!heading || body.length < 24)
53
+ continue; // skip thin/structural sections
54
+ const text = `${heading}: ${body}`.slice(0, 600);
55
+ out.push({
56
+ kind: 'lesson', text, source: `doc:${f}`,
57
+ sig: `doc:${f}:${hash8(text)}`, tags: ['harvest', 'doc', f], confidence: 0.6,
58
+ });
59
+ if (out.length >= MAX_DOC_FACTS)
60
+ return out;
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ const TRIVIAL = /^(merge|wip|typo|fixup|squash|amend|\.+|chore: lint|format)\b/i;
66
+ /** Recent commit subjects as work-record candidates (skips merges/trivial). */
67
+ export function harvestGitCommits(projectPath, limit = 30) {
68
+ if (!existsSync(join(projectPath, '.git')))
69
+ return [];
70
+ let log;
71
+ try {
72
+ log = execFileSync('git', ['-C', projectPath, 'log', `-n${Math.max(1, Math.min(limit, 200))}`,
73
+ '--no-merges', '--pretty=%h%x09%s'], { encoding: 'utf-8', timeout: 5000 });
74
+ }
75
+ catch {
76
+ return [];
77
+ }
78
+ const items = [];
79
+ for (const lineRaw of log.split('\n')) {
80
+ const line = lineRaw.trim();
81
+ if (!line)
82
+ continue;
83
+ const tab = line.indexOf('\t');
84
+ if (tab < 0)
85
+ continue;
86
+ const sha = line.slice(0, tab);
87
+ const subject = line.slice(tab + 1).trim();
88
+ if (subject.length < 8 || TRIVIAL.test(subject))
89
+ continue;
90
+ items.push({
91
+ kind: 'pattern', text: subject.slice(0, 300), source: 'git',
92
+ sig: `git:${sha}`, tags: ['harvest', 'git', `sha:${sha}`], confidence: 0.45,
93
+ });
94
+ }
95
+ return items;
96
+ }
97
+ /**
98
+ * High-signal CODE signals (NOT raw code — that belongs in the symbol index).
99
+ * Two sources: dependency manifests (your real tech stack) and TODO/FIXME/HACK
100
+ * markers (known issues). Bounded so it never floods the review queue.
101
+ */
102
+ export function harvestCodeSignals(projectPath) {
103
+ const out = [];
104
+ // ── package.json → stack fact ──
105
+ const pkgPath = join(projectPath, 'package.json');
106
+ if (existsSync(pkgPath)) {
107
+ try {
108
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
109
+ const deps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).slice(0, 16);
110
+ const scripts = Object.keys(pkg.scripts ?? {}).slice(0, 10);
111
+ if (deps.length || scripts.length) {
112
+ const text = `Stack (package.json): ${deps.join(', ') || '—'}${scripts.length ? ` · scripts: ${scripts.join(', ')}` : ''}`.slice(0, 600);
113
+ out.push({ kind: 'lesson', text, source: 'code:package.json', sig: `code:pkg:${hash8(text)}`, tags: ['harvest', 'code', 'stack'], confidence: 0.6 });
114
+ }
115
+ }
116
+ catch { /* malformed package.json — skip */ }
117
+ }
118
+ // ── other manifests → "uses X" facts (presence + a couple of lead lines) ──
119
+ for (const f of ['Cargo.toml', 'composer.json', 'requirements.txt', 'pyproject.toml', 'go.mod', 'wrangler.toml']) {
120
+ const p = join(projectPath, f);
121
+ if (!existsSync(p))
122
+ continue;
123
+ try {
124
+ const head = readFileSync(p, 'utf-8').split('\n').map((l) => l.trim()).filter(Boolean).slice(0, 6).join(' ').replace(/\s+/g, ' ').slice(0, 400);
125
+ if (head)
126
+ out.push({ kind: 'lesson', text: `Stack (${f}): ${head}`, source: `code:${f}`, sig: `code:${f}:${hash8(head)}`, tags: ['harvest', 'code', 'stack'], confidence: 0.55 });
127
+ }
128
+ catch { /* skip */ }
129
+ }
130
+ // ── TODO/FIXME/HACK/XXX markers via `git grep` (fast, tracked files only, bounded) ──
131
+ if (existsSync(join(projectPath, '.git'))) {
132
+ try {
133
+ const g = execFileSync('git', ['-C', projectPath, 'grep', '-nIE', '\\b(TODO|FIXME|HACK|XXX)\\b',
134
+ '--', '*.ts', '*.tsx', '*.js', '*.py', '*.rs', '*.go', '*.php', '*.rb'], { encoding: 'utf-8', timeout: 6000, maxBuffer: 4 * 1024 * 1024 });
135
+ const ctrl = /[\x00-\x1f\x7f]/g; // eslint-disable-line no-control-regex
136
+ let count = 0;
137
+ for (const lineRaw of g.split('\n')) {
138
+ if (count >= 25)
139
+ break; // cap per project — these go to a review queue
140
+ const line = lineRaw.trim();
141
+ if (!line)
142
+ continue;
143
+ // format: path:lineno:code
144
+ const m = line.match(/^([^:]+):(\d+):(.*)$/);
145
+ if (!m)
146
+ continue;
147
+ const snippet = m[3].trim().replace(ctrl, '').slice(0, 200);
148
+ if (snippet.length < 8)
149
+ continue;
150
+ const text = `${m[1]}:${m[2]} — ${snippet}`;
151
+ out.push({ kind: 'anti_pattern', text, source: 'code:todo', sig: `code:todo:${m[1]}:${m[2]}:${hash8(snippet)}`, tags: ['harvest', 'code', 'todo'], confidence: 0.4 });
152
+ count++;
153
+ }
154
+ }
155
+ catch { /* no matches (git grep exits 1) or not a git repo — fine */ }
156
+ }
157
+ return out;
158
+ }
159
+ /** Harvest one project's docs + git log into the review queue. Idempotent. */
160
+ export function harvestProject(deps, project, opts = {}) {
161
+ const docs = harvestDocFacts(project.path);
162
+ const commits = harvestGitCommits(project.path, opts.gitLimit ?? 30);
163
+ const code = opts.includeCode ? harvestCodeSignals(project.path) : [];
164
+ const items = [...docs, ...commits, ...code];
165
+ let added = 0, skipped = 0;
166
+ const sample = [];
167
+ const seenThisRun = new Set(); // in-run dedup: two identical doc sections share a sig
168
+ for (const it of items) {
169
+ if (seenThisRun.has(it.sig) || deps.existsBySig(project.id, it.sig)) {
170
+ skipped++;
171
+ continue;
172
+ }
173
+ seenThisRun.add(it.sig);
174
+ if (!opts.dryRun)
175
+ deps.addCandidate(project.id, it);
176
+ added++;
177
+ if (sample.length < 5)
178
+ sample.push(`[${it.source}] ${it.text.slice(0, 80)}`);
179
+ }
180
+ return { project: project.name, docFacts: docs.length, commits: commits.length, codeSignals: code.length, added, skipped, sample };
181
+ }
182
+ /** Harvest many projects. Returns a per-project report + totals. */
183
+ export function harvestProjects(deps, projects, opts = {}) {
184
+ const reports = projects.map((p) => harvestProject(deps, p, opts));
185
+ return {
186
+ reports,
187
+ totalAdded: reports.reduce((s, r) => s + r.added, 0),
188
+ totalSkipped: reports.reduce((s, r) => s + r.skipped, 0),
189
+ };
190
+ }
191
+ //# sourceMappingURL=harvest.js.map
package/dist/hours.js CHANGED
@@ -1,13 +1,162 @@
1
- class j{db;constructor(e){this.db=e}report(e){const r=e.default_session_hours??1;let a=`
1
+ /**
2
+ * Hour Ledger + Invoice Generator.
3
+ *
4
+ * Sessions already record start/end timestamps. This module derives:
5
+ * - hours per project / per client / per date range
6
+ * - markdown invoices with per-session line items
7
+ *
8
+ * Solo founders / freelancers use Wyrm for memory; this turns it into
9
+ * their time tracker too — no separate Toggl/Harvest needed.
10
+ *
11
+ * Session duration falls back to a configurable default (e.g. 60 min)
12
+ * when the session has no explicit end_time — common for "I started
13
+ * a session and forgot to close it". The fallback is exposed in the
14
+ * report so the operator can review and correct.
15
+ *
16
+ * @copyright 2026 Ghost Protocol (Pvt) Ltd.
17
+ * @license Proprietary — (c) 2026 Ghost Protocol (Pvt) Ltd. All rights reserved. See LICENSE.
18
+ */
19
+ export class HourLedger {
20
+ db;
21
+ constructor(db) {
22
+ this.db = db;
23
+ }
24
+ /** Hours report for a date range, optionally scoped to a project. */
25
+ report(opts) {
26
+ const fallbackHours = opts.default_session_hours ?? 1.0;
27
+ let sql = `
2
28
  SELECT s.id, s.project_id, s.date, s.objectives, s.completed,
3
29
  s.notes, s.summary, s.created_at, p.name AS project_name
4
30
  FROM sessions s
5
31
  JOIN projects p ON p.id = s.project_id
6
32
  WHERE s.date >= ? AND s.date <= ?
7
33
  AND s.is_archived = 0
8
- `;const c=[e.range_start,e.range_end];e.project_id!=null&&(a+=" AND s.project_id = ?",c.push(e.project_id)),a+=" ORDER BY s.date, s.id";const i=this.db.prepare(a).all(...c),u=[];let d=0,s=0;const o=new Map;for(const t of i){const n=(t.objectives?.length??0)+(t.completed?.length??0)+(t.notes?.length??0)+(t.summary?.length??0),m=n>0?Math.max(r,n/600):r,h=Math.round(m*100)/100,p=n===0;p&&s++,u.push({session_id:t.id,project_id:t.project_id,project_name:t.project_name,date:t.date,hours:h,is_estimated:p,summary:t.summary||t.objectives||t.completed}),d+=h;const _=o.get(t.project_id);_?(_.hours+=h,_.count+=1):o.set(t.project_id,{name:t.project_name,hours:h,count:1})}return{range:{start:e.range_start,end:e.range_end},total_hours:Math.round(d*100)/100,estimated_sessions:s,by_project:Array.from(o.entries()).map(([t,n])=>({project_id:t,project_name:n.name,hours:Math.round(n.hours*100)/100,session_count:n.count})).sort((t,n)=>n.hours-t.hours),entries:u}}invoice(e){const r=this.report({range_start:e.range_start,range_end:e.range_end,project_id:e.project_id,default_session_hours:e.default_session_hours}),a=e.currency??"USD",c=e.hourly_rate_usd,i=r.total_hours*c,u=i,d=e.invoice_number??`INV-${new Date().toISOString().slice(0,10).replace(/-/g,"")}`,s=[];s.push(`# Invoice ${d}`),s.push(""),e.business_name&&(s.push(`**From:** ${e.business_name}`),e.business_address&&s.push(e.business_address.split(`
9
- `).map(o=>` ${o}`).join(`
10
- `)),e.business_contact&&s.push(` ${e.business_contact}`),s.push("")),s.push(`**To:** ${e.client_name}`),e.client_address&&s.push(e.client_address.split(`
11
- `).map(o=>` ${o}`).join(`
12
- `)),s.push(""),s.push(`**Period:** ${r.range.start} \u2192 ${r.range.end}`),s.push(`**Invoice Date:** ${new Date().toISOString().slice(0,10)}`),s.push(`**Rate:** ${a} ${c.toFixed(2)}/hour`),s.push(""),s.push("## Line Items"),s.push(""),s.push("| Date | Project | Hours | Summary |"),s.push("|------|---------|-------|---------|");for(const o of r.entries){const t=(o.summary??"").replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,80),n=o.is_estimated?" *(est.)*":"";s.push(`| ${o.date} | ${o.project_name} | ${o.hours.toFixed(2)}${n} | ${t} |`)}s.push(""),s.push("## Totals"),s.push(""),s.push("| Project | Sessions | Hours |"),s.push("|---------|----------|-------|");for(const o of r.by_project)s.push(`| ${o.project_name} | ${o.session_count} | ${o.hours.toFixed(2)} |`);return s.push(""),s.push(`**Total Hours:** ${r.total_hours.toFixed(2)}`),s.push(`**Subtotal:** ${a} ${i.toFixed(2)}`),s.push(`**Total Due:** ${a} ${u.toFixed(2)}`),s.push(""),r.estimated_sessions>0&&(s.push(`> \u2139\uFE0F ${r.estimated_sessions} session(s) had no recorded work content \u2014 hours estimated at ${e.default_session_hours??1}h default. Review marked rows.`),s.push("")),e.notes&&(s.push("## Notes"),s.push(""),s.push(e.notes),s.push("")),s.join(`
13
- `)}}export{j as HourLedger};
34
+ `;
35
+ const params = [opts.range_start, opts.range_end];
36
+ if (opts.project_id != null) {
37
+ sql += ' AND s.project_id = ?';
38
+ params.push(opts.project_id);
39
+ }
40
+ sql += ' ORDER BY s.date, s.id';
41
+ const rows = this.db.prepare(sql).all(...params);
42
+ const entries = [];
43
+ let totalHours = 0;
44
+ let estimated = 0;
45
+ const byProject = new Map();
46
+ for (const r of rows) {
47
+ // Best-effort: derive hours from session content size + fallback.
48
+ // Sessions store start as `date` (YYYY-MM-DD) and don't have an
49
+ // explicit end. We use a heuristic: count chars across objectives
50
+ // + completed + notes + summary → estimate effort. Floor at fallback.
51
+ const contentChars = (r.objectives?.length ?? 0) +
52
+ (r.completed?.length ?? 0) +
53
+ (r.notes?.length ?? 0) +
54
+ (r.summary?.length ?? 0);
55
+ // ~600 chars/hour is a reasonable summary-density rate for engineering work
56
+ const derived = contentChars > 0 ? Math.max(fallbackHours, contentChars / 600) : fallbackHours;
57
+ const hours = Math.round(derived * 100) / 100;
58
+ const isEstimated = contentChars === 0;
59
+ if (isEstimated)
60
+ estimated++;
61
+ entries.push({
62
+ session_id: r.id,
63
+ project_id: r.project_id,
64
+ project_name: r.project_name,
65
+ date: r.date,
66
+ hours,
67
+ is_estimated: isEstimated,
68
+ summary: r.summary || r.objectives || r.completed,
69
+ });
70
+ totalHours += hours;
71
+ const cur = byProject.get(r.project_id);
72
+ if (cur) {
73
+ cur.hours += hours;
74
+ cur.count += 1;
75
+ }
76
+ else {
77
+ byProject.set(r.project_id, { name: r.project_name, hours, count: 1 });
78
+ }
79
+ }
80
+ return {
81
+ range: { start: opts.range_start, end: opts.range_end },
82
+ total_hours: Math.round(totalHours * 100) / 100,
83
+ estimated_sessions: estimated,
84
+ by_project: Array.from(byProject.entries())
85
+ .map(([id, v]) => ({
86
+ project_id: id,
87
+ project_name: v.name,
88
+ hours: Math.round(v.hours * 100) / 100,
89
+ session_count: v.count,
90
+ }))
91
+ .sort((a, b) => b.hours - a.hours),
92
+ entries,
93
+ };
94
+ }
95
+ /** Generate a markdown invoice from an hour report. */
96
+ invoice(input) {
97
+ const report = this.report({
98
+ range_start: input.range_start,
99
+ range_end: input.range_end,
100
+ project_id: input.project_id,
101
+ default_session_hours: input.default_session_hours,
102
+ });
103
+ const currency = input.currency ?? 'USD';
104
+ const rate = input.hourly_rate_usd;
105
+ const subtotal = report.total_hours * rate;
106
+ const total = subtotal;
107
+ const invoiceNo = input.invoice_number ?? `INV-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}`;
108
+ const lines = [];
109
+ lines.push(`# Invoice ${invoiceNo}`);
110
+ lines.push('');
111
+ if (input.business_name) {
112
+ lines.push(`**From:** ${input.business_name}`);
113
+ if (input.business_address)
114
+ lines.push(input.business_address.split('\n').map(l => ` ${l}`).join('\n'));
115
+ if (input.business_contact)
116
+ lines.push(` ${input.business_contact}`);
117
+ lines.push('');
118
+ }
119
+ lines.push(`**To:** ${input.client_name}`);
120
+ if (input.client_address)
121
+ lines.push(input.client_address.split('\n').map(l => ` ${l}`).join('\n'));
122
+ lines.push('');
123
+ lines.push(`**Period:** ${report.range.start} → ${report.range.end}`);
124
+ lines.push(`**Invoice Date:** ${new Date().toISOString().slice(0, 10)}`);
125
+ lines.push(`**Rate:** ${currency} ${rate.toFixed(2)}/hour`);
126
+ lines.push('');
127
+ lines.push('## Line Items');
128
+ lines.push('');
129
+ lines.push('| Date | Project | Hours | Summary |');
130
+ lines.push('|------|---------|-------|---------|');
131
+ for (const e of report.entries) {
132
+ const summary = (e.summary ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ').slice(0, 80);
133
+ const estimated = e.is_estimated ? ' *(est.)*' : '';
134
+ lines.push(`| ${e.date} | ${e.project_name} | ${e.hours.toFixed(2)}${estimated} | ${summary} |`);
135
+ }
136
+ lines.push('');
137
+ lines.push('## Totals');
138
+ lines.push('');
139
+ lines.push('| Project | Sessions | Hours |');
140
+ lines.push('|---------|----------|-------|');
141
+ for (const p of report.by_project) {
142
+ lines.push(`| ${p.project_name} | ${p.session_count} | ${p.hours.toFixed(2)} |`);
143
+ }
144
+ lines.push('');
145
+ lines.push(`**Total Hours:** ${report.total_hours.toFixed(2)}`);
146
+ lines.push(`**Subtotal:** ${currency} ${subtotal.toFixed(2)}`);
147
+ lines.push(`**Total Due:** ${currency} ${total.toFixed(2)}`);
148
+ lines.push('');
149
+ if (report.estimated_sessions > 0) {
150
+ lines.push(`> ℹ️ ${report.estimated_sessions} session(s) had no recorded work content — hours estimated at ${input.default_session_hours ?? 1.0}h default. Review marked rows.`);
151
+ lines.push('');
152
+ }
153
+ if (input.notes) {
154
+ lines.push('## Notes');
155
+ lines.push('');
156
+ lines.push(input.notes);
157
+ lines.push('');
158
+ }
159
+ return lines.join('\n');
160
+ }
161
+ }
162
+ //# sourceMappingURL=hours.js.map