@vpxa/aikit 0.1.343 → 0.1.345
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/package.json +1 -1
- package/packages/blocks-core/dist/index.mjs +16 -16
- package/packages/cli/dist/index.js +19 -19
- package/packages/cli/dist/{init-DgYgDXBw.js → init-XINdWZ5p.js} +1 -1
- package/packages/cli/dist/{templates-DEHhml1n.js → templates-Cjsh5cLs.js} +48 -16
- package/packages/core/dist/index.d.ts +269 -2
- package/packages/core/dist/index.js +1 -1
- package/packages/flows/dist/index.d.ts +141 -4
- package/packages/flows/dist/index.js +6 -6
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/config-BsS-77rp.js +2 -0
- package/packages/server/dist/config-Ds28Hvip.js +1 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/prelude-DYBTvrwz.js +2 -0
- package/packages/server/dist/prelude-V2gaMyeg.js +1 -0
- package/packages/server/dist/promotion-DRnRfteq.js +3 -0
- package/packages/server/dist/promotion-DzVLWVtx.js +2 -0
- package/packages/server/dist/sampling-0YAQqixD.js +1 -0
- package/packages/server/dist/sampling-BQmYJ4pz.js +2 -0
- package/packages/server/dist/{server-WTo9MN4i.js → server--QWu4dF1.js} +196 -198
- package/packages/server/dist/{server-QHpy3Vo9.js → server-Cv8aM3Xx.js} +195 -199
- package/packages/server/dist/{server-http-fvgPEVn5.js → server-http-BF6fnIQ0.js} +1 -1
- package/packages/server/dist/{server-http-Cxq-Bg3K.js → server-http-DoIPqaqk.js} +1 -1
- package/packages/server/dist/{server-stdio-vC20j-3j.js → server-stdio-CFH9BET5.js} +1 -1
- package/packages/server/dist/{server-stdio-DiT0r0Q3.js → server-stdio-CXF39-d2.js} +1 -1
- package/packages/server/dist/{startup-maintenance-L9NUOBVy.js → startup-maintenance-CBJWiJ7p.js} +1 -1
- package/packages/server/dist/{startup-maintenance-DYmXBVTV.js → startup-maintenance-DX1yTfBa.js} +1 -1
- package/packages/server/dist/version-check-BjFqR01r.js +1 -0
- package/packages/server/dist/version-check-_2wmedTl.js +2 -0
- package/packages/tools/dist/index.d.ts +140 -1
- package/packages/tools/dist/index.js +87 -82
- package/scaffold/dist/adapters/_shared.mjs +9 -9
- package/scaffold/dist/definitions/agents.mjs +2 -2
- package/scaffold/dist/definitions/bodies.mjs +22 -14
- package/scaffold/dist/definitions/flows.mjs +28 -12
- package/scaffold/dist/definitions/protocols.mjs +38 -8
- package/scaffold/dist/definitions/skills/aikit.mjs +80 -17
- package/scaffold/dist/definitions/skills/docs.mjs +9 -0
- package/scaffold/dist/definitions/skills/lesson-learned.mjs +9 -0
- package/scaffold/dist/definitions/skills/multi-agents-development.mjs +10 -5
- package/scaffold/dist/definitions/skills/present.mjs +14 -0
- package/packages/server/dist/config-B-wvmMyo.js +0 -1
- package/packages/server/dist/config-Bx85fwRX.js +0 -2
- package/packages/server/dist/prelude-CYbX3SD5.js +0 -1
- package/packages/server/dist/prelude-SM1mxlBF.js +0 -2
- package/packages/server/dist/promotion-RbjKfC88.js +0 -3
- package/packages/server/dist/promotion-l1L8Vf7U.js +0 -2
- package/packages/server/dist/version-check-2-tfmCnt.js +0 -2
- package/packages/server/dist/version-check-BKtLrLhw.js +0 -1
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { FlowContextSnapshotV1 } from "../../core/dist/index.js";
|
|
2
|
+
|
|
1
3
|
//#region packages/flows/src/types.d.ts
|
|
2
4
|
/**
|
|
3
5
|
* @aikit/flows — Type definitions for the pluggable flow system.
|
|
@@ -164,6 +166,16 @@ interface FlowState {
|
|
|
164
166
|
roots?: string[];
|
|
165
167
|
/** The canonical workspace root that owns this flow run */
|
|
166
168
|
primaryRoot?: string;
|
|
169
|
+
/** L1 snapshot objective. Falls back to topic when absent. */
|
|
170
|
+
objective?: string;
|
|
171
|
+
/** L1 snapshot acceptance criteria. */
|
|
172
|
+
acceptanceCriteria?: string[];
|
|
173
|
+
/** L1 snapshot scope. Falls back to roots when absent. */
|
|
174
|
+
scope?: string[];
|
|
175
|
+
/** L1 snapshot exclusions. */
|
|
176
|
+
exclusions?: string[];
|
|
177
|
+
/** L1 snapshot retrieved references. */
|
|
178
|
+
retrievedRefs?: string[];
|
|
167
179
|
}
|
|
168
180
|
/** Persisted meta.json for a flow run under .flows/{slug}/ */
|
|
169
181
|
interface FlowRunMeta {
|
|
@@ -203,6 +215,31 @@ interface FlowRunMeta {
|
|
|
203
215
|
roots?: string[];
|
|
204
216
|
/** The canonical workspace root that owns this flow run */
|
|
205
217
|
primaryRoot?: string;
|
|
218
|
+
/** L1 snapshot objective — the goal of this flow run. Falls back to topic when absent. */
|
|
219
|
+
objective?: string;
|
|
220
|
+
/** L1 snapshot acceptance criteria. Empty when not specified at start. */
|
|
221
|
+
acceptanceCriteria?: string[];
|
|
222
|
+
/** L1 snapshot scope — explicit scope boundaries. Falls back to roots when absent. */
|
|
223
|
+
scope?: string[];
|
|
224
|
+
/** L1 snapshot exclusions — what's explicitly out of scope. */
|
|
225
|
+
exclusions?: string[];
|
|
226
|
+
/** L1 snapshot retrieved references — accumulates across steps. */
|
|
227
|
+
retrievedRefs?: string[];
|
|
228
|
+
/** Salt for SHA-256 lifecycle owner token. Present only in layered mode. */
|
|
229
|
+
ownerTokenSalt?: string;
|
|
230
|
+
/** SHA-256 hash of lifecycle owner token. Present only in layered mode. */
|
|
231
|
+
ownerTokenHash?: string;
|
|
232
|
+
/** Monotonically increasing owner token version for rotation tracking. */
|
|
233
|
+
ownerTokenVersion?: number;
|
|
234
|
+
/** Append-only audit log of lifecycle events. Present only in layered mode. */
|
|
235
|
+
auditLog?: Array<{
|
|
236
|
+
event: 'claim' | 'backtrack' | 'reset' | 'final-consolidation';
|
|
237
|
+
at: string;
|
|
238
|
+
ownerTokenVersion: number;
|
|
239
|
+
targetStep?: string;
|
|
240
|
+
invalidatedExecutionTokens?: string[];
|
|
241
|
+
reason?: string;
|
|
242
|
+
}>;
|
|
206
243
|
}
|
|
207
244
|
/** Summary of a flow run for listing */
|
|
208
245
|
interface FlowRunSummary {
|
|
@@ -224,7 +261,7 @@ interface FlowRunSummary {
|
|
|
224
261
|
updatedAt: string;
|
|
225
262
|
}
|
|
226
263
|
/** Step action for state machine transitions */
|
|
227
|
-
type StepAction = 'next' | 'skip' | 'redo';
|
|
264
|
+
type StepAction = 'next' | 'skip' | 'redo' | 'backtrack';
|
|
228
265
|
/** Position of an epilogue step relative to the flow's own steps */
|
|
229
266
|
type EpiloguePosition = 'before' | 'after';
|
|
230
267
|
/** An epilogue step — mandatory step injected by aikit around every flow */
|
|
@@ -361,6 +398,42 @@ interface BuiltinFlow {
|
|
|
361
398
|
*/
|
|
362
399
|
declare function getBuiltinFlows(): BuiltinFlow[];
|
|
363
400
|
//#endregion
|
|
401
|
+
//#region packages/flows/src/context-snapshot.d.ts
|
|
402
|
+
/**
|
|
403
|
+
* Set of verified, assumed, and unresolved claims for a flow context snapshot.
|
|
404
|
+
*/
|
|
405
|
+
interface ClaimSet {
|
|
406
|
+
verified: string[];
|
|
407
|
+
assumed: string[];
|
|
408
|
+
unresolved: string[];
|
|
409
|
+
decisions: Array<{
|
|
410
|
+
id: string;
|
|
411
|
+
summary: string;
|
|
412
|
+
rationale: string;
|
|
413
|
+
}>;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Options for building a flow context snapshot.
|
|
417
|
+
*/
|
|
418
|
+
interface BuildSnapshotOptions {
|
|
419
|
+
claims?: ClaimSet;
|
|
420
|
+
/** Optional overrides for snapshot fields. When absent, reads from FlowState. */
|
|
421
|
+
objective?: string;
|
|
422
|
+
acceptanceCriteria?: string[];
|
|
423
|
+
scope?: string[];
|
|
424
|
+
exclusions?: string[];
|
|
425
|
+
retrievedRefs?: string[];
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Construct a FlowContextSnapshotV1 from state machine state + resolved artifacts/claims.
|
|
429
|
+
*
|
|
430
|
+
* @param state - Current flow execution state
|
|
431
|
+
* @param manifest - Flow manifest defining steps, hooks, and artifact paths
|
|
432
|
+
* @param options - Optional claims set
|
|
433
|
+
* @returns A complete FlowContextSnapshotV1
|
|
434
|
+
*/
|
|
435
|
+
declare function buildSnapshot(state: FlowState, manifest: FlowManifest, options?: BuildSnapshotOptions): FlowContextSnapshotV1;
|
|
436
|
+
//#endregion
|
|
364
437
|
//#region packages/flows/src/foundation.d.ts
|
|
365
438
|
declare class FoundationIntegration {
|
|
366
439
|
/**
|
|
@@ -428,6 +501,57 @@ declare class GitInstaller {
|
|
|
428
501
|
private ensureFlowsDir;
|
|
429
502
|
}
|
|
430
503
|
//#endregion
|
|
504
|
+
//#region packages/flows/src/lifecycle-capability.d.ts
|
|
505
|
+
/**
|
|
506
|
+
* Lifecycle owner capability — token generation, validation, and rotation
|
|
507
|
+
* for flow ownership verification.
|
|
508
|
+
*
|
|
509
|
+
* Generates cryptographically random owner tokens, stores only salted SHA-256
|
|
510
|
+
* hashes, and validates presented tokens with constant-time comparison.
|
|
511
|
+
*/
|
|
512
|
+
/** Configuration for owner capability */
|
|
513
|
+
interface OwnerCapabilityConfig {
|
|
514
|
+
/** Byte length of generated token. 32 = 256-bit. Default: 32. */
|
|
515
|
+
tokenBytes?: number;
|
|
516
|
+
/** Salt byte length. Default: 16. */
|
|
517
|
+
saltBytes?: number;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Generate a cryptographically random owner token.
|
|
521
|
+
* Returns the raw hex token. Store only the salted hash.
|
|
522
|
+
*/
|
|
523
|
+
declare function generateOwnerToken(config?: OwnerCapabilityConfig): string;
|
|
524
|
+
/**
|
|
525
|
+
* Hash a token with a salt using SHA-256.
|
|
526
|
+
* Returns hex-encoded hash.
|
|
527
|
+
*/
|
|
528
|
+
declare function hashToken(token: string, salt: string): string;
|
|
529
|
+
/**
|
|
530
|
+
* Validate a presented token against stored salt + hash.
|
|
531
|
+
* Uses constant-time comparison for equal-length hashes.
|
|
532
|
+
* Returns false for length mismatch (safe early exit — no secret data leaked).
|
|
533
|
+
*/
|
|
534
|
+
declare function validateToken(presented: string, salt: string, hash: string): boolean;
|
|
535
|
+
/**
|
|
536
|
+
* Create a full owner capability record for flow start.
|
|
537
|
+
*/
|
|
538
|
+
declare function createOwnerCapability(): {
|
|
539
|
+
rawToken: string;
|
|
540
|
+
salt: string;
|
|
541
|
+
hash: string;
|
|
542
|
+
version: number;
|
|
543
|
+
};
|
|
544
|
+
/**
|
|
545
|
+
* Rotate an owner capability: invalidate old, create new.
|
|
546
|
+
* Returns new raw token (returned once) alongside salt/hash/version.
|
|
547
|
+
*/
|
|
548
|
+
declare function rotateOwnerCapability(currentVersion: number): {
|
|
549
|
+
rawToken: string;
|
|
550
|
+
salt: string;
|
|
551
|
+
hash: string;
|
|
552
|
+
version: number;
|
|
553
|
+
};
|
|
554
|
+
//#endregion
|
|
431
555
|
//#region packages/flows/src/loader.d.ts
|
|
432
556
|
declare class FlowLoader {
|
|
433
557
|
load(sourceDir: string, options?: FlowParseOptions): Promise<FlowResult<{
|
|
@@ -479,7 +603,7 @@ declare class FlowStateMachine {
|
|
|
479
603
|
private readMeta;
|
|
480
604
|
/** Persist a run meta.json to disk */
|
|
481
605
|
private writeMeta;
|
|
482
|
-
/** Backfill
|
|
606
|
+
/** Backfill legacy fields for persisted runs created before token/lifecycle tracking existed */
|
|
483
607
|
private normalizeMeta;
|
|
484
608
|
/** Check whether a step already has a completed execution token */
|
|
485
609
|
private hasCompletedExecution;
|
|
@@ -494,7 +618,14 @@ declare class FlowStateMachine {
|
|
|
494
618
|
/** Convert persisted run metadata into the public FlowState shape */
|
|
495
619
|
private metaToState;
|
|
496
620
|
/** Start a new flow */
|
|
497
|
-
start(flowName: string, manifest: FlowManifest, topic?: string, flowOrigin?: FlowDefinitionOrigin
|
|
621
|
+
start(flowName: string, manifest: FlowManifest, topic?: string, flowOrigin?: FlowDefinitionOrigin, flowOptions?: {
|
|
622
|
+
objective?: string;
|
|
623
|
+
acceptanceCriteria?: string[];
|
|
624
|
+
scope?: string[];
|
|
625
|
+
exclusions?: string[];
|
|
626
|
+
}): FlowResult<FlowState>;
|
|
627
|
+
/** Backtrack to a completed step, invalidating all steps after it */
|
|
628
|
+
backtrack(targetStep: string, manifest: FlowManifest): FlowResult<FlowState>;
|
|
498
629
|
/** Advance the flow: next, skip, or redo current step */
|
|
499
630
|
step(action: StepAction, manifest: FlowManifest): FlowResult<FlowState>;
|
|
500
631
|
/** Get current flow status */
|
|
@@ -503,6 +634,12 @@ declare class FlowStateMachine {
|
|
|
503
634
|
reset(): FlowResult;
|
|
504
635
|
/** Record an artifact produced by a step */
|
|
505
636
|
recordArtifact(name: string, path: string): FlowResult;
|
|
637
|
+
/** Set owner capability fields on the active run (persisted). */
|
|
638
|
+
setOwnerCapability(ownerData: {
|
|
639
|
+
ownerTokenSalt: string;
|
|
640
|
+
ownerTokenHash: string;
|
|
641
|
+
ownerTokenVersion: number;
|
|
642
|
+
}): FlowResult;
|
|
506
643
|
/** List flow runs, optionally filtered by flow name or status */
|
|
507
644
|
listRuns(filter?: {
|
|
508
645
|
flow?: string;
|
|
@@ -524,4 +661,4 @@ declare class SymlinkManager {
|
|
|
524
661
|
private getAgentStem;
|
|
525
662
|
}
|
|
526
663
|
//#endregion
|
|
527
|
-
export { type BuiltinFlow, ClaudePluginAdapter, type ContentTransformFn, CopilotAdapter, type EpilogueConfig, type EpiloguePosition, type EpilogueStepDef, type FlowDefinitionOrigin, type FlowFormat, type FlowFormatAdapter, type FlowHookConfig, FlowLoader, type FlowManifest, type FlowParseOptions, type FlowPhase, type FlowRegistry, type FlowRegistryEntry, FlowRegistryManager, type FlowResult, type FlowRunMeta, type FlowRunSummary, type FlowSourceType, type FlowState, FlowStateMachine, type FlowStatus, type FlowStep, FoundationIntegration, GitInstaller, NativeAdapter, OpenSpecAdapter, type StepAction, SymlinkManager, getBuiltinFlows };
|
|
664
|
+
export { type BuildSnapshotOptions, type BuiltinFlow, type ClaimSet, ClaudePluginAdapter, type ContentTransformFn, CopilotAdapter, type EpilogueConfig, type EpiloguePosition, type EpilogueStepDef, type FlowDefinitionOrigin, type FlowFormat, type FlowFormatAdapter, type FlowHookConfig, FlowLoader, type FlowManifest, type FlowParseOptions, type FlowPhase, type FlowRegistry, type FlowRegistryEntry, FlowRegistryManager, type FlowResult, type FlowRunMeta, type FlowRunSummary, type FlowSourceType, type FlowState, FlowStateMachine, type FlowStatus, type FlowStep, FoundationIntegration, GitInstaller, NativeAdapter, OpenSpecAdapter, type OwnerCapabilityConfig, type StepAction, SymlinkManager, buildSnapshot, createOwnerCapability, generateOwnerToken, getBuiltinFlows, hashToken, rotateOwnerCapability, validateToken };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{copyFileSync as e,cpSync as t,existsSync as n,mkdirSync as r,readFileSync as i,readdirSync as a,renameSync as o,rmSync as s,rmdirSync as c,symlinkSync as l,unlinkSync as u,writeFileSync as d}from"node:fs";import{basename as f,dirname as p,join as m,relative as h}from"node:path";import{parse as g}from"yaml";import{execSync as _,spawnSync as v}from"node:child_process";import{tmpdir as y}from"node:os";const
|
|
1
|
+
import{copyFileSync as e,cpSync as t,existsSync as n,mkdirSync as r,readFileSync as i,readdirSync as a,renameSync as o,rmSync as s,rmdirSync as c,symlinkSync as l,unlinkSync as u,writeFileSync as d}from"node:fs";import{basename as f,dirname as p,join as m,relative as h}from"node:path";import{parse as g}from"yaml";import{execSync as _,spawnSync as v}from"node:child_process";import{tmpdir as y}from"node:os";import{createHash as b,randomBytes as x,timingSafeEqual as S}from"node:crypto";const C=[`spec`,`design`,`plan`,`task`,`execute`,`verify`];function ee(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!t)return{data:{},body:e};let n=g(t[1]),r={};if(n&&typeof n==`object`&&!Array.isArray(n))for(let[e,t]of Object.entries(n))r[e]=String(t);return{data:r,body:t[2]}}function w(e){return e.split(/[-_]/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function T(e){let t=C.indexOf(e);if(t!==-1)return t;let n=e.lastIndexOf(`.`);if(n!==-1){let t=e.slice(n+1),r=C.indexOf(t);if(r!==-1)return r}return 1/0}var E=class{format=`claude-plugin`;detect(e){return n(m(e,`.claude-plugin`,`plugin.json`))}async parse(e,t){let n=this.readPluginJson(e),r=this.discoverSteps(e);await this.materializeNativeSteps(e,r,t);let i=this.discoverAgents(e),a=r.map(({step:e})=>e);return{name:this.readString(n.name)??f(e),version:this.readString(n.version)??`1.0.0`,description:this.readString(n.description)??``,author:this.readString(n.author),steps:a,agents:i,artifacts_dir:`.spec`,install:[]}}readPluginJson(e){let t=m(e,`.claude-plugin`,`plugin.json`);return JSON.parse(i(t,`utf-8`))}readString(e){return typeof e==`string`?e:void 0}discoverSteps(e){let t=m(e,`skills`);if(!n(t))return[];let r=a(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).map(t=>this.readStep(e,t)).filter(e=>e!==null).sort((e,t)=>{let n=Number(e.metadata.order),r=Number(t.metadata.order),i=Number.isFinite(n),a=Number.isFinite(r);if(i&&a)return n-r;if(i)return-1;if(a)return 1;let o=T(e.step.id),s=T(t.step.id);return o===s?e.step.id.localeCompare(t.step.id):o-s});return r.map((e,t)=>({...e,step:{...e.step,requires:t>0?[r[t-1].step.id]:[]}}))}readStep(e,t){let r=m(e,`skills`,t,`SKILL.md`);if(!n(r))return null;let a=i(r,`utf-8`),{data:o,body:s}=ee(a),c=o.name||w(t),l=o.description||`${c} step`;return{step:{id:t,name:c,instruction:`steps/${t}/README.md`,produces:[`${t}.md`],requires:[],agents:[],description:l},metadata:o,content:a,body:s}}syncStepAssets(e,r,i){let a=[`references`,`assets`,`scripts`];for(let o of r)for(let r of a){let a=m(e,`skills`,o.id,r),c=m(e,`steps`,o.id,r);if(n(a)){if(n(c)){if(!i)continue;s(c,{recursive:!0,force:!0})}t(a,c,{recursive:!0})}}}async materializeNativeSteps(e,t,n){for(let i of t){let t=m(e,`steps`,i.step.id);r(t,{recursive:!0});let a=n?.transform?await n.transform({content:i.content,sourceFormat:`claude-plugin`,stepName:i.step.id,metadata:i.metadata}):this.buildStepReadme(i.step.name,i.step.description,i.body);d(m(t,`README.md`),a,`utf-8`)}this.syncStepAssets(e,t.map(({step:e})=>e),n?.forceAssetSync)}buildStepReadme(e,t,n){return[`# ${e}`,``,t,``,`---`,``,n.trim()].join(`
|
|
2
2
|
`).trimEnd().concat(`
|
|
3
|
-
`)}discoverAgents(e){let t=m(e,`agents`);return n(t)?a(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>`agents/${e.name}`):[]}},T=class{format=`copilot`;detect(e){return n(m(e,`.github`,`agents`))}async parse(e,t){let n=a(m(e,`.github`,`agents`),{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>`.github/agents/${e.name}`),r=n.map(e=>this.getStepId(e)),i=n.map((e,t)=>{let n=r[t];return{id:n,name:n.charAt(0).toUpperCase()+n.slice(1),instruction:`steps/${n}/README.md`,produces:[`${n}.md`],requires:t>0?[r[t-1]]:[],agents:[e],description:`${n} agent step`}});return await this.materializeSteps(e,i,t),{name:f(e),version:`1.0.0`,description:`Copilot agents flow from ${f(e)}`,steps:i,agents:n,artifacts_dir:`.spec`,install:[]}}getStepId(e){return f(e,`.md`).toLowerCase().replace(/\.agent$/,``)}async materializeSteps(e,t,n){for(let a of t){let t=a.agents[0];if(!t)continue;let o=i(m(e,t),`utf-8`),s=m(e,`steps`,a.id),c=m(s,`README.md`);r(s,{recursive:!0}),d(c,n?.transform?await n.transform({content:o,sourceFormat:`copilot`,stepName:a.id,metadata:{sourcePath:t,displayName:a.name}}):`# ${a.name}\n\n${o}`,`utf-8`)}}},E=class{format=`native`;detect(e){return n(m(e,`flow.json`))}async parse(e){let t=i(m(e,`flow.json`),`utf-8`);return JSON.parse(t)}},D=class{format=`openspec`;detect(e){return!!(n(m(e,`openspec`,`config.yaml`))||n(m(e,`schemas`))&&this.findSchemaYaml(e))}async parse(e,t){let n=this.readMeta(e),r=this.loadSchema(e),i=this.buildStepsFromSchema(r);return await this.materializeSteps(e,i,r,t),{name:n.name,version:n.version,description:r.description??n.description,author:n.author,steps:i,agents:[],artifacts_dir:`openspec`,install:[]}}readMeta(e){let t=m(e,`package.json`);if(n(t))try{let n=JSON.parse(i(t,`utf-8`));return{name:n.name??f(e),version:n.version??`0.1.0`,description:n.description??`OpenSpec flow`,author:n.author}}catch{}return{name:f(e),version:`0.1.0`,description:`OpenSpec flow`}}readConfigSchema(e){let t=m(e,`openspec`,`config.yaml`);if(!n(t))return`spec-driven`;try{let e=g(i(t,`utf-8`));return typeof e?.schema==`string`&&e.schema.trim().length>0?e.schema:`spec-driven`}catch{return`spec-driven`}}resolveSchemaDir(e){let t=this.readConfigSchema(e),r=m(e,`openspec`,`schemas`,t);if(n(m(r,`schema.yaml`)))return r;let i=m(e,`schemas`,t);if(n(m(i,`schema.yaml`)))return i;try{let e=m(_(`npm root -g`,{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).trim(),`@fission-ai`,`openspec`,`schemas`,t);if(n(m(e,`schema.yaml`)))return e}catch{}return null}parseSchemaArtifacts(e){try{let t=g(e);if(!t||!Array.isArray(t.artifacts))return null;let n=t.artifacts.map(e=>this.normalizeArtifact(e)).filter(e=>e!==null);return n.length===0?null:{name:typeof t.name==`string`&&t.name.trim().length>0?t.name:this.readString(t.schema)??`spec-driven`,version:typeof t.version==`number`?t.version:1,description:this.readString(t.description),artifacts:n,apply:this.normalizeApply(t.apply)}}catch{return null}}loadSchema(e){let t=this.resolveSchemaDir(e);if(t){let e=m(t,`schema.yaml`);try{let t=i(e,`utf-8`),n=this.parseSchemaArtifacts(t);if(n)return n}catch{}}return this.discoverSchemaFromDirectory(e)}discoverSchemaFromDirectory(e){let t=[m(e,`openspec`,`schemas`),m(e,`schemas`)];for(let e of t)if(n(e))try{let t=a(e,{withFileTypes:!0}).filter(e=>e.isDirectory());for(let r of t){let t=m(e,r.name,`schema.yaml`);if(n(t))try{let e=this.parseSchemaArtifacts(i(t,`utf-8`));if(e)return e}catch{}}}catch{}let r=[],o=m(e,`openspec`),s=[],c=this.collectMarkdownFiles(o);for(let e of c){let t=h(o,e).replace(/\\/g,`/`),n=this.toStepIdFromMarkdown(t);!n||s.includes(n)||(r.push({id:n,generates:t,description:`${this.humanizeStepName(n)} phase`,template:f(e),requires:s.length>0?[s[s.length-1]]:[]}),s.push(n))}return{name:this.readConfigSchema(e),version:1,artifacts:r}}collectMarkdownFiles(e){if(!n(e))return[];let t=[];try{let n=a(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name));for(let r of n){let n=m(e,r.name);if(r.isFile()&&r.name.toLowerCase().endsWith(`.md`)){t.push(n);continue}r.isDirectory()&&t.push(...this.collectMarkdownFiles(n))}}catch{}return t}hasFileRecursive(e,t){if(!n(e))return!1;try{let n=a(e,{withFileTypes:!0});for(let r of n)if(r.isFile()&&r.name===t||r.isDirectory()&&this.hasFileRecursive(m(e,r.name),t))return!0}catch{}return!1}findSchemaYaml(e){let t=m(e,`schemas`);if(!n(t))return!1;try{return a(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).some(e=>n(m(t,e.name,`schema.yaml`)))}catch{return!1}}toStepIdFromMarkdown(e){let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)return null;let n=(t[t.length-1]??``).replace(/\.md$/i,``);return(n.toLowerCase()===`readme`&&t.length>1?t[t.length-2]:n).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||null}buildStepsFromSchema(e){let t=e.artifacts.map(e=>({id:e.id,name:this.humanizeStepName(e.id),instruction:`steps/${e.id}/README.md`,produces:e.generates?[e.generates]:[],requires:e.requires,agents:[],description:e.description}));return e.apply&&t.push({id:`apply`,name:`Apply`,instruction:`steps/apply/README.md`,produces:[],requires:e.apply.requires,agents:[],description:`Implement the tasks, writing code and tests according to the design`}),t}async materializeSteps(e,t,i,a){let o=this.resolveSchemaDir(e),s=new Map(i.artifacts.map(e=>[e.id,e]));for(let c of t){let t=m(e,`steps`,c.id),l=m(t,`README.md`);r(t,{recursive:!0});let u=this.resolveInstructionContent(o,c.id,s.get(c.id),i.apply);if(!u){n(l)||d(l,`# ${c.name}\n\n${c.description}\n`,`utf-8`);continue}d(l,a?.transform?await a.transform({content:u,sourceFormat:`openspec`,stepName:c.id,metadata:{schemaName:i.name,displayName:c.name,description:c.description,produces:c.produces,requires:c.requires}}):`# ${c.name}\n\n${u}`,`utf-8`)}}resolveInstructionContent(e,t,r,a){if(t===`apply`&&a?.instruction)return a.instruction;if(!r)return null;if(r.instruction)return r.instruction;if(e&&r.template){let t=m(e,`templates`,r.template);if(n(t))try{return i(t,`utf-8`)}catch{}}return r.description||null}normalizeArtifact(e){if(!e||typeof e!=`object`)return null;let t=e,n=this.readString(t.id),r=this.readString(t.generates);return!n||!r?null:{id:n,generates:r,description:this.readString(t.description)??`${this.humanizeStepName(n)} phase`,template:this.readString(t.template)??``,instruction:this.readString(t.instruction),requires:this.readStringArray(t.requires)}}normalizeApply(e){if(!e||typeof e!=`object`)return;let t=e;return{requires:this.readStringArray(t.requires),tracks:this.readString(t.tracks)??null,instruction:this.readString(t.instruction)}}readString(e){return typeof e==`string`&&e.trim().length>0?e:void 0}readStringArray(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.length>0):[]}humanizeStepName(e){return e.split(/[-_]/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}};const O={name:`aikit:basic`,version:`0.2.0`,description:`Quick development flow for bug fixes, small features, and refactoring`,steps:[{id:`design`,name:`Design Gate`,instruction:`steps/design/README.md`,produces:[`design-decisions.md`],requires:[],agents:[`Researcher-Alpha`,`Researcher-Beta`,`Researcher-Gamma`,`Researcher-Delta`],description:`Evaluate task type, run brainstorming for features, FORGE classification. Auto-skips for bug fixes and refactors.`},{id:`assess`,name:`Assessment`,instruction:`steps/assess/README.md`,produces:[`assessment.md`],requires:[`design-decisions.md`],agents:[`Explorer`,`Researcher-Alpha`],description:`Understand scope, analyze codebase, identify approach`},{id:`implement`,name:`Implementation`,instruction:`steps/implement/README.md`,produces:[`progress.md`],requires:[`assessment.md`],agents:[`Implementer`,`Frontend`],description:`Write code following the assessment plan`},{id:`verify`,name:`Verification`,instruction:`steps/verify/README.md`,produces:[`verify-report.md`],requires:[`progress.md`],agents:[`Code-Reviewer-Alpha`,`Security`],description:`Review code, run tests, validate changes`}],agents:[],artifacts_dir:`.spec`,install:[]},k={name:`aikit:advanced`,version:`0.2.0`,description:`Full development flow for new features, API design, and architecture changes`,steps:[{id:`design`,name:`Design Gate`,instruction:`steps/design/README.md`,produces:[`design-decisions.md`],requires:[],agents:[`Researcher-Alpha`,`Researcher-Beta`,`Researcher-Gamma`,`Researcher-Delta`],description:`Full brainstorming, FORGE classification, decision protocol with parallel research. ADR for critical-tier tasks.`},{id:`spec`,name:`Specification`,instruction:`steps/spec/README.md`,produces:[`spec.md`],requires:[`design-decisions.md`],agents:[`Researcher-Alpha`],description:`Elicit requirements, clarify scope, define acceptance criteria`},{id:`plan`,name:`Planning`,instruction:`steps/plan/README.md`,produces:[`plan.md`],requires:[`spec.md`],agents:[`Planner`,`Explorer`],description:`Analyze codebase, design architecture, create implementation plan`},{id:`task`,name:`Task Breakdown`,instruction:`steps/task/README.md`,produces:[`tasks.md`],requires:[`plan.md`],agents:[`Planner`,`Architect-Reviewer-Alpha`],description:`Break plan into ordered implementation tasks with dependencies`},{id:`execute`,name:`Execution`,instruction:`steps/execute/README.md`,produces:[`progress.md`],requires:[`tasks.md`],agents:[`Orchestrator`,`Implementer`,`Frontend`,`Refactor`],description:`Implement all tasks, write code, write tests`},{id:`verify`,name:`Verification`,instruction:`steps/verify/README.md`,produces:[`verify-report.md`],requires:[`progress.md`],agents:[`Code-Reviewer-Alpha`,`Code-Reviewer-Beta`,`Architect-Reviewer-Alpha`,`Architect-Reviewer-Beta`,`Security`],description:`Dual code review, architecture review, security review, test validation`}],agents:[],artifacts_dir:`.spec`,install:[]};function A(){return[{manifest:O,scaffoldDir:`scaffold/_preview/flows/aikit-basic`},{manifest:k,scaffoldDir:`scaffold/_preview/flows/aikit-advanced`}]}const j=`<!-- aikit foundation context -->`,M=`<!-- end foundation context -->`;function N(e){let t=e.artifacts_dir||`.spec`;return`${j}
|
|
3
|
+
`)}discoverAgents(e){let t=m(e,`agents`);return n(t)?a(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>`agents/${e.name}`):[]}},D=class{format=`copilot`;detect(e){return n(m(e,`.github`,`agents`))}async parse(e,t){let n=a(m(e,`.github`,`agents`),{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>`.github/agents/${e.name}`),r=n.map(e=>this.getStepId(e)),i=n.map((e,t)=>{let n=r[t];return{id:n,name:n.charAt(0).toUpperCase()+n.slice(1),instruction:`steps/${n}/README.md`,produces:[`${n}.md`],requires:t>0?[r[t-1]]:[],agents:[e],description:`${n} agent step`}});return await this.materializeSteps(e,i,t),{name:f(e),version:`1.0.0`,description:`Copilot agents flow from ${f(e)}`,steps:i,agents:n,artifacts_dir:`.spec`,install:[]}}getStepId(e){return f(e,`.md`).toLowerCase().replace(/\.agent$/,``)}async materializeSteps(e,t,n){for(let a of t){let t=a.agents[0];if(!t)continue;let o=i(m(e,t),`utf-8`),s=m(e,`steps`,a.id),c=m(s,`README.md`);r(s,{recursive:!0}),d(c,n?.transform?await n.transform({content:o,sourceFormat:`copilot`,stepName:a.id,metadata:{sourcePath:t,displayName:a.name}}):`# ${a.name}\n\n${o}`,`utf-8`)}}},O=class{format=`native`;detect(e){return n(m(e,`flow.json`))}async parse(e){let t=i(m(e,`flow.json`),`utf-8`);return JSON.parse(t)}},k=class{format=`openspec`;detect(e){return!!(n(m(e,`openspec`,`config.yaml`))||n(m(e,`schemas`))&&this.findSchemaYaml(e))}async parse(e,t){let n=this.readMeta(e),r=this.loadSchema(e),i=this.buildStepsFromSchema(r);return await this.materializeSteps(e,i,r,t),{name:n.name,version:n.version,description:r.description??n.description,author:n.author,steps:i,agents:[],artifacts_dir:`openspec`,install:[]}}readMeta(e){let t=m(e,`package.json`);if(n(t))try{let n=JSON.parse(i(t,`utf-8`));return{name:n.name??f(e),version:n.version??`0.1.0`,description:n.description??`OpenSpec flow`,author:n.author}}catch{}return{name:f(e),version:`0.1.0`,description:`OpenSpec flow`}}readConfigSchema(e){let t=m(e,`openspec`,`config.yaml`);if(!n(t))return`spec-driven`;try{let e=g(i(t,`utf-8`));return typeof e?.schema==`string`&&e.schema.trim().length>0?e.schema:`spec-driven`}catch{return`spec-driven`}}resolveSchemaDir(e){let t=this.readConfigSchema(e),r=m(e,`openspec`,`schemas`,t);if(n(m(r,`schema.yaml`)))return r;let i=m(e,`schemas`,t);if(n(m(i,`schema.yaml`)))return i;try{let e=m(_(`npm root -g`,{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).trim(),`@fission-ai`,`openspec`,`schemas`,t);if(n(m(e,`schema.yaml`)))return e}catch{}return null}parseSchemaArtifacts(e){try{let t=g(e);if(!t||!Array.isArray(t.artifacts))return null;let n=t.artifacts.map(e=>this.normalizeArtifact(e)).filter(e=>e!==null);return n.length===0?null:{name:typeof t.name==`string`&&t.name.trim().length>0?t.name:this.readString(t.schema)??`spec-driven`,version:typeof t.version==`number`?t.version:1,description:this.readString(t.description),artifacts:n,apply:this.normalizeApply(t.apply)}}catch{return null}}loadSchema(e){let t=this.resolveSchemaDir(e);if(t){let e=m(t,`schema.yaml`);try{let t=i(e,`utf-8`),n=this.parseSchemaArtifacts(t);if(n)return n}catch{}}return this.discoverSchemaFromDirectory(e)}discoverSchemaFromDirectory(e){let t=[m(e,`openspec`,`schemas`),m(e,`schemas`)];for(let e of t)if(n(e))try{let t=a(e,{withFileTypes:!0}).filter(e=>e.isDirectory());for(let r of t){let t=m(e,r.name,`schema.yaml`);if(n(t))try{let e=this.parseSchemaArtifacts(i(t,`utf-8`));if(e)return e}catch{}}}catch{}let r=[],o=m(e,`openspec`),s=[],c=this.collectMarkdownFiles(o);for(let e of c){let t=h(o,e).replace(/\\/g,`/`),n=this.toStepIdFromMarkdown(t);!n||s.includes(n)||(r.push({id:n,generates:t,description:`${this.humanizeStepName(n)} phase`,template:f(e),requires:s.length>0?[s[s.length-1]]:[]}),s.push(n))}return{name:this.readConfigSchema(e),version:1,artifacts:r}}collectMarkdownFiles(e){if(!n(e))return[];let t=[];try{let n=a(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name));for(let r of n){let n=m(e,r.name);if(r.isFile()&&r.name.toLowerCase().endsWith(`.md`)){t.push(n);continue}r.isDirectory()&&t.push(...this.collectMarkdownFiles(n))}}catch{}return t}hasFileRecursive(e,t){if(!n(e))return!1;try{let n=a(e,{withFileTypes:!0});for(let r of n)if(r.isFile()&&r.name===t||r.isDirectory()&&this.hasFileRecursive(m(e,r.name),t))return!0}catch{}return!1}findSchemaYaml(e){let t=m(e,`schemas`);if(!n(t))return!1;try{return a(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).some(e=>n(m(t,e.name,`schema.yaml`)))}catch{return!1}}toStepIdFromMarkdown(e){let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)return null;let n=(t[t.length-1]??``).replace(/\.md$/i,``);return(n.toLowerCase()===`readme`&&t.length>1?t[t.length-2]:n).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||null}buildStepsFromSchema(e){let t=e.artifacts.map(e=>({id:e.id,name:this.humanizeStepName(e.id),instruction:`steps/${e.id}/README.md`,produces:e.generates?[e.generates]:[],requires:e.requires,agents:[],description:e.description}));return e.apply&&t.push({id:`apply`,name:`Apply`,instruction:`steps/apply/README.md`,produces:[],requires:e.apply.requires,agents:[],description:`Implement the tasks, writing code and tests according to the design`}),t}async materializeSteps(e,t,i,a){let o=this.resolveSchemaDir(e),s=new Map(i.artifacts.map(e=>[e.id,e]));for(let c of t){let t=m(e,`steps`,c.id),l=m(t,`README.md`);r(t,{recursive:!0});let u=this.resolveInstructionContent(o,c.id,s.get(c.id),i.apply);if(!u){n(l)||d(l,`# ${c.name}\n\n${c.description}\n`,`utf-8`);continue}d(l,a?.transform?await a.transform({content:u,sourceFormat:`openspec`,stepName:c.id,metadata:{schemaName:i.name,displayName:c.name,description:c.description,produces:c.produces,requires:c.requires}}):`# ${c.name}\n\n${u}`,`utf-8`)}}resolveInstructionContent(e,t,r,a){if(t===`apply`&&a?.instruction)return a.instruction;if(!r)return null;if(r.instruction)return r.instruction;if(e&&r.template){let t=m(e,`templates`,r.template);if(n(t))try{return i(t,`utf-8`)}catch{}}return r.description||null}normalizeArtifact(e){if(!e||typeof e!=`object`)return null;let t=e,n=this.readString(t.id),r=this.readString(t.generates);return!n||!r?null:{id:n,generates:r,description:this.readString(t.description)??`${this.humanizeStepName(n)} phase`,template:this.readString(t.template)??``,instruction:this.readString(t.instruction),requires:this.readStringArray(t.requires)}}normalizeApply(e){if(!e||typeof e!=`object`)return;let t=e;return{requires:this.readStringArray(t.requires),tracks:this.readString(t.tracks)??null,instruction:this.readString(t.instruction)}}readString(e){return typeof e==`string`&&e.trim().length>0?e:void 0}readStringArray(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.length>0):[]}humanizeStepName(e){return e.split(/[-_]/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}};const A={name:`aikit:basic`,version:`0.2.0`,description:`Quick development flow for bug fixes, small features, and refactoring`,steps:[{id:`design`,name:`Design Gate`,instruction:`steps/design/README.md`,produces:[`design-decisions.md`],requires:[],agents:[`Researcher-Alpha`,`Researcher-Beta`,`Researcher-Gamma`,`Researcher-Delta`],description:`Evaluate task type, run brainstorming for features, FORGE classification. Auto-skips for bug fixes and refactors.`},{id:`assess`,name:`Assessment`,instruction:`steps/assess/README.md`,produces:[`assessment.md`],requires:[`design-decisions.md`],agents:[`Explorer`,`Researcher-Alpha`],description:`Understand scope, analyze codebase, identify approach`},{id:`implement`,name:`Implementation`,instruction:`steps/implement/README.md`,produces:[`progress.md`],requires:[`assessment.md`],agents:[`Implementer`,`Frontend`],description:`Write code following the assessment plan`},{id:`verify`,name:`Verification`,instruction:`steps/verify/README.md`,produces:[`verify-report.md`],requires:[`progress.md`],agents:[`Code-Reviewer-Alpha`,`Security`],description:`Review code, run tests, validate changes`}],agents:[],artifacts_dir:`.spec`,install:[]},j={name:`aikit:advanced`,version:`0.2.0`,description:`Full development flow for new features, API design, and architecture changes`,steps:[{id:`design`,name:`Design Gate`,instruction:`steps/design/README.md`,produces:[`design-decisions.md`],requires:[],agents:[`Researcher-Alpha`,`Researcher-Beta`,`Researcher-Gamma`,`Researcher-Delta`],description:`Full brainstorming, FORGE classification, decision protocol with parallel research. ADR for critical-tier tasks.`},{id:`spec`,name:`Specification`,instruction:`steps/spec/README.md`,produces:[`spec.md`],requires:[`design-decisions.md`],agents:[`Researcher-Alpha`],description:`Elicit requirements, clarify scope, define acceptance criteria`},{id:`plan`,name:`Planning`,instruction:`steps/plan/README.md`,produces:[`plan.md`],requires:[`spec.md`],agents:[`Planner`,`Explorer`],description:`Analyze codebase, design architecture, create implementation plan`},{id:`task`,name:`Task Breakdown`,instruction:`steps/task/README.md`,produces:[`tasks.md`],requires:[`plan.md`],agents:[`Planner`,`Architect-Reviewer-Alpha`],description:`Break plan into ordered implementation tasks with dependencies`},{id:`execute`,name:`Execution`,instruction:`steps/execute/README.md`,produces:[`progress.md`],requires:[`tasks.md`],agents:[`Orchestrator`,`Implementer`,`Frontend`,`Refactor`],description:`Implement all tasks, write code, write tests`},{id:`verify`,name:`Verification`,instruction:`steps/verify/README.md`,produces:[`verify-report.md`],requires:[`progress.md`],agents:[`Code-Reviewer-Alpha`,`Code-Reviewer-Beta`,`Architect-Reviewer-Alpha`,`Architect-Reviewer-Beta`,`Security`],description:`Dual code review, architecture review, security review, test validation`}],agents:[],artifacts_dir:`.spec`,install:[]};function M(){return[{manifest:A,scaffoldDir:`scaffold/_preview/flows/aikit-basic`},{manifest:j,scaffoldDir:`scaffold/_preview/flows/aikit-advanced`}]}function N(e){switch(e){case`completed`:return`done`;case`skipped`:return`skipped`;case`crashed`:case`in-progress`:return`blocked`}}function P(e){switch(e.outcome){case`completed`:return`Completed`;case`skipped`:return`Skipped`;case`crashed`:return`Crashed`;case`in-progress`:return`In progress`}}function F(e,t,n){let r=n?.claims,i=e.currentStep==null?-1:t.steps.findIndex(t=>t.id===e.currentStep),a=Object.entries(e.artifacts).map(([e,t])=>({name:e,path:t,status:`draft`})),o=e.executionLog.map(e=>({stepId:e.stepId,summary:P(e),outcome:N(e.outcome)}));return{schemaVersion:1,flowSlug:e.flow,runId:e.slug,stepId:e.currentStep,stepIndex:i,stepOrder:t.steps.map(e=>e.id),objective:n?.objective??e.objective??e.topic,acceptanceCriteria:n?.acceptanceCriteria??e.acceptanceCriteria??[],scope:n?.scope??e.scope??e.roots??[],exclusions:n?.exclusions??e.exclusions??[],retrievedRefs:n?.retrievedRefs??e.retrievedRefs??[],verifiedClaims:r?.verified??[],assumedClaims:r?.assumed??[],unresolvedClaims:r?.unresolved??[],decisions:r?.decisions??[],artifacts:a,stepSummaries:o,failures:[],successPatterns:[],candidateLearnings:[],verifiedFinalOutcome:null}}const I=`<!-- aikit foundation context -->`,L=`<!-- end foundation context -->`;function R(e){let t=e.artifacts_dir||`.spec`;return`${I}
|
|
4
4
|
You are operating within the @vpxa/aikit framework.
|
|
5
5
|
- Use aikit MCP tools for all search, analysis, and memory operations
|
|
6
6
|
- Follow agents defined in AGENTS.md for delegation
|
|
@@ -8,8 +8,8 @@ You are operating within the @vpxa/aikit framework.
|
|
|
8
8
|
- Track state via the unified flow tool (for example: flow with action "status" or "step")
|
|
9
9
|
- Active flow: ${e.name} v${e.version}
|
|
10
10
|
- Artifacts go in: .flows/{topic-slug}/${t}/ (resolved at runtime via flow action "start")
|
|
11
|
-
${
|
|
11
|
+
${L}`}var z=class{injectPreamble(e,t){let r=R(t);if(!n(e)){d(e,`${r}\n`,`utf-8`);return}let a=i(e,`utf-8`),o=a.indexOf(I),s=a.indexOf(L);if(o!==-1&&s!==-1){d(e,`${a.slice(0,o)}${r}${a.slice(s+31)}`,`utf-8`);return}d(e,`${r}\n\n${a}`,`utf-8`)}removePreamble(e){if(!n(e))return;let t=i(e,`utf-8`),r=t.indexOf(I),a=t.indexOf(L);r===-1||a===-1||d(e,(t.slice(0,r)+t.slice(a+31)).replace(/^\n+/,``).replace(/\n{3,}/g,`
|
|
12
12
|
|
|
13
|
-
`),`utf-8`)}getTargetFiles(e){let t=[],r=m(e,`.github`,`copilot-instructions.md`);n(r)&&t.push(r);let i=m(e,`CLAUDE.md`);n(i)&&t.push(i);let a=m(e,`AGENTS.md`);return n(a)&&t.push(a),t}};function
|
|
14
|
-
`)}function
|
|
15
|
-
`)}`}:{success:!0}}};function G(){return A().map(e=>({name:e.manifest.name,version:e.manifest.version,source:`builtin`,sourceType:`builtin`,installPath:e.scaffoldDir,format:`native`,registeredAt:`1970-01-01T00:00:00.000Z`,updatedAt:`1970-01-01T00:00:00.000Z`,manifest:e.manifest}))}var K=class{registryPath;constructor(e){this.registryPath=e}load(){if(!n(this.registryPath))return{version:1,flows:{}};try{let e=i(this.registryPath,`utf-8`);return JSON.parse(e)}catch{return{version:1,flows:{}}}}save(e){let t=p(this.registryPath);n(t)||r(t,{recursive:!0}),d(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}register(e){let t=this.load();return t.flows[e.name]=e,this.save(t),{success:!0}}unregister(e){let t=this.load();return t.flows[e]?(delete t.flows[e],this.save(t),{success:!0}):{success:!1,error:`Flow "${e}" not found in registry`}}get(e){return this.load().flows[e]||(G().find(t=>t.name===e)??null)}list(){let e=this.load(),t=new Set(Object.keys(e.flows)),n=Object.values(e.flows);for(let e of G())t.has(e.name)||n.push(e);return n}has(e){return e in this.load().flows?!0:G().some(t=>t.name===e)}},q=class{flowsDir;epilogueConfig;constructor(e,t={before:[],after:[]}){this.flowsDir=e,this.epilogueConfig=t}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`flow`}getMaxSlugLength(){let e=240-m(this.flowsDir,`meta.json`).length-1;return Math.max(1,Math.min(100,e))}fitSlugToBudget(e,t){return e.length<=t?e:e.slice(0,t).replace(/-+$/,``)||e.slice(0,t)}generateSlug(e){let t=new Date,r=[String(t.getMonth()+1).padStart(2,`0`),String(t.getDate()).padStart(2,`0`),String(t.getFullYear())].join(`-`),i=this.slugify(e),a=this.getMaxSlugLength(),o=r.length+1,s=Math.max(1,a-o),c=`${r}-${this.fitSlugToBudget(i,s)}`;if(!n(m(this.flowsDir,c)))return c;for(let e=2;e<=100;e+=1){let t=`-${e}`;if(t.length>=a)continue;let s=Math.max(1,a-o-t.length),c=`${r}-${this.fitSlugToBudget(i,s)}${t}`;if(!n(m(this.flowsDir,c)))return c}throw Error(`Unable to allocate a flow run slug for topic "${e}"`)}getMetaPath(e){return m(this.flowsDir,e,`meta.json`)}buildStepSequence(e){return[...this.epilogueConfig.before.map(e=>({id:e.id,phase:`before`})),...e.steps.map(e=>({id:e.id,phase:`flow`})),...this.epilogueConfig.after.map(e=>({id:e.id,phase:`after`}))]}readMeta(e){let t=this.getMetaPath(e);if(!n(t))return null;try{let e=i(t,`utf-8`);return JSON.parse(e)}catch{return null}}writeMeta(e,t){let i=m(this.flowsDir,e);n(i)||r(i,{recursive:!0});let a=this.getMetaPath(e),s=`${a}.tmp`;d(s,JSON.stringify(t,null,2),`utf-8`),o(s,a)}normalizeMeta(e){let t=e;return t.completedTokens??=[],t.executionLog??=[],t}hasCompletedExecution(e,t){return e.executionLog.some(n=>n.stepId===t&&e.completedTokens.includes(n.token))}markCrashedExecution(e){let t=e.currentToken;if(!(!t||e.completedTokens.includes(t)))for(let n=e.executionLog.length-1;n>=0;--n){let r=e.executionLog[n];if(r.token===t&&r.outcome===`in-progress`){r.outcome=`crashed`;break}}}finalizeCurrentStep(e,t,n){let r=e.currentToken;if(r){e.completedTokens.includes(r)||e.completedTokens.push(r);for(let i=e.executionLog.length-1;i>=0;--i){let a=e.executionLog[i];if(a.token===r){a.completedAt=n,a.outcome=t;break}}}e.currentToken=void 0}activateStep(e,t,n,r){let i=n;for(;i<t.length;){let n=t[i];if(e.currentStep=n.id,e.phase=n.phase,r?.force||!this.hasCompletedExecution(e,n.id)){this.markCrashedExecution(e);let t=Date.now(),r=new Date(t).toISOString(),i=`${n.id}-${t}`;e.currentToken=i,e.executionLog.push({stepId:n.id,token:i,startedAt:r,outcome:`in-progress`});return}n.phase===`flow`?e.completedSteps.includes(n.id)||e.completedSteps.push(n.id):e.completedEpilogueSteps.includes(n.id)||e.completedEpilogueSteps.push(n.id),i+=1}e.currentStep=null,e.currentToken=void 0,e.status=`completed`,e.phase=`after`}findActiveRun(){if(!n(this.flowsDir))return null;for(let e of a(this.flowsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=this.readMeta(e.name);if(t?.status===`active`)return{slug:e.name,meta:t}}return null}metaToState(e,t){let n=this.normalizeMeta(t),r=n.phase??`flow`;return{flow:n.flow,flowOrigin:n.flowOrigin,status:n.status,currentStep:n.currentStep,currentToken:n.currentToken,completedSteps:n.completedSteps,completedTokens:n.completedTokens,skippedSteps:n.skippedSteps,executionLog:n.executionLog,artifacts:n.artifacts,startedAt:n.startedAt,updatedAt:n.updatedAt,slug:e,runDir:m(this.flowsDir,e),topic:n.topic,phase:r,isEpilogue:r!==`flow`,roots:n.roots,primaryRoot:n.primaryRoot}}start(e,t,n,i){let a=this.findActiveRun();if(a)return{success:!1,error:`Flow "${a.meta.flow}" is already active. Reset it first.`};let o=this.buildStepSequence(t);if(!o.length)return{success:!1,error:`Flow has no steps`};try{let a=(n??t.description)||e,s=this.generateSlug(a),c=m(this.flowsDir,s),l=new Date().toISOString(),u=o[0],d={id:s,flow:e,flowVersion:t.version,flowOrigin:i,topic:a,status:`active`,currentStep:u.id,currentToken:void 0,completedSteps:[],completedTokens:[],skippedSteps:[],executionLog:[],artifactsDir:t.artifacts_dir,artifacts:{},startedAt:l,updatedAt:l,phase:u.phase,completedEpilogueSteps:[],skippedEpilogueSteps:[]};return this.activateStep(d,o,0),r(c,{recursive:!0}),r(m(c,t.artifacts_dir),{recursive:!0}),this.writeMeta(s,d),{success:!0,data:this.metaToState(s,d)}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}step(e,t){let r=this.findActiveRun();if(!r)return{success:!1,error:`No active flow`};if(r.meta.status!==`active`)return{success:!1,error:`Flow is ${r.meta.status}, not active`};if(!r.meta.currentStep)return{success:!1,error:`No current step`};let i=r.meta.currentStep,a=this.buildStepSequence(t),o=a.findIndex(e=>e.id===i);if(o===-1)return{success:!1,error:`Current step "${r.meta.currentStep}" not found in manifest`};let s=a[o],c=new Date().toISOString(),l=this.normalizeMeta(r.meta);switch(e){case`next`:if(s.phase===`flow`){let e=t.steps.find(e=>e.id===i);if(e&&e.produces.length>0){let a=m(m(this.flowsDir,r.slug),t.artifacts_dir),o=e.produces.filter(e=>!n(m(a,e)));if(o.length>0)return{success:!1,error:`Step "${i}" cannot advance — missing required artifacts in ${t.artifacts_dir}/: ${o.join(`, `)}. Create these files before advancing.`}}}s.phase===`flow`?l.completedSteps.includes(i)||l.completedSteps.push(i):l.completedEpilogueSteps.includes(i)||l.completedEpilogueSteps.push(i),this.finalizeCurrentStep(l,`completed`,c),this.activateStep(l,a,o+1);break;case`skip`:s.phase===`flow`?l.skippedSteps.includes(i)||l.skippedSteps.push(i):l.skippedEpilogueSteps.includes(i)||l.skippedEpilogueSteps.push(i),this.finalizeCurrentStep(l,`skipped`,c),this.activateStep(l,a,o+1);break;case`redo`:this.markCrashedExecution(l),s.phase===`flow`?(l.completedSteps=l.completedSteps.filter(e=>e!==i),l.skippedSteps=l.skippedSteps.filter(e=>e!==i)):(l.completedEpilogueSteps=l.completedEpilogueSteps.filter(e=>e!==i),l.skippedEpilogueSteps=l.skippedEpilogueSteps.filter(e=>e!==i)),l.currentToken=void 0,this.activateStep(l,a,o,{force:!0});break}return l.updatedAt=c,this.writeMeta(r.slug,l),{success:!0,data:this.metaToState(r.slug,l)}}getStatus(){let e=this.findActiveRun();return e?{success:!0,data:this.metaToState(e.slug,e.meta)}:{success:!1,error:`No active flow`}}reset(){let e=this.findActiveRun();return e?(e.meta.status=`abandoned`,e.meta.currentStep=null,e.meta.updatedAt=new Date().toISOString(),this.writeMeta(e.slug,e.meta),{success:!0}):{success:!0}}recordArtifact(e,t){let n=this.findActiveRun();return n?(n.meta.artifacts[e]=t,n.meta.updatedAt=new Date().toISOString(),this.writeMeta(n.slug,n.meta),{success:!0}):{success:!1,error:`No active flow`}}listRuns(e){if(!n(this.flowsDir))return[];let t=[];for(let n of a(this.flowsDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let r=this.readMeta(n.name);r&&(e?.flow&&r.flow!==e.flow||e?.status&&r.status!==e.status||t.push({id:n.name,flow:r.flow,flowOrigin:r.flowOrigin,topic:r.topic,status:r.status,currentStep:r.currentStep,startedAt:r.startedAt,updatedAt:r.updatedAt}))}return t.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}},J=class{createSymlinks(t,i,a,o){let s=this.getTargets(t,i);for(let t of s){n(t.baseDir)||r(t.baseDir,{recursive:!0});for(let r of o.agents){let i=m(a,r);if(!n(i))continue;let o=this.getAgentStem(r),s=m(t.baseDir,`${o}${t.extension}`);n(s)&&u(s);let c=h(p(s),i);try{l(c,s,`file`)}catch{try{e(i,s)}catch(e){console.warn(`Failed to create symlink or copy fallback for ${i}: ${e instanceof Error?e.message:String(e)}`)}}}}}removeSymlinks(e,t){let r=this.getTargets(e,t);for(let e of r)if(n(e.baseDir))try{let t=a(e.baseDir,{withFileTypes:!0});for(let n of t)!n.isFile()&&!n.isSymbolicLink()||u(m(e.baseDir,n.name));a(e.baseDir).length===0&&c(e.baseDir)}catch{}}getTargets(e,t){return[{ide:`copilot`,baseDir:m(e,`.github`,`agents`,`flows`,t),extension:`.agent.md`},{ide:`claude-code`,baseDir:m(e,`.claude`,`agents`,`flows`,t),extension:`.md`}]}getAgentStem(e){return f(e).replace(/\.agent\.md$/,``).replace(/\.md$/,``)}};export{w as ClaudePluginAdapter,T as CopilotAdapter,W as FlowLoader,K as FlowRegistryManager,q as FlowStateMachine,P as FoundationIntegration,B as GitInstaller,E as NativeAdapter,D as OpenSpecAdapter,J as SymlinkManager,A as getBuiltinFlows};
|
|
13
|
+
`),`utf-8`)}getTargetFiles(e){let t=[],r=m(e,`.github`,`copilot-instructions.md`);n(r)&&t.push(r);let i=m(e,`CLAUDE.md`);n(i)&&t.push(i);let a=m(e,`AGENTS.md`);return n(a)&&t.push(a),t}};function B(e){if(!e||typeof e!=`object`||!(`stderr`in e))return``;let t=e.stderr;return Buffer.isBuffer(t)?t.toString().trim():typeof t==`string`?t.trim():``}function V(e){try{return new URL(e).hostname}catch{}return e.match(/^[^@]+@([^:]+):/)?.[1]??`<host>`}function H(e,t,n){let r=[`Git operation failed for: ${e}`],i=V(e),a=t.includes(`ETIMEDOUT`)||t.includes(`SIGTERM`)||t.toLowerCase().includes(`timed out`),o=n.includes(`Authentication failed`)||n.includes(`could not read Username`)||n.includes(`terminal prompts disabled`)||n.includes(`401`)||n.includes(`403`)||n.includes(`Permission denied`),s=n.includes(`SSL certificate`)||n.includes(`unable to access`)&&n.includes(`SSL`),c=n.includes(`Could not resolve host`)||n.includes(`Name or service not known`),l=n.includes(`SAML`)||n.includes(`single sign-on`);return o||l?(r.push(``),r.push(`Cause: Authentication required or credentials not configured.`),r.push(``),r.push(`To fix this, ensure git can access this repository:`),r.push(``),r.push(` Option 1 - SSH key:`),r.push(` 1. Generate an SSH key: ssh-keygen -t ed25519`),r.push(` 2. Add the public key to your Git hosting account`),r.push(` 3. Use the SSH URL instead: git@<host>:<org>/<repo>.git`),r.push(``),r.push(` Option 2 - Personal Access Token (PAT):`),r.push(` 1. Create a PAT in your Git hosting Settings > Developer settings > Tokens`),r.push(` 2. For GitHub Enterprise with SAML SSO, authorize the token for your org`),r.push(` 3. Configure git credentials:`),r.push(` git config --global credential.helper store`),r.push(` git clone ${e} (enter PAT as password)`),r.push(``),r.push(` Option 3 - Git Credential Manager:`),r.push(` 1. Install: https://github.com/git-ecosystem/git-credential-manager`),r.push(` 2. Run: git clone ${e}`),r.push(` 3. Follow the browser-based auth prompt`),r.push(``),r.push(`After configuring credentials, retry: aikit flow add ${e}`)):a?(r.push(``),r.push(`Cause: Connection timed out - the server did not respond within 60 seconds.`),r.push(``),r.push(`Possible reasons:`),r.push(` - The repository requires VPN access. Ensure your VPN is connected`),r.push(` - The host is behind a firewall or corporate proxy`),r.push(` - The URL may be incorrect`),r.push(``),r.push(`Diagnostics:`),r.push(` 1. Verify the URL is correct: ${e}`),r.push(` 2. Test connectivity: git ls-remote ${e}`),r.push(` 3. If behind a proxy, configure git:`),r.push(` git config --global http.proxy http://proxy:port`),r.push(``),r.push(`If this is a corporate/internal host, you may need to:`),r.push(` - Connect to the corporate VPN`),r.push(` - Add the host to your SSH config or git config`),r.push(` - Ask your IT team to allowlist your machine`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):s?(r.push(``),r.push(`Cause: SSL/TLS certificate verification failed.`),r.push(``),r.push(`This often happens with corporate proxies or self-signed certificates.`),r.push(``),r.push(`To fix:`),r.push(` 1. If your company uses a custom CA, add it:`),r.push(` git config --global http.sslCAInfo /path/to/ca-bundle.crt`),r.push(` 2. As a last resort (not recommended for production):`),r.push(` git config --global http.sslVerify false`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):c?(r.push(``),r.push(`Cause: Cannot resolve hostname.`),r.push(``),r.push(`Check:`),r.push(` 1. Is the URL correct? ${e}`),r.push(` 2. Are you connected to the internet/VPN?`),r.push(` 3. Can you resolve the host? ping ${i}`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):(r.push(``),r.push(`Error: ${t}`),n&&r.push(`Details: ${n}`),r.push(``),r.push(`Troubleshooting:`),r.push(` 1. Verify the URL is a valid git repository: git ls-remote ${e}`),r.push(` 2. Check your git credentials and network connectivity`),r.push(` 3. If the repo requires auth, configure credentials first (PAT or SSH key)`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)),r.join(`
|
|
14
|
+
`)}function U(){try{return v(`git`,[`credential-manager`,`--version`],{stdio:`pipe`,timeout:5e3}).status===0}catch{return!1}}function W(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`authentication failed`)||n.includes(`could not read username`)||n.includes(`saml sso`)||n.includes(`terminal prompts disabled`)||n.includes(`host key verification failed`)||n.includes(`permission denied`)||n.includes(`403`)||n.includes(`401`)}var G=class{flowsDir;constructor(e){this.flowsDir=e}clone(e,t){let r=this.repoNameFromUrl(e),i=m(this.flowsDir,r);if(n(i))if(!n(m(i,`.git`)))s(i,{recursive:!0,force:!0});else return{success:!1,error:`Flow "${r}" already installed at ${i}. Use update instead.`};try{if(this.ensureFlowsDir(),t){let n=process.platform===`win32`?`bat`:`sh`,r=m(y(),`git-askpass-${Date.now()}.${n}`);process.platform===`win32`?d(r,`@echo ${t}`,{mode:448}):d(r,`#!/bin/sh\necho "${t}"`,{mode:448});try{let t=v(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:r}});if(t.status!==0){let e=t.stderr?.toString().trim()??``;throw Error(e||t.error?.message||`git clone failed`)}}finally{try{u(r)}catch{}}}else{let t=v(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}});if(t.status!==0){let e=t.stderr?.toString().trim()??``;throw Error(e||t.error?.message||`git clone failed`)}}return{success:!0,data:i}}catch(r){n(i)&&s(i,{recursive:!0,force:!0});let a=B(r),o=r instanceof Error?r.message:String(r);if(!t&&W(o,a)&&U()){let t=V(e)||e;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n(If a browser window does not open, check your terminal for a device code.)\n`);try{if(this.ensureFlowsDir(),v(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0,data:i};n(i)&&s(i,{recursive:!0,force:!0})}catch{n(i)&&s(i,{recursive:!0,force:!0})}}return{success:!1,error:H(e,o,a)}}}update(e){if(!n(e))return{success:!1,error:`Install path not found: ${e}`};try{return _(`git pull --ff-only`,{cwd:e,stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}}),{success:!0}}catch(t){let n=e;try{n=_(`git remote get-url origin`,{cwd:e,stdio:`pipe`,timeout:1e4}).toString().trim()}catch{}let r=B(t),i=t instanceof Error?t.message:String(t);if(W(i,r)&&U()){let t=V(n)||n;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n`);try{if(v(`git`,[`pull`,`--ff-only`],{cwd:e,stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0}}catch{}}return{success:!1,error:H(n,i,r)}}}copyLocal(e,r){let i=m(this.flowsDir,r);if(n(i))return{success:!1,error:`Flow "${r}" already installed at ${i}`};try{return this.ensureFlowsDir(),t(e,i,{recursive:!0}),{success:!0,data:i}}catch(e){return{success:!1,error:`Copy failed: ${e instanceof Error?e.message:String(e)}`}}}remove(e){if(!n(e))return{success:!0};try{return s(e,{recursive:!0,force:!0}),{success:!0}}catch(e){return{success:!1,error:`Remove failed: ${e instanceof Error?e.message:String(e)}`}}}runInstallDeps(e){for(let t of e)try{if(t.startsWith(`npm:`)){_(`npx skills add ${t.slice(4)} -g`,{stdio:`pipe`,timeout:12e4});continue}if(t.endsWith(`.git`)||t.includes(`github.com`)){_(`npx skills add ${t} -g`,{stdio:`pipe`,timeout:12e4});continue}return{success:!1,error:`Unknown install entry format: ${t}`}}catch(e){return{success:!1,error:`Install dependency failed for "${t}": ${e instanceof Error?e.message:String(e)}`}}return{success:!0}}getLocalCommit(e){try{return _(`git rev-parse HEAD`,{cwd:e,stdio:`pipe`,timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim()||null}catch{return null}}getRemoteCommit(e){try{return _(`git ls-remote origin HEAD`,{cwd:e,stdio:`pipe`,timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim().split(/\s+/)[0]||null}catch{return null}}hasUpdates(e){let t=this.getLocalCommit(e);if(!t)return{success:!1,error:`Could not determine local commit (not a git repo?)`};let n=this.getRemoteCommit(e);return n?{success:!0,data:{localCommit:t,remoteCommit:n,hasUpdates:t!==n}}:{success:!1,error:`Could not reach remote to check for updates`}}repoNameFromUrl(e){return f(e).replace(/\.git$/,``)}ensureFlowsDir(){n(this.flowsDir)||r(this.flowsDir,{recursive:!0})}};function K(e){return x(e?.tokenBytes??32).toString(`hex`)}function q(e){return x(e?.saltBytes??16).toString(`hex`)}function J(e,t){return b(`sha256`).update(t+e).digest(`hex`)}function Y(e,t,n){let r=J(e,t);if(r.length!==n.length)return!1;let i=Buffer.from(r,`hex`),a=Buffer.from(n,`hex`);if(i.length!==a.length)return!1;try{return S(i,a)}catch{return i.compare(a)===0}}function X(){let e=K(),t=q();return{rawToken:e,salt:t,hash:J(e,t),version:1}}function Z(e){let t=K(),n=q();return{rawToken:t,salt:n,hash:J(t,n),version:e+1}}const Q=[new O,new E,new D,new k];function te(e){let t=Q.find(t=>t.format===e);if(!t)throw Error(`No adapter for format: ${e}`);return t}function ne(e){for(let t of Q)if(t.detect(e))return t;return null}var re=class{async load(e,t){if(!n(e))return{success:!1,error:`Source directory not found: ${e}`};let r=ne(e);if(!r)return{success:!1,error:`No format adapter matches source: ${e}`};try{let n=await r.parse(e,t),i=this.validate(n);return i.success?{success:!0,data:{manifest:n,format:r.format}}:i}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}async loadWithFormat(e,t,n){let r=te(t);try{let t=await r.parse(e,n),i=this.validate(t);return i.success?{success:!0,data:t}:i}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}validate(e){let t=[];e.name?.trim()||t.push(`Missing flow name`),e.version?.trim()||t.push(`Missing flow version`),e.steps?.length||t.push(`Flow must have at least one step`);let n=new Set(e.steps.map(e=>e.id));for(let r of e.steps??[]){r.id?.trim()||t.push(`Step missing id`),r.instruction?.trim()||t.push(`Step "${r.id}" missing instruction path`);for(let e of r.requires??[])n.has(e)||t.push(`Step "${r.id}" requires unknown step "${e}"`)}return n.size!==(e.steps?.length??0)&&t.push(`Duplicate step IDs found`),t.length>0?{success:!1,error:`Validation failed:\n${t.join(`
|
|
15
|
+
`)}`}:{success:!0}}};function $(){return M().map(e=>({name:e.manifest.name,version:e.manifest.version,source:`builtin`,sourceType:`builtin`,installPath:e.scaffoldDir,format:`native`,registeredAt:`1970-01-01T00:00:00.000Z`,updatedAt:`1970-01-01T00:00:00.000Z`,manifest:e.manifest}))}var ie=class{registryPath;constructor(e){this.registryPath=e}load(){if(!n(this.registryPath))return{version:1,flows:{}};try{let e=i(this.registryPath,`utf-8`);return JSON.parse(e)}catch{return{version:1,flows:{}}}}save(e){let t=p(this.registryPath);n(t)||r(t,{recursive:!0}),d(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}register(e){let t=this.load();return t.flows[e.name]=e,this.save(t),{success:!0}}unregister(e){let t=this.load();return t.flows[e]?(delete t.flows[e],this.save(t),{success:!0}):{success:!1,error:`Flow "${e}" not found in registry`}}get(e){return this.load().flows[e]||($().find(t=>t.name===e)??null)}list(){let e=this.load(),t=new Set(Object.keys(e.flows)),n=Object.values(e.flows);for(let e of $())t.has(e.name)||n.push(e);return n}has(e){return e in this.load().flows?!0:$().some(t=>t.name===e)}},ae=class{flowsDir;epilogueConfig;constructor(e,t={before:[],after:[]}){this.flowsDir=e,this.epilogueConfig=t}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`flow`}getMaxSlugLength(){let e=240-m(this.flowsDir,`meta.json`).length-1;return Math.max(1,Math.min(100,e))}fitSlugToBudget(e,t){return e.length<=t?e:e.slice(0,t).replace(/-+$/,``)||e.slice(0,t)}generateSlug(e){let t=new Date,r=[String(t.getMonth()+1).padStart(2,`0`),String(t.getDate()).padStart(2,`0`),String(t.getFullYear())].join(`-`),i=this.slugify(e),a=this.getMaxSlugLength(),o=r.length+1,s=Math.max(1,a-o),c=`${r}-${this.fitSlugToBudget(i,s)}`;if(!n(m(this.flowsDir,c)))return c;for(let e=2;e<=100;e+=1){let t=`-${e}`;if(t.length>=a)continue;let s=Math.max(1,a-o-t.length),c=`${r}-${this.fitSlugToBudget(i,s)}${t}`;if(!n(m(this.flowsDir,c)))return c}throw Error(`Unable to allocate a flow run slug for topic "${e}"`)}getMetaPath(e){return m(this.flowsDir,e,`meta.json`)}buildStepSequence(e){return[...this.epilogueConfig.before.map(e=>({id:e.id,phase:`before`})),...e.steps.map(e=>({id:e.id,phase:`flow`})),...this.epilogueConfig.after.map(e=>({id:e.id,phase:`after`}))]}readMeta(e){let t=this.getMetaPath(e);if(!n(t))return null;try{let e=i(t,`utf-8`);return JSON.parse(e)}catch{return null}}writeMeta(e,t){let i=m(this.flowsDir,e);n(i)||r(i,{recursive:!0});let a=this.getMetaPath(e),s=`${a}.tmp`;d(s,JSON.stringify(t,null,2),`utf-8`),o(s,a)}normalizeMeta(e){let t=e;return t.completedTokens??=[],t.executionLog??=[],t.ownerTokenSalt??=void 0,t.ownerTokenHash??=void 0,t.ownerTokenVersion??=void 0,t.auditLog??=void 0,t}hasCompletedExecution(e,t){return e.executionLog.some(n=>n.stepId===t&&e.completedTokens.includes(n.token))}markCrashedExecution(e){let t=e.currentToken;if(!(!t||e.completedTokens.includes(t)))for(let n=e.executionLog.length-1;n>=0;--n){let r=e.executionLog[n];if(r.token===t&&r.outcome===`in-progress`){r.outcome=`crashed`;break}}}finalizeCurrentStep(e,t,n){let r=e.currentToken;if(r){e.completedTokens.includes(r)||e.completedTokens.push(r);for(let i=e.executionLog.length-1;i>=0;--i){let a=e.executionLog[i];if(a.token===r){a.completedAt=n,a.outcome=t;break}}}e.currentToken=void 0}activateStep(e,t,n,r){let i=n;for(;i<t.length;){let n=t[i];if(e.currentStep=n.id,e.phase=n.phase,r?.force||!this.hasCompletedExecution(e,n.id)){this.markCrashedExecution(e);let t=Date.now(),r=new Date(t).toISOString(),i=`${n.id}-${t}`;e.currentToken=i,e.executionLog.push({stepId:n.id,token:i,startedAt:r,outcome:`in-progress`});return}n.phase===`flow`?e.completedSteps.includes(n.id)||e.completedSteps.push(n.id):e.completedEpilogueSteps.includes(n.id)||e.completedEpilogueSteps.push(n.id),i+=1}e.currentStep=null,e.currentToken=void 0,e.status=`completed`,e.phase=`after`}findActiveRun(){if(!n(this.flowsDir))return null;for(let e of a(this.flowsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=this.readMeta(e.name);if(t?.status===`active`)return{slug:e.name,meta:t}}return null}metaToState(e,t){let n=this.normalizeMeta(t),r=n.phase??`flow`;return{flow:n.flow,flowOrigin:n.flowOrigin,status:n.status,currentStep:n.currentStep,currentToken:n.currentToken,completedSteps:n.completedSteps,completedTokens:n.completedTokens,skippedSteps:n.skippedSteps,executionLog:n.executionLog,artifacts:n.artifacts,startedAt:n.startedAt,updatedAt:n.updatedAt,slug:e,runDir:m(this.flowsDir,e),topic:n.topic,phase:r,isEpilogue:r!==`flow`,roots:n.roots,primaryRoot:n.primaryRoot,objective:n.objective,acceptanceCriteria:n.acceptanceCriteria,scope:n.scope,exclusions:n.exclusions,retrievedRefs:n.retrievedRefs}}start(e,t,n,i,a){let o=this.findActiveRun();if(o)return{success:!1,error:`Flow "${o.meta.flow}" is already active. Reset it first.`};let s=this.buildStepSequence(t);if(!s.length)return{success:!1,error:`Flow has no steps`};try{let o=(n??t.description)||e,c=this.generateSlug(o),l=m(this.flowsDir,c),u=new Date().toISOString(),d=s[0],f={id:c,flow:e,flowVersion:t.version,flowOrigin:i,topic:o,status:`active`,currentStep:d.id,currentToken:void 0,completedSteps:[],completedTokens:[],skippedSteps:[],executionLog:[],artifactsDir:t.artifacts_dir,artifacts:{},startedAt:u,updatedAt:u,phase:d.phase,completedEpilogueSteps:[],skippedEpilogueSteps:[],objective:a?.objective,acceptanceCriteria:a?.acceptanceCriteria,scope:a?.scope,exclusions:a?.exclusions,retrievedRefs:[]};return this.activateStep(f,s,0),r(l,{recursive:!0}),r(m(l,t.artifacts_dir),{recursive:!0}),this.writeMeta(c,f),{success:!0,data:this.metaToState(c,f)}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}backtrack(e,t){let r=null,i=null;if(n(this.flowsDir))for(let e of a(this.flowsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=this.readMeta(e.name);if(t&&(t.status===`active`||t.status===`completed`)){r=e.name,i=t;break}}if(!r||!i)return{success:!1,error:`No active flow`};let o=this.buildStepSequence(t),s=o.findIndex(t=>t.id===e);if(s===-1)return{success:!1,error:`Target step "${e}" not found in manifest`};if(e===i.currentStep)return{success:!1,error:`Cannot backtrack to current step — use redo instead`};let c=this.normalizeMeta(i);if(!c.executionLog.some(t=>t.stepId===e&&c.completedTokens.includes(t.token)))return{success:!1,error:`Target step "${e}" has no completed execution token`};let l=new Date().toISOString(),u=[];for(let e=s+1;e<o.length;e++){let t=o[e].id;for(let e of c.executionLog)e.stepId===t&&c.completedTokens.includes(e.token)&&(c.completedTokens=c.completedTokens.filter(t=>t!==e.token),e.outcome=`crashed`,e.completedAt=l,u.push(e.token))}let d=c.completedSteps.indexOf(e);d!==-1&&(c.completedSteps=c.completedSteps.slice(0,d+1)),c.skippedSteps=c.skippedSteps.filter(e=>{let t=o.findIndex(t=>t.id===e);return t===-1||t<=s});for(let e=s+1;e<o.length;e++){let t=o[e].id;c.completedEpilogueSteps=c.completedEpilogueSteps.filter(e=>e!==t),c.skippedEpilogueSteps=c.skippedEpilogueSteps.filter(e=>e!==t)}let f=c.ownerTokenVersion??1;return c.auditLog&&c.auditLog.push({event:`backtrack`,at:l,ownerTokenVersion:f,targetStep:e,invalidatedExecutionTokens:u.length>0?u:void 0}),c.currentToken=void 0,c.status=`active`,this.activateStep(c,o,s,{force:!0}),c.updatedAt=l,this.writeMeta(r,c),{success:!0,data:this.metaToState(r,c)}}step(e,t){let r=this.findActiveRun();if(!r)return{success:!1,error:`No active flow`};if(r.meta.status!==`active`)return{success:!1,error:`Flow is ${r.meta.status}, not active`};if(!r.meta.currentStep)return{success:!1,error:`No current step`};let i=r.meta.currentStep,a=this.buildStepSequence(t),o=a.findIndex(e=>e.id===i);if(o===-1)return{success:!1,error:`Current step "${r.meta.currentStep}" not found in manifest`};let s=a[o],c=new Date().toISOString(),l=this.normalizeMeta(r.meta);switch(e){case`next`:if(s.phase===`flow`){let e=t.steps.find(e=>e.id===i);if(e&&e.produces.length>0){let a=m(m(this.flowsDir,r.slug),t.artifacts_dir),o=e.produces.filter(e=>!n(m(a,e)));if(o.length>0)return{success:!1,error:`Step "${i}" cannot advance — missing required artifacts in ${t.artifacts_dir}/: ${o.join(`, `)}. Create these files before advancing.`}}}s.phase===`flow`?l.completedSteps.includes(i)||l.completedSteps.push(i):l.completedEpilogueSteps.includes(i)||l.completedEpilogueSteps.push(i),this.finalizeCurrentStep(l,`completed`,c),this.activateStep(l,a,o+1);break;case`skip`:s.phase===`flow`?l.skippedSteps.includes(i)||l.skippedSteps.push(i):l.skippedEpilogueSteps.includes(i)||l.skippedEpilogueSteps.push(i),this.finalizeCurrentStep(l,`skipped`,c),this.activateStep(l,a,o+1);break;case`redo`:this.markCrashedExecution(l),s.phase===`flow`?(l.completedSteps=l.completedSteps.filter(e=>e!==i),l.skippedSteps=l.skippedSteps.filter(e=>e!==i)):(l.completedEpilogueSteps=l.completedEpilogueSteps.filter(e=>e!==i),l.skippedEpilogueSteps=l.skippedEpilogueSteps.filter(e=>e!==i)),l.currentToken=void 0,this.activateStep(l,a,o,{force:!0});break;case`backtrack`:return{success:!1,error:`Use the dedicated backtrack() method instead of step("backtrack", ...)`}}return l.updatedAt=c,this.writeMeta(r.slug,l),{success:!0,data:this.metaToState(r.slug,l)}}getStatus(){let e=this.findActiveRun();return e?{success:!0,data:this.metaToState(e.slug,e.meta)}:{success:!1,error:`No active flow`}}reset(){let e=this.findActiveRun();return e?(e.meta.status=`abandoned`,e.meta.currentStep=null,e.meta.updatedAt=new Date().toISOString(),this.writeMeta(e.slug,e.meta),{success:!0}):{success:!0}}recordArtifact(e,t){let n=this.findActiveRun();return n?(n.meta.artifacts[e]=t,n.meta.updatedAt=new Date().toISOString(),this.writeMeta(n.slug,n.meta),{success:!0}):{success:!1,error:`No active flow`}}setOwnerCapability(e){let t=this.findActiveRun();if(!t)return{success:!1,error:`No active flow`};let n=this.normalizeMeta(t.meta);return n.ownerTokenSalt=e.ownerTokenSalt,n.ownerTokenHash=e.ownerTokenHash,n.ownerTokenVersion=e.ownerTokenVersion,n.auditLog??=[],n.updatedAt=new Date().toISOString(),this.writeMeta(t.slug,n),{success:!0}}listRuns(e){if(!n(this.flowsDir))return[];let t=[];for(let n of a(this.flowsDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let r=this.readMeta(n.name);r&&(e?.flow&&r.flow!==e.flow||e?.status&&r.status!==e.status||t.push({id:n.name,flow:r.flow,flowOrigin:r.flowOrigin,topic:r.topic,status:r.status,currentStep:r.currentStep,startedAt:r.startedAt,updatedAt:r.updatedAt}))}return t.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}},oe=class{createSymlinks(t,i,a,o){let s=this.getTargets(t,i);for(let t of s){n(t.baseDir)||r(t.baseDir,{recursive:!0});for(let r of o.agents){let i=m(a,r);if(!n(i))continue;let o=this.getAgentStem(r),s=m(t.baseDir,`${o}${t.extension}`);n(s)&&u(s);let c=h(p(s),i);try{l(c,s,`file`)}catch{try{e(i,s)}catch(e){console.warn(`Failed to create symlink or copy fallback for ${i}: ${e instanceof Error?e.message:String(e)}`)}}}}}removeSymlinks(e,t){let r=this.getTargets(e,t);for(let e of r)if(n(e.baseDir))try{let t=a(e.baseDir,{withFileTypes:!0});for(let n of t)!n.isFile()&&!n.isSymbolicLink()||u(m(e.baseDir,n.name));a(e.baseDir).length===0&&c(e.baseDir)}catch{}}getTargets(e,t){return[{ide:`copilot`,baseDir:m(e,`.github`,`agents`,`flows`,t),extension:`.agent.md`},{ide:`claude-code`,baseDir:m(e,`.claude`,`agents`,`flows`,t),extension:`.md`}]}getAgentStem(e){return f(e).replace(/\.agent\.md$/,``).replace(/\.md$/,``)}};export{E as ClaudePluginAdapter,D as CopilotAdapter,re as FlowLoader,ie as FlowRegistryManager,ae as FlowStateMachine,z as FoundationIntegration,G as GitInstaller,O as NativeAdapter,k as OpenSpecAdapter,oe as SymlinkManager,F as buildSnapshot,X as createOwnerCapability,K as generateOwnerToken,M as getBuiltinFlows,J as hashToken,Z as rotateOwnerCapability,Y as validateToken};
|
|
@@ -5,4 +5,4 @@ import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as
|
|
|
5
5
|
`).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){R.error(`Failed to upsert curated batch`,{batchSize:e.length,...a(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return R.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...a(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;R.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...a(r)});let i=Math.ceil(e.length/2),o=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(o,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!y(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;b(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!y(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;x([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>S(e)).join(`/`);return t.split(`/`).every(e=>v.test(e))?`${L}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
|
|
6
6
|
`).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,i){if(r.instance().isDegraded(`embedder`)){R.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:i,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){R.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:i,...a(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||c(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>I)throw Error(`Content exceeds maximum size of ${I/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}normalizeTags(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}sameTags(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}ensureCategoryPath(e,t){if(!e.startsWith(`${t}/`))throw Error(`Curated path "${e}" must stay within category "${t}"`)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return _(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
|
|
7
7
|
`)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
|
|
8
|
-
`),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const B=i(`server`);function V(e,t){return t?{version:e,...a(t)}:{version:e}}function H(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function U(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function W(){return U()?n({allowPositionals:!0,options:{transport:{type:`string`,default:H()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:H(),port:process.env.AIKIT_PORT??`3210`}}async function G(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=C(),n=W();if(process.on(`unhandledRejection`,e=>{B.error(`Unhandled rejection`,V(t,e))}),process.on(`uncaughtException`,e=>{B.error(`Uncaught exception — exiting`,V(t,e)),process.exit(1)}),B.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-
|
|
8
|
+
`),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const B=i(`server`);function V(e,t){return t?{version:e,...a(t)}:{version:e}}function H(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function U(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function W(){return U()?n({allowPositionals:!0,options:{transport:{type:`string`,default:H()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:H(),port:process.env.AIKIT_PORT??`3210`}}async function G(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=C(),n=W();if(process.on(`unhandledRejection`,e=>{B.error(`Unhandled rejection`,V(t,e))}),process.on(`uncaughtException`,e=>{B.error(`Uncaught exception — exiting`,V(t,e)),process.exit(1)}),B.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-BF6fnIQ0.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-CXF39-d2.js`);await e(t)}}G();export{w as a,O as i,F as n,T as o,P as r,D as s,z as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{o as e,t}from"./supersession-DO_ZROFl.js";import{fileURLToPath as n}from"node:url";import{AIKIT_RUNTIME_PATHS as r,EMBEDDING_DEFAULTS as i,computePartitionKey as a,createLogger as o,getPartitionDir as s,migrateLegacyWorkspaceLayout as c,serializeError as l}from"../../core/dist/index.js";import{existsSync as u,mkdirSync as d,readFileSync as f,writeFileSync as p}from"node:fs";import{dirname as m,isAbsolute as h,relative as g,resolve as _}from"node:path";const v={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},y={working:1,episodic:2,semantic:4,procedural:12};function b(e,t=v){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function x(e,t,n){e.memoryMetaUpdateTier(t,n)}const S={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function C(e){return{...S,...e}}function w(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function T(e){return e&&e in y?e:`working`}function E(e,t,n,r=S,i){let a=typeof r==`string`?T(r):`working`,o=C(typeof r==`string`?i:r),s=w(e,w(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*y[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function D(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=E(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function O(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=E(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function k(e,t){let n=C(t);return e.memoryMetaList().map(t=>D(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const A=m(n(import.meta.url)),j=o(`server`),M=[`auto`,`manual`,`smart`],N={model:i.model,dimensions:i.dimensions,childProcess:!0,idleTimeoutMs:3e5};function P(e){return typeof e==`string`&&M.includes(e)}function F(e,t,n){let r=_(e),i=g(_(t),r);if(i.startsWith(`..`)||h(i))throw Error(`Config ${n} path escapes allowed root: ${e} is not under ${t}`);return r}function I(e,t){let n=_(e),r=g(_(t),n);return!(r.startsWith(`..`)||h(r))}function L(e){return s(a(e))}function R(e,t,n,r,i){let a=r?_(t,r):t;if(!n)return F(a,t,i);let o=_(e,n);return I(o,t)?r&&_(o)===_(t)?F(a,t,i):F(o,t,i):F(a,t,i)}function z(e){let t=[e.store?.path,e.curated?.path,e.onboardDir,e.stateDir,e.l0CardDir];for(let e of t)e&&d(e,{recursive:!0})}function B(e,t){c(t);let n=L(t);e.store={...e.store,path:R(t,n,e.store?.path,r.data,`store`)},e.curated={...e.curated,path:R(t,n,e.curated?.path,r.curated,`curated`)},e.onboardDir=R(t,n,e.onboardDir,r.onboard,`onboard`),e.stateDir=R(t,n,e.stateDir,r.state,`state`),e.l0CardDir=R(t,n,e.l0CardDir,r.l0Cards,`l0CardDir`)}function V(e){let t=process.env.AIKIT_INDEX_MODE;if(P(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function H(){let n=process.env.AIKIT_CONFIG_PATH??(u(_(process.cwd(),`aikit.config.json`))?_(process.cwd(),`aikit.config.json`):_(A,`..`,`..`,`..`,`aikit.config.json`));try{if(!u(n))return j.info(`No config file found, using defaults`,{configPath:n}),W();let r=f(n,`utf-8`),i=JSON.parse(r),a={...N,...i.embedding};if(i.embedding=a,i.memory={retention:{...S,...i.memory?.retention},lessons:{...e,...i.memory?.lessons},consolidation:{...v,...i.memory?.consolidation},supersession:{...t,...i.memory?.supersession}},i.logging?.errorDetails!==void 0&&typeof i.logging.errorDetails!=`boolean`)throw Error(`Config logging.errorDetails must be a boolean`);if(i.logging={errorDetails:i.logging?.errorDetails===!0},!i.sources||!Array.isArray(i.sources)||i.sources.length===0)throw Error(`Config must have at least one source`);if(!i.store?.path)throw Error(`Config must specify store.path`);if(i.autoIndex!==void 0&&typeof i.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(i.indexMode!==void 0&&!P(i.indexMode))throw Error(`Config indexMode must be one of: ${M.join(`, `)}`);if(typeof a.model!=`string`||a.model.trim()===``)throw Error(`Config embedding.model must be a non-empty string`);if(a.nativeDim!==void 0&&(!Number.isInteger(a.nativeDim)||a.nativeDim<=0))throw Error(`Config embedding.nativeDim must be a positive integer`);if(a.dimensions!==void 0&&(!Number.isInteger(a.dimensions)||a.dimensions<=0))throw Error(`Config embedding.dimensions must be a positive integer`);if(a.dimensions!==void 0&&a.nativeDim!==void 0&&a.dimensions>a.nativeDim)throw Error(`Config embedding.dimensions must not exceed embedding.nativeDim`);if(a.queryPrefix!==void 0&&typeof a.queryPrefix!=`string`)throw Error(`Config embedding.queryPrefix must be a string`);let o=m(n);return i.sources=i.sources.map(e=>({...e,path:F(_(o,e.path),o,`source`)})),G(i,n),B(i,o),i.layeredKnowledge===void 0&&(i.layeredKnowledge=process.env.AIKIT_LAYERED_KNOWLEDGE===`true`),i.indexMode=V(i),i}catch(e){let t=`Failed to load config from ${n}. ${e instanceof Error?e.message:String(e)}`;console.error(`\n ⚠ CONFIG ERROR — ${t}\n Check that the file exists, is valid JSON, and all required fields are present.\n`),j.error(`Failed to load config`,{configPath:n,...l(e)}),j.warn(`Falling back to default configuration`,{configPath:n});let r=W();return r.configError=t,r}}const U=[`.git/**`,`**/node_modules/**`,`*.lock`,`pnpm-lock.yaml`,`package-lock.json`,`**/dist/**`,`**/build/**`,`**/out/**`,`**/.output/**`,`**/cdk.out/**`,`**/.next/**`,`**/.nuxt/**`,`**/.vercel/**`,`**/.serverless/**`,`**/.turbo/**`,`**/.cache/**`,`**/.parcel-cache/**`,`**/coverage/**`,`**/.terraform/**`,`**/__pycache__/**`,`**/.venv/**`,`**/.docusaurus/**`,`**/.temp/**`,`**/tmp/**`];function W(){let n=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),i=L(n),a={sources:[{path:n,excludePatterns:[...U]}],serverName:`aikit`,indexing:{chunkSize:800,chunkOverlap:150,minChunkSize:100},embedding:{...N},store:{backend:`sqlite-vec`,path:_(i,r.data)},curated:{path:_(i,r.curated)},memory:{retention:{...S},lessons:{...e},consolidation:{...v},supersession:{...t}},logging:{errorDetails:!1},onboardDir:_(i,r.onboard),stateDir:_(i,r.state)};return a.indexMode=V(a),a}function G(e,t){let n=e.configVersion??0;if(n>=1)return e;if(n<1)for(let t of e.sources){t.excludePatterns=t.excludePatterns??[];let e=new Set(t.excludePatterns);for(let n of U)e.has(n)||t.excludePatterns.push(n)}e.configVersion=1;try{p(t,`${JSON.stringify(e,null,2)}\n`,`utf-8`),j.info(`Config auto-upgraded`,{from:n,to:1,configPath:t})}catch(e){j.warn(`Failed to write upgraded config`,{configPath:t,...l(e)})}return e}function K(e,t){if(!u(t))throw Error(`Workspace root does not exist: ${t}`);c(t),j.debug(`Reconfiguring for workspace root`,{workspaceRoot:t});try{process.chdir(t),j.debug(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){j.warn(`Failed to chdir to workspace root`,{workspaceRoot:t,...l(e)})}e.sources=[{path:t,excludePatterns:e.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],B(e,t),z(e)}export{U as DEFAULT_EXCLUDE_PATTERNS,b as a,v as i,H as loadConfig,D as n,x as o,O as r,K as reconfigureForWorkspace,V as resolveIndexMode,k as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e,t}from"./supersession-CWEne3av.js";import{fileURLToPath as n}from"node:url";import{AIKIT_RUNTIME_PATHS as r,EMBEDDING_DEFAULTS as i,computePartitionKey as a,createLogger as o,getPartitionDir as s,migrateLegacyWorkspaceLayout as c,serializeError as l}from"../../core/dist/index.js";import{existsSync as u,mkdirSync as d,readFileSync as f,writeFileSync as p}from"node:fs";import{dirname as m,isAbsolute as h,relative as g,resolve as _}from"node:path";const v={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},y={working:1,episodic:2,semantic:4,procedural:12};function b(e,t=v){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function x(e,t,n){e.memoryMetaUpdateTier(t,n)}const S={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function C(e){return{...S,...e}}function w(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function T(e){return e&&e in y?e:`working`}function E(e,t,n,r=S,i){let a=typeof r==`string`?T(r):`working`,o=C(typeof r==`string`?i:r),s=w(e,w(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*y[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function D(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=E(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function O(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=E(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function k(e,t){let n=C(t);return e.memoryMetaList().map(t=>D(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const A=m(n(import.meta.url)),j=o(`server`),M=[`auto`,`manual`,`smart`],N={model:i.model,dimensions:i.dimensions,childProcess:!0,idleTimeoutMs:3e5};function P(e){return typeof e==`string`&&M.includes(e)}function F(e,t,n){let r=_(e),i=g(_(t),r);if(i.startsWith(`..`)||h(i))throw Error(`Config ${n} path escapes allowed root: ${e} is not under ${t}`);return r}function I(e,t){let n=_(e),r=g(_(t),n);return!(r.startsWith(`..`)||h(r))}function L(e){return s(a(e))}function R(e,t,n,r,i){let a=r?_(t,r):t;if(!n)return F(a,t,i);let o=_(e,n);return I(o,t)?r&&_(o)===_(t)?F(a,t,i):F(o,t,i):F(a,t,i)}function z(e){let t=[e.store?.path,e.curated?.path,e.onboardDir,e.stateDir,e.l0CardDir];for(let e of t)e&&d(e,{recursive:!0})}function B(e,t){c(t);let n=L(t);e.store={...e.store,path:R(t,n,e.store?.path,r.data,`store`)},e.curated={...e.curated,path:R(t,n,e.curated?.path,r.curated,`curated`)},e.onboardDir=R(t,n,e.onboardDir,r.onboard,`onboard`),e.stateDir=R(t,n,e.stateDir,r.state,`state`),e.l0CardDir=R(t,n,e.l0CardDir,r.l0Cards,`l0CardDir`)}function V(e){let t=process.env.AIKIT_INDEX_MODE;if(P(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function H(){let n=process.env.AIKIT_CONFIG_PATH??(u(_(process.cwd(),`aikit.config.json`))?_(process.cwd(),`aikit.config.json`):_(A,`..`,`..`,`..`,`aikit.config.json`));try{if(!u(n))return j.info(`No config file found, using defaults`,{configPath:n}),W();let r=f(n,`utf-8`),i=JSON.parse(r),a={...N,...i.embedding};if(i.embedding=a,i.memory={retention:{...S,...i.memory?.retention},lessons:{...e,...i.memory?.lessons},consolidation:{...v,...i.memory?.consolidation},supersession:{...t,...i.memory?.supersession}},i.logging?.errorDetails!==void 0&&typeof i.logging.errorDetails!=`boolean`)throw Error(`Config logging.errorDetails must be a boolean`);if(i.logging={errorDetails:i.logging?.errorDetails===!0},!i.sources||!Array.isArray(i.sources)||i.sources.length===0)throw Error(`Config must have at least one source`);if(!i.store?.path)throw Error(`Config must specify store.path`);if(i.autoIndex!==void 0&&typeof i.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(i.indexMode!==void 0&&!P(i.indexMode))throw Error(`Config indexMode must be one of: ${M.join(`, `)}`);if(typeof a.model!=`string`||a.model.trim()===``)throw Error(`Config embedding.model must be a non-empty string`);if(a.nativeDim!==void 0&&(!Number.isInteger(a.nativeDim)||a.nativeDim<=0))throw Error(`Config embedding.nativeDim must be a positive integer`);if(a.dimensions!==void 0&&(!Number.isInteger(a.dimensions)||a.dimensions<=0))throw Error(`Config embedding.dimensions must be a positive integer`);if(a.dimensions!==void 0&&a.nativeDim!==void 0&&a.dimensions>a.nativeDim)throw Error(`Config embedding.dimensions must not exceed embedding.nativeDim`);if(a.queryPrefix!==void 0&&typeof a.queryPrefix!=`string`)throw Error(`Config embedding.queryPrefix must be a string`);let o=m(n);return i.sources=i.sources.map(e=>({...e,path:F(_(o,e.path),o,`source`)})),G(i,n),B(i,o),i.layeredKnowledge===void 0&&(i.layeredKnowledge=process.env.AIKIT_LAYERED_KNOWLEDGE===`true`),i.indexMode=V(i),i}catch(e){let t=`Failed to load config from ${n}. ${e instanceof Error?e.message:String(e)}`;console.error(`\n ⚠ CONFIG ERROR — ${t}\n Check that the file exists, is valid JSON, and all required fields are present.\n`),j.error(`Failed to load config`,{configPath:n,...l(e)}),j.warn(`Falling back to default configuration`,{configPath:n});let r=W();return r.configError=t,r}}const U=[`.git/**`,`**/node_modules/**`,`*.lock`,`pnpm-lock.yaml`,`package-lock.json`,`**/dist/**`,`**/build/**`,`**/out/**`,`**/.output/**`,`**/cdk.out/**`,`**/.next/**`,`**/.nuxt/**`,`**/.vercel/**`,`**/.serverless/**`,`**/.turbo/**`,`**/.cache/**`,`**/.parcel-cache/**`,`**/coverage/**`,`**/.terraform/**`,`**/__pycache__/**`,`**/.venv/**`,`**/.docusaurus/**`,`**/.temp/**`,`**/tmp/**`];function W(){let n=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),i=L(n),a={sources:[{path:n,excludePatterns:[...U]}],serverName:`aikit`,indexing:{chunkSize:800,chunkOverlap:150,minChunkSize:100},embedding:{...N},store:{backend:`sqlite-vec`,path:_(i,r.data)},curated:{path:_(i,r.curated)},memory:{retention:{...S},lessons:{...e},consolidation:{...v},supersession:{...t}},logging:{errorDetails:!1},onboardDir:_(i,r.onboard),stateDir:_(i,r.state)};return a.indexMode=V(a),a}function G(e,t){let n=e.configVersion??0;if(n>=1)return e;if(n<1)for(let t of e.sources){t.excludePatterns=t.excludePatterns??[];let e=new Set(t.excludePatterns);for(let n of U)e.has(n)||t.excludePatterns.push(n)}e.configVersion=1;try{p(t,`${JSON.stringify(e,null,2)}\n`,`utf-8`),j.info(`Config auto-upgraded`,{from:n,to:1,configPath:t})}catch(e){j.warn(`Failed to write upgraded config`,{configPath:t,...l(e)})}return e}function K(e,t){if(!u(t))throw Error(`Workspace root does not exist: ${t}`);c(t),j.debug(`Reconfiguring for workspace root`,{workspaceRoot:t});try{process.chdir(t),j.debug(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){j.warn(`Failed to chdir to workspace root`,{workspaceRoot:t,...l(e)})}e.sources=[{path:t,excludePatterns:e.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],B(e,t),z(e)}export{U as DEFAULT_EXCLUDE_PATTERNS,b as a,v as i,H as loadConfig,D as n,x as o,O as r,K as reconfigureForWorkspace,V as resolveIndexMode,k as t};
|
|
@@ -172,4 +172,4 @@ svg .edge-label{fill:var(--text-muted)}
|
|
|
172
172
|
</div>
|
|
173
173
|
</body>
|
|
174
174
|
</html>`}const H=`<!-- DIAGRAM:SVG -->`;function U(e){let t=e.indexOf(H);if(t===-1)return null;let n=t+20,r=e.indexOf(H,n);if(r===-1)return null;let i=e.slice(n,r).trim();if(i.startsWith(`<svg`))return i;let a=e.slice(Math.max(0,t),r+20),o=a.match(/viewBox="([^"]+)"/),s=o?o[1]:`0 0 1200 800`,c=a.match(/width="(\d+)"/),l=c?c[1]:`1200`,u=a.match(/height="(\d+)"/);return[`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${s}" width="${l}" height="${u?u[1]:`800`}">`,` <defs>`,` <style>`,` text { font-family: system-ui, -apple-system, sans-serif; }`,` .title { font-size: 20px; font-weight: 600; fill: #fff; }`,` .subtitle { font-size: 14px; fill: #94a3b8; }`,` </style>`,` </defs>`,i,`</svg>`].join(`
|
|
175
|
-
`)}function ge(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function _e(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=ge(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=U(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const W=10*1024*1024,G=2e3;function ve(e){switch(e.diagram_type){case`architecture`:return oe(e);case`workflow`:return V(e);case`sequence`:return L(e);case`dataflow`:return le(e);case`lifecycle`:return N(e)}}function K(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s}=ve(e),c=(e.meta??{}).palette===`warm`?`warm`:`technical`;return{html:he().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,c===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s),markdown:a?_(e):void 0}}function q(e,t={}){return K(e,{...t,dualOutput:!1}).html}function ye(e){return _(e)}function be(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>W)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${W/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>G)throw Error(`Too many edges/connections: ${a.length} (max ${G})`)}function xe(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Se(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Ce(){return Se()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function we(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=Ce();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-
|
|
175
|
+
`)}function ge(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function _e(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=ge(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=U(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const W=10*1024*1024,G=2e3;function ve(e){switch(e.diagram_type){case`architecture`:return oe(e);case`workflow`:return V(e);case`sequence`:return L(e);case`dataflow`:return le(e);case`lifecycle`:return N(e)}}function K(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s}=ve(e),c=(e.meta??{}).palette===`warm`?`warm`:`technical`;return{html:he().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,c===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s),markdown:a?_(e):void 0}}function q(e,t={}){return K(e,{...t,dualOutput:!1}).html}function ye(e){return _(e)}function be(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>W)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${W/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>G)throw Error(`Too many edges/connections: ${a.length} (max ${G})`)}function xe(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Se(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Ce(){return Se()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function we(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=Ce();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-DoIPqaqk.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-CFH9BET5.js`);await e(n)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,_e as exportDiagram,U as extractSvg,n as getSessionIdHeader,we as main,r as readPositiveIntEnv,t as readVersion,q as renderHtml,ye as renderMd,K as renderToResult,e as resolveCorsOrigin,xe as sanitizeTitle,o as selectWorkspaceRoot,be as validate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./server-Cv8aM3Xx.js";export{t as buildPreludeInjection,e as generatePrelude};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{t as e}from"./rolldown-runtime-yuFVEuWy.js";import{t}from"./bin.js";import{f as n,r,u as i}from"./supersession-DO_ZROFl.js";import{getGlobalDataDir as a,isUserInstalled as o,listWorkspaces as s}from"../../core/dist/index.js";import{existsSync as c,mkdirSync as l}from"node:fs";import{join as u}from"node:path";var d=e({DEFAULT_PROMOTE_CONFIG:()=>f,adjudicateCandidate:()=>E,checkPromotionGates:()=>w,collectWorkspaceLessons:()=>j,demoteLesson:()=>P,getGlobalCuratedDir:()=>A,promoteLessons:()=>N,scanForDuplicates:()=>M,scorePromotionCandidate:()=>T});const f={minWorkspaces:2,minAvgConfidence:80,similarityThreshold:.7,dryRun:!0};function p(e){return{minWorkspaces:Math.max(2,Math.trunc(e?.minWorkspaces??f.minWorkspaces)),minAvgConfidence:Math.min(100,Math.max(0,Math.trunc(e?.minAvgConfidence??f.minAvgConfidence))),similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??f.similarityThreshold)),dryRun:e?.dryRun??f.dryRun,layeredKnowledge:e?.layeredKnowledge??f.layeredKnowledge}}function m(e,t){let n=e.map(()=>[]);for(let i=0;i<e.length;i+=1)for(let a=i+1;a<e.length;a+=1)r(e[i].insight,e[a].insight)>=t&&(n[i].push(a),n[a].push(i));return n}function h(e){let t=new Set,n=[];for(let r=0;r<e.length;r+=1){if(t.has(r))continue;let i=[r],a=[];for(t.add(r);i.length>0;){let n=i.pop();if(n!==void 0){a.push(n);for(let r of e[n])t.has(r)||(t.add(r),i.push(r))}}n.push(a)}return n}function g(e){return new t(e,null,null)}function _(e){return(e??``).replace(/\s+/g,` `).trim()}function v(e){let t=_(e);return t.length<=80?t:`${t.slice(0,77).replace(/\s+\S*$/,``)}...`}function y(e){return i({title:v(e.insight),context:`Observed across ${e.foundIn.length} workspaces: ${e.foundIn.join(`, `)}`,insight:e.insight,evidence:[`Promoted from workspaces: ${e.foundIn.join(`, `)}`,`Average confidence: ${e.avgConfidence}/100`,`Reason: ${e.reason}`].join(`
|
|
3
|
+
`),confidence:e.avgConfidence,tags:[`lesson`,`promoted`,`global`]})}function b(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function x(e){let t=(Date.now()-e.getTime())/(1440*60*1e3);return t<=1?10:t<=7?8:t<=14?6:t<=21?4:t<=30?2:1}function S(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function C(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function w(e,t){let n=[],r=!!t?.topicKey;n.push({name:`canonical-topic-key`,passed:r,reason:r?void 0:`No canonical topic key provided`});let i=!!(t?.evidenceRefs&&t.evidenceRefs.length>0);n.push({name:`evidence-attached`,passed:i,reason:i?void 0:`No evidence refs attached`});let a=!0,o;if(t?.observedAt){let e=Date.now()-new Date(t.observedAt).getTime();a=e<2592e6,o=a?void 0:`Observation older than 30 days (${Math.round(e/(1440*60*1e3))}d)`}n.push({name:`freshness`,passed:a,reason:o});let s=!t?.hasConflict;n.push({name:`no-unresolved-conflict`,passed:s,reason:s?void 0:`Has unresolved conflict`});let c=!0,l;t?.scope&&t?.targetScope&&(c=t.scope===t.targetScope,l=c?void 0:`Scope "${t.scope}" does not match target "${t.targetScope}"`),n.push({name:`scope-matches`,passed:c,reason:l});let u=!1;t?.actionability&&(u=t.actionability===`high`||t.actionability===`medium`),n.push({name:`actionability-clear`,passed:u,reason:u?void 0:`Actionability is "${t?.actionability??`not set`}"`});let d=!0,f;t?.tokenBudgetRemaining!==void 0&&t?.minTokenBudget!==void 0&&(d=t.tokenBudgetRemaining>=t.minTokenBudget,f=d?void 0:`Token budget ${t.tokenBudgetRemaining} < required ${t.minTokenBudget}`),n.push({name:`token-budget-available`,passed:d,reason:f});let p=n.filter(e=>!e.passed).map(e=>e.name);return{passed:p.length===0,gates:n,failedGates:p}}function T(e,t){let n=b(t?.recurrence??1,1,10),r=b(t?.impact??5,1,10),i=b(e.foundIn.length,1,10),a=t?.observedAt?x(new Date(t.observedAt)):5,o=S(t?.actionability??`medium`),s=C(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function E(e,t,n,i,a){return t.passed?n&&i&&a&&n.some(e=>r(e,a.insight)>=i)?{decision:`supersede`,score:e.totalScore,reason:`Similar candidate already exists at L2`}:e.totalScore<20?{decision:`supersede`,score:e.totalScore,reason:`Score ${e.totalScore}/60 insufficient for promotion`}:e.totalScore<35?{decision:`hold-l3`,score:e.totalScore,reason:`Moderate score ${e.totalScore}/60, needs more evidence or recurrence`}:e.signals.recurrence<3&&e.signals.impact<8?{decision:`hold-l3`,score:e.totalScore,reason:`Low-impact repetition: recurrence=${e.signals.recurrence} < 3 despite score ${e.totalScore}/60`}:e.signals.recurrence<3&&e.signals.impact>=8?{decision:`promote`,score:e.totalScore,reason:`High-impact exception: impact=${e.signals.impact}, score=${e.totalScore}/60`}:{decision:`promote`,score:e.totalScore,reason:`Strong multi-signal score: ${e.totalScore}/60, recurrence=${e.signals.recurrence}, impact=${e.signals.impact}`}:{decision:`reject`,score:e.totalScore,reason:`Hard gates failed: ${t.failedGates.join(`, `)}`}}async function D(e,t){let r=await e.list({category:`lessons`,limit:1e3,orderBy:`updated`,order:`desc`});return(await Promise.all(r.map(async r=>{let i=await e.read(r.path),a=n(i.content),o=_(a.insight);return o?{workspace:t,path:r.path,title:a.title??i.title??r.title,insight:o,confidence:a.confidence??0}:null}))).filter(e=>e!==null)}async function O(e){return(await D(e,`global`)).map(e=>e.insight)}function k(e,t,n){return t.some(t=>r(t,e)>=n)}function A(){let e=u(a(),`global-knowledge`,`.ai`,`curated`);return c(e)||l(e,{recursive:!0}),e}async function j(e){let t=new Map;if(!o())return t;for(let e of s()){let n=u(e.workspacePath,`.ai`,`curated`);if(!c(n))continue;let r=await D(g(n),e.partition);r.length>0&&t.set(e.partition,r)}return t}function M(e,t=f,n){let r=p(t),i=[...e.values()].flat();if(i.length===0)return[];let a=h(m(i,r.similarityThreshold)),o=[];for(let e of a){let t=e.map(e=>i[e]),a=[...new Set(t.map(e=>e.workspace))].sort();if(a.length<r.minWorkspaces)continue;let s=Math.round(t.reduce((e,t)=>e+t.confidence,0)/t.length),c={insight:[...t].sort((e,t)=>t.confidence-e.confidence||e.title.localeCompare(t.title)||e.path.localeCompare(t.path))[0].insight,foundIn:a,avgConfidence:s,action:`skip`,reason:``};if(r.layeredKnowledge){let e=n?.get(c.insight),t=w(c,e),r=T(c,e),i=E(r,t,void 0,void 0,c);c.gateResult=t,c.scoringResult=r,c.adjudication=i,c.action=i.decision===`promote`?`promote`:`skip`,c.reason=i.reason}else c.action=s>=r.minAvgConfidence?`promote`:`skip`,c.reason=s>=r.minAvgConfidence?`Shared across ${a.length} workspaces`:`Below confidence threshold`;o.push(c)}return o.sort((e,t)=>Number(t.action===`promote`)-Number(e.action===`promote`)||t.foundIn.length-e.foundIn.length||t.avgConfidence-e.avgConfidence||e.insight.localeCompare(t.insight))}async function N(e,t,n=f){let r=p(n),i=[],a=await O(t);for(let n of e){if(!(r.layeredKnowledge?n.adjudication?.decision===`promote`:n.action===`promote`)||k(n.insight,a,r.similarityThreshold)||r.dryRun)continue;let e=await t.remember(v(n.insight),y(n),`lessons`,[`lesson`,`promoted`,`global`]);i.push(e.path),a.push(n.insight)}return{candidates:e,promoted:i}}async function P(e,t){try{return await e.forget(t,`Demoted from global knowledge partition`),{removed:!0,path:t}}catch(e){if(e instanceof Error&&/not found/i.test(e.message))return{removed:!1,path:t};throw e}}export{N as a,A as i,j as n,d as o,P as r,M as s,f as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{t}from"./curated-manager-CBKTmAjM.js";import{f as n,r,u as i}from"./supersession-CWEne3av.js";import{getGlobalDataDir as a,isUserInstalled as o,listWorkspaces as s}from"../../core/dist/index.js";import{existsSync as c,mkdirSync as l}from"node:fs";import{join as u}from"node:path";var d=e({DEFAULT_PROMOTE_CONFIG:()=>f,adjudicateCandidate:()=>E,checkPromotionGates:()=>w,collectWorkspaceLessons:()=>j,demoteLesson:()=>P,getGlobalCuratedDir:()=>A,promoteLessons:()=>N,scanForDuplicates:()=>M,scorePromotionCandidate:()=>T});const f={minWorkspaces:2,minAvgConfidence:80,similarityThreshold:.7,dryRun:!0};function p(e){return{minWorkspaces:Math.max(2,Math.trunc(e?.minWorkspaces??f.minWorkspaces)),minAvgConfidence:Math.min(100,Math.max(0,Math.trunc(e?.minAvgConfidence??f.minAvgConfidence))),similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??f.similarityThreshold)),dryRun:e?.dryRun??f.dryRun,layeredKnowledge:e?.layeredKnowledge??f.layeredKnowledge}}function m(e,t){let n=e.map(()=>[]);for(let i=0;i<e.length;i+=1)for(let a=i+1;a<e.length;a+=1)r(e[i].insight,e[a].insight)>=t&&(n[i].push(a),n[a].push(i));return n}function h(e){let t=new Set,n=[];for(let r=0;r<e.length;r+=1){if(t.has(r))continue;let i=[r],a=[];for(t.add(r);i.length>0;){let n=i.pop();if(n!==void 0){a.push(n);for(let r of e[n])t.has(r)||(t.add(r),i.push(r))}}n.push(a)}return n}function g(e){return new t(e,null,null)}function _(e){return(e??``).replace(/\s+/g,` `).trim()}function v(e){let t=_(e);return t.length<=80?t:`${t.slice(0,77).replace(/\s+\S*$/,``)}...`}function y(e){return i({title:v(e.insight),context:`Observed across ${e.foundIn.length} workspaces: ${e.foundIn.join(`, `)}`,insight:e.insight,evidence:[`Promoted from workspaces: ${e.foundIn.join(`, `)}`,`Average confidence: ${e.avgConfidence}/100`,`Reason: ${e.reason}`].join(`
|
|
2
|
+
`),confidence:e.avgConfidence,tags:[`lesson`,`promoted`,`global`]})}function b(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function x(e){let t=(Date.now()-e.getTime())/(1440*60*1e3);return t<=1?10:t<=7?8:t<=14?6:t<=21?4:t<=30?2:1}function S(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function C(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function w(e,t){let n=[],r=!!t?.topicKey;n.push({name:`canonical-topic-key`,passed:r,reason:r?void 0:`No canonical topic key provided`});let i=!!(t?.evidenceRefs&&t.evidenceRefs.length>0);n.push({name:`evidence-attached`,passed:i,reason:i?void 0:`No evidence refs attached`});let a=!0,o;if(t?.observedAt){let e=Date.now()-new Date(t.observedAt).getTime();a=e<2592e6,o=a?void 0:`Observation older than 30 days (${Math.round(e/(1440*60*1e3))}d)`}n.push({name:`freshness`,passed:a,reason:o});let s=!t?.hasConflict;n.push({name:`no-unresolved-conflict`,passed:s,reason:s?void 0:`Has unresolved conflict`});let c=!0,l;t?.scope&&t?.targetScope&&(c=t.scope===t.targetScope,l=c?void 0:`Scope "${t.scope}" does not match target "${t.targetScope}"`),n.push({name:`scope-matches`,passed:c,reason:l});let u=!1;t?.actionability&&(u=t.actionability===`high`||t.actionability===`medium`),n.push({name:`actionability-clear`,passed:u,reason:u?void 0:`Actionability is "${t?.actionability??`not set`}"`});let d=!0,f;t?.tokenBudgetRemaining!==void 0&&t?.minTokenBudget!==void 0&&(d=t.tokenBudgetRemaining>=t.minTokenBudget,f=d?void 0:`Token budget ${t.tokenBudgetRemaining} < required ${t.minTokenBudget}`),n.push({name:`token-budget-available`,passed:d,reason:f});let p=n.filter(e=>!e.passed).map(e=>e.name);return{passed:p.length===0,gates:n,failedGates:p}}function T(e,t){let n=b(t?.recurrence??1,1,10),r=b(t?.impact??5,1,10),i=b(e.foundIn.length,1,10),a=t?.observedAt?x(new Date(t.observedAt)):5,o=S(t?.actionability??`medium`),s=C(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function E(e,t,n,i,a){return t.passed?n&&i&&a&&n.some(e=>r(e,a.insight)>=i)?{decision:`supersede`,score:e.totalScore,reason:`Similar candidate already exists at L2`}:e.totalScore<20?{decision:`supersede`,score:e.totalScore,reason:`Score ${e.totalScore}/60 insufficient for promotion`}:e.totalScore<35?{decision:`hold-l3`,score:e.totalScore,reason:`Moderate score ${e.totalScore}/60, needs more evidence or recurrence`}:e.signals.recurrence<3&&e.signals.impact<8?{decision:`hold-l3`,score:e.totalScore,reason:`Low-impact repetition: recurrence=${e.signals.recurrence} < 3 despite score ${e.totalScore}/60`}:e.signals.recurrence<3&&e.signals.impact>=8?{decision:`promote`,score:e.totalScore,reason:`High-impact exception: impact=${e.signals.impact}, score=${e.totalScore}/60`}:{decision:`promote`,score:e.totalScore,reason:`Strong multi-signal score: ${e.totalScore}/60, recurrence=${e.signals.recurrence}, impact=${e.signals.impact}`}:{decision:`reject`,score:e.totalScore,reason:`Hard gates failed: ${t.failedGates.join(`, `)}`}}async function D(e,t){let r=await e.list({category:`lessons`,limit:1e3,orderBy:`updated`,order:`desc`});return(await Promise.all(r.map(async r=>{let i=await e.read(r.path),a=n(i.content),o=_(a.insight);return o?{workspace:t,path:r.path,title:a.title??i.title??r.title,insight:o,confidence:a.confidence??0}:null}))).filter(e=>e!==null)}async function O(e){return(await D(e,`global`)).map(e=>e.insight)}function k(e,t,n){return t.some(t=>r(t,e)>=n)}function A(){let e=u(a(),`global-knowledge`,`.ai`,`curated`);return c(e)||l(e,{recursive:!0}),e}async function j(e){let t=new Map;if(!o())return t;for(let e of s()){let n=u(e.workspacePath,`.ai`,`curated`);if(!c(n))continue;let r=await D(g(n),e.partition);r.length>0&&t.set(e.partition,r)}return t}function M(e,t=f,n){let r=p(t),i=[...e.values()].flat();if(i.length===0)return[];let a=h(m(i,r.similarityThreshold)),o=[];for(let e of a){let t=e.map(e=>i[e]),a=[...new Set(t.map(e=>e.workspace))].sort();if(a.length<r.minWorkspaces)continue;let s=Math.round(t.reduce((e,t)=>e+t.confidence,0)/t.length),c={insight:[...t].sort((e,t)=>t.confidence-e.confidence||e.title.localeCompare(t.title)||e.path.localeCompare(t.path))[0].insight,foundIn:a,avgConfidence:s,action:`skip`,reason:``};if(r.layeredKnowledge){let e=n?.get(c.insight),t=w(c,e),r=T(c,e),i=E(r,t,void 0,void 0,c);c.gateResult=t,c.scoringResult=r,c.adjudication=i,c.action=i.decision===`promote`?`promote`:`skip`,c.reason=i.reason}else c.action=s>=r.minAvgConfidence?`promote`:`skip`,c.reason=s>=r.minAvgConfidence?`Shared across ${a.length} workspaces`:`Below confidence threshold`;o.push(c)}return o.sort((e,t)=>Number(t.action===`promote`)-Number(e.action===`promote`)||t.foundIn.length-e.foundIn.length||t.avgConfidence-e.avgConfidence||e.insight.localeCompare(t.insight))}async function N(e,t,n=f){let r=p(n),i=[],a=await O(t);for(let n of e){if(!(r.layeredKnowledge?n.adjudication?.decision===`promote`:n.action===`promote`)||k(n.insight,a,r.similarityThreshold)||r.dryRun)continue;let e=await t.remember(v(n.insight),y(n),`lessons`,[`lesson`,`promoted`,`global`]);i.push(e.path),a.push(n.insight)}return{candidates:e,promoted:i}}async function P(e,t){try{return await e.forget(t,`Demoted from global knowledge partition`),{removed:!0,path:t}}catch(e){if(e instanceof Error&&/not found/i.test(e.message))return{removed:!1,path:t};throw e}}export{N as a,A as i,j as n,d as o,P as r,M as s,f as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./server-Cv8aM3Xx.js";export{e as createSamplingClient};
|