zam-core 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -566,12 +566,18 @@ interface PrerequisiteWithToken extends Prerequisite {
566
566
  domain: string;
567
567
  bloom_level: number;
568
568
  }
569
+ /**
570
+ * Collect all prerequisite edges as an adjacency map: child → parent set.
571
+ * Only used for cycle detection; the full graph is loaded once per
572
+ * addPrerequisite call (small N in practice).
573
+ */
574
+ declare function buildAncestorMap(db: Database): Promise<Map<string, Set<string>>>;
569
575
  /**
570
576
  * Returns true if adding edge (tokenId → requiresId) would create a cycle.
571
577
  * Uses BFS from requiresId: if tokenId is reachable, adding the edge closes
572
578
  * a loop.
573
579
  */
574
- declare function wouldCreateCycle(db: Database, tokenId: string, requiresId: string): Promise<boolean>;
580
+ declare function wouldCreateCycle(db: Database, tokenId: string, requiresId: string, ancestors?: Map<string, Set<string>>): Promise<boolean>;
575
581
  /**
576
582
  * Add a prerequisite edge: tokenId requires requiresId.
577
583
  *
@@ -1910,6 +1916,39 @@ declare function cosineSimilarity(a: Float32Array, b: Float32Array): number;
1910
1916
  */
1911
1917
  declare function searchTokensHybrid(db: Database, query: string, opts?: HybridSearchOptions): Promise<HybridScoredToken[]>;
1912
1918
 
1919
+ /**
1920
+ * Foundation suggestions for tokens.
1921
+ * Suggests existing tokens that are semantically related as prerequisite candidates.
1922
+ *
1923
+ * This module is pure math + database queries — zero LLM dependencies, no HTTP.
1924
+ */
1925
+
1926
+ interface FoundationSuggestion {
1927
+ token: Token;
1928
+ similarity: number;
1929
+ alreadyPrerequisite: boolean;
1930
+ wouldCreateCycle: boolean;
1931
+ /** Candidate's bloom_level is higher than the target's — unusual for a foundation. */
1932
+ bloomAboveTarget: boolean;
1933
+ }
1934
+ interface SuggestFoundationsOptions {
1935
+ queryEmbedding: ArrayLike<number>;
1936
+ /** Canonical embedding model id the stored vectors must match. */
1937
+ model: string;
1938
+ /** Set when the target token already exists (register-after / rating-1 flow). */
1939
+ targetTokenId?: string;
1940
+ /** Used for the bloomAboveTarget flag; defaults to 5 (nothing flagged). */
1941
+ targetBloomLevel?: BloomLevel$1;
1942
+ limit?: number;
1943
+ minSimilarity?: number;
1944
+ maxSimilarity?: number;
1945
+ }
1946
+ /**
1947
+ * Suggests existing tokens that are semantically related as prerequisite candidates.
1948
+ * Filters by similarity range and ranks descending by similarity.
1949
+ */
1950
+ declare function suggestFoundations(db: Database, opts: SuggestFoundationsOptions): Promise<FoundationSuggestion[]>;
1951
+
1913
1952
  /**
1914
1953
  * Get the path to ZAM's internal package SKILL.md.
1915
1954
  */
@@ -2194,4 +2233,4 @@ declare function resolveAllBeliefPaths(db: Database): Promise<string[]>;
2194
2233
  */
2195
2234
  declare function resolveAllGoalPaths(db: Database): Promise<string[]>;
2196
2235
 
