@osovv/vv-opencode 2.3.3 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +18 -13
  3. package/dist/cli.js +5 -3
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/doctor.d.ts +4 -0
  6. package/dist/commands/doctor.js +60 -51
  7. package/dist/commands/doctor.js.map +1 -1
  8. package/dist/commands/plugin-toggle.d.ts +0 -16
  9. package/dist/commands/plugin-toggle.js +2 -34
  10. package/dist/commands/plugin-toggle.js.map +1 -1
  11. package/dist/commands/preset.d.ts +0 -8
  12. package/dist/commands/preset.js +3 -24
  13. package/dist/commands/preset.js.map +1 -1
  14. package/dist/commands/role.js +2 -30
  15. package/dist/commands/role.js.map +1 -1
  16. package/dist/commands/session.d.ts +50 -0
  17. package/dist/commands/session.js +354 -0
  18. package/dist/commands/session.js.map +1 -0
  19. package/dist/lib/managed-agents.js +2 -2
  20. package/dist/lib/managed-agents.js.map +1 -1
  21. package/dist/lib/managed-skills.js +3 -3
  22. package/dist/lib/managed-skills.js.map +1 -1
  23. package/dist/lib/opencode/agent-registrations.js +103 -13
  24. package/dist/lib/opencode/agent-registrations.js.map +1 -1
  25. package/dist/lib/opencode/inspection.js +131 -5
  26. package/dist/lib/opencode/inspection.js.map +1 -1
  27. package/dist/plugins/analytics/index.js +8 -19
  28. package/dist/plugins/analytics/index.js.map +1 -1
  29. package/dist/plugins/guardian/index.js +7 -21
  30. package/dist/plugins/guardian/index.js.map +1 -1
  31. package/dist/plugins/hashline-edit/index.js +6 -20
  32. package/dist/plugins/hashline-edit/index.js.map +1 -1
  33. package/dist/plugins/model-roles/index.d.ts +3 -3
  34. package/dist/plugins/model-roles/index.js +8 -8
  35. package/dist/plugins/model-roles/index.js.map +1 -1
  36. package/dist/plugins/peak-hours/index.js +9 -20
  37. package/dist/plugins/peak-hours/index.js.map +1 -1
  38. package/dist/plugins/secrets-redaction/index.js +11 -24
  39. package/dist/plugins/secrets-redaction/index.js.map +1 -1
  40. package/dist/plugins/spec-guard/index.js +10 -22
  41. package/dist/plugins/spec-guard/index.js.map +1 -1
  42. package/dist/plugins/system-context-injection/guidance.d.ts +6 -0
  43. package/dist/plugins/system-context-injection/guidance.js +79 -0
  44. package/dist/plugins/system-context-injection/guidance.js.map +1 -0
  45. package/dist/plugins/system-context-injection/index.js +20 -121
  46. package/dist/plugins/system-context-injection/index.js.map +1 -1
  47. package/dist/plugins/tool-history-compaction/index.js +14 -25
  48. package/dist/plugins/tool-history-compaction/index.js.map +1 -1
  49. package/dist/plugins/web-tools/index.js +14 -25
  50. package/dist/plugins/web-tools/index.js.map +1 -1
  51. package/dist/plugins/workflow/index.d.ts +3 -2
  52. package/dist/plugins/workflow/index.js +6 -22
  53. package/dist/plugins/workflow/index.js.map +1 -1
  54. package/dist/plugins/workflow/input-validation.d.ts +1 -1
  55. package/dist/plugins/workflow/input-validation.js +2 -2
  56. package/dist/plugins/workflow/input-validation.js.map +1 -1
  57. package/dist/plugins/workflow/results.d.ts +40 -40
  58. package/dist/plugins/workflow/system-instruction.md +20 -0
  59. package/dist/runtime/auxiliary.d.ts +11 -6
  60. package/dist/runtime/auxiliary.js +43 -35
  61. package/dist/runtime/auxiliary.js.map +1 -1
  62. package/dist/runtime/context-inspection.d.ts +7 -6
  63. package/dist/runtime/context-inspection.js +37 -43
  64. package/dist/runtime/context-inspection.js.map +1 -1
  65. package/dist/runtime/context.d.ts +22 -45
  66. package/dist/runtime/context.js +348 -634
  67. package/dist/runtime/context.js.map +1 -1
  68. package/dist/runtime/model-registry.d.ts +3 -34
  69. package/dist/runtime/model-registry.js +10 -190
  70. package/dist/runtime/model-registry.js.map +1 -1
  71. package/dist/runtime/session-settings.d.ts +204 -0
  72. package/dist/runtime/session-settings.js +445 -0
  73. package/dist/runtime/session-settings.js.map +1 -0
  74. package/dist/runtime/snapshot-config.d.ts +7 -70
  75. package/dist/runtime/snapshot-config.js +16 -198
  76. package/dist/runtime/snapshot-config.js.map +1 -1
  77. package/dist/runtime/types.d.ts +15 -256
  78. package/dist/runtime/types.js +9 -63
  79. package/dist/runtime/types.js.map +1 -1
  80. package/dist/tui/settings/plugin.d.ts +29 -0
  81. package/dist/tui/settings/plugin.js +134 -0
  82. package/dist/tui/settings/plugin.js.map +1 -0
  83. package/dist/tui.js +12 -12
  84. package/dist/tui.js.map +1 -1
  85. package/package.json +1 -1
  86. package/schemas/vvoc/v3.json +1 -1
  87. package/templates/agents/vv-code-reviewer.md +2 -2
  88. package/templates/agents/vv-controller.md +176 -151
  89. package/templates/agents/vv-implementer.md +2 -2
  90. package/templates/agents/vv-reflector.md +7 -0
  91. package/templates/agents/vv-spec-reviewer.md +2 -2
  92. package/templates/skills/vv-execute/SKILL.md +25 -4
  93. package/templates/skills/vv-execute/references/tool-contracts.md +3 -3
  94. package/templates/skills/vv-reflect/SKILL.md +1 -0
  95. package/templates/skills/vv-reflect/references/session-graph.py +581 -7
  96. package/templates/skills/vv-review/SKILL.md +2 -2
  97. package/dist/lib/rebind-request.d.ts +0 -41
  98. package/dist/lib/rebind-request.js +0 -134
  99. package/dist/lib/rebind-request.js.map +0 -1
  100. package/dist/runtime/snapshot-store.d.ts +0 -63
  101. package/dist/runtime/snapshot-store.js +0 -668
  102. package/dist/runtime/snapshot-store.js.map +0 -1
  103. package/dist/runtime/snapshots.d.ts +0 -36
  104. package/dist/runtime/snapshots.js +0 -508
  105. package/dist/runtime/snapshots.js.map +0 -1
  106. package/dist/tui/rebind/plugin.d.ts +0 -22
  107. package/dist/tui/rebind/plugin.js +0 -101
  108. package/dist/tui/rebind/plugin.js.map +0 -1
