prjct-cli 2.43.0 → 2.43.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -48
- package/dist/bin/prjct-core.mjs +2 -2
- package/dist/daemon/entry.mjs +1 -1
- package/dist/mcp/server.mjs +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,63 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
-
Vault v2 — signal-first RAG. The generated vault now renders knowledge, not telemetry: on this repo it dropped from 326 files to ~113 with zero information loss (everything stays in SQLite).
|
|
6
|
-
|
|
7
|
-
### Changed
|
|
8
|
-
- **Machine signals quarantined to one `signals.md` dashboard.** Detector output (hot-file churn, skill-miss, friction, recurring bugs — 45% of all entries on a busy project) no longer spawns per-entry notes or tag pages. One page, grouped by section, hot files deduped per path, every row block-anchored so `[[signals#^mem-N|title]]` refs still resolve. The graph shows one hub instead of a dust cloud of `hot-file-NNN` nodes.
|
|
9
|
-
- **Tag pages are link-only.** The old `tags/<key>/<value>.md` model copied every entry's full content into every tag page it appeared on (54% of vault files, all duplicated content). Now: one `tags/<key>.md` index per dimension with values as sections and entries as wikilinks, plus a `tags.md` master index. Dimensions used by fewer than 2 entries get no page (orphan-node guard).
|
|
10
|
-
- **Native Obsidian frontmatter tags.** `tags: { topic: "x" }` (a YAML flow map Obsidian ignores) → `tags: [topic/x]` — graph coloring/filtering and the tag pane now work. Machine bookkeeping keys (source/session/touches/hash/…) are excluded from note bodies and frontmatter; they stay queryable in SQLite.
|
|
11
|
-
- **index.md is a dashboard.** Recent decisions and known traps surface as wikilinks on the landing page; signals get their own section.
|
|
12
|
-
- **Readable filenames.** Slugs cut at word boundaries (no more `…-porque-la-key-guardada-es-de.md`); `retro` entries get per-entry notes.
|
|
13
|
-
|
|
14
|
-
### Fixed
|
|
15
|
-
- **CI/Release no longer resolve bun `latest` per run.** `setup-bun` queried the bun tags API on every workflow run (the 500-prone call that aborted the v2.42.6 release) and silently drifted from local dev. All non-canary jobs now pin via a single `.bun-version` file; the install-compat matrix keeps `latest` deliberately as the canary.
|
|
16
|
-
- **SIGHUP now actually reloads.** The handler refreshed only the explicit-dispatch instance; schema-covered commands kept pre-reload group instances forever (the registry's lazy memos were never reset). Both lazy layers now register resetters and SIGHUP clears them.
|
|
17
|
-
|
|
18
|
-
### Changed
|
|
19
|
-
- **`routingMode: 'cold-only'`** — spec/audit-spec's "shim must serve these cold" condition moves from a side list in scripts/build.js into the manifest; the generated shim skip set is byte-identical, but the truth now lives where a manifest cleanup can't accidentally delete it.
|
|
20
|
-
- **Subagents get the repeat-miss slot** — the "Keeps being missed" entry the session digest gained now reaches subagent digests too (they do most of the editing and were blind to it).
|
|
21
|
-
- **Prune throttle is in-process** — the kv-store counter paid a read+write per session Stop just to decide "skip pruning" 9/10 times; per-process counting is the safe direction (cold runs prune more often, never less).
|
|
22
|
-
|
|
23
|
-
Fixes from a full code review of the v2.42.0–v2.42.4 range (7 review angles, 42 candidates, verified).
|
|
24
|
-
|
|
25
5
|
### Fixed
|
|
26
|
-
- **
|
|
27
|
-
- **`mapOptions` numbers**: non-numeric input for a numeric flag maps to `undefined` (flag ignored) instead of `NaN`.
|
|
28
|
-
|
|
29
|
-
### Changed
|
|
30
|
-
- New CI guard: `manifest-completeness` instantiates every command group and verifies each manifest `routing.method` actually exists — restoring the registration-time validation the lazy refactor deferred to first dispatch.
|
|
31
|
-
- `registerLazyMethod` memoizes the resolved instance+method pair (was re-resolving per dispatch); dead `registerMethod` deleted (single registration mechanism).
|
|
32
|
-
- `runBinCommand` imports moved into the branches that use them — every bin command was paying the `version` branch's chalk/ai-provider/file-helper imports.
|
|
33
|
-
- `compareSemver` deduped to the `schemas/model.ts` implementation; the monotonic-stamp rule shared between `nextKvStamp` and `updateDoc`; `cosineSimilarity` single-sourced over `dot`/`l2Norm`.
|
|
6
|
+
- **CRITICAL: the memory cap no longer deletes knowledge.** `capEntries` (runs on every `prjct sync`) counted ALL `memory.%` events against the 500-row cap — high-churn telemetry (`memory.post_edit` fires on every file edit) inflated the total and the age-ordered delete silently destroyed the OLDEST remembered decisions/gotchas/learnings while keeping hundreds of newer telemetry rows. `memory.remember.*` is now invisible to the cap (count and delete); knowledge leaves the log only via `prjct forget`. The delete is also exact-id based instead of an id-range sweep. If a past sync capped your project: the `memories` mirror table still holds the rows with their original ids — restorable.
|
|
34
7
|
|
|
8
|
+
## [2.43.2] - 2026-06-11
|
|
35
9
|
|
|
36
|
-
|
|
10
|
+
### Bug Fixes
|
|
37
11
|
|
|
38
|
-
|
|
39
|
-
- **Post-upgrade re-setup silently never ran.** `bin/prjct.ts` invoked `setup.run()` through a default export that the ESM-standardization PR (#132, 2026-02) deleted — `bin/` sits outside core's typecheck, so the call threw `TypeError` into its own catch and only stamped the version, on every upgrade, for four months. `run()` is a named export now and bin imports it directly.
|
|
12
|
+
- release job is idempotent — recovery path for partial failures + retried npm publish (#426)
|
|
40
13
|
|
|
41
|
-
### Performance
|
|
42
|
-
- **FTS5 prefix indexes** (migration 29): `searchFts` matches every keyword as a prefix query, but the FTS table had no prefix indexes — each term scanned the full-term index. Recreated with `prefix='2 3 4'` + content rebuild.
|
|
43
|
-
|
|
44
|
-
### Changed
|
|
45
|
-
- **MCP tool descriptions are intent-led.** Six tools (analysis, workflow rules/list/status, signatures, history) were noun phrases with no "when to reach for this"; each now states what it returns and when to use it.
|
|
46
|
-
- **`package.json` overrides documented** in CONTRIBUTING.md — vulnerability class, the PR that introduced each pin (#251/#326), and the removal condition.
|
|
47
14
|
|
|
48
|
-
|
|
49
|
-
- **God-files split.** `infrastructure/setup.ts` (892 → 472) extracted `codex-skill.ts` + `statusline-installer.ts`; `memory/project-memory.ts` (1086 → 660) extracted `entries.ts` (types + row mapping + pure filters) and `format.ts` (markdown rendering). All importers updated per the no-re-export rule.
|
|
50
|
-
- **Dropped the `glob` dependency** — the single call site (monorepo workspace discovery) uses native `node:fs` `globSync` (node ≥22 / bun; the engine floor is already 22.5). `@types/node@22` pinned as a devDependency (types resolved to a transitive v20 that predates `globSync`).
|
|
15
|
+
## [2.43.1] - 2026-06-11
|
|
51
16
|
|
|
52
|
-
###
|
|
53
|
-
- **Daemon command groups load lazily.** `PrjctCommands` and the registry bindings eagerly imported and instantiated all ~18 command-group classes at daemon startup; both now use memoized dynamic-import loaders (new `registerLazyMethod`), so the first socket request stops paying for the whole command tree (daemon module import: 67ms → 40ms warm).
|
|
17
|
+
### Bug Fixes
|
|
54
18
|
|
|
55
|
-
|
|
56
|
-
- **All prjct data paths honor `PRJCT_CLI_HOME`.** New shared lazy resolver (`core/infrastructure/cli-home.ts`); fixed the four sites with no override at all — the embeddings key file, the auto-updater state dir, the context7 verify cache, and session-cleanup's rotation, which had drifted from the writer's path and rotated the user's *real* cache file from test runs.
|
|
57
|
-
- Dropped the dead `daemon start --port/--no-http` flags — parsed for years but never accepted by `startDaemon` (the latent type error only surfaced when the handler moved under core's typecheck).
|
|
19
|
+
- memory cap never deletes knowledge — exclude memory.remember.* from capEntries (#425)
|
|
58
20
|
|
|
59
|
-
### Refactoring
|
|
60
|
-
- **`bin/prjct.ts` split**: the ~550 lines of bin-only command handlers moved to `core/cli/bin-commands.ts` (1082 → 536 lines); the entry point keeps startup concerns only.
|
|
61
|
-
- **`core/workflow/` → `core/workflow-engine/`** — disambiguates the rule engine from `core/workflows/` (implementations).
|
|
62
21
|
|
|
63
22
|
## [2.43.0] - 2026-06-10
|
|
64
23
|
|
package/dist/bin/prjct-core.mjs
CHANGED
|
@@ -637,7 +637,7 @@ CREATE TABLE velocity_sprints (
|
|
|
637
637
|
AND entity_id = ?
|
|
638
638
|
AND content_hash = ?`,e,t.entityType,t.entityId,t.contentHash),E.run(e,`INSERT INTO sync_pending
|
|
639
639
|
(project_id, entity_type, entity_id, event_type, content_hash, payload, enqueued_at)
|
|
640
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`,e,t.entityType??null,t.entityId??null,t.eventType??null,t.contentHash??null,s,r),{id:E.get(e,"SELECT last_insert_rowid() AS id")?.id??0,event:t,enqueuedAt:r}}list(e,t){let r=t?"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC LIMIT ?":"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC";return(t?E.query(e,r,e,t):E.query(e,r,e)).map(o=>this.rowToEntry(o))}count(e){return E.get(e,"SELECT COUNT(*) AS n FROM sync_pending WHERE project_id = ?",e)?.n??0}clearUpTo(e,t){if(t<=0)return 0;let r=this.count(e);return E.run(e,"DELETE FROM sync_pending WHERE project_id = ? AND id <= ?",e,t),r-this.count(e)}clearAll(e){E.run(e,"DELETE FROM sync_pending WHERE project_id = ?",e)}clearByIds(e,t){if(t.length===0)return;let r=t.map(()=>"?").join(",");E.run(e,`DELETE FROM sync_pending WHERE project_id = ? AND id IN (${r})`,e,...t)}rowToEntry(e){let t;try{t=JSON.parse(e.payload)}catch{t={type:"unknown.corrupt",path:[],data:null,timestamp:e.enqueued_at,projectId:e.project_id}}return{id:e.id,event:t,enqueuedAt:e.enqueued_at}}},Gr=new Xu});var Ku,Sn,fa=h(()=>{"use strict";fe();Oy();le();V();Ku=class{static{c(this,"SyncEventBus")}async publish(e){Gr.append(e.projectId,e)}async getPending(e){return Gr.list(e).map(t=>t.event)}async clearPending(e){Gr.clearAll(e)}async getPendingEntries(e){return Gr.list(e)}async clearPendingUpTo(e,t){return Gr.clearUpTo(e,t)}async clearPendingByIds(e,t){Gr.clearByIds(e,t)}async updateLastSync(e){let t=_.getLastSyncPath(e),r={timestamp:T(),success:!0};await we(t,r)}async getLastSync(e){let t=_.getLastSyncPath(e);return await je(t,null)}},Sn=new Ku});var Yu={};A(Yu,{default:()=>tt});import uA from"node:crypto";import Ny from"node:fs/promises";import Ly from"node:os";import dA from"node:path";function Hy(){return uA.randomUUID()}var Uy,Fy,zu,pA,tt,js=h(()=>{"use strict";fe();V();Uy="https://api.prjct.app",Fy={apiKey:null,apiUrl:Uy,userId:null,email:null,lastAuth:null};c(Hy,"freshDeviceId");zu=class{static{c(this,"AuthConfigManager")}configPath;cachedConfig=null;constructor(){this.configPath=_.getAuthConfigPath()}getConfigPath(){return this.configPath}async read(){if(this.cachedConfig)return this.cachedConfig;let e=await je(this.configPath),t=e??{...Fy},r=!1;if(t.deviceId||(t.deviceId=Hy(),r=!0),t.hostname||(t.hostname=Ly.hostname(),r=!0),this.cachedConfig=t,r&&e)try{await we(this.configPath,this.cachedConfig),await Ny.chmod(this.configPath,384)}catch{}return this.cachedConfig}async getDeviceId(){return(await this.read()).deviceId??Hy()}async getHostname(){return(await this.read()).hostname??Ly.hostname()}async write(e){let r={...await this.read(),...e,lastAuth:new Date().toISOString()};await gn(dA.dirname(this.configPath)),await we(this.configPath,r),await Ny.chmod(this.configPath,384),this.cachedConfig=r}async hasAuth(){let e=await this.read();return e.apiKey!==null&&e.apiKey.length>0}async getApiKey(){return(await this.read()).apiKey}async getApiUrl(){return(await this.read()).apiUrl||Uy}async saveAuth(e,t,r){await this.write({apiKey:e,userId:t,email:r})}async clearAuth(){this.cachedConfig={...Fy},await we(this.configPath,this.cachedConfig)}async getStatus(){let e=await this.read();return{authenticated:e.apiKey!==null,email:e.email,apiKeyPrefix:e.apiKey?`${e.apiKey.substring(0,12)}...`:null,lastAuth:e.lastAuth}}clearCache(){this.cachedConfig=null}},pA=new zu,tt=pA});var Gy={};A(Gy,{publishCRUD:()=>Wy,publishCRUDSync:()=>vn});import mA from"node:crypto";function gA(n){let e=n&&typeof n=="object"&&!Array.isArray(n)?JSON.stringify(hA(n)):JSON.stringify(n);return mA.createHash("sha256").update(e).digest("hex")}function hA(n){let e={};for(let t of Object.keys(n).sort())e[t]=n[t];return e}async function yA(){if(Qu)return Qu;try{let{default:n}=await Promise.resolve().then(()=>(js(),Yu)),e=n;if(typeof e.getDeviceId=="function"){let t=await e.getDeviceId();return Qu=t,t}return"unknown-device"}catch{return"unknown-device"}}async function Wy(n){try{let e=await yA(),t=gA(n.data),r={type:`${n.entityType}.${fA[n.eventType]}`,path:[n.entityType,n.entityId],data:n.data,timestamp:new Date().toISOString(),projectId:n.projectId,entityType:n.entityType,entityId:n.entityId,eventType:n.eventType,contentHash:t,deviceId:e,originDeviceId:n.originDeviceId??e,revisionCount:n.revisionCount??1};await Sn.publish(r)}catch{}}function vn(n){Wy(n)}var fA,Qu,Lo=h(()=>{"use strict";fa();fA={upsert:"updated",delete:"deleted"};c(gA,"hashPayload");c(hA,"sortKeys");Qu=null;c(yA,"resolveDeviceId");c(Wy,"publishCRUD");c(vn,"publishCRUDSync")});var Bn,Zu,mt,fr=h(()=>{"use strict";Gn();Lo();le();z();Bn={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Zu=class{static{c(this,"ArchiveStorage")}archive(e,t){let r=qe(),s=T();return P.run(e,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,t.entityType,t.entityId,JSON.stringify(t.entityData),t.summary??null,s,t.reason),vn({projectId:e,entityType:"archives",entityId:r,eventType:"upsert",data:{id:r,entity_type:t.entityType,entity_id:t.entityId,summary:t.summary??null,reason:t.reason,archived_at:s}}),r}archiveMany(e,t){if(t.length===0)return 0;let r=T();return P.transaction(e,s=>{let o=s.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of t)o.run(qe(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,r,i.reason)}),t.length}getArchived(e,t,r=50){return t?P.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,r):P.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(e){let t=P.query(e,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let s of t){let o=s.entity_type;o in r&&(r[o]=s.count),r.total+=s.count}return r}restore(e,t){let r=P.get(e,"SELECT * FROM archives WHERE id = ?",t);return r?(P.run(e,"DELETE FROM archives WHERE id = ?",t),JSON.parse(r.entity_data)):null}pruneOldArchives(e,t){let r=new Date(Date.now()-t*24*60*60*1e3).toISOString(),s=this.getTotalCount(e);P.run(e,"DELETE FROM archives WHERE archived_at < ?",r);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return P.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},mt=new Zu});var ed,Ve,qn=h(()=>{"use strict";te();fr();z();ed=class{static{c(this,"MemoryService")}async log(e,t,r,s){try{let o=await j.getProjectId(e);return o?{eventId:E.appendEvent(o,`memory.${t}`,{...r,author:s}),projectId:o}:null}catch(o){return console.error(`Memory log error: ${o instanceof Error?o.message:String(o)}`),null}}async getRecent(e,t=100){try{let r=await j.getProjectId(e);return r?E.query(r,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(o=>{let i=JSON.parse(o.data),{author:a,...l}=i;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:l,author:a}}):[]}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async search(e,t,r=50){let s=await this.getRecent(e,1e3),o=t.toLowerCase();return s.filter(i=>{let a=i.action.toLowerCase().includes(o),l=JSON.stringify(i.data).toLowerCase().includes(o);return a||l}).slice(-r)}async getByAction(e,t,r=50){try{let s=await j.getProjectId(e);return s?E.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${t}`,r).reverse().map(i=>{let a=JSON.parse(i.data),{author:l,...u}=a;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:l}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(e){try{let t=await j.getProjectId(e);if(!t)return;E.run(t,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(t){console.error(`Memory clear error: ${t instanceof Error?t.message:String(t)}`)}}async getRecentEvents(e,t=100){try{return E.query(e,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>{let o=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...o}})}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async capEntries(e){try{let r=E.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(r<=Bn.MEMORY_MAX_ENTRIES)return 0;let s=r-Bn.MEMORY_MAX_ENTRIES,o=E.query(e,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?",s);mt.archiveMany(e,o.map((a,l)=>({entityType:"memory_entry",entityId:`memory-${a.timestamp||l}`,entityData:{type:a.type,data:JSON.parse(a.data),timestamp:a.timestamp},summary:a.type.replace("memory.",""),reason:"overflow"})));let i=o[o.length-1]?.id;return i!==void 0&&E.run(e,"DELETE FROM events WHERE type LIKE 'memory.%' AND id <= ?",i),s}catch(t){return console.error(`Memory cap error: ${t instanceof Error?t.message:String(t)}`),0}}},Ve=new ed});var By,td,Zt,qy,Br,Fo=h(()=>{"use strict";By="memory.",td="remember.",Zt=`${By}${td}`,qy=`${By}task.tagged`,Br="status.changed"});function nd(n){return!(n.type==="improvement-signal"||n.tags?.pattern==="hot-file")}function Vy(n,e){try{return JSON.parse(n)}catch{return e}}function qr(n){let e=n.type.slice(Zt.length),t=Vy(n.data,{});return{id:`mem_${n.id}`,type:e,content:t.content??"",tags:t.tags??{},rememberedAt:n.timestamp,source:t.source,provenance:t.provenance??"declared"}}function ga(n){let e=n.data?Vy(n.data,{}):{},t=e.tags??{};return n.type&&(t.type=n.type),{id:`ship_${n.id}`,type:"shipped",content:n.name,tags:t,rememberedAt:n.shipped_at,source:e.taskId,provenance:"extracted"}}function Jy(n,e){let t=e.toLowerCase();if(n.content.toLowerCase().includes(t))return!0;for(let r of Object.values(n.tags))if(r.toLowerCase().includes(t))return!0;return!1}function Xy(n,e){for(let[t,r]of Object.entries(e))if(n.tags[t]!==r)return!1;return!0}function Ky(n){let e=new Set,t=[];for(let r of n){let s=r.tags.key;if(!s){t.push(r);continue}let o=`${r.type}::${s}`;e.has(o)||(e.add(o),t.push(r))}return t}function rd(n){let e=new Set;for(let t of n){t.tags["superseded-by"]&&e.add(t.id);for(let r of["supersedes","duplicates"]){let s=t.tags[r];if(s)for(let o of String(s).matchAll(kA))e.add(`mem_${o[1]}`)}}return e}var wA,$s,kA,Ho=h(()=>{"use strict";Fo();wA=["fact","decision","learning","gotcha","pattern","anti-pattern","shipped","inbox","todo","idea","insight","question","source","person","spec"],$s=wA;c(nd,"isModelMemory");c(Vy,"safeJson");c(qr,"rowToEntry");c(ga,"shippedRowToEntry");c(Jy,"matchesTopic");c(Xy,"matchesTags");c(Ky,"dedupeLatestByKey");kA=/\bmem[_-](\d+)\b/g;c(rd,"collectSupersededIds")});var id={};A(id,{extractCorrectionIds:()=>od,extractRefIds:()=>Yy,usefulnessService:()=>Vn});function Yy(n,e){let t=new Set;for(let r of PA){let s=e[r];if(s)for(let o of String(s).matchAll(sd))t.add(`mem_${o[1]}`)}for(let r of n.matchAll(sd))t.add(`mem_${r[1]}`);for(let r of od(e))t.delete(r);return[...t]}function od(n){let e=new Set;for(let t of AA){let r=n[t];if(r)for(let s of String(r).matchAll(sd))e.add(`mem_${s[1]}`)}return[...e]}function zy(n,e,t,r,s){E.run(n,`INSERT INTO memory_usefulness (memory_id, score, ${r}, last_used_at)
|
|
640
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,e,t.entityType??null,t.entityId??null,t.eventType??null,t.contentHash??null,s,r),{id:E.get(e,"SELECT last_insert_rowid() AS id")?.id??0,event:t,enqueuedAt:r}}list(e,t){let r=t?"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC LIMIT ?":"SELECT * FROM sync_pending WHERE project_id = ? ORDER BY id ASC";return(t?E.query(e,r,e,t):E.query(e,r,e)).map(o=>this.rowToEntry(o))}count(e){return E.get(e,"SELECT COUNT(*) AS n FROM sync_pending WHERE project_id = ?",e)?.n??0}clearUpTo(e,t){if(t<=0)return 0;let r=this.count(e);return E.run(e,"DELETE FROM sync_pending WHERE project_id = ? AND id <= ?",e,t),r-this.count(e)}clearAll(e){E.run(e,"DELETE FROM sync_pending WHERE project_id = ?",e)}clearByIds(e,t){if(t.length===0)return;let r=t.map(()=>"?").join(",");E.run(e,`DELETE FROM sync_pending WHERE project_id = ? AND id IN (${r})`,e,...t)}rowToEntry(e){let t;try{t=JSON.parse(e.payload)}catch{t={type:"unknown.corrupt",path:[],data:null,timestamp:e.enqueued_at,projectId:e.project_id}}return{id:e.id,event:t,enqueuedAt:e.enqueued_at}}},Gr=new Xu});var Ku,Sn,fa=h(()=>{"use strict";fe();Oy();le();V();Ku=class{static{c(this,"SyncEventBus")}async publish(e){Gr.append(e.projectId,e)}async getPending(e){return Gr.list(e).map(t=>t.event)}async clearPending(e){Gr.clearAll(e)}async getPendingEntries(e){return Gr.list(e)}async clearPendingUpTo(e,t){return Gr.clearUpTo(e,t)}async clearPendingByIds(e,t){Gr.clearByIds(e,t)}async updateLastSync(e){let t=_.getLastSyncPath(e),r={timestamp:T(),success:!0};await we(t,r)}async getLastSync(e){let t=_.getLastSyncPath(e);return await je(t,null)}},Sn=new Ku});var Yu={};A(Yu,{default:()=>tt});import uA from"node:crypto";import Ny from"node:fs/promises";import Ly from"node:os";import dA from"node:path";function Hy(){return uA.randomUUID()}var Uy,Fy,zu,pA,tt,js=h(()=>{"use strict";fe();V();Uy="https://api.prjct.app",Fy={apiKey:null,apiUrl:Uy,userId:null,email:null,lastAuth:null};c(Hy,"freshDeviceId");zu=class{static{c(this,"AuthConfigManager")}configPath;cachedConfig=null;constructor(){this.configPath=_.getAuthConfigPath()}getConfigPath(){return this.configPath}async read(){if(this.cachedConfig)return this.cachedConfig;let e=await je(this.configPath),t=e??{...Fy},r=!1;if(t.deviceId||(t.deviceId=Hy(),r=!0),t.hostname||(t.hostname=Ly.hostname(),r=!0),this.cachedConfig=t,r&&e)try{await we(this.configPath,this.cachedConfig),await Ny.chmod(this.configPath,384)}catch{}return this.cachedConfig}async getDeviceId(){return(await this.read()).deviceId??Hy()}async getHostname(){return(await this.read()).hostname??Ly.hostname()}async write(e){let r={...await this.read(),...e,lastAuth:new Date().toISOString()};await gn(dA.dirname(this.configPath)),await we(this.configPath,r),await Ny.chmod(this.configPath,384),this.cachedConfig=r}async hasAuth(){let e=await this.read();return e.apiKey!==null&&e.apiKey.length>0}async getApiKey(){return(await this.read()).apiKey}async getApiUrl(){return(await this.read()).apiUrl||Uy}async saveAuth(e,t,r){await this.write({apiKey:e,userId:t,email:r})}async clearAuth(){this.cachedConfig={...Fy},await we(this.configPath,this.cachedConfig)}async getStatus(){let e=await this.read();return{authenticated:e.apiKey!==null,email:e.email,apiKeyPrefix:e.apiKey?`${e.apiKey.substring(0,12)}...`:null,lastAuth:e.lastAuth}}clearCache(){this.cachedConfig=null}},pA=new zu,tt=pA});var Gy={};A(Gy,{publishCRUD:()=>Wy,publishCRUDSync:()=>vn});import mA from"node:crypto";function gA(n){let e=n&&typeof n=="object"&&!Array.isArray(n)?JSON.stringify(hA(n)):JSON.stringify(n);return mA.createHash("sha256").update(e).digest("hex")}function hA(n){let e={};for(let t of Object.keys(n).sort())e[t]=n[t];return e}async function yA(){if(Qu)return Qu;try{let{default:n}=await Promise.resolve().then(()=>(js(),Yu)),e=n;if(typeof e.getDeviceId=="function"){let t=await e.getDeviceId();return Qu=t,t}return"unknown-device"}catch{return"unknown-device"}}async function Wy(n){try{let e=await yA(),t=gA(n.data),r={type:`${n.entityType}.${fA[n.eventType]}`,path:[n.entityType,n.entityId],data:n.data,timestamp:new Date().toISOString(),projectId:n.projectId,entityType:n.entityType,entityId:n.entityId,eventType:n.eventType,contentHash:t,deviceId:e,originDeviceId:n.originDeviceId??e,revisionCount:n.revisionCount??1};await Sn.publish(r)}catch{}}function vn(n){Wy(n)}var fA,Qu,Lo=h(()=>{"use strict";fa();fA={upsert:"updated",delete:"deleted"};c(gA,"hashPayload");c(hA,"sortKeys");Qu=null;c(yA,"resolveDeviceId");c(Wy,"publishCRUD");c(vn,"publishCRUDSync")});var Bn,Zu,mt,fr=h(()=>{"use strict";Gn();Lo();le();z();Bn={SHIPPED_RETENTION_DAYS:90,IDEA_DORMANT_DAYS:180,QUEUE_COMPLETED_DAYS:7,PAUSED_TASK_DAYS:30,MEMORY_MAX_ENTRIES:500},Zu=class{static{c(this,"ArchiveStorage")}archive(e,t){let r=qe(),s=T();return P.run(e,"INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)",r,t.entityType,t.entityId,JSON.stringify(t.entityData),t.summary??null,s,t.reason),vn({projectId:e,entityType:"archives",entityId:r,eventType:"upsert",data:{id:r,entity_type:t.entityType,entity_id:t.entityId,summary:t.summary??null,reason:t.reason,archived_at:s}}),r}archiveMany(e,t){if(t.length===0)return 0;let r=T();return P.transaction(e,s=>{let o=s.prepare("INSERT INTO archives (id, entity_type, entity_id, entity_data, summary, archived_at, reason) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let i of t)o.run(qe(),i.entityType,i.entityId,JSON.stringify(i.entityData),i.summary??null,r,i.reason)}),t.length}getArchived(e,t,r=50){return t?P.query(e,"SELECT * FROM archives WHERE entity_type = ? ORDER BY archived_at DESC LIMIT ?",t,r):P.query(e,"SELECT * FROM archives ORDER BY archived_at DESC LIMIT ?",r)}getStats(e){let t=P.query(e,"SELECT entity_type, COUNT(*) as count FROM archives GROUP BY entity_type"),r={shipped:0,idea:0,queue_task:0,paused_task:0,memory_entry:0,total:0};for(let s of t){let o=s.entity_type;o in r&&(r[o]=s.count),r.total+=s.count}return r}restore(e,t){let r=P.get(e,"SELECT * FROM archives WHERE id = ?",t);return r?(P.run(e,"DELETE FROM archives WHERE id = ?",t),JSON.parse(r.entity_data)):null}pruneOldArchives(e,t){let r=new Date(Date.now()-t*24*60*60*1e3).toISOString(),s=this.getTotalCount(e);P.run(e,"DELETE FROM archives WHERE archived_at < ?",r);let o=this.getTotalCount(e);return s-o}getTotalCount(e){return P.get(e,"SELECT COUNT(*) as count FROM archives")?.count??0}},mt=new Zu});var ed,Ve,qn=h(()=>{"use strict";te();fr();z();ed=class{static{c(this,"MemoryService")}async log(e,t,r,s){try{let o=await j.getProjectId(e);return o?{eventId:E.appendEvent(o,`memory.${t}`,{...r,author:s}),projectId:o}:null}catch(o){return console.error(`Memory log error: ${o instanceof Error?o.message:String(o)}`),null}}async getRecent(e,t=100){try{let r=await j.getProjectId(e);return r?E.query(r,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(o=>{let i=JSON.parse(o.data),{author:a,...l}=i;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:l,author:a}}):[]}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async search(e,t,r=50){let s=await this.getRecent(e,1e3),o=t.toLowerCase();return s.filter(i=>{let a=i.action.toLowerCase().includes(o),l=JSON.stringify(i.data).toLowerCase().includes(o);return a||l}).slice(-r)}async getByAction(e,t,r=50){try{let s=await j.getProjectId(e);return s?E.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${t}`,r).reverse().map(i=>{let a=JSON.parse(i.data),{author:l,...u}=a;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:l}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(e){try{let t=await j.getProjectId(e);if(!t)return;E.run(t,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(t){console.error(`Memory clear error: ${t instanceof Error?t.message:String(t)}`)}}async getRecentEvents(e,t=100){try{return E.query(e,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>{let o=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...o}})}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async capEntries(e){try{let r=E.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%' AND type NOT LIKE 'memory.remember.%'")?.cnt??0;if(r<=Bn.MEMORY_MAX_ENTRIES)return 0;let s=r-Bn.MEMORY_MAX_ENTRIES,o=E.query(e,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' AND type NOT LIKE 'memory.remember.%' ORDER BY id ASC LIMIT ?",s);return mt.archiveMany(e,o.map((i,a)=>({entityType:"memory_entry",entityId:`memory-${i.timestamp||a}`,entityData:{type:i.type,data:JSON.parse(i.data),timestamp:i.timestamp},summary:i.type.replace("memory.",""),reason:"overflow"}))),E.transaction(e,i=>{let a=i.prepare("DELETE FROM events WHERE id = ?");for(let l of o)a.run(l.id)}),s}catch(t){return console.error(`Memory cap error: ${t instanceof Error?t.message:String(t)}`),0}}},Ve=new ed});var By,td,Zt,qy,Br,Fo=h(()=>{"use strict";By="memory.",td="remember.",Zt=`${By}${td}`,qy=`${By}task.tagged`,Br="status.changed"});function nd(n){return!(n.type==="improvement-signal"||n.tags?.pattern==="hot-file")}function Vy(n,e){try{return JSON.parse(n)}catch{return e}}function qr(n){let e=n.type.slice(Zt.length),t=Vy(n.data,{});return{id:`mem_${n.id}`,type:e,content:t.content??"",tags:t.tags??{},rememberedAt:n.timestamp,source:t.source,provenance:t.provenance??"declared"}}function ga(n){let e=n.data?Vy(n.data,{}):{},t=e.tags??{};return n.type&&(t.type=n.type),{id:`ship_${n.id}`,type:"shipped",content:n.name,tags:t,rememberedAt:n.shipped_at,source:e.taskId,provenance:"extracted"}}function Jy(n,e){let t=e.toLowerCase();if(n.content.toLowerCase().includes(t))return!0;for(let r of Object.values(n.tags))if(r.toLowerCase().includes(t))return!0;return!1}function Xy(n,e){for(let[t,r]of Object.entries(e))if(n.tags[t]!==r)return!1;return!0}function Ky(n){let e=new Set,t=[];for(let r of n){let s=r.tags.key;if(!s){t.push(r);continue}let o=`${r.type}::${s}`;e.has(o)||(e.add(o),t.push(r))}return t}function rd(n){let e=new Set;for(let t of n){t.tags["superseded-by"]&&e.add(t.id);for(let r of["supersedes","duplicates"]){let s=t.tags[r];if(s)for(let o of String(s).matchAll(kA))e.add(`mem_${o[1]}`)}}return e}var wA,$s,kA,Ho=h(()=>{"use strict";Fo();wA=["fact","decision","learning","gotcha","pattern","anti-pattern","shipped","inbox","todo","idea","insight","question","source","person","spec"],$s=wA;c(nd,"isModelMemory");c(Vy,"safeJson");c(qr,"rowToEntry");c(ga,"shippedRowToEntry");c(Jy,"matchesTopic");c(Xy,"matchesTags");c(Ky,"dedupeLatestByKey");kA=/\bmem[_-](\d+)\b/g;c(rd,"collectSupersededIds")});var id={};A(id,{extractCorrectionIds:()=>od,extractRefIds:()=>Yy,usefulnessService:()=>Vn});function Yy(n,e){let t=new Set;for(let r of PA){let s=e[r];if(s)for(let o of String(s).matchAll(sd))t.add(`mem_${o[1]}`)}for(let r of n.matchAll(sd))t.add(`mem_${r[1]}`);for(let r of od(e))t.delete(r);return[...t]}function od(n){let e=new Set;for(let t of AA){let r=n[t];if(r)for(let s of String(r).matchAll(sd))e.add(`mem_${s[1]}`)}return[...e]}function zy(n,e,t,r,s){E.run(n,`INSERT INTO memory_usefulness (memory_id, score, ${r}, last_used_at)
|
|
641
641
|
VALUES (?, ?, 1, ?)
|
|
642
642
|
ON CONFLICT(memory_id) DO UPDATE SET
|
|
643
643
|
score = score + ?, ${r} = ${r} + 1, last_used_at = excluded.last_used_at`,e,t,s,t)}function ha(n,e,t,r){E.run(n,`INSERT INTO memory_usefulness (memory_id, score, last_used_at)
|
|
@@ -1774,7 +1774,7 @@ if [ -f "$CONFIG" ]; then
|
|
|
1774
1774
|
fi
|
|
1775
1775
|
fi
|
|
1776
1776
|
echo "prjct"
|
|
1777
|
-
`;await Ne.writeFile(s,k,{mode:493})}await jx(t,s),await Ax(e,t)}catch(n){H(n)||B.warn(`Status line warning: ${w(n)}`)}}async function Ll(n,e){if(!await v(n))return;let t=await Ne.readdir(n);for(let r of t)if(r.endsWith(".sh")){let s=Qe.join(n,r),o=Qe.join(e,r);await Ne.copyFile(s,o),await Ne.chmod(o,493)}}async function jx(n,e){try{if(await v(n)){if((await Ne.lstat(n)).isSymbolicLink()&&await Ne.readlink(n)===e)return;await Ne.unlink(n)}await Ne.symlink(e,n)}catch{try{await v(e)&&(await Ne.copyFile(e,n),await Ne.chmod(n,493))}catch(r){H(r)||B.warn(`Symlink fallback warning: ${r.message}`)}}}var _x=h(()=>{"use strict";N();V();$t();$e();fe();c(Ax,"ensureStatusLineSettings");c($x,"installStatusLine");c(Ll,"installStatusLineModules");c(jx,"ensureStatusLineSymlink")});var Dx={};A(Dx,{run:()=>Ix});import{execFileSync as eF}from"node:child_process";import nr from"node:fs/promises";import ph from"node:os";import rr from"node:path";import ve from"chalk";async function tF(n){let e=n.name==="claude"?"@anthropic-ai/claude-code":"@google/gemini-cli";if(!xx.isAvailable("npm"))return console.log(`${ve.yellow("\u26A0\uFE0F npm is not available")}`),console.log(""),console.log(`${ve.dim(`Install ${n.displayName} using one of:`)}`),console.log(ve.dim(" \u2022 Install Node.js: https://nodejs.org")),console.log(ve.dim(` \u2022 Use Homebrew: brew install ${n.name==="claude"?"claude":"gemini"}`)),console.log(ve.dim(` \u2022 Use npx directly: npx ${e}`)),console.log(""),!1;try{return console.log(ve.yellow(`\u{1F4E6} ${n.displayName} not found. Installing...`)),console.log(""),eF("npm",["install","-g",e],{stdio:"inherit",timeout:Ls("NPM_INSTALL")}),console.log(""),console.log(`${ve.green("\u2713")} ${n.displayName} installed successfully`),console.log(""),!0}catch(t){let r=t;return r.killed&&r.signal==="SIGTERM"?(console.log(ve.yellow(`\u26A0\uFE0F Installation timed out for ${n.displayName}`)),console.log(""),console.log(ve.dim("The npm install took too long. Try:")),console.log(ve.dim(" \u2022 Set PRJCT_TIMEOUT_NPM_INSTALL=300000 for 5 minutes")),console.log(ve.dim(` \u2022 Run manually: npm install -g ${e}`))):console.log(ve.yellow(`\u26A0\uFE0F Failed to install ${n.displayName}: ${r.message}`)),console.log(""),console.log(ve.dim("Alternative installation methods:")),console.log(ve.dim(` \u2022 npm: npm install -g ${e}`)),console.log(ve.dim(` \u2022 yarn: yarn global add ${e}`)),console.log(ve.dim(` \u2022 pnpm: pnpm add -g ${e}`)),console.log(ve.dim(` \u2022 brew: brew install ${n.name==="claude"?"claude":"gemini"}`)),console.log(""),!1}}async function Ix(){let n=await Hn(),e=await Su(),t={provider:e.provider,providers:[],cliInstalled:!1,commandsAdded:0,commandsUpdated:0,configAction:null},r=["claude","gemini"];for(let i of r){let a=yt[i],l=n[i],u={provider:i,cliInstalled:!1,commandsAdded:0,commandsUpdated:0,configAction:null};if(!l.installed)if(i===e.provider)if(await tF(a))u.cliInstalled=!0,t.cliInstalled=!0;else throw new Error(`${a.displayName} installation failed`);else continue;if(i==="claude"){if(await Le.detectActiveProvider()){let p=await Le.syncCommands();p.success&&(u.commandsAdded=p.added,u.commandsUpdated=p.updated,t.commandsAdded+=p.added,t.commandsUpdated+=p.updated);let m=await Le.installGlobalConfig();m.success&&(u.configAction=m.action,t.configAction||(t.configAction=m.action)),await Le.installDocs(),await $x(),await xn.ensureReady()}}else if(i==="gemini"){await nF()&&(u.commandsAdded=1,t.commandsAdded+=1);let p=await rF();p.success&&(u.configAction=p.action)}t.providers.push(u)}if((await Do()).installed&&(await sF()).success&&console.log(` ${ve.green("\u2713")} Antigravity skill installed`),(await dr()).installed){if(!(await kc()).success)throw new Error("Codex skill installation failed");let a=await ns({autoRepair:!0});if(!a.verified)throw new Error(a.message||"Codex p. router verification failed");console.log(` ${ve.green("\u2713")} Codex skill installed`),console.log(` ${ve.green("\u2713")} Codex p. router ready`)}await bi.saveConfig(se,await Le.getInstallPath(),e.provider),await oF();for(let i of t.providers)iF(i,yt[i.provider]);return t}async function nF(){try{let n=rr.join(ph.homedir(),".gemini","commands"),e=rr.join(n,"p.toml");try{return await nr.unlink(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}catch(n){return B.warn(`Gemini router cleanup warning: ${w(n)}`),!1}}async function rF(){try{let n=rr.join(ph.homedir(),".gemini"),e=rr.join(n,"GEMINI.md");await nr.mkdir(n,{recursive:!0});let t=Be("global/GEMINI.md");if(!t){let l=rr.join(dt,"templates","global","GEMINI.md");t=await nr.readFile(l,"utf-8")}let r="",s=!1;try{r=await nr.readFile(e,"utf-8"),s=!0}catch(l){if(H(l))s=!1;else throw l}let a=Rs(s?r:"",t,"<!-- prjct:start - DO NOT REMOVE THIS MARKER -->","<!-- prjct:end - DO NOT REMOVE THIS MARKER -->");return await nr.writeFile(e,a.content,"utf-8"),{success:!0,action:a.action}}catch(n){return B.warn(`Gemini config warning: ${w(n)}`),{success:!1,action:null}}}async function sF(){try{let n=rr.join(ph.homedir(),".gemini","antigravity","skills"),e=rr.join(n,"prjct"),t=rr.join(e,"SKILL.md");await nr.mkdir(e,{recursive:!0});let r=await v(t),s=Be("antigravity/SKILL.md");if(!s){let o=rr.join(dt,"templates","antigravity","SKILL.md");if(!await v(o))return B.warn("Antigravity SKILL.md template not found"),{success:!1,action:null};s=await nr.readFile(o,"utf-8")}return await nr.writeFile(t,s,"utf-8"),{success:!0,action:r?"updated":"created"}}catch(n){return B.warn(`Antigravity skill warning: ${w(n)}`),{success:!1,action:null}}}async function oF(){try{let n=_.globalProjectsDir;if(!await v(n))return;let e=(await nr.readdir(n,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name),t=0;for(let r of e)try{let s=P.getDoc(r,"project");if(!s)continue;s.cliVersion!==se&&(s.cliVersion=se,P.setDoc(r,"project",s),t++)}catch{}t>0&&console.log(` ${ve.green("\u2713")} Updated ${t} project(s) to v${se}`)}catch(n){H(n)||B.warn(`Migration warning: ${w(n)}`)}}function iF(n,e){if(console.log(""),n.cliInstalled?console.log(` ${ve.green("\u2713")} ${e.displayName} CLI installed`):console.log(` ${ve.green("\u2713")} ${e.displayName} CLI found`),n.commandsAdded+n.commandsUpdated>0){let r=[];n.commandsAdded>0&&r.push(`${n.commandsAdded} new`),n.commandsUpdated>0&&r.push(`${n.commandsUpdated} updated`),console.log(` ${ve.green("\u2713")} Commands synced (${r.join(", ")})`)}else console.log(` ${ve.green("\u2713")} Commands up to date`);n.configAction==="created"?console.log(` ${ve.green("\u2713")} Global config created (${e.contextFile})`):n.configAction==="updated"?console.log(` ${ve.green("\u2713")} Global config updated (${e.contextFile})`):n.configAction==="appended"&&console.log(` ${ve.green("\u2713")} Global config merged (${e.contextFile})`),console.log("")}var aF,Mx=h(()=>{"use strict";wn();Js();Px();z();N();qa();V();$t();$e();Xe();zs();Qt();pl();ca();fe();_x();c(tF,"installAICLI");c(Ix,"run");c(nF,"installGeminiRouter");c(rF,"installGeminiGlobalConfig");c(sF,"installAntigravitySkill");c(oF,"migrateProjectsCliVersion");c(iF,"showResults");aF=process.argv[1]?.includes("setup.ts")||process.argv[1]?.includes("setup.js");aF&&Ix().catch(n=>{console.error("Setup error:",n.message),process.exit(1)})});var Ox=Xx((aoe,cF)=>{cF.exports={name:"prjct-cli",version:"2.43.0",description:"Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",main:"dist/bin/prjct.mjs",bin:{prjct:"bin/prjct"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},scripts:{build:"node scripts/build.js","build:node":"node scripts/build.js",release:"node scripts/release.js","release:patch":"node scripts/release.js patch","release:minor":"node scripts/release.js minor","release:major":"node scripts/release.js major",prepare:"lefthook install","update-commands":`bun -e "const installer = require('./core/infrastructure/command-installer'); installer.syncCommands().then(r => console.log('Commands updated:', r)).catch(e => console.error('Error:', e.message))"`,"install-global":"./scripts/install.sh",update:"./scripts/update.sh",test:"bun test","test:watch":"bun test --watch","test:coverage":"bun test --coverage",typecheck:"tsc --noEmit -p core/tsconfig.json","typecheck:watch":"tsc --noEmit -p core/tsconfig.json --watch",validate:"bun scripts/validate-commands.js",lint:"biome lint .","lint:fix":"biome lint --write .",knip:"knip","lint:meta":"bun core/cli/lint-meta-commentary.ts",format:"biome format --write .","format:check":"biome format .",check:"biome check .","check:fix":"biome check --write .","test:e2e":"bun test core/__tests__/e2e/"},keywords:["claude-code","gemini-cli","ai-agents","context-layer","developer-tools","ai-assistant","productivity","mcp","llm","coding-agents"],author:"prjct.app",license:"MIT",dependencies:{"@clack/prompts":"1.0.0","@modelcontextprotocol/sdk":"1.29.0",chalk:"4.1.2",chokidar:"5.0.0","jsonc-parser":"3.3.1",zod:"3.25.76"},overrides:{"path-to-regexp":"8.4.0","brace-expansion":"5.0.5","fast-uri":">=3.1.2",hono:">=4.12.18","ip-address":">=10.1.1"},devDependencies:{"@biomejs/biome":"2.3.13","@types/bun":"latest","@types/chokidar":"2.1.7","@types/node":"^22",esbuild:"0.25.0",knip:"6.3.1",lefthook:"2.1.0",typescript:"5.9.3"},repository:{type:"git",url:"git+https://github.com/jlopezlira/prjct-cli.git"},bugs:{url:"https://github.com/jlopezlira/prjct-cli/issues"},homepage:"https://prjct.app",packageManager:"bun@1.2.23",engines:{bun:">=1.0.0",node:">=22.5.0"},files:["assets/","bin/prjct","dist/","templates/","scripts/ensure-bun.sh","scripts/install.sh","LICENSE","README.md","CHANGELOG.md"],prepublishOnly:"node scripts/build.js"}});var fF={};import Nx from"node:os";import Fl from"node:path";import fs from"chalk";async function lF(){let[n,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(n)){let r=await Promise.resolve().then(()=>Kx(Ox()));await pF(r.version),process.exit(0)}if(["-h","--help",void 0].includes(n)&&(mF(),process.exit(0)),n&&jl(n)&&!Ue.getByName(n)){let r=Al[n];r&&(g.failWithHint({message:`'prjct ${n}' was removed in v2. ${r.note}`,hint:`Use: ${r.replacement}`}),process.exit(1))}if(n&&!Ue.getByName(n)&&!(e.length===0&&Pi(n)!==null)){let s=[n,...e.filter(i=>!i.startsWith("-"))].join(" "),o=e.filter(i=>i.startsWith("-"));n="capture",e=[s,...o]}let t=e.includes("--md");t||g.start();try{let r=Ue.getByName(n);if(!r){let m=Pi(n),f=m?`Did you mean 'prjct ${m}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";g.failWithHint(ei("UNKNOWN_COMMAND",{message:`Unknown command: ${n}`,hint:f})),t||g.end(),process.exit(1)}if(r.deprecated){let m=r.replacedBy?`Use 'prjct ${r.replacedBy}' instead`:"Run 'prjct --help' to see available commands";g.failWithHint({message:`Command '${n}' is deprecated`,hint:m}),t||g.end(),process.exit(1)}r.implemented||(g.failWithHint({message:`Command '${n}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),t||g.end(),process.exit(1));let{parsedArgs:s,options:o}=dF(r,e),i=!process.stdin.isTTY||o.md===!0||o.json===!0;r.requiresLlm&&!i&&(g.failWithHint({message:`'prjct ${n}' requires an AI agent to process its output`,hint:`Use 'p. ${n}' inside Claude/Cursor, or add --md flag`}),t||g.end(),process.exit(1));let a=uF(r,s);a&&(g.failWithHint(a),t||g.end(),process.exit(1));let l=null,u=Date.now();try{l=await j.getProjectId(process.cwd()),l&&(await ro.expireIfStale(l),await ro.touch(l))}catch{}let d=new $r,p;if(n==="analyze")p=await d.analyze(o);else if(n==="setup")p=await d.setup(o);else if(n==="update"||n==="upgrade")p=await d.update(o);else{let m=s.join(" ")||null,f=o.md===!0,y=Ue.getByName(n);if(y?.optionSchema)p=await Ue.executeWithOptions(n,m,process.cwd(),Pl(o,y.optionSchema));else{let b={spec:c(S=>$l(d,(S??"").trim().split(/\s+/).filter(Boolean),o,process.cwd()),"spec"),"audit-spec":c(S=>S?d.specAudit(S,process.cwd(),{md:f}):Promise.resolve({success:!1,error:"audit-spec requires a spec id"}),"audit-spec"),init:c(S=>d.init({idea:S,yes:o.yes===!0,pack:o.pack?String(o.pack):void 0,persona:o.persona?String(o.persona):void 0}),"init"),sync:c(()=>d.sync(process.cwd(),{preview:o.preview===!0||o["dry-run"]===!0,yes:o.yes===!0,json:o.json===!0,md:f,package:o.package?String(o.package):void 0,full:o.full===!0}),"sync"),"analysis-save-llm":c(S=>S?d.saveLlmAnalysis(S,process.cwd(),{md:f}):Promise.resolve({success:!1,error:"analysis-save-llm requires a JSON payload as positional arg"}),"analysis-save-llm"),regen:c(()=>d.regenVault(process.cwd(),{md:f}),"regen"),start:c(()=>d.start(),"start"),login:c(()=>d.login({md:f,url:o.url?String(o.url):void 0}),"login"),logout:c(()=>d.logout(),"logout"),auth:c(S=>d.auth(S,{md:f}),"auth")}[n];if(b)p=await b(m);else throw new Error(`Command '${n}' has no handler`)}}if(l){let m=Date.now()-u;try{await ro.trackCommand(l,n,m)}catch{}try{await Si.recordTiming(l,"command_duration",m,{command:n});let f=globalThis.__perfStartNs;if(f){let y=Number(process.hrtime.bigint()-f)/1e6;await Si.recordTiming(l,"startup_time",y)}await Si.recordMemory(l,{command:n})}catch{}}p?.message&&console.log(p.message),t||g.end(),process.exit(p?.success?0:1)}catch(r){console.error("Error:",w(r)),process.env.DEBUG&&console.error(su(r)),t||g.end(),process.exit(1)}}function uF(n,e){if(!n.params)return null;let t=n.params.match(/<[^>]+>/g);if(!t||t.length===0)return null;if(e.length<t.length){let r=t.map(o=>o.slice(1,-1)).join(", "),s=n.usage.terminal||`prjct ${n.name} ${n.params}`;return ei("MISSING_PARAM",{message:`Missing required parameter: ${r}`,hint:`Usage: ${s}`})}return null}function dF(n,e){let t=[],r={};for(let s=0;s<e.length;s++){let o=e[s];if(o.startsWith("--")){let i=o.slice(2);s+1<e.length&&!e[s+1].startsWith("--")?r[i]=e[++s]:r[i]=!0}else t.push(o)}return{parsedArgs:t,options:r}}async function pF(n){let e=await Hn(),t=Fl.join(Nx.homedir(),".claude","commands","p.md"),r=Fl.join(Nx.homedir(),".gemini","commands","p.toml"),[s,o,i,a]=await Promise.all([v(t),v(r),v(Fl.join(process.cwd(),".cursor","commands","sync.md")),v(Fl.join(process.cwd(),".cursor"))]),l=await Do();console.log(lh(n)),console.log(So("Claude Code",e.claude.installed?s?"ready":"installed":"missing",e.claude.version?fs.dim(` (v${e.claude.version})`):"")),console.log(So("Gemini CLI",e.gemini.installed?o?"ready":"installed":"missing",e.gemini.version?fs.dim(` (v${e.gemini.version})`):"")),console.log(So("Antigravity",l.installed?l.skillInstalled?"ready":"detected":"missing",l.installed&&!l.skillInstalled?` ${fs.dim("(run prjct start)")}`:"")),console.log(So("Cursor IDE",i?"ready":a?"detected":"missing",i?` ${fs.dim("(use /sync, /task)")}`:a?` ${fs.dim("(run prjct init)")}`:"","\u25CB no .cursor/ folder")),console.log(`
|
|
1777
|
+
`;await Ne.writeFile(s,k,{mode:493})}await jx(t,s),await Ax(e,t)}catch(n){H(n)||B.warn(`Status line warning: ${w(n)}`)}}async function Ll(n,e){if(!await v(n))return;let t=await Ne.readdir(n);for(let r of t)if(r.endsWith(".sh")){let s=Qe.join(n,r),o=Qe.join(e,r);await Ne.copyFile(s,o),await Ne.chmod(o,493)}}async function jx(n,e){try{if(await v(n)){if((await Ne.lstat(n)).isSymbolicLink()&&await Ne.readlink(n)===e)return;await Ne.unlink(n)}await Ne.symlink(e,n)}catch{try{await v(e)&&(await Ne.copyFile(e,n),await Ne.chmod(n,493))}catch(r){H(r)||B.warn(`Symlink fallback warning: ${r.message}`)}}}var _x=h(()=>{"use strict";N();V();$t();$e();fe();c(Ax,"ensureStatusLineSettings");c($x,"installStatusLine");c(Ll,"installStatusLineModules");c(jx,"ensureStatusLineSymlink")});var Dx={};A(Dx,{run:()=>Ix});import{execFileSync as eF}from"node:child_process";import nr from"node:fs/promises";import ph from"node:os";import rr from"node:path";import ve from"chalk";async function tF(n){let e=n.name==="claude"?"@anthropic-ai/claude-code":"@google/gemini-cli";if(!xx.isAvailable("npm"))return console.log(`${ve.yellow("\u26A0\uFE0F npm is not available")}`),console.log(""),console.log(`${ve.dim(`Install ${n.displayName} using one of:`)}`),console.log(ve.dim(" \u2022 Install Node.js: https://nodejs.org")),console.log(ve.dim(` \u2022 Use Homebrew: brew install ${n.name==="claude"?"claude":"gemini"}`)),console.log(ve.dim(` \u2022 Use npx directly: npx ${e}`)),console.log(""),!1;try{return console.log(ve.yellow(`\u{1F4E6} ${n.displayName} not found. Installing...`)),console.log(""),eF("npm",["install","-g",e],{stdio:"inherit",timeout:Ls("NPM_INSTALL")}),console.log(""),console.log(`${ve.green("\u2713")} ${n.displayName} installed successfully`),console.log(""),!0}catch(t){let r=t;return r.killed&&r.signal==="SIGTERM"?(console.log(ve.yellow(`\u26A0\uFE0F Installation timed out for ${n.displayName}`)),console.log(""),console.log(ve.dim("The npm install took too long. Try:")),console.log(ve.dim(" \u2022 Set PRJCT_TIMEOUT_NPM_INSTALL=300000 for 5 minutes")),console.log(ve.dim(` \u2022 Run manually: npm install -g ${e}`))):console.log(ve.yellow(`\u26A0\uFE0F Failed to install ${n.displayName}: ${r.message}`)),console.log(""),console.log(ve.dim("Alternative installation methods:")),console.log(ve.dim(` \u2022 npm: npm install -g ${e}`)),console.log(ve.dim(` \u2022 yarn: yarn global add ${e}`)),console.log(ve.dim(` \u2022 pnpm: pnpm add -g ${e}`)),console.log(ve.dim(` \u2022 brew: brew install ${n.name==="claude"?"claude":"gemini"}`)),console.log(""),!1}}async function Ix(){let n=await Hn(),e=await Su(),t={provider:e.provider,providers:[],cliInstalled:!1,commandsAdded:0,commandsUpdated:0,configAction:null},r=["claude","gemini"];for(let i of r){let a=yt[i],l=n[i],u={provider:i,cliInstalled:!1,commandsAdded:0,commandsUpdated:0,configAction:null};if(!l.installed)if(i===e.provider)if(await tF(a))u.cliInstalled=!0,t.cliInstalled=!0;else throw new Error(`${a.displayName} installation failed`);else continue;if(i==="claude"){if(await Le.detectActiveProvider()){let p=await Le.syncCommands();p.success&&(u.commandsAdded=p.added,u.commandsUpdated=p.updated,t.commandsAdded+=p.added,t.commandsUpdated+=p.updated);let m=await Le.installGlobalConfig();m.success&&(u.configAction=m.action,t.configAction||(t.configAction=m.action)),await Le.installDocs(),await $x(),await xn.ensureReady()}}else if(i==="gemini"){await nF()&&(u.commandsAdded=1,t.commandsAdded+=1);let p=await rF();p.success&&(u.configAction=p.action)}t.providers.push(u)}if((await Do()).installed&&(await sF()).success&&console.log(` ${ve.green("\u2713")} Antigravity skill installed`),(await dr()).installed){if(!(await kc()).success)throw new Error("Codex skill installation failed");let a=await ns({autoRepair:!0});if(!a.verified)throw new Error(a.message||"Codex p. router verification failed");console.log(` ${ve.green("\u2713")} Codex skill installed`),console.log(` ${ve.green("\u2713")} Codex p. router ready`)}await bi.saveConfig(se,await Le.getInstallPath(),e.provider),await oF();for(let i of t.providers)iF(i,yt[i.provider]);return t}async function nF(){try{let n=rr.join(ph.homedir(),".gemini","commands"),e=rr.join(n,"p.toml");try{return await nr.unlink(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}catch(n){return B.warn(`Gemini router cleanup warning: ${w(n)}`),!1}}async function rF(){try{let n=rr.join(ph.homedir(),".gemini"),e=rr.join(n,"GEMINI.md");await nr.mkdir(n,{recursive:!0});let t=Be("global/GEMINI.md");if(!t){let l=rr.join(dt,"templates","global","GEMINI.md");t=await nr.readFile(l,"utf-8")}let r="",s=!1;try{r=await nr.readFile(e,"utf-8"),s=!0}catch(l){if(H(l))s=!1;else throw l}let a=Rs(s?r:"",t,"<!-- prjct:start - DO NOT REMOVE THIS MARKER -->","<!-- prjct:end - DO NOT REMOVE THIS MARKER -->");return await nr.writeFile(e,a.content,"utf-8"),{success:!0,action:a.action}}catch(n){return B.warn(`Gemini config warning: ${w(n)}`),{success:!1,action:null}}}async function sF(){try{let n=rr.join(ph.homedir(),".gemini","antigravity","skills"),e=rr.join(n,"prjct"),t=rr.join(e,"SKILL.md");await nr.mkdir(e,{recursive:!0});let r=await v(t),s=Be("antigravity/SKILL.md");if(!s){let o=rr.join(dt,"templates","antigravity","SKILL.md");if(!await v(o))return B.warn("Antigravity SKILL.md template not found"),{success:!1,action:null};s=await nr.readFile(o,"utf-8")}return await nr.writeFile(t,s,"utf-8"),{success:!0,action:r?"updated":"created"}}catch(n){return B.warn(`Antigravity skill warning: ${w(n)}`),{success:!1,action:null}}}async function oF(){try{let n=_.globalProjectsDir;if(!await v(n))return;let e=(await nr.readdir(n,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name),t=0;for(let r of e)try{let s=P.getDoc(r,"project");if(!s)continue;s.cliVersion!==se&&(s.cliVersion=se,P.setDoc(r,"project",s),t++)}catch{}t>0&&console.log(` ${ve.green("\u2713")} Updated ${t} project(s) to v${se}`)}catch(n){H(n)||B.warn(`Migration warning: ${w(n)}`)}}function iF(n,e){if(console.log(""),n.cliInstalled?console.log(` ${ve.green("\u2713")} ${e.displayName} CLI installed`):console.log(` ${ve.green("\u2713")} ${e.displayName} CLI found`),n.commandsAdded+n.commandsUpdated>0){let r=[];n.commandsAdded>0&&r.push(`${n.commandsAdded} new`),n.commandsUpdated>0&&r.push(`${n.commandsUpdated} updated`),console.log(` ${ve.green("\u2713")} Commands synced (${r.join(", ")})`)}else console.log(` ${ve.green("\u2713")} Commands up to date`);n.configAction==="created"?console.log(` ${ve.green("\u2713")} Global config created (${e.contextFile})`):n.configAction==="updated"?console.log(` ${ve.green("\u2713")} Global config updated (${e.contextFile})`):n.configAction==="appended"&&console.log(` ${ve.green("\u2713")} Global config merged (${e.contextFile})`),console.log("")}var aF,Mx=h(()=>{"use strict";wn();Js();Px();z();N();qa();V();$t();$e();Xe();zs();Qt();pl();ca();fe();_x();c(tF,"installAICLI");c(Ix,"run");c(nF,"installGeminiRouter");c(rF,"installGeminiGlobalConfig");c(sF,"installAntigravitySkill");c(oF,"migrateProjectsCliVersion");c(iF,"showResults");aF=process.argv[1]?.includes("setup.ts")||process.argv[1]?.includes("setup.js");aF&&Ix().catch(n=>{console.error("Setup error:",n.message),process.exit(1)})});var Ox=Xx((aoe,cF)=>{cF.exports={name:"prjct-cli",version:"2.43.2",description:"Context layer for AI agents. Project context for Claude Code, Gemini CLI, and more.",main:"dist/bin/prjct.mjs",bin:{prjct:"bin/prjct"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},scripts:{build:"node scripts/build.js","build:node":"node scripts/build.js",release:"node scripts/release.js","release:patch":"node scripts/release.js patch","release:minor":"node scripts/release.js minor","release:major":"node scripts/release.js major",prepare:"lefthook install","update-commands":`bun -e "const installer = require('./core/infrastructure/command-installer'); installer.syncCommands().then(r => console.log('Commands updated:', r)).catch(e => console.error('Error:', e.message))"`,"install-global":"./scripts/install.sh",update:"./scripts/update.sh",test:"bun test","test:watch":"bun test --watch","test:coverage":"bun test --coverage",typecheck:"tsc --noEmit -p core/tsconfig.json","typecheck:watch":"tsc --noEmit -p core/tsconfig.json --watch",validate:"bun scripts/validate-commands.js",lint:"biome lint .","lint:fix":"biome lint --write .",knip:"knip","lint:meta":"bun core/cli/lint-meta-commentary.ts",format:"biome format --write .","format:check":"biome format .",check:"biome check .","check:fix":"biome check --write .","test:e2e":"bun test core/__tests__/e2e/"},keywords:["claude-code","gemini-cli","ai-agents","context-layer","developer-tools","ai-assistant","productivity","mcp","llm","coding-agents"],author:"prjct.app",license:"MIT",dependencies:{"@clack/prompts":"1.0.0","@modelcontextprotocol/sdk":"1.29.0",chalk:"4.1.2",chokidar:"5.0.0","jsonc-parser":"3.3.1",zod:"3.25.76"},overrides:{"path-to-regexp":"8.4.0","brace-expansion":"5.0.5","fast-uri":">=3.1.2",hono:">=4.12.18","ip-address":">=10.1.1"},devDependencies:{"@biomejs/biome":"2.3.13","@types/bun":"latest","@types/chokidar":"2.1.7","@types/node":"^22",esbuild:"0.25.0",knip:"6.3.1",lefthook:"2.1.0",typescript:"5.9.3"},repository:{type:"git",url:"git+https://github.com/jlopezlira/prjct-cli.git"},bugs:{url:"https://github.com/jlopezlira/prjct-cli/issues"},homepage:"https://prjct.app",packageManager:"bun@1.2.23",engines:{bun:">=1.0.0",node:">=22.5.0"},files:["assets/","bin/prjct","dist/","templates/","scripts/ensure-bun.sh","scripts/install.sh","LICENSE","README.md","CHANGELOG.md"],prepublishOnly:"node scripts/build.js"}});var fF={};import Nx from"node:os";import Fl from"node:path";import fs from"chalk";async function lF(){let[n,...e]=process.argv.slice(2);if(["-v","--version","version"].includes(n)){let r=await Promise.resolve().then(()=>Kx(Ox()));await pF(r.version),process.exit(0)}if(["-h","--help",void 0].includes(n)&&(mF(),process.exit(0)),n&&jl(n)&&!Ue.getByName(n)){let r=Al[n];r&&(g.failWithHint({message:`'prjct ${n}' was removed in v2. ${r.note}`,hint:`Use: ${r.replacement}`}),process.exit(1))}if(n&&!Ue.getByName(n)&&!(e.length===0&&Pi(n)!==null)){let s=[n,...e.filter(i=>!i.startsWith("-"))].join(" "),o=e.filter(i=>i.startsWith("-"));n="capture",e=[s,...o]}let t=e.includes("--md");t||g.start();try{let r=Ue.getByName(n);if(!r){let m=Pi(n),f=m?`Did you mean 'prjct ${m}'? Run 'prjct --help' for all commands`:"Run 'prjct --help' to see available commands";g.failWithHint(ei("UNKNOWN_COMMAND",{message:`Unknown command: ${n}`,hint:f})),t||g.end(),process.exit(1)}if(r.deprecated){let m=r.replacedBy?`Use 'prjct ${r.replacedBy}' instead`:"Run 'prjct --help' to see available commands";g.failWithHint({message:`Command '${n}' is deprecated`,hint:m}),t||g.end(),process.exit(1)}r.implemented||(g.failWithHint({message:`Command '${n}' is not yet implemented`,hint:"Run 'prjct --help' to see available commands",docs:"https://github.com/jlopezlira/prjct-cli"}),t||g.end(),process.exit(1));let{parsedArgs:s,options:o}=dF(r,e),i=!process.stdin.isTTY||o.md===!0||o.json===!0;r.requiresLlm&&!i&&(g.failWithHint({message:`'prjct ${n}' requires an AI agent to process its output`,hint:`Use 'p. ${n}' inside Claude/Cursor, or add --md flag`}),t||g.end(),process.exit(1));let a=uF(r,s);a&&(g.failWithHint(a),t||g.end(),process.exit(1));let l=null,u=Date.now();try{l=await j.getProjectId(process.cwd()),l&&(await ro.expireIfStale(l),await ro.touch(l))}catch{}let d=new $r,p;if(n==="analyze")p=await d.analyze(o);else if(n==="setup")p=await d.setup(o);else if(n==="update"||n==="upgrade")p=await d.update(o);else{let m=s.join(" ")||null,f=o.md===!0,y=Ue.getByName(n);if(y?.optionSchema)p=await Ue.executeWithOptions(n,m,process.cwd(),Pl(o,y.optionSchema));else{let b={spec:c(S=>$l(d,(S??"").trim().split(/\s+/).filter(Boolean),o,process.cwd()),"spec"),"audit-spec":c(S=>S?d.specAudit(S,process.cwd(),{md:f}):Promise.resolve({success:!1,error:"audit-spec requires a spec id"}),"audit-spec"),init:c(S=>d.init({idea:S,yes:o.yes===!0,pack:o.pack?String(o.pack):void 0,persona:o.persona?String(o.persona):void 0}),"init"),sync:c(()=>d.sync(process.cwd(),{preview:o.preview===!0||o["dry-run"]===!0,yes:o.yes===!0,json:o.json===!0,md:f,package:o.package?String(o.package):void 0,full:o.full===!0}),"sync"),"analysis-save-llm":c(S=>S?d.saveLlmAnalysis(S,process.cwd(),{md:f}):Promise.resolve({success:!1,error:"analysis-save-llm requires a JSON payload as positional arg"}),"analysis-save-llm"),regen:c(()=>d.regenVault(process.cwd(),{md:f}),"regen"),start:c(()=>d.start(),"start"),login:c(()=>d.login({md:f,url:o.url?String(o.url):void 0}),"login"),logout:c(()=>d.logout(),"logout"),auth:c(S=>d.auth(S,{md:f}),"auth")}[n];if(b)p=await b(m);else throw new Error(`Command '${n}' has no handler`)}}if(l){let m=Date.now()-u;try{await ro.trackCommand(l,n,m)}catch{}try{await Si.recordTiming(l,"command_duration",m,{command:n});let f=globalThis.__perfStartNs;if(f){let y=Number(process.hrtime.bigint()-f)/1e6;await Si.recordTiming(l,"startup_time",y)}await Si.recordMemory(l,{command:n})}catch{}}p?.message&&console.log(p.message),t||g.end(),process.exit(p?.success?0:1)}catch(r){console.error("Error:",w(r)),process.env.DEBUG&&console.error(su(r)),t||g.end(),process.exit(1)}}function uF(n,e){if(!n.params)return null;let t=n.params.match(/<[^>]+>/g);if(!t||t.length===0)return null;if(e.length<t.length){let r=t.map(o=>o.slice(1,-1)).join(", "),s=n.usage.terminal||`prjct ${n.name} ${n.params}`;return ei("MISSING_PARAM",{message:`Missing required parameter: ${r}`,hint:`Usage: ${s}`})}return null}function dF(n,e){let t=[],r={};for(let s=0;s<e.length;s++){let o=e[s];if(o.startsWith("--")){let i=o.slice(2);s+1<e.length&&!e[s+1].startsWith("--")?r[i]=e[++s]:r[i]=!0}else t.push(o)}return{parsedArgs:t,options:r}}async function pF(n){let e=await Hn(),t=Fl.join(Nx.homedir(),".claude","commands","p.md"),r=Fl.join(Nx.homedir(),".gemini","commands","p.toml"),[s,o,i,a]=await Promise.all([v(t),v(r),v(Fl.join(process.cwd(),".cursor","commands","sync.md")),v(Fl.join(process.cwd(),".cursor"))]),l=await Do();console.log(lh(n)),console.log(So("Claude Code",e.claude.installed?s?"ready":"installed":"missing",e.claude.version?fs.dim(` (v${e.claude.version})`):"")),console.log(So("Gemini CLI",e.gemini.installed?o?"ready":"installed":"missing",e.gemini.version?fs.dim(` (v${e.gemini.version})`):"")),console.log(So("Antigravity",l.installed?l.skillInstalled?"ready":"detected":"missing",l.installed&&!l.skillInstalled?` ${fs.dim("(run prjct start)")}`:"")),console.log(So("Cursor IDE",i?"ready":a?"detected":"missing",i?` ${fs.dim("(use /sync, /task)")}`:a?` ${fs.dim("(run prjct init)")}`:"","\u25CB no .cursor/ folder")),console.log(`
|
|
1778
1778
|
${fs.dim("Run 'prjct start' for Claude/Gemini, 'prjct init' for Cursor")}
|
|
1779
1779
|
${fs.cyan("https://prjct.app")}
|
|
1780
1780
|
`)}function mF(){console.log(`
|
package/dist/daemon/entry.mjs
CHANGED
|
@@ -665,7 +665,7 @@ ${a}`}return`${s}
|
|
|
665
665
|
|
|
666
666
|
${e}`}formatKeepAChangelogEntry(e,t){let n=[`## [${e.version}] - ${t}`];if(n.push(""),e.sections)for(let[s,o]of Object.entries(e.sections)){n.push(`### ${s}`);for(let i of o)n.push(`- ${i}`);n.push("")}else e.description&&(n.push("### Added"),n.push(`- ${e.description}`),n.push(""));return n.join(`
|
|
667
667
|
`)}formatMarkdownEntry(e,t){let n=[`## ${e.version} - ${t}`];if(n.push(""),e.sections)for(let[s,o]of Object.entries(e.sections)){n.push(`### ${s}`);for(let i of o)n.push(`- ${i}`);n.push("")}else e.description&&(n.push(`- ${e.description}`),n.push(""));return n.join(`
|
|
668
|
-
`)}}});function dC(r){return r instanceof Ir}function Ie(r){return dC(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var Ir,Vo,qo,Ns,An=h(()=>{"use strict";Ir=class extends Error{static{c(this,"PrjctError")}code;isOperational;constructor(e,t="PRJCT_ERROR"){super(e),this.name="PrjctError",this.code=t,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}},Vo=class r extends Ir{static{c(this,"ProjectError")}constructor(e,t="PROJECT_ERROR"){super(e,t),this.name="ProjectError"}static notInitialized(){return new r("Project not initialized. Run /p:init first.","PROJECT_NOT_INIT")}static notFound(e){return new r(`Project not found: ${e}`,"PROJECT_NOT_FOUND")}static invalidId(e){return new r(`Invalid project ID: ${e}`,"PROJECT_INVALID_ID")}},qo=class r extends Ir{static{c(this,"TemplateError")}constructor(e,t="TEMPLATE_ERROR"){super(e,t),this.name="TemplateError"}static notFound(e){return new r(`Template not found: ${e}.md`,"TEMPLATE_NOT_FOUND")}static parseFailed(e){return new r(`Failed to parse template: ${e}`,"TEMPLATE_PARSE_ERROR")}},Ns=class r extends Ir{static{c(this,"AgentError")}constructor(e,t="AGENT_ERROR"){super(e,t),this.name="AgentError"}static notSupported(e){return new r(`Unsupported agent type: ${e}`,"AGENT_NOT_SUPPORTED")}static initFailed(e){return new r(`Agent initialization failed: ${e}`,"AGENT_INIT_FAILED")}};c(dC,"isPrjctError");c(Ie,"getErrorMessage")});var Wc={};F(Wc,{PACKAGE_ROOT:()=>on,VERSION:()=>De,getPackageRoot:()=>Uc,getVersion:()=>Xo,resetPackageRoot:()=>Hc});import Fc from"node:fs";import Jo from"node:path";function Uc(){if(Dr)return Dr;let r=__dirname;for(let e=0;e<5;e++){let t=Jo.join(r,"package.json");if(Fc.existsSync(t))try{if(JSON.parse(Fc.readFileSync(t,"utf-8")).name==="prjct-cli")return Dr=r,r}catch{}r=Jo.dirname(r)}return Dr=Jo.join(__dirname,"..","..",".."),Dr}function Xo(){if(tr)return tr;let r=process.env.PRJCT_VERSION;if(r&&/^\d+\.\d+\.\d+/.test(r))return tr=r,tr;try{let e=Jo.join(Uc(),"package.json");return tr=JSON.parse(Fc.readFileSync(e,"utf-8")).version,tr}catch(e){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",w(e)),"0.0.0"}}function Hc(r){Dr=r,tr=null}var tr,Dr,De,on,pt=h(()=>{"use strict";W();tr=null,Dr=null;c(Uc,"getPackageRoot");c(Xo,"getVersion");c(Hc,"resetPackageRoot");De=Xo(),on=Uc()});async function zo(r){try{let{stdout:e}=await U(r,{timeout:5e3});return{success:!0,output:e.trim()}}catch{return{success:!1,output:""}}}async function pC(){let r=await zo("gh api user --jq .login");return r.success&&r.output||(r=await zo("git config --global github.user"),r.success&&r.output)?r.output:null}async function mC(){let r=await zo("git config user.name");return r.success&&r.output?r.output:null}async function gC(){let r=await zo("git config user.email");return r.success&&r.output?r.output:null}async function $r(){let[r,e,t]=await Promise.all([pC(),mC(),gC()]);return{github:r,email:t,name:e||r||"Unknown"}}var Ko=h(()=>{"use strict";Ce();c(zo,"execCommand");c(pC,"detectGitHubUsername");c(mC,"detectGitName");c(gC,"detectGitEmail");c($r,"detect")});var Or={};F(Or,{default:()=>j});import Bc from"node:fs/promises";import fC from"node:path";import*as Yo from"jsonc-parser";function Af(r){let e=[],t=Yo.parse(r,e,{allowTrailingComma:!0,disallowComments:!1});if(e.length>0){let n=e[0];throw new SyntaxError(`JSON parse error at offset ${n.offset}: ${Yo.printParseErrorCode(n.error)}`)}return t}var Vc,hC,j,ae=h(()=>{"use strict";An();W();oe();Y();pt();Ko();fe();c(Af,"parseJsonc");Vc=class{static{c(this,"ConfigManager")}async readConfig(e){try{let t=_.getLocalConfigPath(e),n=await Bc.readFile(t,"utf-8");return Af(n)}catch(t){return L(t)||console.warn(`Warning: Could not read config at ${e}: ${Ie(t)}`),null}}async writeConfig(e,t){let n=_.getLocalConfigPath(e);await ke(n,t)}async readGlobalConfig(e){try{let t=_.getGlobalProjectConfigPath(e),n=await Bc.readFile(t,"utf-8");return Af(n)}catch(t){return L(t)||console.warn(`Warning: Could not read global config for ${e}: ${Ie(t)}`),null}}async writeGlobalConfig(e,t){let n=_.getGlobalProjectConfigPath(e);await ke(n,t)}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=b();t={projectId:e,authors:[],version:De,lastSync:n},await this.writeGlobalConfig(e,t)}return t}async createConfig(e,t){let n=_.generateProjectId(e),s=_.getGlobalProjectPath(n),o=_.getDisplayPath(s),i=b(),a={projectId:n,dataPath:o,showMetrics:!0};await this.writeConfig(e,a);let l={projectId:n,authors:[{name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:i,lastActivity:i}],version:De,created:i,lastSync:i};return await this.writeGlobalConfig(n,l),a}async updateLastSync(e){let t=await this.getProjectId(e),n=await this.readGlobalConfig(t);n&&(n.lastSync=b(),await this.writeGlobalConfig(t,n))}validateConfig(e){return!(!e||!e.projectId||!e.dataPath)}async needsMigration(e){if(!await _.hasLegacyStructure(e))return!1;if(!await _.hasConfig(e))return!0;let s=await this.readConfig(e);if(!s||!s.projectId)return!0;let o=_.getGlobalProjectPath(s.projectId);try{return(await Bc.readdir(fC.join(o,"core"))).length===0}catch(i){return L(i),!0}}async getProjectId(e){let t=await this.readConfig(e);if(t?.projectId)return t.projectId;try{let{worktreeService:n}=await Promise.resolve().then(()=>(jo(),_o));if(await n.detect(e)){let o=await n.getMainWorktree(e);if(o!==e){let i=await this.readConfig(o);if(i?.projectId)return i.projectId}}}catch{}return""}async findAuthor(e,t){let n=await this.readGlobalConfig(e);return!n||!n.authors?null:n.authors.find(s=>s.github===t)||null}async addAuthor(e,t){let n=await this.ensureGlobalConfig(e);if(n.authors.some(i=>i.github===t.github))return;let o=b();n.authors.push({name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:o,lastActivity:o}),n.lastSync=o,await this.writeGlobalConfig(e,n)}async updateAuthorActivity(e,t){let n=await this.readGlobalConfig(e);if(!n||!n.authors)return;let s=n.authors.find(o=>o.github===t);s&&(s.lastActivity=b(),n.lastSync=s.lastActivity,await this.writeGlobalConfig(e,n))}async getCurrentAuthor(e){let t=await $r(),n=await this.getProjectId(e);return await this.addAuthor(n,{name:t.name??void 0,email:t.email??void 0,github:t.github??void 0}),t.github||t.name||"Unknown"}async isConfigured(e){let t=await this.readConfig(e);return this.validateConfig(t)}async getShowMetrics(e){return(await this.readConfig(e))?.showMetrics??!0}async setShowMetrics(e,t){let n=await this.readConfig(e);n&&(n.showMetrics=t,await this.writeConfig(e,n))}async getConfigWithDefaults(e){let t=await this.readConfig(e);if(t)return t;let n=_.generateProjectId(e);return{projectId:n,dataPath:_.getDisplayPath(_.getGlobalProjectPath(n))}}},hC=new Vc,j=hC});var qc,Me,an=h(()=>{"use strict";ae();Pn();z();qc=class{static{c(this,"MemoryService")}async log(e,t,n,s){try{let o=await j.getProjectId(e);return o?{eventId:k.appendEvent(o,`memory.${t}`,{...n,author:s}),projectId:o}:null}catch(o){return console.error(`Memory log error: ${o instanceof Error?o.message:String(o)}`),null}}async getRecent(e,t=100){try{let n=await j.getProjectId(e);return n?k.query(n,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(o=>{let i=JSON.parse(o.data),{author:a,...l}=i;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:l,author:a}}):[]}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(n)}`),[]}}async search(e,t,n=50){let s=await this.getRecent(e,1e3),o=t.toLowerCase();return s.filter(i=>{let a=i.action.toLowerCase().includes(o),l=JSON.stringify(i.data).toLowerCase().includes(o);return a||l}).slice(-n)}async getByAction(e,t,n=50){try{let s=await j.getProjectId(e);return s?k.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${t}`,n).reverse().map(i=>{let a=JSON.parse(i.data),{author:l,...u}=a;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:l}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(e){try{let t=await j.getProjectId(e);if(!t)return;k.run(t,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(t){console.error(`Memory clear error: ${t instanceof Error?t.message:String(t)}`)}}async getRecentEvents(e,t=100){try{return k.query(e,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>{let o=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...o}})}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(n)}`),[]}}async capEntries(e){try{let n=k.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(n<=sn.MEMORY_MAX_ENTRIES)return 0;let s=n-sn.MEMORY_MAX_ENTRIES,o=k.query(e,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?",s);Qe.archiveMany(e,o.map((a,l)=>({entityType:"memory_entry",entityId:`memory-${a.timestamp||l}`,entityData:{type:a.type,data:JSON.parse(a.data),timestamp:a.timestamp},summary:a.type.replace("memory.",""),reason:"overflow"})));let i=o[o.length-1]?.id;return i!==void 0&&k.run(e,"DELETE FROM events WHERE type LIKE 'memory.%' AND id <= ?",i),s}catch(t){return console.error(`Memory cap error: ${t instanceof Error?t.message:String(t)}`),0}}},Me=new qc});import nr from"node:path";function Jc(r){return/^\d+\.\d+\.\d+/.test(r)}function rr(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);if(!e)return r;let[,t,n,s,o]=e;if(o){let i=o.split("."),a=i.length-1;return/^\d+$/.test(i[a])?(i[a]=String(Number(i[a])+1),`${t}.${n}.${s}-${i.join(".")}`):`${t}.${n}.${s}-${o}.1`}return`${t}.${n}.${Number(s)+1}`}function yC(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);return e?`${e[1]}.${Number(e[2])+1}.0`:r}function wC(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);return e?`${Number(e[1])+1}.0.0`:r}function kC(r,e){return e==="major"?wC(r):e==="minor"?yC(r):rr(r)}function Df(r){let e=(r??"").toLowerCase().trim();return e?/^[a-z]+(\([^)]*\))?!:/.test(e)||e.includes("breaking change")?"major":/^(fix|chore|docs|refactor|perf|style|test|build|ci|revert)(\([^)]*\))?:/.test(e)?"patch":"minor":"patch"}function _f(r){let e=r.match(/\[package\]([\s\S]*?)(?=\n\[|\n*$)/);return e?e[1].match(/^\s*version\s*=\s*"([^"]+)"/m)?.[1]??null:null}function jf(r){let e=r.match(/\[project\]([\s\S]*?)(?=\n\[|\n*$)/);if(e){let n=e[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}let t=r.match(/\[tool\.poetry\]([\s\S]*?)(?=\n\[|\n*$)/);if(t){let n=t[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}return null}function If(r){return r.match(/<Version>([^<]+)<\/Version>/)?.[1]?.trim()??null}var Qo,$f=h(()=>{"use strict";Ce();Y();Qo=class{static{c(this,"VersionService")}projectPath;constructor(e){this.projectPath=e}async detect(){let e=[()=>this.fromPackageJson(),()=>this.fromCargoToml(),()=>this.fromPyprojectToml(),()=>this.fromCsproj(),()=>this.fromVersionFile("VERSION"),()=>this.fromVersionFile("version.txt"),()=>this.fromGitTag()];for(let t of e){let n=await t();if(n)return n}return this.createFallbackVersion()}async bump(e="patch"){let t=await this.detect();if(t.file){let s=await this.readVersionFromGitHead(t.file,t.format);if(s&&this.isAheadOf(t.current,s))return t.current}let n=kC(t.current,e);return await this.writeVersion({...t,next:n}),n}async readVersionFromGitHead(e,t){try{let n=nr.relative(this.projectPath,e),{stdout:s}=await ge("git",["show",`HEAD:${n}`],{cwd:this.projectPath});if(t==="json")return JSON.parse(s).version??null;if(t==="plaintext"){let o=s.trim();return Jc(o)?o:null}return t==="toml"?_f(s)??jf(s):t==="xml"?If(s):null}catch{return null}}isAheadOf(e,t){let n=e.split(".").map(o=>Number.parseInt(o,10)||0),s=t.split(".").map(o=>Number.parseInt(o,10)||0);for(let o=0;o<3;o++){let i=n[o]??0,a=s[o]??0;if(i>a)return!0;if(i<a)return!1}return!1}async fromPackageJson(){let e=nr.join(this.projectPath,"package.json"),t=await Ne(e,null);return t?.version?{current:t.version,next:rr(t.version),file:e,format:"json"}:null}async fromCargoToml(){let e=nr.join(this.projectPath,"Cargo.toml"),t=await Tt(e,"");if(!t)return null;let n=_f(t);return n?{current:n,next:rr(n),file:e,format:"toml"}:null}async fromPyprojectToml(){let e=nr.join(this.projectPath,"pyproject.toml"),t=await Tt(e,"");if(!t)return null;let n=jf(t);return n?{current:n,next:rr(n),file:e,format:"toml"}:null}async fromCsproj(){let e=await Tn(this.projectPath,{extension:".csproj"});if(e.length===0)return null;let t=nr.join(this.projectPath,e[0]),n=await Tt(t,"");if(!n)return null;let s=If(n);return s?{current:s,next:rr(s),file:t,format:"xml"}:null}async fromVersionFile(e){let t=nr.join(this.projectPath,e),n=await Tt(t,"");if(!n)return null;let s=n.trim();return Jc(s)?{current:s,next:rr(s),file:t,format:"plaintext"}:null}async fromGitTag(){try{let{stdout:e}=await U("git tag --sort=-v:refname",{cwd:this.projectPath}),t=e.trim().split(`
|
|
668
|
+
`)}}});function dC(r){return r instanceof Ir}function Ie(r){return dC(r)||r instanceof Error?r.message:typeof r=="string"?r:"Unknown error"}var Ir,Vo,qo,Ns,An=h(()=>{"use strict";Ir=class extends Error{static{c(this,"PrjctError")}code;isOperational;constructor(e,t="PRJCT_ERROR"){super(e),this.name="PrjctError",this.code=t,this.isOperational=!0,Error.captureStackTrace?.(this,this.constructor)}},Vo=class r extends Ir{static{c(this,"ProjectError")}constructor(e,t="PROJECT_ERROR"){super(e,t),this.name="ProjectError"}static notInitialized(){return new r("Project not initialized. Run /p:init first.","PROJECT_NOT_INIT")}static notFound(e){return new r(`Project not found: ${e}`,"PROJECT_NOT_FOUND")}static invalidId(e){return new r(`Invalid project ID: ${e}`,"PROJECT_INVALID_ID")}},qo=class r extends Ir{static{c(this,"TemplateError")}constructor(e,t="TEMPLATE_ERROR"){super(e,t),this.name="TemplateError"}static notFound(e){return new r(`Template not found: ${e}.md`,"TEMPLATE_NOT_FOUND")}static parseFailed(e){return new r(`Failed to parse template: ${e}`,"TEMPLATE_PARSE_ERROR")}},Ns=class r extends Ir{static{c(this,"AgentError")}constructor(e,t="AGENT_ERROR"){super(e,t),this.name="AgentError"}static notSupported(e){return new r(`Unsupported agent type: ${e}`,"AGENT_NOT_SUPPORTED")}static initFailed(e){return new r(`Agent initialization failed: ${e}`,"AGENT_INIT_FAILED")}};c(dC,"isPrjctError");c(Ie,"getErrorMessage")});var Wc={};F(Wc,{PACKAGE_ROOT:()=>on,VERSION:()=>De,getPackageRoot:()=>Uc,getVersion:()=>Xo,resetPackageRoot:()=>Hc});import Fc from"node:fs";import Jo from"node:path";function Uc(){if(Dr)return Dr;let r=__dirname;for(let e=0;e<5;e++){let t=Jo.join(r,"package.json");if(Fc.existsSync(t))try{if(JSON.parse(Fc.readFileSync(t,"utf-8")).name==="prjct-cli")return Dr=r,r}catch{}r=Jo.dirname(r)}return Dr=Jo.join(__dirname,"..","..",".."),Dr}function Xo(){if(tr)return tr;let r=process.env.PRJCT_VERSION;if(r&&/^\d+\.\d+\.\d+/.test(r))return tr=r,tr;try{let e=Jo.join(Uc(),"package.json");return tr=JSON.parse(Fc.readFileSync(e,"utf-8")).version,tr}catch(e){return process.env.PRJCT_DEBUG==="1"&&console.error("Failed to read version from package.json:",w(e)),"0.0.0"}}function Hc(r){Dr=r,tr=null}var tr,Dr,De,on,pt=h(()=>{"use strict";W();tr=null,Dr=null;c(Uc,"getPackageRoot");c(Xo,"getVersion");c(Hc,"resetPackageRoot");De=Xo(),on=Uc()});async function zo(r){try{let{stdout:e}=await U(r,{timeout:5e3});return{success:!0,output:e.trim()}}catch{return{success:!1,output:""}}}async function pC(){let r=await zo("gh api user --jq .login");return r.success&&r.output||(r=await zo("git config --global github.user"),r.success&&r.output)?r.output:null}async function mC(){let r=await zo("git config user.name");return r.success&&r.output?r.output:null}async function gC(){let r=await zo("git config user.email");return r.success&&r.output?r.output:null}async function $r(){let[r,e,t]=await Promise.all([pC(),mC(),gC()]);return{github:r,email:t,name:e||r||"Unknown"}}var Ko=h(()=>{"use strict";Ce();c(zo,"execCommand");c(pC,"detectGitHubUsername");c(mC,"detectGitName");c(gC,"detectGitEmail");c($r,"detect")});var Or={};F(Or,{default:()=>j});import Bc from"node:fs/promises";import fC from"node:path";import*as Yo from"jsonc-parser";function Af(r){let e=[],t=Yo.parse(r,e,{allowTrailingComma:!0,disallowComments:!1});if(e.length>0){let n=e[0];throw new SyntaxError(`JSON parse error at offset ${n.offset}: ${Yo.printParseErrorCode(n.error)}`)}return t}var Vc,hC,j,ae=h(()=>{"use strict";An();W();oe();Y();pt();Ko();fe();c(Af,"parseJsonc");Vc=class{static{c(this,"ConfigManager")}async readConfig(e){try{let t=_.getLocalConfigPath(e),n=await Bc.readFile(t,"utf-8");return Af(n)}catch(t){return L(t)||console.warn(`Warning: Could not read config at ${e}: ${Ie(t)}`),null}}async writeConfig(e,t){let n=_.getLocalConfigPath(e);await ke(n,t)}async readGlobalConfig(e){try{let t=_.getGlobalProjectConfigPath(e),n=await Bc.readFile(t,"utf-8");return Af(n)}catch(t){return L(t)||console.warn(`Warning: Could not read global config for ${e}: ${Ie(t)}`),null}}async writeGlobalConfig(e,t){let n=_.getGlobalProjectConfigPath(e);await ke(n,t)}async ensureGlobalConfig(e){let t=await this.readGlobalConfig(e);if(!t){let n=b();t={projectId:e,authors:[],version:De,lastSync:n},await this.writeGlobalConfig(e,t)}return t}async createConfig(e,t){let n=_.generateProjectId(e),s=_.getGlobalProjectPath(n),o=_.getDisplayPath(s),i=b(),a={projectId:n,dataPath:o,showMetrics:!0};await this.writeConfig(e,a);let l={projectId:n,authors:[{name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:i,lastActivity:i}],version:De,created:i,lastSync:i};return await this.writeGlobalConfig(n,l),a}async updateLastSync(e){let t=await this.getProjectId(e),n=await this.readGlobalConfig(t);n&&(n.lastSync=b(),await this.writeGlobalConfig(t,n))}validateConfig(e){return!(!e||!e.projectId||!e.dataPath)}async needsMigration(e){if(!await _.hasLegacyStructure(e))return!1;if(!await _.hasConfig(e))return!0;let s=await this.readConfig(e);if(!s||!s.projectId)return!0;let o=_.getGlobalProjectPath(s.projectId);try{return(await Bc.readdir(fC.join(o,"core"))).length===0}catch(i){return L(i),!0}}async getProjectId(e){let t=await this.readConfig(e);if(t?.projectId)return t.projectId;try{let{worktreeService:n}=await Promise.resolve().then(()=>(jo(),_o));if(await n.detect(e)){let o=await n.getMainWorktree(e);if(o!==e){let i=await this.readConfig(o);if(i?.projectId)return i.projectId}}}catch{}return""}async findAuthor(e,t){let n=await this.readGlobalConfig(e);return!n||!n.authors?null:n.authors.find(s=>s.github===t)||null}async addAuthor(e,t){let n=await this.ensureGlobalConfig(e);if(n.authors.some(i=>i.github===t.github))return;let o=b();n.authors.push({name:t.name||"Unknown",email:t.email||"",github:t.github||"",firstContribution:o,lastActivity:o}),n.lastSync=o,await this.writeGlobalConfig(e,n)}async updateAuthorActivity(e,t){let n=await this.readGlobalConfig(e);if(!n||!n.authors)return;let s=n.authors.find(o=>o.github===t);s&&(s.lastActivity=b(),n.lastSync=s.lastActivity,await this.writeGlobalConfig(e,n))}async getCurrentAuthor(e){let t=await $r(),n=await this.getProjectId(e);return await this.addAuthor(n,{name:t.name??void 0,email:t.email??void 0,github:t.github??void 0}),t.github||t.name||"Unknown"}async isConfigured(e){let t=await this.readConfig(e);return this.validateConfig(t)}async getShowMetrics(e){return(await this.readConfig(e))?.showMetrics??!0}async setShowMetrics(e,t){let n=await this.readConfig(e);n&&(n.showMetrics=t,await this.writeConfig(e,n))}async getConfigWithDefaults(e){let t=await this.readConfig(e);if(t)return t;let n=_.generateProjectId(e);return{projectId:n,dataPath:_.getDisplayPath(_.getGlobalProjectPath(n))}}},hC=new Vc,j=hC});var qc,Me,an=h(()=>{"use strict";ae();Pn();z();qc=class{static{c(this,"MemoryService")}async log(e,t,n,s){try{let o=await j.getProjectId(e);return o?{eventId:k.appendEvent(o,`memory.${t}`,{...n,author:s}),projectId:o}:null}catch(o){return console.error(`Memory log error: ${o instanceof Error?o.message:String(o)}`),null}}async getRecent(e,t=100){try{let n=await j.getProjectId(e);return n?k.query(n,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(o=>{let i=JSON.parse(o.data),{author:a,...l}=i;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:l,author:a}}):[]}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(n)}`),[]}}async search(e,t,n=50){let s=await this.getRecent(e,1e3),o=t.toLowerCase();return s.filter(i=>{let a=i.action.toLowerCase().includes(o),l=JSON.stringify(i.data).toLowerCase().includes(o);return a||l}).slice(-n)}async getByAction(e,t,n=50){try{let s=await j.getProjectId(e);return s?k.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${t}`,n).reverse().map(i=>{let a=JSON.parse(i.data),{author:l,...u}=a;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:u,author:l}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(e){try{let t=await j.getProjectId(e);if(!t)return;k.run(t,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(t){console.error(`Memory clear error: ${t instanceof Error?t.message:String(t)}`)}}async getRecentEvents(e,t=100){try{return k.query(e,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",t).reverse().map(s=>{let o=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...o}})}catch(n){return console.error(`Memory read error: ${n instanceof Error?n.message:String(n)}`),[]}}async capEntries(e){try{let n=k.get(e,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%' AND type NOT LIKE 'memory.remember.%'")?.cnt??0;if(n<=sn.MEMORY_MAX_ENTRIES)return 0;let s=n-sn.MEMORY_MAX_ENTRIES,o=k.query(e,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' AND type NOT LIKE 'memory.remember.%' ORDER BY id ASC LIMIT ?",s);return Qe.archiveMany(e,o.map((i,a)=>({entityType:"memory_entry",entityId:`memory-${i.timestamp||a}`,entityData:{type:i.type,data:JSON.parse(i.data),timestamp:i.timestamp},summary:i.type.replace("memory.",""),reason:"overflow"}))),k.transaction(e,i=>{let a=i.prepare("DELETE FROM events WHERE id = ?");for(let l of o)a.run(l.id)}),s}catch(t){return console.error(`Memory cap error: ${t instanceof Error?t.message:String(t)}`),0}}},Me=new qc});import nr from"node:path";function Jc(r){return/^\d+\.\d+\.\d+/.test(r)}function rr(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);if(!e)return r;let[,t,n,s,o]=e;if(o){let i=o.split("."),a=i.length-1;return/^\d+$/.test(i[a])?(i[a]=String(Number(i[a])+1),`${t}.${n}.${s}-${i.join(".")}`):`${t}.${n}.${s}-${o}.1`}return`${t}.${n}.${Number(s)+1}`}function yC(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);return e?`${e[1]}.${Number(e[2])+1}.0`:r}function wC(r){let e=r.match(/^(\d+)\.(\d+)\.(\d+)/);return e?`${Number(e[1])+1}.0.0`:r}function kC(r,e){return e==="major"?wC(r):e==="minor"?yC(r):rr(r)}function Df(r){let e=(r??"").toLowerCase().trim();return e?/^[a-z]+(\([^)]*\))?!:/.test(e)||e.includes("breaking change")?"major":/^(fix|chore|docs|refactor|perf|style|test|build|ci|revert)(\([^)]*\))?:/.test(e)?"patch":"minor":"patch"}function _f(r){let e=r.match(/\[package\]([\s\S]*?)(?=\n\[|\n*$)/);return e?e[1].match(/^\s*version\s*=\s*"([^"]+)"/m)?.[1]??null:null}function jf(r){let e=r.match(/\[project\]([\s\S]*?)(?=\n\[|\n*$)/);if(e){let n=e[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}let t=r.match(/\[tool\.poetry\]([\s\S]*?)(?=\n\[|\n*$)/);if(t){let n=t[1].match(/^\s*version\s*=\s*"([^"]+)"/m);if(n)return n[1]}return null}function If(r){return r.match(/<Version>([^<]+)<\/Version>/)?.[1]?.trim()??null}var Qo,$f=h(()=>{"use strict";Ce();Y();Qo=class{static{c(this,"VersionService")}projectPath;constructor(e){this.projectPath=e}async detect(){let e=[()=>this.fromPackageJson(),()=>this.fromCargoToml(),()=>this.fromPyprojectToml(),()=>this.fromCsproj(),()=>this.fromVersionFile("VERSION"),()=>this.fromVersionFile("version.txt"),()=>this.fromGitTag()];for(let t of e){let n=await t();if(n)return n}return this.createFallbackVersion()}async bump(e="patch"){let t=await this.detect();if(t.file){let s=await this.readVersionFromGitHead(t.file,t.format);if(s&&this.isAheadOf(t.current,s))return t.current}let n=kC(t.current,e);return await this.writeVersion({...t,next:n}),n}async readVersionFromGitHead(e,t){try{let n=nr.relative(this.projectPath,e),{stdout:s}=await ge("git",["show",`HEAD:${n}`],{cwd:this.projectPath});if(t==="json")return JSON.parse(s).version??null;if(t==="plaintext"){let o=s.trim();return Jc(o)?o:null}return t==="toml"?_f(s)??jf(s):t==="xml"?If(s):null}catch{return null}}isAheadOf(e,t){let n=e.split(".").map(o=>Number.parseInt(o,10)||0),s=t.split(".").map(o=>Number.parseInt(o,10)||0);for(let o=0;o<3;o++){let i=n[o]??0,a=s[o]??0;if(i>a)return!0;if(i<a)return!1}return!1}async fromPackageJson(){let e=nr.join(this.projectPath,"package.json"),t=await Ne(e,null);return t?.version?{current:t.version,next:rr(t.version),file:e,format:"json"}:null}async fromCargoToml(){let e=nr.join(this.projectPath,"Cargo.toml"),t=await Tt(e,"");if(!t)return null;let n=_f(t);return n?{current:n,next:rr(n),file:e,format:"toml"}:null}async fromPyprojectToml(){let e=nr.join(this.projectPath,"pyproject.toml"),t=await Tt(e,"");if(!t)return null;let n=jf(t);return n?{current:n,next:rr(n),file:e,format:"toml"}:null}async fromCsproj(){let e=await Tn(this.projectPath,{extension:".csproj"});if(e.length===0)return null;let t=nr.join(this.projectPath,e[0]),n=await Tt(t,"");if(!n)return null;let s=If(n);return s?{current:s,next:rr(s),file:t,format:"xml"}:null}async fromVersionFile(e){let t=nr.join(this.projectPath,e),n=await Tt(t,"");if(!n)return null;let s=n.trim();return Jc(s)?{current:s,next:rr(s),file:t,format:"plaintext"}:null}async fromGitTag(){try{let{stdout:e}=await U("git tag --sort=-v:refname",{cwd:this.projectPath}),t=e.trim().split(`
|
|
669
669
|
`);for(let n of t){let s=n.trim().replace(/^v/,"");if(Jc(s))return{current:s,next:rr(s),file:null,format:"git-tag"}}}catch{}return null}async createFallbackVersion(){let e=nr.join(this.projectPath,"VERSION");return await En(e,`0.1.0
|
|
670
670
|
`),{current:"0.1.0",next:"0.1.1",file:e,format:"plaintext"}}async writeVersion(e){if(!e.file){e.format==="git-tag"&&await ge("git",["tag",`v${e.next}`],{cwd:this.projectPath});return}switch(e.format){case"json":await this.writeJsonVersion(e.file,e.next);break;case"toml":await this.writeTomlVersion(e.file,e.next);break;case"xml":await this.writeXmlVersion(e.file,e.next);break;case"plaintext":await En(e.file,`${e.next}
|
|
671
671
|
`);break}}async writeJsonVersion(e,t){let n=await Ne(e,{});n&&(n.version=t,await ke(e,n))}async writeTomlVersion(e,t){let n=await Tt(e,"");if(!n)return;let s=n.replace(/^(\s*version\s*=\s*")([^"]+)(")/m,`$1${t}$3`);await En(e,s)}async writeXmlVersion(e,t){let n=await Tt(e,"");if(!n)return;let s=n.replace(/(<Version>)([^<]+)(<\/Version>)/,`$1${t}$3`);await En(e,s)}};c(Jc,"isSemver");c(rr,"bumpPatch");c(yC,"bumpMinor");c(wC,"bumpMajor");c(kC,"bumpVersion");c(Df,"inferBumpLevel");c(_f,"parseTomlVersion");c(jf,"parsePyprojectVersion");c(If,"parseCsprojVersion")});var Xc,Ze,Ls=h(()=>{"use strict";Is();z();Xc=class{static{c(this,"CustomWorkflowStorage")}createWorkflow(e,t){let n=new Date().toISOString();k.run(e,`INSERT INTO custom_workflows (name, description, created_at, updated_at, is_builtin, enabled, metadata)
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -631,7 +631,7 @@ ${h.join(`
|
|
|
631
631
|
END { for (f in files) print files[f], lastmod[f], f }
|
|
632
632
|
'`,{cwd:n,maxBuffer:10485760}),r=Math.floor(Date.now()/1e3),s=e.trim().split(`
|
|
633
633
|
`).filter(Boolean);for(let i of s){let o=i.match(/^(\d+)\s+(\d+)\s+(.+)$/);if(o){let a=parseInt(o[1],10),l=parseInt(o[2],10),u=o[3],d=Math.floor((r-l)/86400);t.set(u,{commits:a,daysAgo:d})}}}catch{}return t}function lw(n,t,e,r){let s=[],i=0,o=0,a=0,l=0,u=0,d=n.toLowerCase(),p=d.split("/").join(" ").split(/[^a-z0-9]+/);for(let T of t){d.includes(T)&&(i+=.3,s.push(`keyword:${T}`));for(let b of p)if(b.includes(T)||T.includes(b)){i+=.15;break}}i=Math.min(1,i);for(let[T,b]of Object.entries(Yu))for(let P of b)if(d.includes(P)&&t.some(D=>b.includes(D)||D.includes(T)||T.includes(D))){o+=.4,s.push(`domain:${T}`);break}o=Math.min(1,o);let m=e.get(n);m&&(m.daysAgo<=1?(a=1,s.push("recent:1d")):m.daysAgo<=3?(a=.8,s.push("recent:3d")):m.daysAgo<=7?(a=.6,s.push("recent:1w")):m.daysAgo<=30&&(a=.3,s.push("recent:1m")),m.commits>=5&&(a=Math.min(1,a+.2)));let g=Ps.basename(n).toLowerCase();if((g.includes("index")||g.includes("main")||g.includes("app")||g.includes("entry"))&&(l=.5,s.push("import:0")),(d.includes("/core/")||d.includes("/shared/")||d.includes("/lib/"))&&(l=Math.max(l,.3),s.some(T=>T.startsWith("import:"))||s.push("import:1")),r){let T=r.get(n);T!==void 0&&(u=(T+1)/2,T>0?s.push("history:boosted"):T<0&&s.push("history:penalized"))}let x=r&&r.size>0?i*.54+o*.18+a*.13+l*.05+u*.1:i*.6+o*.2+a*.15+l*.05;return{path:n,score:Math.min(1,x),reasons:[...new Set(s)]}}function uw(n){let t=n.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("__tests__")||t.includes("__mocks__")||t.includes("/tests/")||t.includes("/test/")||t.endsWith("_test.go")||t.endsWith("_test.py")}var Do=f(()=>{"use strict";J();wt();Vt();ep();c(_s,"findRelevantFiles");c(ow,"extractKeywords");c(aw,"getAllCodeFiles");c(cw,"getGitRecency");c(lw,"scoreFile");c(uw,"isTestFile")});var lp,$o,Xt,up,cn,br=f(()=>{"use strict";lp="memory.",$o="remember.",Xt=`${lp}${$o}`,up=`${lp}task.tagged`,cn="status.changed"});function dp(n,t){try{return JSON.parse(n)}catch{return t}}function ln(n){let t=n.type.slice(Xt.length),e=dp(n.data,{});return{id:`mem_${n.id}`,type:t,content:e.content??"",tags:e.tags??{},rememberedAt:n.timestamp,source:e.source,provenance:e.provenance??"declared"}}function js(n){let t=n.data?dp(n.data,{}):{},e=t.tags??{};return n.type&&(e.type=n.type),{id:`ship_${n.id}`,type:"shipped",content:n.name,tags:e,rememberedAt:n.shipped_at,source:t.taskId,provenance:"extracted"}}function mp(n,t){let e=t.toLowerCase();if(n.content.toLowerCase().includes(e))return!0;for(let r of Object.values(n.tags))if(r.toLowerCase().includes(e))return!0;return!1}function gp(n,t){for(let[e,r]of Object.entries(t))if(n.tags[e]!==r)return!1;return!0}function fp(n){let t=new Set,e=[];for(let r of n){let s=r.tags.key;if(!s){e.push(r);continue}let i=`${r.type}::${s}`;t.has(i)||(t.add(i),e.push(r))}return e}function Mo(n){let t=new Set;for(let e of n){e.tags["superseded-by"]&&t.add(e.id);for(let r of["supersedes","duplicates"]){let s=e.tags[r];if(s)for(let i of String(s).matchAll(bw))t.add(`mem_${i[1]}`)}}return t}var Oo,pp,bw,Is=f(()=>{"use strict";br();Oo=["fact","decision","learning","gotcha","pattern","anti-pattern","shipped","inbox","todo","idea","insight","question","source","person","spec"],pp=Oo;c(dp,"safeJson");c(ln,"rowToEntry");c(js,"shippedRowToEntry");c(mp,"matchesTopic");c(gp,"matchesTags");c(fp,"dedupeLatestByKey");bw=/\bmem[_-](\d+)\b/g;c(Mo,"collectSupersededIds")});function Lo(n){let t=[];for(let{name:e,re:r}of hp)r.test(n)&&t.push(e);return t}function yp(n){return n.replace(/[`*_[\](){}<>\\]/g,t=>`\\${t}`)}var hp,WC,Ds=f(()=>{"use strict";hp=[{name:"instruction-override",re:/\b(ignore|disregard|override|forget)\b[^.]{0,40}\b(previous|prior|above|system|prompt|instructions?|rules?|constraints?)\b/i},{name:"role-play-injection",re:/\b(you\s+are\s+now|act\s+as|pretend\s+to\s+be|roleplay\s+as|assume\s+the\s+role)\b[^.]{0,40}\b(system|admin|root|developer|operator|jailbreak)\b/i},{name:"jailbreak-phrase",re:/\b(DAN\s+mode|do\s+anything\s+now|without\s+restrictions?|bypass\s+(?:safety|filters?|guidelines?)|jailbreak\s+mode)\b/i},{name:"fake-system-tag",re:/<\s*(?:system|assistant|tool[_-]?call|function[_-]?call)\s*>/i}],WC=hp.map(n=>n.name);c(Lo,"scanForPromptInjection");c(yp,"escapeMarkdownInline")});function vw(n){return n.replace(/[[\]|]/g,"").replace(/\s+/g," ").trim()}function Fe(n){let t=(n.content??"").trim();t=t.replace(/^(?:[-*•]\s+|\s+)+/,""),t=t.replace(/^(?:\[\[[^\]]*\]\]|mem[_-]\d+)[\s:,-]*/i,"").trim();let e=t.length;for(let i of[/\n/,/\.\s/,/:\s/,/;\s/,/\s—\s/,/\s\(/]){let o=t.match(i);o&&o.index!==void 0&&o.index>4&&o.index<e&&(e=o.index)}let r=t.slice(0,e).replace(/\s+/g," ").trim();if(r=r.replace(/\[\[[^\]|]*\|([^\]]*)\]\]/g,"$1").replace(/\[\[([^\]]*)\]\]/g,"$1").trim(),r.length>wp){let i=r.slice(0,wp),o=i.lastIndexOf(" ");r=`${(o>40?i.slice(0,o):i).trim()}\u2026`}r.length<6&&(r=`${n.type} ${n.id}`);let s=n.tags?.pr;return s&&!new RegExp(`\\b#?${s}\\b`).test(r)&&(r=`${r} (PR #${s})`),r}function de(n,t){return n.replace(/\[\[(mem[_-]\d+)\]\]/gi,"$1").replace(/\bmem[_-](\d+)\b/g,(e,r)=>{let s=`mem_${r}`,i=t?.idTypeIndex?.get(s),o=t?.idTitleIndex?.get(s),a=t?.idSlugIndex?.get(s),l=o?vw(o):s;return t?.signalIds?.has(s)?`[[signals#^mem-${r}|${l}]]`:a&&i&&t?.perEntryTypes?.has(i)?`[[${a}|${l}]]`:i?`[[${i}#^mem-${r}|${l}]]`:o?`[[${s}|${l}]]`:`\`${s}\``})}function un(n,t){if(n.length===0)return"> No matching memory entries.";let e=new Map;for(let u of n){let d=e.get(u.type)??[];d.push(u),e.set(u.type,d)}let r=["decision","learning","anti-pattern","gotcha","pattern","fact","inbox","todo","idea","insight","question","source","person","shipped"],s=[],i={declared:"DECL",extracted:"EXTR",inferred:"INFR",ambiguous:"AMBG"},o=t?.boundary==="llm",a=c((u,d)=>{if(d.length!==0){s.push(`### ${u.toUpperCase()}`);for(let p of d){let m=Object.entries(p.tags).filter(([S])=>!t?.vault||!Ns.has(S)).map(([S,D])=>`${S}=${o?yp(D):D}`).join(" "),g=i[p.provenance],h=t?.vault?de(p.content,t):p.content,x=m?` _(${t?.vault?de(m,t):m})_`:"",T=p.id.replace(/^mem[_-]/,""),b=t?.vault?` ^mem-${T}`:"",P=`- \`${g}\` [${p.id} \xB7 ${p.type}] ${h}${x}${b}`;o?(s.push(`<user_content id="${p.id}" type="${p.type}">`),s.push(P),s.push("</user_content>")):s.push(P)}s.push("")}},"renderGroup"),l=new Set;for(let u of r){let d=e.get(u);!d||d.length===0||(a(u,d),l.add(u))}for(let[u,d]of e)l.has(u)||a(u,d);return s.join(`
|
|
634
|
-
`).trim()}var Ns,wp,pn=f(()=>{"use strict";Ds();Ns=new Set(["source","session","window_days","window-days","touches","occurrences","phrase","slug","hash","content-hash","content_hash","key","kind","spec-id","spec_id"]),wp=72;c(vw,"linkLabel");c(Fe,"deriveTitle");c(de,"linkifyMemRefs");c(un,"formatMemoryMd")});var Fo,At,dn=f(()=>{"use strict";bt();on();Q();Fo=class{static{c(this,"MemoryService")}async log(t,e,r,s){try{let i=await X.getProjectId(t);return i?{eventId:k.appendEvent(i,`memory.${e}`,{...r,author:s}),projectId:i}:null}catch(i){return console.error(`Memory log error: ${i instanceof Error?i.message:String(i)}`),null}}async getRecent(t,e=100){try{let r=await X.getProjectId(t);return r?k.query(r,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",e).reverse().map(i=>{let o=JSON.parse(i.data),{author:a,...l}=o;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:l,author:a}}):[]}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async search(t,e,r=50){let s=await this.getRecent(t,1e3),i=e.toLowerCase();return s.filter(o=>{let a=o.action.toLowerCase().includes(i),l=JSON.stringify(o.data).toLowerCase().includes(i);return a||l}).slice(-r)}async getByAction(t,e,r=50){try{let s=await X.getProjectId(t);return s?k.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${e}`,r).reverse().map(o=>{let a=JSON.parse(o.data),{author:l,...u}=a;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:u,author:l}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(t){try{let e=await X.getProjectId(t);if(!e)return;k.run(e,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(e){console.error(`Memory clear error: ${e instanceof Error?e.message:String(e)}`)}}async getRecentEvents(t,e=100){try{return k.query(t,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",e).reverse().map(s=>{let i=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...i}})}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async capEntries(t){try{let r=k.get(t,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%'")?.cnt??0;if(r<=Se.MEMORY_MAX_ENTRIES)return 0;let s=r-Se.MEMORY_MAX_ENTRIES,i=k.query(t,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id ASC LIMIT ?",s);Ht.archiveMany(t,i.map((a
|
|
634
|
+
`).trim()}var Ns,wp,pn=f(()=>{"use strict";Ds();Ns=new Set(["source","session","window_days","window-days","touches","occurrences","phrase","slug","hash","content-hash","content_hash","key","kind","spec-id","spec_id"]),wp=72;c(vw,"linkLabel");c(Fe,"deriveTitle");c(de,"linkifyMemRefs");c(un,"formatMemoryMd")});var Fo,At,dn=f(()=>{"use strict";bt();on();Q();Fo=class{static{c(this,"MemoryService")}async log(t,e,r,s){try{let i=await X.getProjectId(t);return i?{eventId:k.appendEvent(i,`memory.${e}`,{...r,author:s}),projectId:i}:null}catch(i){return console.error(`Memory log error: ${i instanceof Error?i.message:String(i)}`),null}}async getRecent(t,e=100){try{let r=await X.getProjectId(t);return r?k.query(r,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",e).reverse().map(i=>{let o=JSON.parse(i.data),{author:a,...l}=o;return{timestamp:i.timestamp,action:i.type.replace("memory.",""),data:l,author:a}}):[]}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async search(t,e,r=50){let s=await this.getRecent(t,1e3),i=e.toLowerCase();return s.filter(o=>{let a=o.action.toLowerCase().includes(i),l=JSON.stringify(o.data).toLowerCase().includes(i);return a||l}).slice(-r)}async getByAction(t,e,r=50){try{let s=await X.getProjectId(t);return s?k.query(s,"SELECT type, data, timestamp FROM events WHERE type = ? ORDER BY id DESC LIMIT ?",`memory.${e}`,r).reverse().map(o=>{let a=JSON.parse(o.data),{author:l,...u}=a;return{timestamp:o.timestamp,action:o.type.replace("memory.",""),data:u,author:l}}):[]}catch(s){return console.error(`Memory read error: ${s instanceof Error?s.message:String(s)}`),[]}}async clear(t){try{let e=await X.getProjectId(t);if(!e)return;k.run(e,"DELETE FROM events WHERE type LIKE 'memory.%'")}catch(e){console.error(`Memory clear error: ${e instanceof Error?e.message:String(e)}`)}}async getRecentEvents(t,e=100){try{return k.query(t,"SELECT type, data, timestamp FROM events WHERE type LIKE 'memory.%' ORDER BY id DESC LIMIT ?",e).reverse().map(s=>{let i=JSON.parse(s.data);return{timestamp:s.timestamp,action:s.type.replace("memory.",""),...i}})}catch(r){return console.error(`Memory read error: ${r instanceof Error?r.message:String(r)}`),[]}}async capEntries(t){try{let r=k.get(t,"SELECT COUNT(*) as cnt FROM events WHERE type LIKE 'memory.%' AND type NOT LIKE 'memory.remember.%'")?.cnt??0;if(r<=Se.MEMORY_MAX_ENTRIES)return 0;let s=r-Se.MEMORY_MAX_ENTRIES,i=k.query(t,"SELECT id, type, data, timestamp FROM events WHERE type LIKE 'memory.%' AND type NOT LIKE 'memory.remember.%' ORDER BY id ASC LIMIT ?",s);return Ht.archiveMany(t,i.map((o,a)=>({entityType:"memory_entry",entityId:`memory-${o.timestamp||a}`,entityData:{type:o.type,data:JSON.parse(o.data),timestamp:o.timestamp},summary:o.type.replace("memory.",""),reason:"overflow"}))),k.transaction(t,o=>{let a=o.prepare("DELETE FROM events WHERE id = ?");for(let l of i)a.run(l.id)}),s}catch(e){return console.error(`Memory cap error: ${e instanceof Error?e.message:String(e)}`),0}}},At=new Fo});var Ho={};st(Ho,{extractCorrectionIds:()=>Wo,extractRefIds:()=>Sp,usefulnessService:()=>$w});function Sp(n,t){let e=new Set;for(let r of Dw){let s=t[r];if(s)for(let i of String(s).matchAll(Uo))e.add(`mem_${i[1]}`)}for(let r of n.matchAll(Uo))e.add(`mem_${r[1]}`);for(let r of Wo(t))e.delete(r);return[...e]}function Wo(n){let t=new Set;for(let e of Nw){let r=n[e];if(r)for(let s of String(r).matchAll(Uo))t.add(`mem_${s[1]}`)}return[...t]}function kp(n,t,e,r,s){k.run(n,`INSERT INTO memory_usefulness (memory_id, score, ${r}, last_used_at)
|
|
635
635
|
VALUES (?, ?, 1, ?)
|
|
636
636
|
ON CONFLICT(memory_id) DO UPDATE SET
|
|
637
637
|
score = score + ?, ${r} = ${r} + 1, last_used_at = excluded.last_used_at`,t,e,s,e)}function $s(n,t,e,r){k.run(n,`INSERT INTO memory_usefulness (memory_id, score, last_used_at)
|