@fractaal/pi-goal-x 0.20.1 → 0.28.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 (95) hide show
  1. package/README.md +38 -293
  2. package/dist/goal-auditor.d.ts +7 -61
  3. package/dist/goal-auditor.js +98 -300
  4. package/dist/goal-auditor.js.map +1 -1
  5. package/dist/goal-contract.d.ts +205 -0
  6. package/dist/goal-contract.js +135 -0
  7. package/dist/goal-contract.js.map +1 -0
  8. package/dist/goal-transcript-events.d.ts +54 -0
  9. package/dist/goal-transcript-events.js +177 -0
  10. package/dist/goal-transcript-events.js.map +1 -0
  11. package/dist/goal-widget.d.ts +13 -0
  12. package/dist/goal-widget.js +45 -0
  13. package/dist/goal-widget.js.map +1 -0
  14. package/dist/goal.d.ts +8 -49
  15. package/dist/goal.js +581 -3648
  16. package/dist/goal.js.map +1 -1
  17. package/dist/legacy-migration.d.ts +61 -0
  18. package/dist/legacy-migration.js +306 -0
  19. package/dist/legacy-migration.js.map +1 -0
  20. package/docs/architecture.md +14 -232
  21. package/extensions/goal-auditor.ts +108 -363
  22. package/extensions/goal-contract.ts +149 -0
  23. package/extensions/goal-transcript-events.ts +194 -0
  24. package/extensions/goal-widget.ts +50 -0
  25. package/extensions/goal.ts +602 -3920
  26. package/extensions/legacy-migration.ts +340 -0
  27. package/package.json +46 -21
  28. package/dist/goal-compaction.d.ts +0 -10
  29. package/dist/goal-compaction.js +0 -104
  30. package/dist/goal-compaction.js.map +0 -1
  31. package/dist/goal-core.d.ts +0 -19
  32. package/dist/goal-core.js +0 -66
  33. package/dist/goal-core.js.map +0 -1
  34. package/dist/goal-draft.d.ts +0 -71
  35. package/dist/goal-draft.js +0 -201
  36. package/dist/goal-draft.js.map +0 -1
  37. package/dist/goal-ledger.d.ts +0 -139
  38. package/dist/goal-ledger.js +0 -306
  39. package/dist/goal-ledger.js.map +0 -1
  40. package/dist/goal-policy.d.ts +0 -127
  41. package/dist/goal-policy.js +0 -359
  42. package/dist/goal-policy.js.map +0 -1
  43. package/dist/goal-pool.d.ts +0 -17
  44. package/dist/goal-pool.js +0 -85
  45. package/dist/goal-pool.js.map +0 -1
  46. package/dist/goal-questionnaire.d.ts +0 -56
  47. package/dist/goal-questionnaire.js +0 -733
  48. package/dist/goal-questionnaire.js.map +0 -1
  49. package/dist/goal-record.d.ts +0 -94
  50. package/dist/goal-record.js +0 -155
  51. package/dist/goal-record.js.map +0 -1
  52. package/dist/goal-settings.d.ts +0 -56
  53. package/dist/goal-settings.js +0 -184
  54. package/dist/goal-settings.js.map +0 -1
  55. package/dist/goal-tool-names.d.ts +0 -20
  56. package/dist/goal-tool-names.js +0 -69
  57. package/dist/goal-tool-names.js.map +0 -1
  58. package/dist/prompts/goal-prompts.d.ts +0 -17
  59. package/dist/prompts/goal-prompts.js +0 -304
  60. package/dist/prompts/goal-prompts.js.map +0 -1
  61. package/dist/storage/goal-files.d.ts +0 -40
  62. package/dist/storage/goal-files.js +0 -320
  63. package/dist/storage/goal-files.js.map +0 -1
  64. package/dist/widgets/goal-escape-dialog.d.ts +0 -15
  65. package/dist/widgets/goal-escape-dialog.js +0 -118
  66. package/dist/widgets/goal-escape-dialog.js.map +0 -1
  67. package/dist/widgets/goal-notifications.d.ts +0 -5
  68. package/dist/widgets/goal-notifications.js +0 -9
  69. package/dist/widgets/goal-notifications.js.map +0 -1
  70. package/dist/widgets/goal-widget.d.ts +0 -58
  71. package/dist/widgets/goal-widget.js +0 -282
  72. package/dist/widgets/goal-widget.js.map +0 -1
  73. package/dist/widgets/task-list-overlay.d.ts +0 -8
  74. package/dist/widgets/task-list-overlay.js +0 -321
  75. package/dist/widgets/task-list-overlay.js.map +0 -1
  76. package/docs/agent-flow-design.md +0 -432
  77. package/docs/agentic-runtime-prd.md +0 -764
  78. package/docs/goal-ts-refactor-test-strategy.md +0 -82
  79. package/docs/pi-autoresearch-survey.md +0 -45
  80. package/extensions/goal-compaction.ts +0 -133
  81. package/extensions/goal-core.ts +0 -77
  82. package/extensions/goal-draft.ts +0 -263
  83. package/extensions/goal-ledger.ts +0 -354
  84. package/extensions/goal-policy.ts +0 -389
  85. package/extensions/goal-pool.ts +0 -98
  86. package/extensions/goal-questionnaire.ts +0 -779
  87. package/extensions/goal-record.ts +0 -256
  88. package/extensions/goal-settings.ts +0 -181
  89. package/extensions/goal-tool-names.ts +0 -76
  90. package/extensions/prompts/goal-prompts.ts +0 -308
  91. package/extensions/storage/goal-files.ts +0 -352
  92. package/extensions/widgets/goal-escape-dialog.ts +0 -146
  93. package/extensions/widgets/goal-notifications.ts +0 -9
  94. package/extensions/widgets/goal-widget.ts +0 -378
  95. package/extensions/widgets/task-list-overlay.ts +0 -389