@@ -0,0 +1,204 @@
1
+ import { type OrchestrationProfile } from "../lib/orchestration.js";
2
+ import type { VvocConfig } from "../lib/vvoc-config.js";
3
+ import type { NativeSessionView } from "./types.js";
4
+ /** Native session metadata key holding the family settings record. */
5
+ export declare const SESSION_SETTINGS_METADATA_KEY = "vvoc:settings";
6
+ /** Record schema version this module reads and writes. */
7
+ export declare const FAMILY_SETTINGS_VERSION: 1;
8
+ /** Bound on host-verified parent/fork lineage traversal. */
9
+ export declare const MAX_LINEAGE_HOPS = 64;
10
+ /**
11
+ * Host-internal primary agents whose sessions exist only to serve host
12
+ * housekeeping. Their context work never births or resolves family settings;
13
+ * they are never family members with their own behavior.
14
+ */
15
+ export declare const INTERNAL_PRIMARY_AGENTS: ReadonlySet<string>;
16
+ /** Narrow resolved settings record persisted on a family root session. */
17
+ export interface FamilySettings {
18
+ readonly version: typeof FAMILY_SETTINGS_VERSION;
19
+ /** Name of the preset explicitly applied to this family, when one was. */
20
+ readonly preset?: string | undefined;
21
+ /** Resolved role-id to canonical model-selection strings. */
22
+ readonly roles: Readonly<Record<string, string>>;
23
+ /** Resolved orchestration profile name. */
24
+ readonly profile: OrchestrationProfile;
25
+ /** Resolved plugin toggle booleans for the vvoc-managed plugin names. */
26
+ readonly plugins: Readonly<Record<string, boolean>>;
27
+ }
28
+ /** Whether a resolution came from root metadata or fell back to the live configuration. */
29
+ export type FamilySettingsSource = "metadata" | "config";
30
+ /** Consumer-facing resolution for one session's family. */
31
+ export interface FamilySettingsView {
32
+ /** Family root session id; also the metadata holder. */
33
+ readonly familyId: string;
34
+ /** Directory of the family root session. */
35
+ readonly locationDirectory: string | undefined;
36
+ /** Native model of the family root session, when known. */
37
+ readonly rootModel?: import("./types.js").ModelSelection | undefined;
38
+ /** The resolved narrow settings record. */
39
+ readonly settings: FamilySettings;
40
+ /** Family settings projected over the live effective configuration (credentials only from live). */
41
+ readonly vvoc: VvocConfig;
42
+ /** Concrete selections parsed from the settings roles. */
43
+ readonly roleModels: Readonly<Record<string, import("./types.js").ModelSelection>>;
44
+ /** Where the settings came from. */
45
+ readonly source: FamilySettingsSource;
46
+ /** Deterministic short content identity of the settings record. */
47
+ readonly settingsId: string;
48
+ }
49
+ /** Lineage could not be resolved safely, so no settings were resolved. */
50
+ export declare class SessionLineageError extends Error {
51
+ readonly code = "SESSION_LINEAGE_INVALID";
52
+ constructor(message: string);
53
+ }
54
+ /**
55
+ * Strictly decode an unknown metadata value into a settings record. Any shape
56
+ * mismatch, unknown version, or invalid profile yields undefined so callers can
57
+ * fail soft to the live configuration; the reason is returned for bounded
58
+ * diagnostics.
59
+ */
60
+ export declare function decodeFamilySettings(value: unknown): {
61
+ readonly settings: FamilySettings;
62
+ readonly error?: undefined;
63
+ } | {
64
+ readonly settings?: undefined;
65
+ readonly error: string;
66
+ };
67
+ /** Resolve the current effective configuration into a settings record. */
68
+ export declare function settingsFromConfig(config: VvocConfig): FamilySettings;
69
+ /** Deterministic short content identity of a settings record. */
70
+ export declare function settingsId(settings: FamilySettings): string;
71
+ /** Read and decode the settings record from one metadata map. */
72
+ export declare function readSettingsFromMetadata(metadata: Readonly<Record<string, unknown>> | undefined): {
73
+ readonly settings: FamilySettings;
74
+ } | {
75
+ readonly error: string;
76
+ } | undefined;
77
+ /**
78
+ * Copy a metadata map and set only the settings key, leaving every foreign key
79
+ * untouched. This is the merge half of every read-modify-write: callers read
80
+ * the host's full metadata map, merge through here, and write the result back
81
+ * because the native write replaces the whole map.
82
+ */
83
+ export declare function mergeSettingsIntoMetadata(metadata: Readonly<Record<string, unknown>> | undefined, settings: FamilySettings): Record<string, unknown>;
84
+ /**
85
+ * Project family settings over the live effective configuration for plugin
86
+ * consumers. The live document is deep-cloned and only the family-governed
87
+ * fields are overridden: roles, orchestration profile, and plugin toggle
88
+ * booleans. Detail inside object-valued plugin entries (schedules, modes,
89
+ * budgets) and every credential keep coming from the live configuration.
90
+ */
91
+ export declare function projectFamilyConfig(settings: FamilySettings, live: VvocConfig): VvocConfig;
92
+ /** Resolve a session's family root through host-verified lineage. */
93
+ export declare function resolveSessionFamily(input: {
94
+ readonly sessionID: string;
95
+ readSession(sessionID: string): Promise<NativeSessionView | undefined>;
96
+ }): Promise<string>;
97
+ /**
98
+ * True when a session view is a birthable family root: no parent, no fork
99
+ * source, and not a host-internal primary agent session.
100
+ */
101
+ export declare function isFamilyRootView(view: NativeSessionView): boolean;
102
+ /**
103
+ * Narrow settings resolution service consumed by native plugins. Resolution is
104
+ * fail-soft: a session whose lineage cannot be resolved yields undefined
105
+ * instead of failing the caller's request path.
106
+ */
107
+ export interface FamilySettingsService {
108
+ /** Family root session id for a session (host-verified lineage). */
109
+ familyOf(sessionID: string): Promise<string>;
110
+ /** Resolve settings for a session's family, birthing root records lazily. */
111
+ resolve(sessionID: string): Promise<FamilySettingsView | undefined>;
112
+ /** Consumer-facing alias of {@link resolve}. */
113
+ configFor(sessionID: string): Promise<FamilySettingsView | undefined>;
114
+ /** Release service-owned caches; never stops the host. */
115
+ dispose(): void;
116
+ }
117
+ /**
118
+ * Structural client seam for out-of-process settings changes (CLI and TUI).
119
+ * The real authenticated `OpenCodeClient` satisfies it; results are decoded at
120
+ * the checked boundary because the generated parameter types are not faithful
121
+ * wire shapes.
122
+ */
123
+ export interface SessionSettingsClient {
124
+ readonly session: {
125
+ get(input: {
126
+ readonly sessionID: string;
127
+ }): Promise<unknown>;
128
+ update(input: {
129
+ readonly sessionID: string;
130
+ readonly title?: string | undefined;
131
+ readonly metadata?: unknown;
132
+ }): Promise<unknown>;
133
+ };
134
+ }
135
+ /**
136
+ * Walk a session's lineage to its family root through the client seam. The
137
+ * walk mirrors the runtime resolver: parentID first, then fork source, with
138
+ * the same cycle and depth guards.
139
+ */
140
+ export declare function resolveFamilyRootViaClient(client: SessionSettingsClient, sessionID: string): Promise<NativeSessionView>;
141
+ /**
142
+ * Read-modify-write the settings key of one session's family root through the
143
+ * client seam. The full metadata map is re-read immediately before the write
144
+ * and merged through {@link mergeSettingsIntoMetadata}, so foreign keys survive
145
+ * and only the named family's root is touched. `apply` receives the root's
146
+ * current settings (or undefined) and returns the next record.
147
+ */
148
+ export declare function updateFamilySettingsViaClient(input: {
149
+ readonly client: SessionSettingsClient;
150
+ readonly sessionID: string;
151
+ apply(current: FamilySettings | undefined): FamilySettings | Promise<FamilySettings>;
152
+ }): Promise<{
153
+ readonly rootID: string;
154
+ readonly settings: FamilySettings;
155
+ }>;
156
+ /** One legacy family-binding pointer read from a bindings scope. */
157
+ export interface LegacyFamilyBinding {
158
+ readonly familyId: string;
159
+ readonly snapshotHash: string;
160
+ }
161
+ /**
162
+ * Injectable reader over the legacy bindings and content-addressed snapshot
163
+ * directories. The default implementation reads the project-scoped directories
164
+ * under the global vvoc data dir.
165
+ */
166
+ export interface LegacyBindingsReader {
167
+ listFamilies(): Promise<readonly LegacyFamilyBinding[]>;
168
+ /** Decoded legacy behaviour-projection snapshot, or undefined when unreadable. */
169
+ readSnapshot(hash: string): Promise<unknown>;
170
+ }
171
+ /** Bounded migration summary for one scope. */
172
+ export interface MigrationOutcome {
173
+ /** Families whose settings were written into live root metadata. */
174
+ readonly converted: readonly string[];
175
+ /** Families with nothing convertible (dead root, unreadable or invalid snapshot). */
176
+ readonly skipped: readonly string[];
177
+ /** Families whose metadata write failed; legacy directories are kept for retry. */
178
+ readonly failed: readonly string[];
179
+ /** Whether the legacy directories were removed after a fully successful pass. */
180
+ readonly pruned: boolean;
181
+ }
182
+ /**
183
+ * Convert legacy family bindings into root metadata and prune the legacy
184
+ * directories only after every convertible family was written. Dead roots and
185
+ * unreadable legacy snapshots are skipped (there is nothing to convert), while
186
+ * a metadata write failure keeps the directories so the next start retries.
187
+ * The conversion is idempotent: rewriting the same resolved settings is a
188
+ * no-op, and a completed pass leaves no directories to migrate again.
189
+ */
190
+ export declare function migrateFamilyBindings(deps: {
191
+ readonly reader: LegacyBindingsReader;
192
+ readSession(sessionID: string): Promise<NativeSessionView | undefined>;
193
+ /** Read-modify-write the settings key into the root's metadata. */
194
+ writeSettings(sessionID: string, settings: FamilySettings): Promise<void>;
195
+ }): Promise<MigrationOutcome>;
196
+ /** Default file-backed legacy reader plus its directory pruning. */
197
+ export declare function fileLegacyBindingsReader(paths: {
198
+ readonly bindingsDir?: string | undefined;
199
+ readonly snapshotsDir?: string | undefined;
200
+ readonly rebindDir?: string | undefined;
201
+ readonly scopeKey: string;
202
+ }): LegacyBindingsReader & {
203
+ prune(): Promise<void>;
204
+ };
@@ -0,0 +1,445 @@
1
+ // FILE: src/runtime/session-settings.ts
2
+ // VERSION: 1.0.0
3
+ // START_MODULE_CONTRACT
4
+ // PURPOSE: Own the session-owned family settings record stored in native session metadata: the narrow resolved record format, strict decode, birth from the effective configuration, family-root lineage resolution, read-modify-write metadata merging, the projected consumer view with live credentials, and the one-shot legacy-binding migration.
5
+ // SCOPE: Pure record/projection/lineage helpers plus the file-backed legacy bindings reader and migration converter. Family settings are resolved values only (roles, orchestration profile, plugin toggle booleans, optional preset name) and never carry credential values. No host session access of its own: callers supply session reads and metadata writes, so this module never talks to the host client and never persists anything except through injected write callbacks.
6
+ // DEPENDS: [node:crypto, node:fs/promises, node:path, src/lib/orchestration.ts, src/lib/plugin-toggle-config.ts, src/lib/vvoc-config.ts, src/lib/vvoc-paths.ts, src/runtime/types.ts]
7
+ // LINKS: [M-NATIVE-RUNTIME, V-M-NATIVE-RUNTIME]
8
+ // ROLE: RUNTIME
9
+ // MAP_MODE: EXPORTS
10
+ // END_MODULE_CONTRACT
11
+ //
12
+ // START_MODULE_MAP
13
+ // SESSION_SETTINGS_METADATA_KEY - Native session metadata key holding the family settings record.
14
+ // FAMILY_SETTINGS_VERSION - Record schema version this module reads and writes.
15
+ // MAX_LINEAGE_HOPS - Bound on host-verified parent/fork lineage traversal.
16
+ // INTERNAL_PRIMARY_AGENTS - Host-internal primary agents whose work never births family settings.
17
+ // FamilySettings - Narrow resolved settings record persisted on a family root.
18
+ // FamilySettingsView - Consumer-facing resolution: settings plus projected config and role models.
19
+ // FamilySettingsSource - Whether a resolution came from root metadata or the live configuration.
20
+ // SessionLineageError - Lineage could not be resolved safely, so no settings were resolved.
21
+ // decodeFamilySettings - Strictly decode an unknown metadata value into a settings record.
22
+ // settingsFromConfig - Resolve the current effective configuration into a settings record.
23
+ // projectFamilyConfig - Project settings over the live configuration for consumers.
24
+ // settingsId - Deterministic short content identity of a settings record.
25
+ // readSettingsFromMetadata - Read and decode the settings record from one metadata map.
26
+ // mergeSettingsIntoMetadata - Copy a metadata map and set only the settings key (RMW merge).
27
+ // resolveSessionFamily - Resolve a session's family root through host-verified lineage.
28
+ // isFamilyRootView - True when a session view is a birthable family root.
29
+ // FamilySettingsService - Narrow settings resolution service consumed by native plugins.
30
+ // SessionSettingsClient - Structural client seam for out-of-process settings changes.
31
+ // resolveFamilyRootViaClient - Walk a session's lineage to its family root through the client seam.
32
+ // updateFamilySettingsViaClient - Read-modify-write the settings key of one family root through the client seam.
33
+ // LegacyFamilyBinding - One legacy family-binding pointer read from the bindings scope.
34
+ // LegacyBindingsReader - Injectable reader over the legacy bindings and snapshot directories.
35
+ // MigrationOutcome - Bounded migration summary for one scope.
36
+ // migrateFamilyBindings - Convert legacy family bindings into root metadata, then prune legacy directories on full success.
37
+ // fileLegacyBindingsReader - Default file-backed legacy reader plus its directory pruning.
38
+ // END_MODULE_MAP
39
+ //
40
+ // START_CHANGE_SUMMARY
41
+ // LAST_CHANGE: [C-SESSION-OWNED-SETTINGS T-001 - Added the session-owned family settings record, lineage resolver, RMW metadata merge, projected consumer view, and the one-shot legacy-binding migration.]
42
+ // END_CHANGE_SUMMARY
43
+ import { createHash } from "node:crypto";
44
+ import { readdir, readFile, rm } from "node:fs/promises";
45
+ import { join } from "node:path";
46
+ import { createOrchestrationConfig, parseOrchestrationProfile, } from "../lib/orchestration.js";
47
+ import { isPluginEnabled, PLUGIN_TOGGLE_NAMES } from "../lib/plugin-toggle-config.js";
48
+ import { getGlobalVvocDataDir } from "../lib/vvoc-paths.js";
49
+ /** Native session metadata key holding the family settings record. */
50
+ export const SESSION_SETTINGS_METADATA_KEY = "vvoc:settings";
51
+ /** Record schema version this module reads and writes. */
52
+ export const FAMILY_SETTINGS_VERSION = 1;
53
+ /** Bound on host-verified parent/fork lineage traversal. */
54
+ export const MAX_LINEAGE_HOPS = 64;
55
+ /**
56
+ * Host-internal primary agents whose sessions exist only to serve host
57
+ * housekeeping. Their context work never births or resolves family settings;
58
+ * they are never family members with their own behavior.
59
+ */
60
+ export const INTERNAL_PRIMARY_AGENTS = new Set([
61
+ "title",
62
+ "summary",
63
+ "compaction",
64
+ ]);
65
+ /** Lineage could not be resolved safely, so no settings were resolved. */
66
+ export class SessionLineageError extends Error {
67
+ code = "SESSION_LINEAGE_INVALID";
68
+ constructor(message) {
69
+ super(message);
70
+ this.name = "SessionLineageError";
71
+ }
72
+ }
73
+ // START_BLOCK_RECORD_CODEC
74
+ function isRecord(value) {
75
+ return typeof value === "object" && value !== null && !Array.isArray(value);
76
+ }
77
+ function isRoleMap(value) {
78
+ if (!isRecord(value))
79
+ return false;
80
+ for (const [key, entry] of Object.entries(value)) {
81
+ if (key.length === 0 || typeof entry !== "string" || entry.trim().length === 0)
82
+ return false;
83
+ }
84
+ return true;
85
+ }
86
+ function isToggleMap(value) {
87
+ if (!isRecord(value))
88
+ return false;
89
+ for (const [key, entry] of Object.entries(value)) {
90
+ if (key.length === 0 || typeof entry !== "boolean")
91
+ return false;
92
+ }
93
+ return true;
94
+ }
95
+ /**
96
+ * Strictly decode an unknown metadata value into a settings record. Any shape
97
+ * mismatch, unknown version, or invalid profile yields undefined so callers can
98
+ * fail soft to the live configuration; the reason is returned for bounded
99
+ * diagnostics.
100
+ */
101
+ export function decodeFamilySettings(value) {
102
+ if (!isRecord(value))
103
+ return { error: "settings record is not an object" };
104
+ if (value.version !== FAMILY_SETTINGS_VERSION) {
105
+ return { error: `unsupported settings version ${String(value.version)}` };
106
+ }
107
+ if (!isRoleMap(value.roles))
108
+ return { error: "roles are not a nonempty-string map" };
109
+ if (!isToggleMap(value.plugins))
110
+ return { error: "plugins are not a boolean map" };
111
+ let profile;
112
+ try {
113
+ profile = parseOrchestrationProfile(value.profile, "decode family settings");
114
+ }
115
+ catch {
116
+ return { error: `unknown orchestration profile ${String(value.profile)}` };
117
+ }
118
+ const preset = value.preset;
119
+ if (preset !== undefined && (typeof preset !== "string" || preset.trim().length === 0)) {
120
+ return { error: "preset is present but not a nonempty string" };
121
+ }
122
+ return {
123
+ settings: {
124
+ version: FAMILY_SETTINGS_VERSION,
125
+ roles: { ...value.roles },
126
+ profile,
127
+ plugins: { ...value.plugins },
128
+ ...(preset === undefined ? {} : { preset: preset.trim() }),
129
+ },
130
+ };
131
+ }
132
+ /** Resolve the current effective configuration into a settings record. */
133
+ export function settingsFromConfig(config) {
134
+ return {
135
+ version: FAMILY_SETTINGS_VERSION,
136
+ roles: { ...config.roles },
137
+ profile: createOrchestrationConfig(config.orchestration).profile,
138
+ plugins: Object.fromEntries(PLUGIN_TOGGLE_NAMES.map((name) => [name, isPluginEnabled(config, name)])),
139
+ };
140
+ }
141
+ function sortJson(value) {
142
+ if (Array.isArray(value))
143
+ return value.map(sortJson);
144
+ if (value === null || typeof value !== "object")
145
+ return value;
146
+ const record = value;
147
+ const sorted = {};
148
+ for (const key of Object.keys(record).sort())
149
+ sorted[key] = sortJson(record[key]);
150
+ return sorted;
151
+ }
152
+ /** Deterministic short content identity of a settings record. */
153
+ export function settingsId(settings) {
154
+ return createHash("sha256")
155
+ .update(JSON.stringify(sortJson(settings)))
156
+ .digest("hex")
157
+ .slice(0, 16);
158
+ }
159
+ /** Read and decode the settings record from one metadata map. */
160
+ export function readSettingsFromMetadata(metadata) {
161
+ if (metadata === undefined)
162
+ return undefined;
163
+ const raw = metadata[SESSION_SETTINGS_METADATA_KEY];
164
+ if (raw === undefined)
165
+ return undefined;
166
+ const decoded = decodeFamilySettings(raw);
167
+ return decoded.error === undefined ? { settings: decoded.settings } : { error: decoded.error };
168
+ }
169
+ /**
170
+ * Copy a metadata map and set only the settings key, leaving every foreign key
171
+ * untouched. This is the merge half of every read-modify-write: callers read
172
+ * the host's full metadata map, merge through here, and write the result back
173
+ * because the native write replaces the whole map.
174
+ */
175
+ export function mergeSettingsIntoMetadata(metadata, settings) {
176
+ const merged = { ...metadata };
177
+ merged[SESSION_SETTINGS_METADATA_KEY] = settings;
178
+ return merged;
179
+ }
180
+ // END_BLOCK_RECORD_CODEC
181
+ // START_BLOCK_PROJECTION
182
+ function isPlainRecord(value) {
183
+ return typeof value === "object" && value !== null && !Array.isArray(value);
184
+ }
185
+ /**
186
+ * Project family settings over the live effective configuration for plugin
187
+ * consumers. The live document is deep-cloned and only the family-governed
188
+ * fields are overridden: roles, orchestration profile, and plugin toggle
189
+ * booleans. Detail inside object-valued plugin entries (schedules, modes,
190
+ * budgets) and every credential keep coming from the live configuration.
191
+ */
192
+ export function projectFamilyConfig(settings, live) {
193
+ const projected = structuredClone(live);
194
+ projected.roles = { ...settings.roles };
195
+ projected.orchestration = { profile: settings.profile };
196
+ const livePlugins = isPlainRecord(projected.plugins) ? { ...projected.plugins } : {};
197
+ for (const [name, enabled] of Object.entries(settings.plugins)) {
198
+ const liveEntry = livePlugins[name];
199
+ if (enabled === false) {
200
+ livePlugins[name] = false;
201
+ continue;
202
+ }
203
+ // Resolved enabled wins over a later live disable while preserving live detail.
204
+ if (liveEntry === undefined || typeof liveEntry === "boolean") {
205
+ livePlugins[name] = true;
206
+ }
207
+ else if (isPlainRecord(liveEntry)) {
208
+ livePlugins[name] = { ...liveEntry, enabled: true };
209
+ }
210
+ }
211
+ projected.plugins = livePlugins;
212
+ return projected;
213
+ }
214
+ // END_BLOCK_PROJECTION
215
+ // START_BLOCK_LINEAGE_RESOLUTION
216
+ /** Resolve a session's family root through host-verified lineage. */
217
+ export async function resolveSessionFamily(input) {
218
+ const seen = new Set();
219
+ let current = input.sessionID;
220
+ for (let hop = 0; hop < MAX_LINEAGE_HOPS; hop += 1) {
221
+ if (seen.has(current)) {
222
+ throw new SessionLineageError("Session lineage contains a cycle; refusing to resolve.");
223
+ }
224
+ seen.add(current);
225
+ const view = await input.readSession(current);
226
+ if (view === undefined) {
227
+ throw new SessionLineageError(`Session ${current} could not be read from the host.`);
228
+ }
229
+ const parent = typeof view.parentID === "string" && view.parentID.length > 0
230
+ ? view.parentID
231
+ : typeof view.forkSessionID === "string" && view.forkSessionID.length > 0
232
+ ? view.forkSessionID
233
+ : undefined;
234
+ if (parent === undefined)
235
+ return current;
236
+ current = parent;
237
+ }
238
+ throw new SessionLineageError("Session lineage exceeds the supported depth.");
239
+ }
240
+ /**
241
+ * True when a session view is a birthable family root: no parent, no fork
242
+ * source, and not a host-internal primary agent session.
243
+ */
244
+ export function isFamilyRootView(view) {
245
+ const hasParent = (view.parentID !== undefined && view.parentID.length > 0) ||
246
+ (view.forkSessionID !== undefined && view.forkSessionID.length > 0);
247
+ if (hasParent)
248
+ return false;
249
+ return !(view.agent !== undefined && INTERNAL_PRIMARY_AGENTS.has(view.agent));
250
+ }
251
+ function decodeClientSession(value) {
252
+ if (!isRecord(value))
253
+ return undefined;
254
+ const data = isRecord(value.data) ? value.data : value;
255
+ const id = data.id;
256
+ if (typeof id !== "string" || id.length === 0)
257
+ return undefined;
258
+ const parentID = typeof data.parentID === "string" ? data.parentID : undefined;
259
+ const forkRaw = data.fork;
260
+ const forkSessionID = typeof data.forkSessionID === "string"
261
+ ? data.forkSessionID
262
+ : isRecord(forkRaw) && typeof forkRaw.sessionID === "string"
263
+ ? forkRaw.sessionID
264
+ : undefined;
265
+ const modelRaw = data.model;
266
+ const model = isRecord(modelRaw) && typeof modelRaw.id === "string" && typeof modelRaw.providerID === "string"
267
+ ? {
268
+ providerID: modelRaw.providerID,
269
+ modelID: modelRaw.id,
270
+ ...(typeof modelRaw.variant === "string" ? { variant: modelRaw.variant } : {}),
271
+ }
272
+ : undefined;
273
+ const agent = typeof data.agent === "string" ? data.agent : undefined;
274
+ const metadata = isRecord(data.metadata) ? data.metadata : undefined;
275
+ return {
276
+ id,
277
+ ...(parentID === undefined ? {} : { parentID }),
278
+ ...(forkSessionID === undefined ? {} : { forkSessionID }),
279
+ ...(agent === undefined ? {} : { agent }),
280
+ ...(metadata === undefined ? {} : { metadata }),
281
+ ...(model === undefined ? {} : { model }),
282
+ };
283
+ }
284
+ /**
285
+ * Walk a session's lineage to its family root through the client seam. The
286
+ * walk mirrors the runtime resolver: parentID first, then fork source, with
287
+ * the same cycle and depth guards.
288
+ */
289
+ export async function resolveFamilyRootViaClient(client, sessionID) {
290
+ const seen = new Set();
291
+ let current = sessionID;
292
+ let view;
293
+ for (let hop = 0; hop < MAX_LINEAGE_HOPS; hop += 1) {
294
+ if (seen.has(current)) {
295
+ throw new SessionLineageError("Session lineage contains a cycle; refusing to update.");
296
+ }
297
+ seen.add(current);
298
+ view = decodeClientSession(await client.session.get({ sessionID: current }));
299
+ if (view === undefined) {
300
+ throw new SessionLineageError(`Session ${current} could not be read from the host.`);
301
+ }
302
+ const parent = typeof view.parentID === "string" && view.parentID.length > 0
303
+ ? view.parentID
304
+ : typeof view.forkSessionID === "string" && view.forkSessionID.length > 0
305
+ ? view.forkSessionID
306
+ : undefined;
307
+ if (parent === undefined)
308
+ return view;
309
+ current = parent;
310
+ }
311
+ throw new SessionLineageError("Session lineage exceeds the supported depth.");
312
+ }
313
+ /**
314
+ * Read-modify-write the settings key of one session's family root through the
315
+ * client seam. The full metadata map is re-read immediately before the write
316
+ * and merged through {@link mergeSettingsIntoMetadata}, so foreign keys survive
317
+ * and only the named family's root is touched. `apply` receives the root's
318
+ * current settings (or undefined) and returns the next record.
319
+ */
320
+ export async function updateFamilySettingsViaClient(input) {
321
+ const root = await resolveFamilyRootViaClient(input.client, input.sessionID);
322
+ const current = readSettingsFromMetadata(root.metadata);
323
+ if (current !== undefined && "error" in current) {
324
+ throw new Error(`Family settings for ${root.id} are invalid: ${current.error}`);
325
+ }
326
+ const next = await input.apply(current === undefined ? undefined : current.settings);
327
+ const updated = decodeClientSession(await input.client.session.get({ sessionID: root.id }));
328
+ const metadata = mergeSettingsIntoMetadata(updated?.metadata, next);
329
+ await input.client.session.update({ sessionID: root.id, metadata });
330
+ return { rootID: root.id, settings: next };
331
+ }
332
+ function isPlainObject(value) {
333
+ return typeof value === "object" && value !== null && !Array.isArray(value);
334
+ }
335
+ /**
336
+ * Convert legacy family bindings into root metadata and prune the legacy
337
+ * directories only after every convertible family was written. Dead roots and
338
+ * unreadable legacy snapshots are skipped (there is nothing to convert), while
339
+ * a metadata write failure keeps the directories so the next start retries.
340
+ * The conversion is idempotent: rewriting the same resolved settings is a
341
+ * no-op, and a completed pass leaves no directories to migrate again.
342
+ */
343
+ export async function migrateFamilyBindings(deps) {
344
+ const converted = [];
345
+ const skipped = [];
346
+ const failed = [];
347
+ let families;
348
+ try {
349
+ families = await deps.reader.listFamilies();
350
+ }
351
+ catch {
352
+ // No legacy scope readable: migration is a no-op and nothing is pruned.
353
+ return { converted, skipped, failed, pruned: false };
354
+ }
355
+ for (const family of families) {
356
+ try {
357
+ let root;
358
+ try {
359
+ root = await deps.readSession(family.familyId);
360
+ }
361
+ catch {
362
+ // A host read failure means the family root is gone: nothing to convert.
363
+ root = undefined;
364
+ }
365
+ if (root === undefined || !isFamilyRootView(root)) {
366
+ skipped.push(family.familyId);
367
+ continue;
368
+ }
369
+ const snapshot = await deps.reader.readSnapshot(family.snapshotHash);
370
+ if (!isPlainObject(snapshot) || !isPlainObject(snapshot.policy)) {
371
+ skipped.push(family.familyId);
372
+ continue;
373
+ }
374
+ await deps.writeSettings(family.familyId, settingsFromConfig(snapshot.policy));
375
+ converted.push(family.familyId);
376
+ }
377
+ catch {
378
+ failed.push(family.familyId);
379
+ }
380
+ }
381
+ const pruned = failed.length === 0;
382
+ if (pruned)
383
+ await pruneLegacyDirs(deps.reader);
384
+ return { converted, skipped, failed, pruned };
385
+ }
386
+ /** Default file-backed legacy reader plus its directory pruning. */
387
+ export function fileLegacyBindingsReader(paths) {
388
+ const dataDir = getGlobalVvocDataDir();
389
+ // Scope hashing mirrors the legacy binding-store layout.
390
+ const scope = createHash("sha256").update(paths.scopeKey).digest("hex").slice(0, 32);
391
+ const bindingsDir = paths.bindingsDir ?? join(dataDir, "bindings", scope);
392
+ const snapshotsDir = paths.snapshotsDir ?? join(dataDir, "snapshots", scope);
393
+ const rebindDir = paths.rebindDir ?? join(dataDir, "rebind");
394
+ const reader = {
395
+ async listFamilies() {
396
+ let names;
397
+ try {
398
+ names = await readdir(join(bindingsDir, "families"));
399
+ }
400
+ catch {
401
+ return [];
402
+ }
403
+ const families = [];
404
+ for (const name of names) {
405
+ if (!name.endsWith(".json"))
406
+ continue;
407
+ try {
408
+ const value = JSON.parse(await readFile(join(bindingsDir, "families", name), "utf8"));
409
+ if (isPlainObject(value) &&
410
+ typeof value.familyId === "string" &&
411
+ typeof value.snapshotHash === "string") {
412
+ families.push({ familyId: value.familyId, snapshotHash: value.snapshotHash });
413
+ }
414
+ }
415
+ catch {
416
+ // Unreadable pointer: nothing to convert for it.
417
+ }
418
+ }
419
+ return families;
420
+ },
421
+ async readSnapshot(hash) {
422
+ // Legacy projections lived beside the pointers, inside the binding scope.
423
+ try {
424
+ return JSON.parse(await readFile(join(bindingsDir, "policies", `${hash}.json`), "utf8"));
425
+ }
426
+ catch {
427
+ return undefined;
428
+ }
429
+ },
430
+ async prune() {
431
+ await rm(bindingsDir, { recursive: true, force: true });
432
+ await rm(snapshotsDir, { recursive: true, force: true });
433
+ await rm(rebindDir, { recursive: true, force: true });
434
+ },
435
+ };
436
+ return reader;
437
+ }
438
+ async function pruneLegacyDirs(reader) {
439
+ const prunable = reader;
440
+ if (typeof prunable.prune !== "function")
441
+ return;
442
+ await prunable.prune();
443
+ }
444
+ // END_BLOCK_MIGRATION
445
+ //# sourceMappingURL=session-settings.js.map