runcloud 0.2.216 → 0.2.217
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/commands/goals.js +314 -0
- package/dist/goalReportOutbox.js +181 -0
- package/dist/goalStopReport.js +71 -0
- package/dist/goalSyncTypes.js +1 -0
- package/dist/index.js +2 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/runcloud-0.2.217.tgz +0 -0
- package/runcloud-0.2.216.tgz +0 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { ApiClient, friendlyApiError } from '../api.js';
|
|
6
|
+
import { loadCredentials, normalizeApiUrl } from '../config.js';
|
|
7
|
+
import { flushGoalReports, submitGoalReport } from '../goalReportOutbox.js';
|
|
8
|
+
import { deliverStoppedGoalReport, parseGoalReport } from '../goalStopReport.js';
|
|
9
|
+
import { GOAL_SYNC_API } from '../goalSyncTypes.js';
|
|
10
|
+
export function assertGoalEnvironment(apiUrl, environment) {
|
|
11
|
+
if (environment === undefined)
|
|
12
|
+
return;
|
|
13
|
+
if (environment !== 'dev' && environment !== 'prod')
|
|
14
|
+
throw new Error('--env must be dev or prod.');
|
|
15
|
+
const hostname = new URL(apiUrl).hostname;
|
|
16
|
+
const actual = hostname === 'api.newly.app' ? 'prod'
|
|
17
|
+
: hostname === 'api-dev.newly.app' || (hostname.startsWith('cp-api-dev-') && hostname.endsWith('.run.app')) ? 'dev' : undefined;
|
|
18
|
+
if (actual !== environment)
|
|
19
|
+
throw new Error(`--env ${environment} does not match the configured API ${apiUrl}. Sign in to that environment or set NEWLY_API_URL and NEWLY_API_TOKEN together.`);
|
|
20
|
+
}
|
|
21
|
+
export function goalSyncContext(options) {
|
|
22
|
+
let credentials;
|
|
23
|
+
if (options.sessionAuth) {
|
|
24
|
+
try {
|
|
25
|
+
credentials = JSON.parse(readFileSync(join(process.env.NEWLY_HOME ?? join(homedir(), '.newly'), 'dogfood-session'), 'utf8'));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new Error('No staff session. Run newly dogfood login, or set NEWLY_API_URL and NEWLY_API_TOKEN to an authenticated staff session.');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
credentials = loadCredentials();
|
|
33
|
+
}
|
|
34
|
+
if (!credentials?.apiUrl || !credentials.token)
|
|
35
|
+
throw new Error('Sign in with newly login, or provide NEWLY_API_URL and NEWLY_API_TOKEN.');
|
|
36
|
+
const apiUrl = normalizeApiUrl(credentials.apiUrl);
|
|
37
|
+
assertGoalEnvironment(apiUrl, options.env);
|
|
38
|
+
return { client: new ApiClient(apiUrl, credentials.token), apiUrl, account: reportAccount(credentials) };
|
|
39
|
+
}
|
|
40
|
+
export function reportAccount(credentials) {
|
|
41
|
+
return credentials.account ?? `token-sha256:${createHash('sha256').update(credentials.token).digest('hex').slice(0, 32)}`;
|
|
42
|
+
}
|
|
43
|
+
function objectOption(value, name) {
|
|
44
|
+
let result;
|
|
45
|
+
try {
|
|
46
|
+
result = typeof value === 'string' ? JSON.parse(value) : value;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw new Error(`${name} must be a JSON object.`);
|
|
50
|
+
}
|
|
51
|
+
if (!result || typeof result !== 'object' || Array.isArray(result))
|
|
52
|
+
throw new Error(`${name} must be a JSON object.`);
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
export function goalMetricWindow(value, now = new Date()) {
|
|
56
|
+
if (value === 'complete-7d') {
|
|
57
|
+
const to = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
|
58
|
+
return { from: new Date(to.getTime() - 7 * 86400_000).toISOString(), to: to.toISOString(), timeZone: 'UTC' };
|
|
59
|
+
}
|
|
60
|
+
const window = objectOption(value, '--window');
|
|
61
|
+
if (typeof window.snapshot === 'string' && Object.keys(window).length === 1 && window.snapshot.trim() && window.snapshot.length <= 100) {
|
|
62
|
+
return { snapshot: window.snapshot };
|
|
63
|
+
}
|
|
64
|
+
if (typeof window.from !== 'string' || typeof window.to !== 'string' || typeof window.timeZone !== 'string'
|
|
65
|
+
|| !Number.isFinite(Date.parse(window.from)) || !Number.isFinite(Date.parse(window.to)) || Date.parse(window.from) >= Date.parse(window.to)) {
|
|
66
|
+
throw new Error('--window needs {from,to,timeZone} with increasing ISO dates, or {snapshot} with an ISO date.');
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
new Intl.DateTimeFormat('en', { timeZone: window.timeZone });
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
throw new Error('--window has an invalid timeZone.');
|
|
73
|
+
}
|
|
74
|
+
return { from: new Date(window.from).toISOString(), to: new Date(window.to).toISOString(), timeZone: window.timeZone };
|
|
75
|
+
}
|
|
76
|
+
function output(value, options) {
|
|
77
|
+
if (options.json) {
|
|
78
|
+
console.log(JSON.stringify(value));
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const result = value;
|
|
82
|
+
if (Array.isArray(result.goals)) {
|
|
83
|
+
console.log(result.goals.map((goal) => `${goal.id}\t${goal.slug}\t${goal.state}\t${goal.title}`).join('\n') || 'No goals.');
|
|
84
|
+
}
|
|
85
|
+
else if (Array.isArray(result.metrics)) {
|
|
86
|
+
console.log(result.metrics.map((metric) => `${metric.id}\t${metric.unit}\t${metric.sampleable ? 'sampleable' : 'unavailable'}\t${metric.title}`).join('\n') || 'No matching metrics.');
|
|
87
|
+
}
|
|
88
|
+
else if (result.status === 'queued') {
|
|
89
|
+
console.log(`Report queued locally (${result.outboxId}). Run newly goals report flush to retry delivery.`);
|
|
90
|
+
}
|
|
91
|
+
else if (result.status === 'delivered') {
|
|
92
|
+
console.log(`Report delivered (${result.reportId}).`);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
console.log(JSON.stringify(value, null, 2));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const repeat = (value, previous) => [...previous, value];
|
|
99
|
+
const segment = encodeURIComponent;
|
|
100
|
+
const pathFor = (goalId, suffix = '') => `${GOAL_SYNC_API}/goals/${segment(goalId)}${suffix}`;
|
|
101
|
+
async function findGoal(context, identifier) {
|
|
102
|
+
const view = await context.client.get(GOAL_SYNC_API);
|
|
103
|
+
const goal = view.goals.find((goal) => goal.id === identifier || goal.slug === identifier);
|
|
104
|
+
if (!goal)
|
|
105
|
+
throw new Error(`Goal not found: ${identifier}`);
|
|
106
|
+
return goal;
|
|
107
|
+
}
|
|
108
|
+
async function catalog(context) {
|
|
109
|
+
const result = await context.client.get(`${GOAL_SYNC_API}/metrics/catalog`);
|
|
110
|
+
return result.metrics;
|
|
111
|
+
}
|
|
112
|
+
function addOptions(command) {
|
|
113
|
+
return command.option('--env <environment>', 'assert dev or prod matches the configured credentials')
|
|
114
|
+
.option('--json', 'print machine-readable JSON')
|
|
115
|
+
.option('--session-auth', 'use the staff session saved by newly dogfood login');
|
|
116
|
+
}
|
|
117
|
+
export function registerGoals(program, dependencies = {}) {
|
|
118
|
+
const contextFor = dependencies.context ?? goalSyncContext;
|
|
119
|
+
const print = dependencies.output ?? output;
|
|
120
|
+
const run = (action) => async (...parameters) => {
|
|
121
|
+
const command = parameters.at(-1);
|
|
122
|
+
const options = command.optsWithGlobals();
|
|
123
|
+
try {
|
|
124
|
+
print(await action(contextFor(options), options, command.args), options);
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
const message = friendlyApiError(error);
|
|
128
|
+
console.error(options.json ? JSON.stringify({ ok: false, error: message }) : message);
|
|
129
|
+
process.exitCode = 1;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
const goals = addOptions(program.command('goals').description('Goal Sync goals, evidence, reports, and human decisions'));
|
|
133
|
+
goals.command('list').description('List goals').action(run(async (context) => {
|
|
134
|
+
const view = await context.client.get(GOAL_SYNC_API);
|
|
135
|
+
return { goals: view.goals };
|
|
136
|
+
}));
|
|
137
|
+
goals.command('show <goal>').description('Show a goal and its evidence (ID or slug)').action(run(async (context, _options, [identifier]) => {
|
|
138
|
+
const view = await context.client.get(GOAL_SYNC_API);
|
|
139
|
+
const goal = view.goals.find((goal) => goal.id === identifier || goal.slug === identifier);
|
|
140
|
+
if (!goal)
|
|
141
|
+
throw new Error(`Goal not found: ${identifier}`);
|
|
142
|
+
const belonging = (items) => items.filter((item) => item.goalId === goal.id);
|
|
143
|
+
return { goal, observations: belonging(view.observations), reports: belonging(view.reports), decisions: belonging(view.decisions) };
|
|
144
|
+
}));
|
|
145
|
+
goals.command('create <slug>').description('Create a draft goal; assign owners separately')
|
|
146
|
+
.requiredOption('--title <text>', 'goal title').option('--product <product>', 'newly, runcloud, or internal', 'newly')
|
|
147
|
+
.option('--kind <kind>', 'measured, exploratory, or qualitative', 'measured')
|
|
148
|
+
.requiredOption('--bet <text>', 'falsifiable bet').requiredOption('--proof-question <text>', 'what evidence will decide the bet')
|
|
149
|
+
.requiredOption('--next <text>', 'next concrete move')
|
|
150
|
+
.action(run(async (context, options, [slug]) => {
|
|
151
|
+
if (!['newly', 'runcloud', 'internal'].includes(String(options.product)))
|
|
152
|
+
throw new Error('Invalid --product.');
|
|
153
|
+
if (!['measured', 'exploratory', 'qualitative'].includes(String(options.kind)))
|
|
154
|
+
throw new Error('Invalid --kind.');
|
|
155
|
+
return context.client.post(`${GOAL_SYNC_API}/goals`, { slug, title: options.title, product: options.product,
|
|
156
|
+
kind: options.kind, bet: options.bet, proofQuestion: options.proofQuestion, nextMove: options.next });
|
|
157
|
+
}));
|
|
158
|
+
goals.command('assign <goal>').description('Add human owners to a goal')
|
|
159
|
+
.requiredOption('--owner <user-id>', 'authenticated human user ID; repeat for multiple owners', repeat, [])
|
|
160
|
+
.action(run(async (context, options, [identifier]) => {
|
|
161
|
+
const goal = await findGoal(context, identifier);
|
|
162
|
+
return context.client.post(pathFor(goal.id, '/owners'), { ownerIds: options.owner });
|
|
163
|
+
}));
|
|
164
|
+
goals.command('start <goal>').description('Activate a measured goal with explicit instrumentation certification')
|
|
165
|
+
.requiredOption('--certify-instrumentation', 'certify the attached measurement and baseline are usable')
|
|
166
|
+
.option('--revision <number>', 'expected revision (otherwise fetched immediately before patch)')
|
|
167
|
+
.action(run(async (context, options, [identifier]) => {
|
|
168
|
+
const goal = await findGoal(context, identifier);
|
|
169
|
+
if (goal.kind === 'exploratory')
|
|
170
|
+
throw new Error('Use decision propose --action start-exploration for an unquantified exploration.');
|
|
171
|
+
const revision = options.revision === undefined ? goal.revision : Number(options.revision);
|
|
172
|
+
if (!Number.isSafeInteger(revision) || revision < 1)
|
|
173
|
+
throw new Error('--revision must be a positive integer.');
|
|
174
|
+
return context.client.patch(pathFor(goal.id), { revision, state: 'active', certifyInstrumentation: true });
|
|
175
|
+
}));
|
|
176
|
+
goals.command('update <goal>').description('Update the current move, proof question, or owner-assessed state')
|
|
177
|
+
.option('--title <text>', 'updated title').option('--bet <text>', 'updated draft bet; active bets require a pivot decision')
|
|
178
|
+
.option('--proof-question <text>', 'updated inspectable proof question').option('--next <text>', 'updated next move')
|
|
179
|
+
.option('--state <state>', 'observing, held, or achieved; the server verifies linked evidence')
|
|
180
|
+
.option('--revision <number>', 'expected revision (otherwise fetched immediately before patch)')
|
|
181
|
+
.action(run(async (context, options, [identifier]) => {
|
|
182
|
+
if (options.state && !['observing', 'held', 'achieved'].includes(String(options.state)))
|
|
183
|
+
throw new Error('--state must be observing, held, or achieved. Use start or a team decision for other transitions.');
|
|
184
|
+
const fields = { ...(options.title ? { title: options.title } : {}), ...(options.bet ? { bet: options.bet } : {}),
|
|
185
|
+
...(options.proofQuestion ? { proofQuestion: options.proofQuestion } : {}), ...(options.next ? { nextMove: options.next } : {}),
|
|
186
|
+
...(options.state ? { state: options.state } : {}) };
|
|
187
|
+
if (!Object.keys(fields).length)
|
|
188
|
+
throw new Error('Provide at least one field to update.');
|
|
189
|
+
const goal = await findGoal(context, identifier);
|
|
190
|
+
const revision = options.revision === undefined ? goal.revision : Number(options.revision);
|
|
191
|
+
if (!Number.isSafeInteger(revision) || revision < 1)
|
|
192
|
+
throw new Error('--revision must be a positive integer.');
|
|
193
|
+
return context.client.patch(pathFor(goal.id), { revision, ...fields });
|
|
194
|
+
}));
|
|
195
|
+
const agent = goals.command('agent').description('Attach an agent session');
|
|
196
|
+
agent.command('attach <goal>').requiredOption('--session <id>', 'agent session ID').requiredOption('--task <text>', 'assigned task')
|
|
197
|
+
.action(run(async (context, options, [identifier]) => {
|
|
198
|
+
const goal = await findGoal(context, identifier);
|
|
199
|
+
return context.client.post(pathFor(goal.id, '/agents'), { sessionId: options.session, task: options.task });
|
|
200
|
+
}));
|
|
201
|
+
const metric = goals.command('metric').description('Attach and sample versioned admin instrumentation');
|
|
202
|
+
metric.command('add <goal>').requiredOption('--metric <enum>', 'catalog enum ID')
|
|
203
|
+
.option('--definition-version <number>', 'freeze catalog definition version (defaults to the current catalog)')
|
|
204
|
+
.option('--role <role>', 'primary, guardrail, or supporting', 'primary').option('--direction <direction>', 'up, down, or neutral', 'up')
|
|
205
|
+
.option('--source-options <json>', 'explicit options consumed by the existing admin source', '{}')
|
|
206
|
+
.option('--select <json>', 'explicit row/dimension selection', '{}')
|
|
207
|
+
.requiredOption('--window <json-or-period>', 'frozen {from,to,timeZone}, {snapshot}, or complete-7d (UTC)')
|
|
208
|
+
.option('--baseline-observation <id>', 'existing baseline observation ID').option('--target <number>', 'numeric target')
|
|
209
|
+
.option('--unit <unit>', 'expected source unit').action(run(async (context, options, [identifier]) => {
|
|
210
|
+
if (!['primary', 'guardrail', 'supporting'].includes(String(options.role)))
|
|
211
|
+
throw new Error('Invalid --role.');
|
|
212
|
+
if (!['up', 'down', 'neutral'].includes(String(options.direction)))
|
|
213
|
+
throw new Error('Invalid --direction.');
|
|
214
|
+
const select = objectOption(options.select, '--select');
|
|
215
|
+
const sourceOptions = objectOption(options.sourceOptions, '--source-options');
|
|
216
|
+
const window = goalMetricWindow(options.window);
|
|
217
|
+
const goal = await findGoal(context, identifier);
|
|
218
|
+
const definition = (await catalog(context)).find((metric) => metric.id === options.metric);
|
|
219
|
+
if (!definition)
|
|
220
|
+
throw new Error('Unknown metric enum. Use newly metrics list.');
|
|
221
|
+
const definitionVersion = options.definitionVersion === undefined ? definition.definitionVersion : Number(options.definitionVersion);
|
|
222
|
+
if (!Number.isSafeInteger(definitionVersion) || definitionVersion < 1)
|
|
223
|
+
throw new Error('Invalid --definition-version.');
|
|
224
|
+
const target = options.target === undefined ? undefined : Number(options.target);
|
|
225
|
+
if (target !== undefined && !Number.isFinite(target))
|
|
226
|
+
throw new Error('--target must be finite.');
|
|
227
|
+
return context.client.post(pathFor(goal.id, '/metrics'), { metric: definition.id, definitionVersion,
|
|
228
|
+
role: options.role, direction: options.direction, sourceOptions, select, window,
|
|
229
|
+
...(options.baselineObservation ? { baselineObservationId: options.baselineObservation } : {}),
|
|
230
|
+
...(target === undefined ? {} : { target }), ...(options.unit ? { expectedUnit: options.unit } : {}) });
|
|
231
|
+
}));
|
|
232
|
+
const sample = async (context, identifier, binding) => {
|
|
233
|
+
const goal = await findGoal(context, identifier);
|
|
234
|
+
return context.client.post(pathFor(goal.id, `/metrics/${segment(binding)}/observe`), {});
|
|
235
|
+
};
|
|
236
|
+
metric.command('sample <goal> <binding>').action(run((context, _options, [goal, binding]) => sample(context, goal, binding)));
|
|
237
|
+
const report = goals.command('report').description('Submit and reliably deliver agent reports');
|
|
238
|
+
report.command('submit <goal-id>').description('Submit a report using the immutable DB goal ID (works offline)')
|
|
239
|
+
.option('--file <path>', 'report JSON file; - reads stdin').option('--session <id>', 'agent session ID')
|
|
240
|
+
.option('--turn <id>', 'stable agent turn ID').option('--phase <text>', 'agent phase', 'work')
|
|
241
|
+
.option('--outcome <outcome>', 'progressed, no-change, waiting-evidence, blocked, failed, stopped-without-report')
|
|
242
|
+
.option('--summary <text>', 'factual work summary').option('--evidence <ref>', 'proof URL or reference; repeat', repeat, [])
|
|
243
|
+
.option('--next <text>', 'next concrete move').option('--blocker <text>', 'specific blocker').option('--next-check <iso>', 'next evidence check timestamp')
|
|
244
|
+
.action(run(async (context, options, [goalId]) => {
|
|
245
|
+
const input = options.file ? JSON.parse(readFileSync(options.file === '-' ? 0 : String(options.file), 'utf8')) : {
|
|
246
|
+
sessionId: options.session, turnId: options.turn, phase: options.phase, outcome: options.outcome,
|
|
247
|
+
summary: options.summary, evidence: options.evidence, nextMove: options.next, blocker: options.blocker ?? null, nextCheckAt: options.nextCheck ?? null
|
|
248
|
+
};
|
|
249
|
+
return submitGoalReport(context, goalId, parseGoalReport(input));
|
|
250
|
+
}));
|
|
251
|
+
report.command('flush').description('Retry saved reports once, using their original API and account')
|
|
252
|
+
.action(run(async (context) => {
|
|
253
|
+
const result = await flushGoalReports(context);
|
|
254
|
+
if (result.rejected)
|
|
255
|
+
process.exitCode = 1;
|
|
256
|
+
return result;
|
|
257
|
+
}));
|
|
258
|
+
report.command('stopped <goal-id>').description('Opt-in runtime stop adapter; consumes metadata without starting an agent')
|
|
259
|
+
.option('--file <path>', 'runtime stop-event JSON; - reads stdin', '-').option('--session <id>', 'override missing session ID')
|
|
260
|
+
.option('--turn <id>', 'override missing stable turn ID')
|
|
261
|
+
.option('--report-file <path>', 'existing authored report JSON to deliver when this turn stops')
|
|
262
|
+
.action(run(async (context, options, [goalId]) => deliverStoppedGoalReport(context, goalId, JSON.parse(readFileSync(options.file === '-' ? 0 : String(options.file), 'utf8')), { sessionId: options.session, turnId: options.turn,
|
|
263
|
+
...(options.reportFile ? { report: JSON.parse(readFileSync(String(options.reportFile), 'utf8')) } : {}) })));
|
|
264
|
+
const decision = goals.command('decision').description('Propose changes and record authenticated human decisions');
|
|
265
|
+
decision.command('propose <goal>').requiredOption('--action <action>', 'start-exploration, pivot, stop, or reallocate')
|
|
266
|
+
.requiredOption('--reason <text>', 'evidence and reason for this decision').option('--bet <text>', 'proposed replacement bet')
|
|
267
|
+
.option('--next <text>', 'proposed next move').option('--owner <id>', 'proposed human owner; repeat', repeat, [])
|
|
268
|
+
.action(run(async (context, options, [identifier]) => {
|
|
269
|
+
if (!['start-exploration', 'pivot', 'stop', 'reallocate'].includes(String(options.action)))
|
|
270
|
+
throw new Error('Invalid decision --action.');
|
|
271
|
+
const goal = await findGoal(context, identifier);
|
|
272
|
+
return context.client.post(pathFor(goal.id, '/decisions'), { action: options.action, reason: options.reason,
|
|
273
|
+
proposal: { ...(options.bet ? { bet: options.bet } : {}), ...(options.next ? { nextMove: options.next } : {}),
|
|
274
|
+
...(options.owner.length ? { ownerIds: options.owner } : {}) } });
|
|
275
|
+
}));
|
|
276
|
+
decision.command('vote <decision>').requiredOption('--choice <yes-or-no>', 'yes or no; voter identity comes from authentication')
|
|
277
|
+
.action(run(async (context, options, [id]) => {
|
|
278
|
+
if (!['yes', 'no'].includes(String(options.choice)))
|
|
279
|
+
throw new Error('--choice must be yes or no.');
|
|
280
|
+
return context.client.post(`${GOAL_SYNC_API}/decisions/${segment(id)}/votes`, { choice: options.choice });
|
|
281
|
+
}));
|
|
282
|
+
decision.command('veto <decision>').description('Record the authenticated CEO veto')
|
|
283
|
+
.requiredOption('--reason <text>', 'reason for the CEO veto')
|
|
284
|
+
.action(run((context, options, [id]) => context.client.post(`${GOAL_SYNC_API}/decisions/${segment(id)}/veto`, { reason: options.reason })));
|
|
285
|
+
decision.command('apply <decision>').description('Apply an approved proposal after the team decision and CEO veto check')
|
|
286
|
+
.action(run((context, _options, [id]) => context.client.post(`${GOAL_SYNC_API}/decisions/${segment(id)}/apply`, {})));
|
|
287
|
+
const policy = goals.command('policy').description('Inspect or configure the four-engineer electorate and CEO veto authority');
|
|
288
|
+
policy.command('show').action(run((context) => context.client.get(`${GOAL_SYNC_API}/policy`)));
|
|
289
|
+
policy.command('set').requiredOption('--engineer <user-id>', 'exactly four distinct authenticated human IDs; repeat', repeat, [])
|
|
290
|
+
.requiredOption('--ceo <user-id>', 'CEO user ID with veto authority; repeat if needed', repeat, [])
|
|
291
|
+
.action(run(async (context, options) => {
|
|
292
|
+
if (new Set(options.engineer).size !== 4 || options.engineer.length !== 4)
|
|
293
|
+
throw new Error('Policy requires exactly four distinct --engineer IDs.');
|
|
294
|
+
return context.client.put(`${GOAL_SYNC_API}/policy`, { engineerUserIds: options.engineer, ceoUserIds: options.ceo });
|
|
295
|
+
}));
|
|
296
|
+
const metrics = addOptions(program.command('metrics').description('Discover documented /admin Goal Sync instrumentation'));
|
|
297
|
+
metrics.command('list').option('--source <source>', 'instrumentation source (admin)', 'admin')
|
|
298
|
+
.option('--family <family>', 'filter catalog family').option('--search <text>', 'search enum, title, and definition')
|
|
299
|
+
.option('--sampleable', 'only metrics implemented by the measurement resolver')
|
|
300
|
+
.action(run(async (context, options) => {
|
|
301
|
+
if (options.source !== 'admin')
|
|
302
|
+
throw new Error('--source must be admin.');
|
|
303
|
+
return { metrics: (await catalog(context)).filter((metric) => (!options.family || metric.family === options.family) && (!options.sampleable || metric.sampleable)
|
|
304
|
+
&& (!options.search || `${metric.id} ${metric.title} ${metric.definition}`.toLowerCase().includes(String(options.search).toLowerCase()))) };
|
|
305
|
+
}));
|
|
306
|
+
metrics.command('describe <metric>').action(run(async (context, _options, [identifier]) => {
|
|
307
|
+
const metric = (await catalog(context)).find((metric) => metric.id === identifier || metric.member === identifier);
|
|
308
|
+
if (!metric)
|
|
309
|
+
throw new Error(`Metric not found: ${identifier}`);
|
|
310
|
+
return { metric };
|
|
311
|
+
}));
|
|
312
|
+
metrics.command('sample').requiredOption('--goal <goal>', 'goal ID or slug').requiredOption('--binding <id>', 'attached metric binding ID')
|
|
313
|
+
.action(run((context, options) => sample(context, String(options.goal), String(options.binding))));
|
|
314
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { closeSync, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { ApiError, ApiTransportError } from './api.js';
|
|
6
|
+
import { GOAL_SYNC_API } from './goalSyncTypes.js';
|
|
7
|
+
export function reportOutboxDirectory(context) {
|
|
8
|
+
return context.outboxDirectory ?? join(process.env.NEWLY_HOME ?? join(homedir(), '.newly'), 'goal-sync', 'report-outbox');
|
|
9
|
+
}
|
|
10
|
+
export function goalReportKey(apiUrl, goalId, sessionId, turnId) {
|
|
11
|
+
return createHash('sha256').update(JSON.stringify([apiUrl, goalId, sessionId, turnId])).digest('hex');
|
|
12
|
+
}
|
|
13
|
+
function readEntry(path) {
|
|
14
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
15
|
+
if (value.version !== 1 || !value.id || !value.apiUrl || !value.report?.sessionId || !value.report.turnId) {
|
|
16
|
+
throw new Error(`Invalid Goal Sync outbox entry: ${path}`);
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function writeEntry(path, entry) {
|
|
21
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
22
|
+
writeTemporary(temporary, entry);
|
|
23
|
+
renameSync(temporary, path);
|
|
24
|
+
}
|
|
25
|
+
function writeTemporary(path, entry) {
|
|
26
|
+
const fd = openSync(path, 'wx', 0o600);
|
|
27
|
+
try {
|
|
28
|
+
writeFileSync(fd, JSON.stringify(entry) + '\n');
|
|
29
|
+
fsyncSync(fd);
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
closeSync(fd);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function acquireLock(path) {
|
|
36
|
+
const lockPath = `${path}.lock`;
|
|
37
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
38
|
+
try {
|
|
39
|
+
const fd = openSync(lockPath, 'wx', 0o600);
|
|
40
|
+
writeFileSync(fd, String(process.pid));
|
|
41
|
+
closeSync(fd);
|
|
42
|
+
return () => { unlinkSync(lockPath); };
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error.code !== 'EEXIST')
|
|
46
|
+
throw error;
|
|
47
|
+
let pid;
|
|
48
|
+
try {
|
|
49
|
+
pid = Number(readFileSync(lockPath, 'utf8'));
|
|
50
|
+
}
|
|
51
|
+
catch (readError) {
|
|
52
|
+
if (readError.code === 'ENOENT')
|
|
53
|
+
continue;
|
|
54
|
+
throw readError;
|
|
55
|
+
}
|
|
56
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
57
|
+
return null;
|
|
58
|
+
try {
|
|
59
|
+
process.kill(pid, 0);
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
catch (processError) {
|
|
63
|
+
if (processError.code !== 'ESRCH')
|
|
64
|
+
return null;
|
|
65
|
+
try {
|
|
66
|
+
unlinkSync(lockPath);
|
|
67
|
+
}
|
|
68
|
+
catch (unlinkError) {
|
|
69
|
+
if (unlinkError.code !== 'ENOENT')
|
|
70
|
+
throw unlinkError;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
function isRetryable(error) {
|
|
78
|
+
if (error instanceof ApiTransportError)
|
|
79
|
+
return true;
|
|
80
|
+
if (error instanceof ApiError)
|
|
81
|
+
return error.status === 408 || error.status === 429 || error.status >= 500;
|
|
82
|
+
return error instanceof Error && ['AbortError', 'TimeoutError'].includes(error.name);
|
|
83
|
+
}
|
|
84
|
+
function delivery(entry) {
|
|
85
|
+
return { status: entry.status === 'delivered' ? 'delivered' : 'queued', outboxId: entry.id,
|
|
86
|
+
...(entry.reportId ? { reportId: entry.reportId } : {}) };
|
|
87
|
+
}
|
|
88
|
+
export function findGoalReport(context, goalId, sessionId, turnId) {
|
|
89
|
+
const key = goalReportKey(context.apiUrl, goalId, sessionId, turnId);
|
|
90
|
+
const path = join(reportOutboxDirectory(context), `${key}.json`);
|
|
91
|
+
return existsSync(path) ? readEntry(path) : null;
|
|
92
|
+
}
|
|
93
|
+
async function deliverEntry(context, path) {
|
|
94
|
+
const release = acquireLock(path);
|
|
95
|
+
if (!release)
|
|
96
|
+
return delivery(readEntry(path));
|
|
97
|
+
try {
|
|
98
|
+
const entry = readEntry(path);
|
|
99
|
+
if (entry.apiUrl !== context.apiUrl || entry.account !== (context.account ?? null)) {
|
|
100
|
+
throw new Error('Report is pinned to another API endpoint or account. Use its original credentials to flush it.');
|
|
101
|
+
}
|
|
102
|
+
if (entry.status === 'delivered')
|
|
103
|
+
return delivery(entry);
|
|
104
|
+
entry.attempts++;
|
|
105
|
+
entry.lastAttemptAt = new Date().toISOString();
|
|
106
|
+
entry.status = 'pending';
|
|
107
|
+
writeEntry(path, entry);
|
|
108
|
+
try {
|
|
109
|
+
const result = await context.client.post(`${GOAL_SYNC_API}/goals/${encodeURIComponent(entry.goalId)}/reports`, entry.report, { signal: AbortSignal.timeout(15_000) });
|
|
110
|
+
if (typeof result?.report?.id !== 'string' || !result.report.id)
|
|
111
|
+
throw new Error('Goal Sync returned no report receipt; the saved report remains pending.');
|
|
112
|
+
entry.status = 'delivered';
|
|
113
|
+
entry.reportId = result.report.id;
|
|
114
|
+
delete entry.errorStatus;
|
|
115
|
+
writeEntry(path, entry);
|
|
116
|
+
return delivery(entry);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (isRetryable(error) || (error instanceof Error && error.message.startsWith('Goal Sync returned no report receipt'))) {
|
|
120
|
+
writeEntry(path, entry);
|
|
121
|
+
return delivery(entry);
|
|
122
|
+
}
|
|
123
|
+
entry.status = 'rejected';
|
|
124
|
+
if (error instanceof ApiError)
|
|
125
|
+
entry.errorStatus = error.status;
|
|
126
|
+
writeEntry(path, entry);
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
release();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
export async function submitGoalReport(context, goalId, report) {
|
|
135
|
+
const directory = reportOutboxDirectory(context);
|
|
136
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
137
|
+
const id = goalReportKey(context.apiUrl, goalId, report.sessionId, report.turnId);
|
|
138
|
+
const path = join(directory, `${id}.json`);
|
|
139
|
+
const entry = { version: 1, id, apiUrl: context.apiUrl, account: context.account ?? null, goalId,
|
|
140
|
+
report, status: 'pending', attempts: 0, createdAt: new Date().toISOString() };
|
|
141
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
142
|
+
writeTemporary(temporary, entry);
|
|
143
|
+
try {
|
|
144
|
+
linkSync(temporary, path);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
if (error.code !== 'EEXIST')
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
unlinkSync(temporary);
|
|
152
|
+
}
|
|
153
|
+
const saved = readEntry(path);
|
|
154
|
+
if (JSON.stringify(saved.report) !== JSON.stringify(report)) {
|
|
155
|
+
throw new Error('A different report already exists for this goal/session/turn. Reports are immutable; use a new turn ID for a new report.');
|
|
156
|
+
}
|
|
157
|
+
return deliverEntry(context, path);
|
|
158
|
+
}
|
|
159
|
+
export async function flushGoalReports(context) {
|
|
160
|
+
const directory = reportOutboxDirectory(context);
|
|
161
|
+
const result = { delivered: 0, queued: 0, rejected: 0, skipped: 0 };
|
|
162
|
+
if (!existsSync(directory))
|
|
163
|
+
return result;
|
|
164
|
+
for (const name of readdirSync(directory).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).sort()) {
|
|
165
|
+
const path = join(directory, name);
|
|
166
|
+
const entry = readEntry(path);
|
|
167
|
+
if (entry.status === 'delivered')
|
|
168
|
+
continue;
|
|
169
|
+
if (entry.apiUrl !== context.apiUrl || entry.account !== (context.account ?? null)) {
|
|
170
|
+
result.skipped++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
result[(await deliverEntry(context, path)).status]++;
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
result.rejected++;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { closeSync, openSync, readSync, statSync } from 'node:fs';
|
|
2
|
+
import { findGoalReport, submitGoalReport } from './goalReportOutbox.js';
|
|
3
|
+
export function parseGoalReport(value) {
|
|
4
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
5
|
+
throw new Error('Report must be a JSON object.');
|
|
6
|
+
const input = value;
|
|
7
|
+
const text = (key) => {
|
|
8
|
+
if (typeof input[key] !== 'string' || !input[key].trim())
|
|
9
|
+
throw new Error(`Report ${key} must be a nonempty string.`);
|
|
10
|
+
return input[key];
|
|
11
|
+
};
|
|
12
|
+
const outcome = text('outcome');
|
|
13
|
+
if (!['progressed', 'no-change', 'waiting-evidence', 'blocked', 'failed', 'stopped-without-report'].includes(outcome)) {
|
|
14
|
+
throw new Error('Invalid report outcome.');
|
|
15
|
+
}
|
|
16
|
+
if (!Array.isArray(input.evidence) || !input.evidence.every((item) => typeof item === 'string'))
|
|
17
|
+
throw new Error('Report evidence must be a string array.');
|
|
18
|
+
for (const key of ['blocker', 'nextCheckAt']) {
|
|
19
|
+
if (input[key] !== null && typeof input[key] !== 'string' && input[key] !== undefined)
|
|
20
|
+
throw new Error(`Report ${key} must be a string or null.`);
|
|
21
|
+
}
|
|
22
|
+
if (input.nextCheckAt && !Number.isFinite(Date.parse(input.nextCheckAt)))
|
|
23
|
+
throw new Error('Report nextCheckAt must be an ISO timestamp.');
|
|
24
|
+
return { sessionId: text('sessionId'), turnId: text('turnId'), phase: text('phase'),
|
|
25
|
+
outcome: outcome, summary: text('summary'), evidence: input.evidence,
|
|
26
|
+
nextMove: text('nextMove'), blocker: input.blocker ?? null, nextCheckAt: input.nextCheckAt ?? null };
|
|
27
|
+
}
|
|
28
|
+
function lastAssistantTurn(path) {
|
|
29
|
+
const fd = openSync(path, 'r');
|
|
30
|
+
try {
|
|
31
|
+
const size = statSync(path).size;
|
|
32
|
+
const buffer = Buffer.alloc(Math.min(size, 4 * 1024 * 1024));
|
|
33
|
+
readSync(fd, buffer, 0, buffer.length, size - buffer.length);
|
|
34
|
+
for (const line of buffer.toString('utf8').split('\n').reverse()) {
|
|
35
|
+
try {
|
|
36
|
+
const value = JSON.parse(line);
|
|
37
|
+
if (value.type === 'assistant' || value.message?.role === 'assistant')
|
|
38
|
+
return value.turnId ?? value.message?.id;
|
|
39
|
+
}
|
|
40
|
+
catch { }
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
closeSync(fd);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function stoppedGoalReport(event, overrides = {}) {
|
|
49
|
+
if (!event || typeof event !== 'object' || Array.isArray(event))
|
|
50
|
+
throw new Error('Stop event must be a JSON object.');
|
|
51
|
+
const metadata = event;
|
|
52
|
+
const sessionId = overrides.sessionId ?? metadata.sessionId ?? metadata.session_id ?? metadata.threadId ?? metadata.thread_id;
|
|
53
|
+
let turnId = overrides.turnId ?? metadata.turnId ?? metadata.turn_id;
|
|
54
|
+
if (!turnId && typeof metadata.transcript_path === 'string')
|
|
55
|
+
turnId = lastAssistantTurn(metadata.transcript_path);
|
|
56
|
+
if (typeof sessionId !== 'string' || !sessionId || typeof turnId !== 'string' || !turnId) {
|
|
57
|
+
throw new Error('Stop event needs stable session and turn IDs. Pass --session and --turn when the runtime omits them.');
|
|
58
|
+
}
|
|
59
|
+
return { sessionId, turnId, phase: 'stopped', outcome: 'stopped-without-report',
|
|
60
|
+
summary: 'Agent stopped without a submitted Goal Sync report.', evidence: [],
|
|
61
|
+
nextMove: 'Inspect the agent session and submit evidence for the next turn.', blocker: null, nextCheckAt: null };
|
|
62
|
+
}
|
|
63
|
+
export async function deliverStoppedGoalReport(context, goalId, event, overrides = {}) {
|
|
64
|
+
const stopped = stoppedGoalReport(event, overrides);
|
|
65
|
+
const authored = overrides.report === undefined ? undefined : parseGoalReport(overrides.report);
|
|
66
|
+
if (authored && (authored.sessionId !== stopped.sessionId || authored.turnId !== stopped.turnId)) {
|
|
67
|
+
throw new Error('The authored report does not match the runtime session and turn. Refusing to attribute it to this stop event.');
|
|
68
|
+
}
|
|
69
|
+
const existing = findGoalReport(context, goalId, stopped.sessionId, stopped.turnId);
|
|
70
|
+
return submitGoalReport(context, goalId, authored ?? existing?.report ?? stopped);
|
|
71
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const GOAL_SYNC_API = '/admin/goal-sync';
|
package/dist/index.js
CHANGED
|
@@ -26,6 +26,7 @@ import { registerAppStore } from './commands/appStore.js';
|
|
|
26
26
|
import { registerUpdate } from './commands/update.js';
|
|
27
27
|
import { registerToken } from './commands/token.js';
|
|
28
28
|
import { registerDogfood } from './commands/dogfood.js';
|
|
29
|
+
import { registerGoals } from './commands/goals.js';
|
|
29
30
|
import { CLI_VERSION } from './version.js';
|
|
30
31
|
const program = new Command('newly')
|
|
31
32
|
.description('Develop, provision, and deploy Newly backends')
|
|
@@ -56,4 +57,5 @@ registerAppStore(program);
|
|
|
56
57
|
registerUpdate(program);
|
|
57
58
|
registerToken(program);
|
|
58
59
|
registerDogfood(program);
|
|
60
|
+
registerGoals(program);
|
|
59
61
|
await program.parseAsync(process.argv);
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = '0.2.
|
|
1
|
+
export const CLI_VERSION = '0.2.217';
|
package/package.json
CHANGED
|
Binary file
|
package/runcloud-0.2.216.tgz
DELETED
|
Binary file
|