@@ -0,0 +1,149 @@
1
+ import { Type, type Static } from "typebox";
2
+
3
+ export const GOAL_SCHEMA_VERSION = 1 as const;
4
+ export const GOAL_STATE_ENTRY = "pi-goal-state-v1";
5
+ export const GOAL_RECEIPT_ENTRY = "pi-goal-receipt-v1";
6
+ export const GOAL_PROPOSAL_REVISION_ENTRY = "pi-goal-proposal-revision-v1";
7
+ export const GOAL_STATE_EVENT = "pi-goal:state";
8
+ export const GOAL_STATE_REQUEST_EVENT = "pi-goal:request-state";
9
+ export const GOAL_PROPOSAL_EVENT = "pi-goal:proposal";
10
+ export const GOAL_CONTINUATION_MESSAGE = "pi-goal-continuation-v1";
11
+ export const GOAL_ID_MAX_LENGTH = 256;
12
+ export const GOAL_OBJECTIVE_MAX_LENGTH = 128 * 1024;
13
+ export const GOAL_TIMESTAMP_MAX_LENGTH = 64;
14
+ export const GOAL_PAUSE_REASON_MAX_LENGTH = 2_048;
15
+ export const GOAL_PAUSE_SUGGESTED_ACTION_MAX_LENGTH = 2_048;
16
+ export const GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH = 12_000;
17
+ export const GOAL_COMPLETION_SUMMARY_MAX_LENGTH = 4_000;
18
+ export const GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH = 12_000;
19
+
20
+ export const GoalUsageSchema = Type.Object({
21
+ tokensUsed: Type.Number({ minimum: 0 }),
22
+ activeSeconds: Type.Number({ minimum: 0 }),
23
+ }, { additionalProperties: false });
24
+
25
+ export const GoalPauseSchema = Type.Object({
26
+ reason: Type.String({ minLength: 1, maxLength: GOAL_PAUSE_REASON_MAX_LENGTH }),
27
+ suggestedAction: Type.Optional(Type.String({ minLength: 1, maxLength: GOAL_PAUSE_SUGGESTED_ACTION_MAX_LENGTH })),
28
+ }, { additionalProperties: false });
29
+
30
+ export const GoalAuditRejectionSchema = Type.Object({
31
+ rejectedAt: Type.String({ minLength: 1, maxLength: GOAL_TIMESTAMP_MAX_LENGTH }),
32
+ report: Type.String({ minLength: 1, maxLength: GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH }),
33
+ }, { additionalProperties: false });
34
+
35
+ export const GoalCompletionSchema = Type.Object({
36
+ approvedAt: Type.String({ minLength: 1, maxLength: GOAL_TIMESTAMP_MAX_LENGTH }),
37
+ summary: Type.String({ minLength: 1, maxLength: GOAL_COMPLETION_SUMMARY_MAX_LENGTH }),
38
+ auditorReport: Type.String({ minLength: 1, maxLength: GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH }),
39
+ }, { additionalProperties: false });
40
+
41
+ const GoalCommonProperties = {
42
+ id: Type.String({ minLength: 1, maxLength: GOAL_ID_MAX_LENGTH }),
43
+ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH }),
44
+ usage: GoalUsageSchema,
45
+ createdAt: Type.String({ minLength: 1, maxLength: GOAL_TIMESTAMP_MAX_LENGTH }),
46
+ updatedAt: Type.String({ minLength: 1, maxLength: GOAL_TIMESTAMP_MAX_LENGTH }),
47
+ pause: Type.Optional(GoalPauseSchema),
48
+ lastAuditRejection: Type.Optional(GoalAuditRejectionSchema),
49
+ completion: Type.Optional(GoalCompletionSchema),
50
+ };
51
+
52
+ export const GoalSchema = Type.Union([
53
+ Type.Object({ ...GoalCommonProperties, status: Type.Literal("active"), autoContinue: Type.Literal(true) }, { additionalProperties: false }),
54
+ Type.Object({ ...GoalCommonProperties, status: Type.Literal("paused"), autoContinue: Type.Literal(false) }, { additionalProperties: false }),
55
+ Type.Object({ ...GoalCommonProperties, status: Type.Literal("complete"), autoContinue: Type.Literal(false) }, { additionalProperties: false }),
56
+ ]);
57
+
58
+ export const GoalStateSchema = Type.Object({
59
+ schemaVersion: Type.Literal(GOAL_SCHEMA_VERSION),
60
+ revision: Type.Integer({ minimum: 0 }),
61
+ goal: Type.Union([GoalSchema, Type.Null()]),
62
+ }, { additionalProperties: false });
63
+
64
+ export const GoalProposalSchema = Type.Object({
65
+ schemaVersion: Type.Literal(GOAL_SCHEMA_VERSION),
66
+ revision: Type.Integer({ minimum: 0 }),
67
+ proposal: Type.Union([
68
+ Type.Object({
69
+ kind: Type.Union([Type.Literal("create"), Type.Literal("tweak")]),
70
+ objective: Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH }),
71
+ currentObjective: Type.Optional(Type.String({ minLength: 1, maxLength: GOAL_OBJECTIVE_MAX_LENGTH })),
72
+ }, { additionalProperties: false }),
73
+ Type.Null(),
74
+ ]),
75
+ }, { additionalProperties: false });
76
+
77
+ export type GoalUsage = Static<typeof GoalUsageSchema>;
78
+ export type GoalPause = Static<typeof GoalPauseSchema>;
79
+ export type GoalAuditRejection = Static<typeof GoalAuditRejectionSchema>;
80
+ export type GoalCompletion = Static<typeof GoalCompletionSchema>;
81
+ export type Goal = Static<typeof GoalSchema>;
82
+ export type GoalState = Static<typeof GoalStateSchema>;
83
+ export type GoalProposal = Static<typeof GoalProposalSchema>;
84
+
85
+ function record(value: unknown): Record<string, unknown> | null {
86
+ return value !== null && typeof value === "object" && !Array.isArray(value)
87
+ ? value as Record<string, unknown>
88
+ : null;
89
+ }
90
+
91
+ function nonEmptyString(value: unknown, maxLength = Number.POSITIVE_INFINITY): value is string {
92
+ return typeof value === "string" && value.trim().length > 0 && value.length <= maxLength;
93
+ }
94
+
95
+ function hasOnlyKeys(raw: Record<string, unknown>, allowed: readonly string[]): boolean {
96
+ const keys = new Set(allowed);
97
+ return Object.keys(raw).every((key) => keys.has(key));
98
+ }
99
+
100
+ function validUsage(value: unknown): value is GoalUsage {
101
+ const raw = record(value);
102
+ return !!raw && hasOnlyKeys(raw, ["tokensUsed", "activeSeconds"])
103
+ && typeof raw.tokensUsed === "number" && Number.isFinite(raw.tokensUsed) && raw.tokensUsed >= 0
104
+ && typeof raw.activeSeconds === "number" && Number.isFinite(raw.activeSeconds) && raw.activeSeconds >= 0;
105
+ }
106
+
107
+ export function isGoal(value: unknown): value is Goal {
108
+ const raw = record(value);
109
+ if (!raw || !hasOnlyKeys(raw, ["id", "objective", "status", "autoContinue", "usage", "createdAt", "updatedAt", "pause", "lastAuditRejection", "completion"])) return false;
110
+ if (!nonEmptyString(raw.id, GOAL_ID_MAX_LENGTH) || !nonEmptyString(raw.objective, GOAL_OBJECTIVE_MAX_LENGTH)) return false;
111
+ if (raw.status !== "active" && raw.status !== "paused" && raw.status !== "complete") return false;
112
+ if (raw.autoContinue !== (raw.status === "active") || !validUsage(raw.usage)) return false;
113
+ if (!nonEmptyString(raw.createdAt, GOAL_TIMESTAMP_MAX_LENGTH) || !nonEmptyString(raw.updatedAt, GOAL_TIMESTAMP_MAX_LENGTH)) return false;
114
+ const pause = raw.pause === undefined ? null : record(raw.pause);
115
+ if (raw.pause !== undefined && (!pause || !hasOnlyKeys(pause, ["reason", "suggestedAction"]) || !nonEmptyString(pause.reason, GOAL_PAUSE_REASON_MAX_LENGTH) || (pause.suggestedAction !== undefined && !nonEmptyString(pause.suggestedAction, GOAL_PAUSE_SUGGESTED_ACTION_MAX_LENGTH)))) return false;
116
+ const rejection = raw.lastAuditRejection === undefined ? null : record(raw.lastAuditRejection);
117
+ if (raw.lastAuditRejection !== undefined && (!rejection || !hasOnlyKeys(rejection, ["rejectedAt", "report"]) || !nonEmptyString(rejection.rejectedAt, GOAL_TIMESTAMP_MAX_LENGTH) || !nonEmptyString(rejection.report, GOAL_AUDIT_REJECTION_REPORT_MAX_LENGTH))) return false;
118
+ const completion = raw.completion === undefined ? null : record(raw.completion);
119
+ if (raw.completion !== undefined && (!completion || !hasOnlyKeys(completion, ["approvedAt", "summary", "auditorReport"]) || !nonEmptyString(completion.approvedAt, GOAL_TIMESTAMP_MAX_LENGTH) || !nonEmptyString(completion.summary, GOAL_COMPLETION_SUMMARY_MAX_LENGTH) || !nonEmptyString(completion.auditorReport, GOAL_COMPLETION_AUDITOR_REPORT_MAX_LENGTH))) return false;
120
+ return true;
121
+ }
122
+
123
+ export function isGoalState(value: unknown): value is GoalState {
124
+ const raw = record(value);
125
+ return !!raw && hasOnlyKeys(raw, ["schemaVersion", "revision", "goal"])
126
+ && raw.schemaVersion === GOAL_SCHEMA_VERSION
127
+ && typeof raw.revision === "number" && Number.isSafeInteger(raw.revision) && raw.revision >= 0
128
+ && (raw.goal === null || isGoal(raw.goal));
129
+ }
130
+
131
+ export function parseGoalState(value: unknown): GoalState | null {
132
+ return isGoalState(value) ? structuredClone(value) : null;
133
+ }
134
+
135
+ export function isGoalProposal(value: unknown): value is GoalProposal {
136
+ const raw = record(value);
137
+ if (!raw || !hasOnlyKeys(raw, ["schemaVersion", "revision", "proposal"])) return false;
138
+ if (raw.schemaVersion !== GOAL_SCHEMA_VERSION || typeof raw.revision !== "number" || !Number.isSafeInteger(raw.revision) || raw.revision < 0) return false;
139
+ if (raw.proposal === null) return true;
140
+ const proposal = record(raw.proposal);
141
+ return !!proposal && hasOnlyKeys(proposal, ["kind", "objective", "currentObjective"])
142
+ && (proposal.kind === "create" || proposal.kind === "tweak")
143
+ && nonEmptyString(proposal.objective, GOAL_OBJECTIVE_MAX_LENGTH)
144
+ && (proposal.currentObjective === undefined || nonEmptyString(proposal.currentObjective, GOAL_OBJECTIVE_MAX_LENGTH));
145
+ }
146
+
147
+ export function parseGoalProposal(value: unknown): GoalProposal | null {
148
+ return isGoalProposal(value) ? structuredClone(value) : null;
149
+ }
@@ -0,0 +1,194 @@
1
+ import { Type, type Static } from "typebox";
2
+
3
+ export const GOAL_TRANSCRIPT_EVENT = "pi-goal:transcript-event";
4
+
5
+ export const GOAL_TRANSCRIPT_EVENT_KINDS = [
6
+ "goal_started",
7
+ "goal_updated",
8
+ "goal_paused",
9
+ "goal_resumed",
10
+ "goal_completion_rejected",
11
+ "goal_completed",
12
+ "goal_abandoned",
13
+ "goal_notice",
14
+ "goal_error",
15
+ ] as const;
16
+
17
+ export type GoalTranscriptEventKind = typeof GOAL_TRANSCRIPT_EVENT_KINDS[number];
18
+ export type GoalTranscriptEventLevel = "info" | "warning" | "error";
19
+
20
+ const FIELD_LIMITS = {
21
+ goalId: 160,
22
+ objective: 20_000,
23
+ changeSummary: 2_000,
24
+ reason: 2_000,
25
+ suggestedAction: 2_000,
26
+ completionSummary: 4_000,
27
+ auditorReport: 12_000,
28
+ message: 4_000,
29
+ tuiMessage: 4_000,
30
+ } as const;
31
+
32
+ const EventCommonProperties = {
33
+ version: Type.Literal(1),
34
+ emittedAt: Type.String({ minLength: 1, maxLength: 64 }),
35
+ level: Type.Union([Type.Literal("info"), Type.Literal("warning"), Type.Literal("error")]),
36
+ goalId: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.goalId })),
37
+ objective: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.objective })),
38
+ autoContinue: Type.Optional(Type.Boolean()),
39
+ changeSummary: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.changeSummary })),
40
+ reason: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.reason })),
41
+ suggestedAction: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.suggestedAction })),
42
+ completionSummary: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.completionSummary })),
43
+ auditorReport: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.auditorReport })),
44
+ tuiMessage: Type.String({ maxLength: FIELD_LIMITS.tuiMessage }),
45
+ };
46
+
47
+ export const GoalTranscriptEventSchema = Type.Union([
48
+ Type.Object({
49
+ ...EventCommonProperties,
50
+ kind: Type.Union([
51
+ Type.Literal("goal_started"),
52
+ Type.Literal("goal_updated"),
53
+ Type.Literal("goal_paused"),
54
+ Type.Literal("goal_resumed"),
55
+ Type.Literal("goal_completion_rejected"),
56
+ Type.Literal("goal_completed"),
57
+ Type.Literal("goal_abandoned"),
58
+ ]),
59
+ message: Type.Optional(Type.String({ maxLength: FIELD_LIMITS.message })),
60
+ }, { additionalProperties: false }),
61
+ Type.Object({
62
+ ...EventCommonProperties,
63
+ kind: Type.Union([Type.Literal("goal_notice"), Type.Literal("goal_error")]),
64
+ message: Type.String({ minLength: 1, maxLength: FIELD_LIMITS.message }),
65
+ }, { additionalProperties: false }),
66
+ ]);
67
+
68
+ export type GoalTranscriptEvent = Static<typeof GoalTranscriptEventSchema>;
69
+ type WithoutEventEnvelope<T> = T extends unknown ? Omit<T, "version" | "emittedAt"> : never;
70
+ export type GoalTranscriptEventInput = WithoutEventEnvelope<GoalTranscriptEvent>;
71
+
72
+ /**
73
+ * Keep a small deterministic margin below common 64 KiB transport boundaries.
74
+ * Enforce the producer contract in UTF-8 bytes rather than JavaScript string
75
+ * units so optional downstream adapters never need to guess or truncate.
76
+ */
77
+ export const GOAL_TRANSCRIPT_DATA_MAX_BYTES = 60 * 1024;
78
+
79
+ type SemanticTextField = Exclude<keyof typeof FIELD_LIMITS, "tuiMessage">;
80
+
81
+ // Event-specific human meaning wins before general context and audit detail.
82
+ // Later fields are deterministically truncated or omitted when the total
83
+ // serialized UTF-8 budget is exhausted.
84
+ const SEMANTIC_TEXT_PRIORITY: readonly SemanticTextField[] = [
85
+ "goalId",
86
+ "message",
87
+ "reason",
88
+ "completionSummary",
89
+ "changeSummary",
90
+ "suggestedAction",
91
+ "objective",
92
+ "auditorReport",
93
+ ];
94
+
95
+ const utf8Encoder = new TextEncoder();
96
+
97
+ function bounded(value: string | undefined, max: number): string | undefined {
98
+ if (value === undefined || value.length <= max) return value;
99
+ let end = max;
100
+ const last = value.charCodeAt(end - 1);
101
+ if (last >= 0xD800 && last <= 0xDBFF) end -= 1;
102
+ return value.slice(0, end);
103
+ }
104
+
105
+ function semanticDataBytes(event: GoalTranscriptEvent): number {
106
+ const { tuiMessage: _tuiMessage, ...goal } = event;
107
+ return utf8Encoder.encode(JSON.stringify({ goal })).byteLength;
108
+ }
109
+
110
+ const EVENT_KEYS = new Set([
111
+ "version", "kind", "emittedAt", "level", "goalId", "objective", "autoContinue",
112
+ "changeSummary", "reason", "suggestedAction", "completionSummary", "auditorReport", "message", "tuiMessage",
113
+ ]);
114
+ const EVENT_KINDS = new Set<string>(GOAL_TRANSCRIPT_EVENT_KINDS);
115
+
116
+ export function isGoalTranscriptEvent(value: unknown): value is GoalTranscriptEvent {
117
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
118
+ const event = value as Record<string, unknown>;
119
+ if (!Object.keys(event).every((key) => EVENT_KEYS.has(key))) return false;
120
+ if (event.version !== 1 || typeof event.kind !== "string" || !EVENT_KINDS.has(event.kind)) return false;
121
+ if (typeof event.emittedAt !== "string" || event.emittedAt.length === 0 || event.emittedAt.length > 64) return false;
122
+ if (event.level !== "info" && event.level !== "warning" && event.level !== "error") return false;
123
+ if (typeof event.tuiMessage !== "string" || event.tuiMessage.length > FIELD_LIMITS.tuiMessage) return false;
124
+ if (event.autoContinue !== undefined && typeof event.autoContinue !== "boolean") return false;
125
+ if ((event.kind === "goal_notice" || event.kind === "goal_error") && (typeof event.message !== "string" || event.message.trim().length === 0)) return false;
126
+ for (const field of SEMANTIC_TEXT_PRIORITY) {
127
+ const text = event[field];
128
+ if (text !== undefined && (typeof text !== "string" || text.length > FIELD_LIMITS[field])) return false;
129
+ }
130
+ return semanticDataBytes(event as GoalTranscriptEvent) <= GOAL_TRANSCRIPT_DATA_MAX_BYTES;
131
+ }
132
+
133
+ export function parseGoalTranscriptEvent(value: unknown): GoalTranscriptEvent | null {
134
+ return isGoalTranscriptEvent(value) ? structuredClone(value) : null;
135
+ }
136
+
137
+ function addTextWithinBudget(
138
+ event: GoalTranscriptEvent,
139
+ field: SemanticTextField,
140
+ value: string | undefined,
141
+ ): void {
142
+ const clamped = bounded(value, FIELD_LIMITS[field]);
143
+ if (clamped === undefined) return;
144
+
145
+ const full = { ...event, [field]: clamped };
146
+ if (semanticDataBytes(full) <= GOAL_TRANSCRIPT_DATA_MAX_BYTES) {
147
+ Object.assign(event, { [field]: clamped });
148
+ return;
149
+ }
150
+
151
+ let low = 0;
152
+ let high = clamped.length;
153
+ let best = "";
154
+ while (low <= high) {
155
+ const midpoint = Math.floor((low + high) / 2);
156
+ const candidate = bounded(clamped, midpoint) ?? "";
157
+ const next = { ...event, [field]: candidate };
158
+ if (semanticDataBytes(next) <= GOAL_TRANSCRIPT_DATA_MAX_BYTES) {
159
+ best = candidate;
160
+ low = midpoint + 1;
161
+ } else {
162
+ high = midpoint - 1;
163
+ }
164
+ }
165
+ if (best) Object.assign(event, { [field]: best });
166
+ }
167
+
168
+ /**
169
+ * Build the public Goal transcript contract at one bounded boundary. Internal
170
+ * state snapshots, ledgers, continuation checkpoints, and audit animation never
171
+ * pass through this function.
172
+ */
173
+ export function createGoalTranscriptEvent(
174
+ input: GoalTranscriptEventInput,
175
+ emittedAt = new Date().toISOString(),
176
+ ): GoalTranscriptEvent {
177
+ const requiredMessage = input.kind === "goal_notice" || input.kind === "goal_error" ? input.message.trim() : undefined;
178
+ if (requiredMessage === "") {
179
+ throw new Error(`${input.kind} requires a non-empty message.`);
180
+ }
181
+ const event = {
182
+ version: 1,
183
+ kind: input.kind,
184
+ emittedAt: bounded(emittedAt, 64) ?? "",
185
+ level: input.level,
186
+ tuiMessage: bounded(input.tuiMessage, FIELD_LIMITS.tuiMessage) ?? "",
187
+ } as GoalTranscriptEvent;
188
+ if (input.autoContinue !== undefined) event.autoContinue = input.autoContinue;
189
+ for (const field of SEMANTIC_TEXT_PRIORITY) {
190
+ const value = field === "message" && requiredMessage !== undefined ? requiredMessage : input[field] as string | undefined;
191
+ addTextWithinBudget(event, field, value);
192
+ }
193
+ return event;
194
+ }
@@ -0,0 +1,50 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import type { Component, TUI } from "@earendil-works/pi-tui";
3
+ import { truncateToWidth } from "@earendil-works/pi-tui";
4
+ import type { GoalState } from "./goal-contract.ts";
5
+
6
+ export class GoalWidget implements Component {
7
+ private readonly tui: TUI;
8
+ private readonly theme: Theme;
9
+ private readonly getState: () => GoalState;
10
+ private readonly isAuditing: () => boolean;
11
+
12
+ constructor(tui: TUI, theme: Theme, getState: () => GoalState, isAuditing: () => boolean) {
13
+ this.tui = tui;
14
+ this.theme = theme;
15
+ this.getState = getState;
16
+ this.isAuditing = isAuditing;
17
+ }
18
+
19
+ update(): void {
20
+ this.tui.requestRender();
21
+ }
22
+
23
+ render(width: number): string[] {
24
+ const goal = this.getState().goal;
25
+ if (!goal) return [];
26
+ const status = this.isAuditing()
27
+ ? { icon: "◌", label: "auditing", color: "warning" as const }
28
+ : goal.status === "complete"
29
+ ? { icon: "✓", label: "complete", color: "success" as const }
30
+ : goal.status === "paused"
31
+ ? { icon: "◐", label: "paused", color: "warning" as const }
32
+ : { icon: "●", label: "running", color: "accent" as const };
33
+ const lines = [
34
+ `${this.theme.fg(status.color, status.icon)} ${this.theme.fg(status.color, this.theme.bold("Goal"))} ${this.theme.fg("muted", status.label)}`,
35
+ `${this.theme.fg("dim", "└─")} ${this.theme.fg("text", goal.objective.replace(/\s+/g, " ").trim())}`,
36
+ ];
37
+ if (goal.pause) {
38
+ lines.push(`${this.theme.fg("warning", "blocker")} ${this.theme.fg("warning", goal.pause.reason)}`);
39
+ if (goal.pause.suggestedAction) lines.push(`${this.theme.fg("dim", "next")} ${this.theme.fg("muted", goal.pause.suggestedAction)}`);
40
+ }
41
+ if (goal.lastAuditRejection) {
42
+ lines.push(`${this.theme.fg("warning", "audit")} ${this.theme.fg("muted", goal.lastAuditRejection.report.replace(/\s+/g, " ").trim())}`);
43
+ }
44
+ return lines.map((line) => truncateToWidth(line, Math.max(1, width), "…"));
45
+ }
46
+
47
+ invalidate(): void {
48
+ this.update();
49
+ }
50
+ }