2197
- export { type ADOConfig, type ADOCredentials, type AgentSkill, type AnalysisResult, type ApplySessionSynthesisInput, type ApplySessionSynthesisResult, BUILT_IN_SENSITIVE_MATCHERS, type BloomLevel$1 as BloomLevel, type CaptureDecision, type CaptureDenialReason, type CaptureRequest, type Card, type CardDeletionImpact, type CardState$1 as CardState, type CascadeBlockResult, type CommandRecord, type CommandSequence, type ConfirmFoundationsResult, type ConnectionOptions, type CreateAgentSkillInput, type CreateGoalInput, type CreateReviewInput, type CreateSessionInput, type CreateTokenInput, type Credentials, type CurriculumCardInput, DEFAULT_OBSERVER_POLICY, DEFAULT_REVIEW_CONTEXT_MAX_CHARS, type Database, type DatabaseProvider, type DatabaseTargetInfo, type DatabaseValue, type DeleteCardResult, type DeleteTokenResult, type DiscoveryOptions, type DomainCompetence, type EmbeddedTokenRow, type EmbeddingCoverage, type EmbeddingStaleness, type EvaluateInput, type EvaluateResult, type ExecuteReviewActionInput, type ExecutionContext, type FSRSParameters, type FoundationProposalInput, type Goal, type GoalFrontmatter, type GoalStatus, type GoalSummary, HOMEBREW_CASK, type HybridScoredToken, type HybridSearchOptions, type ImportCurriculumResult, type ImportResult, type InstallChannel, type InstallConfig, type InstallMode, type InstallPlan, type InstallResult, type LocalLLMRunner, type LogStepInput, type MachineAiConfig, type MachineProviderRecord, type MachineRoleBinding, type MonitorEvent, type Neighborhood, type NeighborhoodToken, OBSERVER_POLICY_UNSET_HINT, OBSERVER_POLICY_VERSION, type ObservationRating, type ObserverConsent, type ObserverPolicy, type ObserverRetention, type ObserverScope, type ObserverSettingKey, type OllamaDetectionOptions, type PersonalCard, type PrepareSessionSynthesisInput, type Prerequisite, type PrerequisiteWithToken, type PromptInput, REVIEW_CONTEXT_CACHE_TTL_MS, type Rating, type RecallPrompt, type RemoteDatabaseOptions, type RepoPaths, type ResolvedCaptureTarget, type ResolvedReference, type ReviewActionResult, type ReviewActionType, type ReviewContext, type ReviewLog, type ReviewQueue, type ReviewQueueItem, type ReviewQueueOptions, type RunResult, SIDECAR_POLICY_FILE, SNAPSHOT_VERSION, type SchedulingCard, type Session, type SessionStep, type SessionSummary, type SessionSynthesisCandidate, type SessionSynthesisEvidence, type SessionSynthesisPreview, type SessionSynthesisRecord, type SidecarPrivacyPolicy, type SkillProposal, type SkillSource, type SnapshotManifest, type SourceProposalInput, type SplitProposalInput, type Statement, type SupportedLocale, type SymbiosisMode, type SynthesisConfidence, type SystemProfile, type Token, type TokenDeleteImpact, type TokenEmbedding, type TokenNeedingEmbedding, type TokenPattern, type TranslationKey, type TursoCredentials, UI_OBSERVATION_PROTOCOL_VERSION, type UiActionType, type UiApplicationContext, type UiCandidateToken, type UiEvidenceRef, type UiEvidenceType, type UiObservationKind, type UiObservationReport, type UiObservedAction, type UnblockResult, type UpdateActionKind, type UpdateCardInput, type UpdateDecision, type UpdateStep, type UpdateStepKind, type UpdateTokenInput, type UserSetting, type UserStats, WINGET_PACKAGE_ID, type WorkItem, type WorkspaceConfig, type WorkspaceKind, type WorkspaceSourceControl, addPrerequisite, analyzeObservation, appendUiObservationReport, applySessionSynthesis, buildReviewQueue, buildUiSynthesisCandidates, cascadeBlock, clearADOCredentials, clearProviderApiKey, clearReviewContextCache, clearTursoCredentials, compareVersions, computeContentHash, confirmCardSplit, confirmFoundations, confirmSourceImport, cosineSimilarity, createAgentSkill, createFSRS, createGoal, createToken, decidePostCapture, decidePreCapture, decideUpdate, decodeEmbedding, deleteCardForUser, deleteSetting, deleteToken, deprecateToken, detectSyncProvider, detectSystemLocale, discoverSkills, distributeGlobalSkills, embeddingContentForToken, encodeEmbedding, endSession, ensureCard, ensureMonitorDir, ensureUiObserverDir, evaluateRating, executeReviewAction, exportSnapshot, extractTasks, extractTokenRefs, fetchActiveWorkItems, findTokens, generateBashHooks, generateBashUnhooks, generateConceptFreeCue, generatePowerShellHooks, generatePowerShellUnhooks, generatePrompt, generateTokenSlug, generateZshHooks, generateZshUnhooks, getADOCredentials, getActiveWorkspace, getActiveWorkspaceId, getAgentSkill, getAllSettings, getAllSettingsDetailed, getBlockedCards, getCard, getCardById, getCardDeletionImpact, getConfiguredWorkspaces, getDatabaseTargetInfo, getDefaultDbPath, getDependents, getDomainCompetence, getDueCards, getEmbeddingCoverage, getGoal, getGoalTree, getInstallChannel, getInstallMode, getMachineAiConfig, getMonitorDir, getMonitorLogStats, getMonitorPath, getPackageSkillPath, getPrerequisites, getProviderApiKey, getRepoPaths, getReviewsForCard, getReviewsForUser, getSessionSummary, getSessionSynthesisRecords, getSetting, getSystemProfile, getTokenById, getTokenBySlug, getTokenDeleteImpact, getTokenEmbedding, getTokenNeighborhood, getTursoCredentials, getUiObservationPath, getUiObserverDir, getUserStats, hasCommand, importCurriculumCards, importSnapshot, injectShellHooks, installFastFlowLM, installOllama, installOpenCode, interleave, isObserverPolicyConfigured, isOllamaInstalled, isUiObservationReport, listAgentSkills, listEmbeddedTokens, listGoals, listPersonalCards, listProviderApiKeyRefs, listTokens, listTokensNeedingEmbedding, loadADOConfig, loadCredentials, loadInstallConfig, logReview, logStep, matchBuiltInSensitive, matchDenylist, matchesFilePath, monitorLogExists, normalizeLocale, normalizePath, openDatabase, openDatabaseWithSync, openRemoteDatabase, pairCommands, parseGoalFile, parseMonitorLog, parseObserverList, parseObserverPolicy, parseSnapshot, parseUiObservationLog, planOpenCodeInstall, planUpdate, prepareLocalModel, prepareSessionSynthesis, readMonitorLog, readUiObservationLog, removeConfiguredWorkspace, resolveAllBeliefPaths, resolveAllGoalPaths, resolveObserverPolicy, resolveOllamaCommand, resolveReference, resolveRepoPath, resolveReviewContext, saveConfiguredWorkspaces, saveCredentials, saveInstallConfig, saveMachineAiConfig, searchTokensHybrid, serializeGoal, setADOCredentials, setActiveWorkspaceId, setInstallChannel, setInstallMode, setProviderApiKey, setSetting, setTursoCredentials, slugify, startSession, syncObserverSidecarPolicy, t, toSidecarPrivacyPolicy, uiObservationLogExists, uiObservationTimeSpan, unblockReady, updateCard, updateGoalStatus, updateToken, upsertConfiguredWorkspace, upsertTokenEmbedding, verifySnapshot, wouldCreateCycle, writeMonitorEvent };
2236
+ export { type ADOConfig, type ADOCredentials, type AgentSkill, type AnalysisResult, type ApplySessionSynthesisInput, type ApplySessionSynthesisResult, BUILT_IN_SENSITIVE_MATCHERS, type BloomLevel$1 as BloomLevel, type CaptureDecision, type CaptureDenialReason, type CaptureRequest, type Card, type CardDeletionImpact, type CardState$1 as CardState, type CascadeBlockResult, type CommandRecord, type CommandSequence, type ConfirmFoundationsResult, type ConnectionOptions, type CreateAgentSkillInput, type CreateGoalInput, type CreateReviewInput, type CreateSessionInput, type CreateTokenInput, type Credentials, type CurriculumCardInput, DEFAULT_OBSERVER_POLICY, DEFAULT_REVIEW_CONTEXT_MAX_CHARS, type Database, type DatabaseProvider, type DatabaseTargetInfo, type DatabaseValue, type DeleteCardResult, type DeleteTokenResult, type DiscoveryOptions, type DomainCompetence, type EmbeddedTokenRow, type EmbeddingCoverage, type EmbeddingStaleness, type EvaluateInput, type EvaluateResult, type ExecuteReviewActionInput, type ExecutionContext, type FSRSParameters, type FoundationProposalInput, type FoundationSuggestion, type Goal, type GoalFrontmatter, type GoalStatus, type GoalSummary, HOMEBREW_CASK, type HybridScoredToken, type HybridSearchOptions, type ImportCurriculumResult, type ImportResult, type InstallChannel, type InstallConfig, type InstallMode, type InstallPlan, type InstallResult, type LocalLLMRunner, type LogStepInput, type MachineAiConfig, type MachineProviderRecord, type MachineRoleBinding, type MonitorEvent, type Neighborhood, type NeighborhoodToken, OBSERVER_POLICY_UNSET_HINT, OBSERVER_POLICY_VERSION, type ObservationRating, type ObserverConsent, type ObserverPolicy, type ObserverRetention, type ObserverScope, type ObserverSettingKey, type OllamaDetectionOptions, type PersonalCard, type PrepareSessionSynthesisInput, type Prerequisite, type PrerequisiteWithToken, type PromptInput, REVIEW_CONTEXT_CACHE_TTL_MS, type Rating, type RecallPrompt, type RemoteDatabaseOptions, type RepoPaths, type ResolvedCaptureTarget, type ResolvedReference, type ReviewActionResult, type ReviewActionType, type ReviewContext, type ReviewLog, type ReviewQueue, type ReviewQueueItem, type ReviewQueueOptions, type RunResult, SIDECAR_POLICY_FILE, SNAPSHOT_VERSION, type SchedulingCard, type Session, type SessionStep, type SessionSummary, type SessionSynthesisCandidate, type SessionSynthesisEvidence, type SessionSynthesisPreview, type SessionSynthesisRecord, type SidecarPrivacyPolicy, type SkillProposal, type SkillSource, type SnapshotManifest, type SourceProposalInput, type SplitProposalInput, type Statement, type SuggestFoundationsOptions, type SupportedLocale, type SymbiosisMode, type SynthesisConfidence, type SystemProfile, type Token, type TokenDeleteImpact, type TokenEmbedding, type TokenNeedingEmbedding, type TokenPattern, type TranslationKey, type TursoCredentials, UI_OBSERVATION_PROTOCOL_VERSION, type UiActionType, type UiApplicationContext, type UiCandidateToken, type UiEvidenceRef, type UiEvidenceType, type UiObservationKind, type UiObservationReport, type UiObservedAction, type UnblockResult, type UpdateActionKind, type UpdateCardInput, type UpdateDecision, type UpdateStep, type UpdateStepKind, type UpdateTokenInput, type UserSetting, type UserStats, WINGET_PACKAGE_ID, type WorkItem, type WorkspaceConfig, type WorkspaceKind, type WorkspaceSourceControl, addPrerequisite, analyzeObservation, appendUiObservationReport, applySessionSynthesis, buildAncestorMap, buildReviewQueue, buildUiSynthesisCandidates, cascadeBlock, clearADOCredentials, clearProviderApiKey, clearReviewContextCache, clearTursoCredentials, compareVersions, computeContentHash, confirmCardSplit, confirmFoundations, confirmSourceImport, cosineSimilarity, createAgentSkill, createFSRS, createGoal, createToken, decidePostCapture, decidePreCapture, decideUpdate, decodeEmbedding, deleteCardForUser, deleteSetting, deleteToken, deprecateToken, detectSyncProvider, detectSystemLocale, discoverSkills, distributeGlobalSkills, embeddingContentForToken, encodeEmbedding, endSession, ensureCard, ensureMonitorDir, ensureUiObserverDir, evaluateRating, executeReviewAction, exportSnapshot, extractTasks, extractTokenRefs, fetchActiveWorkItems, findTokens, generateBashHooks, generateBashUnhooks, generateConceptFreeCue, generatePowerShellHooks, generatePowerShellUnhooks, generatePrompt, generateTokenSlug, generateZshHooks, generateZshUnhooks, getADOCredentials, getActiveWorkspace, getActiveWorkspaceId, getAgentSkill, getAllSettings, getAllSettingsDetailed, getBlockedCards, getCard, getCardById, getCardDeletionImpact, getConfiguredWorkspaces, getDatabaseTargetInfo, getDefaultDbPath, getDependents, getDomainCompetence, getDueCards, getEmbeddingCoverage, getGoal, getGoalTree, getInstallChannel, getInstallMode, getMachineAiConfig, getMonitorDir, getMonitorLogStats, getMonitorPath, getPackageSkillPath, getPrerequisites, getProviderApiKey, getRepoPaths, getReviewsForCard, getReviewsForUser, getSessionSummary, getSessionSynthesisRecords, getSetting, getSystemProfile, getTokenById, getTokenBySlug, getTokenDeleteImpact, getTokenEmbedding, getTokenNeighborhood, getTursoCredentials, getUiObservationPath, getUiObserverDir, getUserStats, hasCommand, importCurriculumCards, importSnapshot, injectShellHooks, installFastFlowLM, installOllama, installOpenCode, interleave, isObserverPolicyConfigured, isOllamaInstalled, isUiObservationReport, listAgentSkills, listEmbeddedTokens, listGoals, listPersonalCards, listProviderApiKeyRefs, listTokens, listTokensNeedingEmbedding, loadADOConfig, loadCredentials, loadInstallConfig, logReview, logStep, matchBuiltInSensitive, matchDenylist, matchesFilePath, monitorLogExists, normalizeLocale, normalizePath, openDatabase, openDatabaseWithSync, openRemoteDatabase, pairCommands, parseGoalFile, parseMonitorLog, parseObserverList, parseObserverPolicy, parseSnapshot, parseUiObservationLog, planOpenCodeInstall, planUpdate, prepareLocalModel, prepareSessionSynthesis, readMonitorLog, readUiObservationLog, removeConfiguredWorkspace, resolveAllBeliefPaths, resolveAllGoalPaths, resolveObserverPolicy, resolveOllamaCommand, resolveReference, resolveRepoPath, resolveReviewContext, saveConfiguredWorkspaces, saveCredentials, saveInstallConfig, saveMachineAiConfig, searchTokensHybrid, serializeGoal, setADOCredentials, setActiveWorkspaceId, setInstallChannel, setInstallMode, setProviderApiKey, setSetting, setTursoCredentials, slugify, startSession, suggestFoundations, syncObserverSidecarPolicy, t, toSidecarPrivacyPolicy, uiObservationLogExists, uiObservationTimeSpan, unblockReady, updateCard, updateGoalStatus, updateToken, upsertConfiguredWorkspace, upsertTokenEmbedding, verifySnapshot, wouldCreateCycle, writeMonitorEvent };
package/dist/index.js CHANGED
@@ -2215,9 +2215,9 @@ async function buildAncestorMap(db) {
2215
2215
  }
2216
2216
  return map;
2217
2217
  }
2218
- async function wouldCreateCycle(db, tokenId, requiresId) {
2218
+ async function wouldCreateCycle(db, tokenId, requiresId, ancestors) {
2219
2219
  if (tokenId === requiresId) return true;
2220
- const ancestors = await buildAncestorMap(db);
2220
+ const map = ancestors ?? await buildAncestorMap(db);
2221
2221
  const visited = /* @__PURE__ */ new Set();
2222
2222
  const queue = [requiresId];
2223
2223
  while (queue.length > 0) {
@@ -2225,7 +2225,7 @@ async function wouldCreateCycle(db, tokenId, requiresId) {
2225
2225
  if (current === tokenId) return true;
2226
2226
  if (visited.has(current)) continue;
2227
2227
  visited.add(current);
2228
- const parents = ancestors.get(current);
2228
+ const parents = map.get(current);
2229
2229
  if (parents) {
2230
2230
  for (const parent of parents) {
2231
2231
  if (!visited.has(parent)) queue.push(parent);
@@ -4850,6 +4850,71 @@ async function searchTokensHybrid(db, query, opts) {
4850
4850
  return results.slice(0, limit);
4851
4851
  }
4852
4852
 
4853
+ // src/kernel/search/suggestions.ts
4854
+ async function suggestFoundations(db, opts) {
4855
+ const minSimilarity = opts.minSimilarity ?? 0.45;
4856
+ const maxSimilarity = opts.maxSimilarity ?? 0.85;
4857
+ const limit = opts.limit ?? 5;
4858
+ const targetBloomLevel = opts.targetBloomLevel ?? 5;
4859
+ if (minSimilarity >= maxSimilarity) {
4860
+ return [];
4861
+ }
4862
+ const embedded = await listEmbeddedTokens(db, opts.model);
4863
+ if (embedded.length === 0) {
4864
+ return [];
4865
+ }
4866
+ const queryVec = Float32Array.from(opts.queryEmbedding);
4867
+ const candidates = [];
4868
+ for (const row of embedded) {
4869
+ if (opts.targetTokenId && row.token.id === opts.targetTokenId) {
4870
+ continue;
4871
+ }
4872
+ const similarity = cosineSimilarity(queryVec, row.embedding);
4873
+ if (similarity >= minSimilarity && similarity < maxSimilarity) {
4874
+ candidates.push({ token: row.token, similarity });
4875
+ }
4876
+ }
4877
+ candidates.sort((a, b) => {
4878
+ if (Math.abs(a.similarity - b.similarity) > 1e-9) {
4879
+ return b.similarity - a.similarity;
4880
+ }
4881
+ return a.token.slug.localeCompare(b.token.slug);
4882
+ });
4883
+ const topCandidates = candidates.slice(0, limit);
4884
+ const prereqIds = /* @__PURE__ */ new Set();
4885
+ let ancestors;
4886
+ if (opts.targetTokenId) {
4887
+ const prereqs = await getPrerequisites(db, opts.targetTokenId);
4888
+ for (const p of prereqs) {
4889
+ prereqIds.add(p.requires_id);
4890
+ }
4891
+ ancestors = await buildAncestorMap(db);
4892
+ }
4893
+ const results = [];
4894
+ for (const cand of topCandidates) {
4895
+ let alreadyPrerequisite = false;
4896
+ let wouldCreateCycleFlag = false;
4897
+ const bloomAboveTarget = cand.token.bloom_level > targetBloomLevel;
4898
+ if (opts.targetTokenId) {
4899
+ alreadyPrerequisite = prereqIds.has(cand.token.id);
4900
+ wouldCreateCycleFlag = await wouldCreateCycle(
4901
+ db,
4902
+ opts.targetTokenId,
4903
+ cand.token.id,
4904
+ ancestors
4905
+ );
4906
+ }
4907
+ results.push({
4908
+ token: cand.token,
4909
+ similarity: cand.similarity,
4910
+ alreadyPrerequisite,
4911
+ wouldCreateCycle: wouldCreateCycleFlag,
4912
+ bloomAboveTarget
4913
+ });
4914
+ }
4915
+ return results;
4916
+ }
4917
+
4853
4918
  // src/kernel/system/hooks.ts
4854
4919
  import {
4855
4920
  appendFileSync as appendFileSync3,
@@ -5874,6 +5939,7 @@ export {
5874
5939
  analyzeObservation,
5875
5940
  appendUiObservationReport,
5876
5941
  applySessionSynthesis,
5942
+ buildAncestorMap,
5877
5943
  buildReviewQueue,
5878
5944
  buildUiSynthesisCandidates,
5879
5945
  cascadeBlock,
@@ -6037,6 +6103,7 @@ export {
6037
6103
  setTursoCredentials,
6038
6104
  slugify,
6039
6105
  startSession,
6106
+ suggestFoundations,
6040
6107
  syncObserverSidecarPolicy,
6041
6108
  t,
6042
6109
  toSidecarPrivacyPolicy,