loopengine 0.3.65 → 0.3.67

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.
@@ -12,15 +12,50 @@
12
12
  //
13
13
  // A lever describes a mechanism, never a promised result: why it tends
14
14
  // to move the measure, and how to see whether it does.
15
- import { readFileSync, statSync } from 'node:fs';
15
+ //
16
+ // Focuses are data too: the playbook lists them (an id, a label people
17
+ // read, and a hint the planner reads), and its levers belong to them.
18
+ //
19
+ // Each workspace also has its own playbook, .loopengine/playbook-local.json:
20
+ // focuses and levers the goal planner wrote when nothing in the shared
21
+ // playbook fit (a goal about hiring, a lever the playbook lacks). Their
22
+ // ids carry "x-" (focus "x-hiring", lever "x-hiring.x-screen-applicants",
23
+ // or "new-signups.x-..." for a new lever under a shared focus), so they
24
+ // never clash with shared ones. They're used like shared ones, in this
25
+ // workspace only.
26
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
16
27
  import { join } from 'node:path';
28
+ /** The shared playbook's focuses, as bundled. */
17
29
  export const GOAL_FOCUSES = ['new-signups', 'activation', 'retention', 'faster-support', 'revenue-recovery', 'ops-hygiene'];
30
+ /** Whether an id is a workspace's own focus or lever (never shared as is). */
31
+ export const isLocalId = (id) => /(^|\.)x-/.test(id);
32
+ const FOCUS_ID = /^[a-z][a-z0-9-]{1,48}$/;
18
33
  const PLAYBOOK_FILE = new URL('./playbook.json', import.meta.url);
19
- /** Checks the playbook's shape, naming the lever at fault. */
20
- export function parsePlaybook(raw) {
34
+ function parseFocuses(raw, where) {
35
+ if (raw === undefined)
36
+ return [];
37
+ if (!Array.isArray(raw))
38
+ throw new Error(`${where}: "focuses" must be a list`);
39
+ return raw.map((item, i) => {
40
+ const f = (item ?? {});
41
+ const at = `${where} focus ${typeof f.id === 'string' ? f.id : `#${i + 1}`}`;
42
+ if (typeof f.id !== 'string' || !FOCUS_ID.test(f.id))
43
+ throw new Error(`${at}: id must be lowercase words with hyphens`);
44
+ if (typeof f.label !== 'string' || !f.label.trim())
45
+ throw new Error(`${at}: "label" must be non-empty text`);
46
+ if (typeof f.hint !== 'string' || !f.hint.trim())
47
+ throw new Error(`${at}: "hint" must be non-empty text`);
48
+ return { id: f.id, label: f.label.trim(), hint: f.hint.trim() };
49
+ });
50
+ }
51
+ /** Checks the playbook's shape, naming the lever at fault. A lever's
52
+ * focus must be one the playbook lists, or one of `knownFocuses`. */
53
+ export function parsePlaybook(raw, knownFocuses = GOAL_FOCUSES) {
21
54
  if (!raw || typeof raw !== 'object' || !Array.isArray(raw.levers))
22
55
  throw new Error('playbook.json: expected { "levers": [...] }');
23
56
  const version = typeof raw.version === 'number' ? raw.version : 0;
57
+ const focuses = parseFocuses(raw.focuses, 'playbook.json');
58
+ const allowed = new Set([...knownFocuses, ...focuses.map((f) => f.id)]);
24
59
  const seen = new Set();
25
60
  const levers = (raw.levers).map((item, i) => {
26
61
  const l = (item ?? {});
@@ -32,8 +67,8 @@ export function parsePlaybook(raw) {
32
67
  const num = (k) => { if (typeof l[k] !== 'number' || l[k] < 0)
33
68
  throw new Error(`${where}: "${k}" must be a number`); return l[k]; };
34
69
  const focus = text('focus');
35
- if (!GOAL_FOCUSES.includes(focus))
36
- throw new Error(`${where}: focus must be one of ${GOAL_FOCUSES.join(', ')}`);
70
+ if (!allowed.has(focus))
71
+ throw new Error(`${where}: focus must be one of ${[...allowed].join(', ')}`);
37
72
  const id = text('id');
38
73
  if (!id.startsWith(`${focus}.`))
39
74
  throw new Error(`${where}: its id must start with "${focus}."`);
@@ -55,12 +90,13 @@ export function parsePlaybook(raw) {
55
90
  guardrails: list('guardrails'), template: text('template'),
56
91
  };
57
92
  });
58
- return { version, levers };
93
+ return { version, focuses, levers };
59
94
  }
60
95
  const playbook = parsePlaybook(JSON.parse(readFileSync(PLAYBOOK_FILE, 'utf8')));
61
96
  /** The playbook bundled with this package. */
62
97
  export const PLAYBOOK_VERSION = playbook.version;
63
98
  export const LEVERS = playbook.levers;
99
+ export const FOCUSES = playbook.focuses;
64
100
  // ---- The playbook in use: the bundled one, merged with the latest one a
65
101
  // Cloud workspace fetched (core/playbook-sync.ts keeps it in the project,
66
102
  // .loopengine/playbook-cache.json). By lever id: a fetched lever replaces
@@ -82,31 +118,87 @@ export function mergePlaybooks(bundled, fetched) {
82
118
  byId.set(l.id, l);
83
119
  return [...byId.values()].filter((l) => !retired.has(l.id));
84
120
  }
85
- /** The levers in use, and the version they come from (the fetched one's
86
- * when there is one, else the bundled one's). */
121
+ const localFile = (dir) => join(dir, '.loopengine', 'playbook-local.json');
122
+ const mtime = (file) => {
123
+ try {
124
+ return String(statSync(file).mtimeMs);
125
+ }
126
+ catch {
127
+ return 'none';
128
+ }
129
+ };
130
+ /** The workspace's own focuses and levers (empty when there are none, or
131
+ * the file doesn't pass the checks). */
132
+ export function readLocalPlaybook(dir = cacheDir) {
133
+ if (!dir || !existsSync(localFile(dir)))
134
+ return { focuses: [], levers: [] };
135
+ try {
136
+ const raw = JSON.parse(readFileSync(localFile(dir), 'utf8'));
137
+ const parsed = parsePlaybook({ levers: raw.levers ?? [], focuses: raw.focuses ?? [] }, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
138
+ return { focuses: parsed.focuses.filter((f) => isLocalId(f.id)), levers: parsed.levers.filter((l) => isLocalId(l.id)) };
139
+ }
140
+ catch {
141
+ return { focuses: [], levers: [] };
142
+ }
143
+ }
144
+ /** Adds focuses and levers to the workspace's own playbook (by id: a new
145
+ * one is added, one with an id already there replaces it). Only local
146
+ * ids ("x-...") are kept. */
147
+ export function addToLocalPlaybook(dir, add) {
148
+ const current = readLocalPlaybook(dir);
149
+ const focuses = new Map(current.focuses.map((f) => [f.id, f]));
150
+ for (const f of add.focuses ?? [])
151
+ if (isLocalId(f.id))
152
+ focuses.set(f.id, f);
153
+ const levers = new Map(current.levers.map((l) => [l.id, l]));
154
+ for (const l of add.levers ?? [])
155
+ if (isLocalId(l.id))
156
+ levers.set(l.id, l);
157
+ const next = { focuses: [...focuses.values()], levers: [...levers.values()] };
158
+ // Checked as a whole before it's written: a bad lever fails here.
159
+ parsePlaybook(next, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
160
+ mkdirSync(join(dir, '.loopengine'), { recursive: true });
161
+ const file = localFile(dir);
162
+ const temp = `${file}.${process.pid}.tmp`;
163
+ writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`);
164
+ renameSync(temp, file);
165
+ if (dir === cacheDir)
166
+ memo = undefined;
167
+ return next;
168
+ }
169
+ /** The playbook in use: the bundled one, the fetched one over it, and the
170
+ * workspace's own focuses and levers; the version is the shared one's. */
87
171
  export function activePlaybook() {
88
172
  if (!cacheDir)
89
- return { version: PLAYBOOK_VERSION, levers: LEVERS };
173
+ return { version: PLAYBOOK_VERSION, focuses: FOCUSES, levers: LEVERS };
90
174
  const file = join(cacheDir, '.loopengine', 'playbook-cache.json');
91
- let key = 'none';
92
- try {
93
- key = String(statSync(file).mtimeMs);
94
- }
95
- catch { }
175
+ const key = `${mtime(file)}|${mtime(localFile(cacheDir))}`;
96
176
  if (memo?.key === key)
97
177
  return memo;
98
178
  let fetched;
99
- if (key !== 'none') {
179
+ if (!key.startsWith('none|')) {
100
180
  try {
101
181
  const raw = JSON.parse(readFileSync(file, 'utf8'));
102
- const parsed = parsePlaybook(raw);
103
- fetched = { version: parsed.version, levers: parsed.levers, retired: Array.isArray(raw.retired) ? raw.retired.filter((x) => typeof x === 'string') : [] };
182
+ const parsed = parsePlaybook(raw, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
183
+ fetched = { ...parsed, retired: Array.isArray(raw.retired) ? raw.retired.filter((x) => typeof x === 'string') : [] };
104
184
  }
105
185
  catch { }
106
186
  }
107
- memo = { key, levers: mergePlaybooks(LEVERS, fetched), version: fetched?.version ?? PLAYBOOK_VERSION };
187
+ const local = readLocalPlaybook(cacheDir);
188
+ const focusById = new Map(FOCUSES.map((f) => [f.id, f]));
189
+ for (const f of fetched?.focuses ?? [])
190
+ focusById.set(f.id, f);
191
+ for (const f of local.focuses)
192
+ focusById.set(f.id, f);
193
+ memo = { key, focuses: [...focusById.values()], levers: [...mergePlaybooks(LEVERS, fetched), ...local.levers], version: fetched?.version ?? PLAYBOOK_VERSION };
108
194
  return memo;
109
195
  }
196
+ /** A focus's label for people: its playbook label, else its id. */
197
+ export function focusLabel(id) {
198
+ if (id === 'other')
199
+ return 'Something else';
200
+ return activePlaybook().focuses.find((f) => f.id === id)?.label ?? id;
201
+ }
110
202
  /** The levers in use for a focus. */
111
203
  export function leversFor(focus) {
112
204
  return activePlaybook().levers.filter((l) => l.focus === focus);
@@ -1,6 +1,38 @@
1
1
  {
2
+ "version": 3,
3
+ "focuses": [
4
+ {
5
+ "id": "new-signups",
6
+ "label": "Getting new signups or customers",
7
+ "hint": "more people signing up, buying or getting in touch for the first time"
8
+ },
9
+ {
10
+ "id": "activation",
11
+ "label": "Getting new users started",
12
+ "hint": "new users reaching their first real use: setup finished, first key step taken"
13
+ },
14
+ {
15
+ "id": "retention",
16
+ "label": "Keeping users",
17
+ "hint": "people who use it continuing to, renewing, or coming back"
18
+ },
19
+ {
20
+ "id": "faster-support",
21
+ "label": "Faster support",
22
+ "hint": "answering customers sooner and better"
23
+ },
24
+ {
25
+ "id": "revenue-recovery",
26
+ "label": "Recovering revenue",
27
+ "hint": "failed payments, abandoned checkouts and lapsed customers won back"
28
+ },
29
+ {
30
+ "id": "ops-hygiene",
31
+ "label": "Smoother operations",
32
+ "hint": "exceptions, stuck items and deadlines caught before they cost anything"
33
+ }
34
+ ],
2
35
  "$comment": "Playbook v1 for the goal planner (core/system-agents/goal-planner.ts). A lever is one proven way to move a kind of goal. Ids are stable: saved workflows, discards and eval expectations refer to them, so change wording freely but never an id. Loaded and checked by core/system-agents/goal-playbooks.ts.",
3
- "version": 2,
4
36
  "levers": [
5
37
  {
6
38
  "id": "new-signups.answer-intent-posts",
package/dist/index.d.ts CHANGED
@@ -127,8 +127,8 @@ export { createTrackedApprover, listApprovals, decideApproval, findApproval } fr
127
127
  export { scaffoldAgent, scaffoldSubagent, AgentNameError, AgentExistsError, AgentNotFoundError, AgentModelError } from './bin/cli.js';
128
128
  export type { AgentTemplateOptions } from './bin/cli.js';
129
129
  export { goalsPageHtml } from './web/goals-page.js';
130
- export { GoalError, acceptJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, type ChainStep, goalView, type AssignmentView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, type Goal, type GoalJob, type GoalJobState, type JobDoer, type GoalWorkflow, type GoalsDeps, type LeverEvent, migrateGoal } from './web/goals-admin.js';
130
+ export { GoalError, acceptJob, addJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, type ChainStep, goalView, type AssignmentView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, type Goal, type GoalJob, type GoalJobState, type JobDoer, type GoalWorkflow, type GoalsDeps, type LeverEvent, migrateGoal, migrateGoalFiles } from './web/goals-admin.js';
131
131
  export { sendLeverEvents, sharesLeverStats, startLeverEventsSync } from './web/lever-events-sync.js';
132
- export { runGoalPipeline, type GoalPlan, type GoalContext } from './core/system-agents/goal-planner.js';
132
+ export { runGoalPipeline, shapeJob, type GoalPlan, type GoalContext, type ShapedJob } from './core/system-agents/goal-planner.js';
133
133
  export { LEVERS, PLAYBOOK_VERSION, activePlaybook, setPlaybookProjectDir, type Lever } from './core/system-agents/goal-playbooks.js';
134
134
  export { startPlaybookSync, syncPlaybook, playbookSyncConfig } from './core/playbook-sync.js';
package/dist/index.js CHANGED
@@ -118,8 +118,8 @@ export { scaffoldAgent, scaffoldSubagent, AgentNameError, AgentExistsError, Agen
118
118
  // playbook, kept current on Cloud by core/playbook-sync.ts: a project's
119
119
  // own adapters/http.ts imports these.
120
120
  export { goalsPageHtml } from './web/goals-page.js';
121
- export { GoalError, acceptJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, goalView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, migrateGoal } from './web/goals-admin.js';
121
+ export { GoalError, acceptJob, addJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, goalView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, migrateGoal, migrateGoalFiles } from './web/goals-admin.js';
122
122
  export { sendLeverEvents, sharesLeverStats, startLeverEventsSync } from './web/lever-events-sync.js';
123
- export { runGoalPipeline } from './core/system-agents/goal-planner.js';
123
+ export { runGoalPipeline, shapeJob } from './core/system-agents/goal-planner.js';
124
124
  export { LEVERS, PLAYBOOK_VERSION, activePlaybook, setPlaybookProjectDir } from './core/system-agents/goal-playbooks.js';
125
125
  export { startPlaybookSync, syncPlaybook, playbookSyncConfig } from './core/playbook-sync.js';
@@ -88,6 +88,18 @@ export interface GoalJob {
88
88
  result?: string;
89
89
  /** For a recurring job done by several workflows: what runs after what. */
90
90
  chain?: ChainStep[];
91
+ /** A job the person added themselves: their own words, and how the
92
+ * planner judged it ("changed" or "warned", with its note). */
93
+ added?: {
94
+ idea: string;
95
+ verdict: 'added' | 'changed' | 'warned';
96
+ note?: string;
97
+ alternative?: string;
98
+ };
99
+ /** The person asked to keep this job's approach to their workspace: its
100
+ * lever events are never sent, and its lever is never offered as a
101
+ * candidate for the shared playbook. */
102
+ keepPrivate?: true;
91
103
  /** How much the person changed the suggested request before building it
92
104
  * (edits to the built workflow's instructions later don't count). */
93
105
  edited?: EditAmount;
@@ -169,8 +181,15 @@ export interface GoalsDeps {
169
181
  } | undefined>;
170
182
  }
171
183
  /** A goal as saved before jobs (its `workflows`, a built one's `built`
172
- * link) read as one with jobs; one saved since, as it is. */
184
+ * link) read as one with jobs; one saved since, as it is. Each becomes a
185
+ * job: a built one active, done by its workflow; one not built yet takes
186
+ * the kind its playbook lever usually makes (a finite list is a one-off
187
+ * job). Each gets a measure: the lever's, else how it was said to move
188
+ * the goal. */
173
189
  export declare function migrateGoal(raw: Record<string, unknown>): Goal;
190
+ /** Rewrites every goal saved before jobs in the new form (jobs, with
191
+ * their workflows as doers), once, at start. Returns how many changed. */
192
+ export declare function migrateGoalFiles(deps: GoalsDeps): number;
174
193
  export declare function getGoal(deps: GoalsDeps, id: string): Goal;
175
194
  /** Newest first. */
176
195
  export declare function listGoals(deps: GoalsDeps): Goal[];
@@ -225,6 +244,16 @@ export declare function markBuilt(deps: GoalsDeps, id: string, workflowId: strin
225
244
  title?: unknown;
226
245
  description?: unknown;
227
246
  }): Goal;
247
+ export declare function addJob(deps: GoalsDeps, id: string, input: {
248
+ idea?: unknown;
249
+ private?: unknown;
250
+ }): Promise<{
251
+ goal: Goal;
252
+ verdict: 'added' | 'changed' | 'warned' | 'refused';
253
+ note: string;
254
+ alternative: string;
255
+ jobId?: string;
256
+ }>;
228
257
  /** Checks a chain against the job's workflows: each step joins two of
229
258
  * them, its condition and inputs make sense, every required input of the
230
259
  * next run is filled, and nothing loops. Returns it tidied, with ids. */
@@ -284,11 +313,12 @@ export declare function goalView(deps: GoalsDeps, goal: Goal): Promise<Goal & {
284
313
  /** none (same words), light (mostly the same: names, a schedule, tone)
285
314
  * or heavy (a different request), by how many words the two share. */
286
315
  export declare function editAmount(before: string, after: string): EditAmount;
287
- /** What happened to a lever's job: suggested, saved, discarded (with a
316
+ /** What happened to a lever's job: suggested (by the planner) or added
317
+ * (by the person, in their own words), saved, discarded (with a
288
318
  * reason), restored; built (a workflow does it) or done (a once job
289
319
  * finished); edited (its request, at Build); then, from its workflow,
290
320
  * kept_14d, used (weekly) and removed. */
291
- export type LeverEventType = 'suggested' | 'saved' | 'discarded' | 'discard_reason' | 'restored' | 'built' | 'done' | 'edited' | 'kept_14d' | 'used' | 'removed';
321
+ export type LeverEventType = 'suggested' | 'added' | 'saved' | 'discarded' | 'discard_reason' | 'restored' | 'built' | 'done' | 'edited' | 'kept_14d' | 'used' | 'removed';
292
322
  export interface LeverEvent {
293
323
  id: string;
294
324
  type: LeverEventType;
@@ -296,6 +326,8 @@ export interface LeverEvent {
296
326
  goal: string;
297
327
  /** The job (its id under the goal). */
298
328
  job: string;
329
+ /** From a job kept to the workspace: never sent. */
330
+ private?: true;
299
331
  leverId?: string;
300
332
  /** The lever's label (for a new idea, the planner's own, generic). */
301
333
  lever: string;
@@ -36,8 +36,8 @@
36
36
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
37
37
  import { randomBytes } from 'node:crypto';
38
38
  import { join } from 'node:path';
39
- import { agentName, runGoalPipeline } from '../core/system-agents/goal-planner.js';
40
- import { GOAL_FOCUSES } from '../core/system-agents/goal-playbooks.js';
39
+ import { agentName, runGoalPipeline, shapeJob } from '../core/system-agents/goal-planner.js';
40
+ import { activePlaybook, addToLocalPlaybook } from '../core/system-agents/goal-playbooks.js';
41
41
  /** Runs a chain may start one after another, after the first. */
42
42
  export const MAX_CHAIN_DEPTH = 5;
43
43
  export class GoalError extends Error {
@@ -63,23 +63,55 @@ function write(deps, goal) {
63
63
  return goal;
64
64
  }
65
65
  /** A goal as saved before jobs (its `workflows`, a built one's `built`
66
- * link) read as one with jobs; one saved since, as it is. */
66
+ * link) read as one with jobs; one saved since, as it is. Each becomes a
67
+ * job: a built one active, done by its workflow; one not built yet takes
68
+ * the kind its playbook lever usually makes (a finite list is a one-off
69
+ * job). Each gets a measure: the lever's, else how it was said to move
70
+ * the goal. */
67
71
  export function migrateGoal(raw) {
68
72
  if (Array.isArray(raw.jobs))
69
73
  return raw;
70
74
  const { workflows, ...rest } = raw;
75
+ let levers = [];
76
+ try {
77
+ levers = activePlaybook().levers;
78
+ }
79
+ catch { }
71
80
  const jobs = (Array.isArray(workflows) ? workflows : []).map((w) => {
72
81
  const { built, ...x } = w;
82
+ const lever = typeof x.leverId === 'string' ? levers.find((l) => l.id === x.leverId) : undefined;
83
+ const kind = built || x.state === 'built' ? 'recurring' : lever?.kind ?? 'recurring';
73
84
  return {
74
85
  ...x,
75
- kind: 'recurring',
76
- measure: typeof x.measure === 'string' ? x.measure : '',
86
+ kind,
87
+ measure: typeof x.measure === 'string' && x.measure ? x.measure : lever?.measureLink ?? (typeof x.measureLink === 'string' ? x.measureLink : ''),
77
88
  state: x.state === 'built' ? 'active' : x.state,
78
89
  doers: built ? [{ type: 'workflow', ...built }] : [],
79
90
  };
80
91
  });
81
92
  return { ...rest, jobs };
82
93
  }
94
+ /** Rewrites every goal saved before jobs in the new form (jobs, with
95
+ * their workflows as doers), once, at start. Returns how many changed. */
96
+ export function migrateGoalFiles(deps) {
97
+ const dir = goalsDir(deps);
98
+ if (!existsSync(dir))
99
+ return 0;
100
+ let changed = 0;
101
+ for (const f of readdirSync(dir).filter((name) => /^g-[a-z0-9-]+\.json$/.test(name))) {
102
+ try {
103
+ const raw = JSON.parse(readFileSync(join(dir, f), 'utf8'));
104
+ if (Array.isArray(raw.jobs) || !Array.isArray(raw.workflows))
105
+ continue;
106
+ write(deps, migrateGoal(raw));
107
+ changed++;
108
+ }
109
+ catch (err) {
110
+ console.error(`[loopengine] couldn't move goals/${f} to jobs:`, err instanceof Error ? err.message : err);
111
+ }
112
+ }
113
+ return changed;
114
+ }
83
115
  export function getGoal(deps, id) {
84
116
  const file = goalFile(deps, id);
85
117
  if (!existsSync(file))
@@ -193,6 +225,16 @@ function startPlanning(deps, goal) {
193
225
  saved: planning.jobs.map((w) => ({ title: w.title, lever: w.lever, ...(w.leverId ? { leverId: w.leverId } : {}), state: w.state })),
194
226
  ...(planning.focus ? { focus: planning.focus } : {}),
195
227
  });
228
+ // A focus or levers the planner wrote, because the playbook had none
229
+ // that fit, go in the workspace's own playbook for next time.
230
+ if (plan.brief.newFocus || plan.newLevers?.length) {
231
+ try {
232
+ addToLocalPlaybook(deps.projectDir(), { ...(plan.brief.newFocus ? { focuses: [plan.brief.newFocus] } : {}), levers: plan.newLevers ?? [] });
233
+ }
234
+ catch (err) {
235
+ console.error('[loopengine] couldn\'t add the planner\'s focus and levers to the playbook:', err instanceof Error ? err.message : err);
236
+ }
237
+ }
196
238
  const latest = getGoal(deps, planning.id);
197
239
  // The planner is told what's there; anything it repeats anyway is dropped.
198
240
  const fresh = plan.workflows.map((w) => toJob(w, round, deps)).filter((w, i, all) => !latest.jobs.some((old) => sameLever(old, w)) && all.findIndex((x) => sameLever(x, w)) === i);
@@ -237,7 +279,7 @@ export function createGoal(deps, input) {
237
279
  export function generateMore(deps, id, input = {}) {
238
280
  const goal = getGoal(deps, id);
239
281
  const text = typeof input.goal === 'string' && input.goal.trim() ? input.goal.trim().slice(0, MAX_GOAL_CHARS) : goal.goal;
240
- const focus = typeof input.focus === 'string' && [...GOAL_FOCUSES, 'other'].includes(input.focus) ? input.focus : goal.focus;
282
+ const focus = typeof input.focus === 'string' && [...activePlaybook().focuses.map((f) => f.id), 'other'].includes(input.focus) ? input.focus : goal.focus;
241
283
  return startPlanning(deps, { ...goal, goal: text, ...(focus ? { focus } : {}) });
242
284
  }
243
285
  // ---- What the person does with a job (/goals/<id>/jobs/<jobId>).
@@ -345,6 +387,52 @@ export function markBuilt(deps, id, workflowId, input) {
345
387
  recordLeverEvent(deps, goal, w, 'edited', { amount: edited });
346
388
  return updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, state: 'active', doers: [...x.doers.filter((d) => !(d.type === 'workflow' && d.agent === doer.agent && d.workflowId === doer.workflowId)), doer], agent: { name: input.agent, isNew: false }, ...(edited ? { edited } : {}) }));
347
389
  }
390
+ // ---- A job the person adds, in their own words: the planner shapes it
391
+ // (kind, measure, agent, request, a lever or a new generic one) and
392
+ // judges it: added, added with changes, added with a warning, or refused
393
+ // (deceptive, illegal, against a platform's rules). One that's added is
394
+ // saved, ready to build or assign.
395
+ export async function addJob(deps, id, input) {
396
+ const idea = typeof input.idea === 'string' ? input.idea.trim() : '';
397
+ if (idea.length < 5)
398
+ throw new GoalError('Say what the job is, e.g. "Thank every new customer by email within a day".');
399
+ if (idea.length > 1000)
400
+ throw new GoalError('Keep it under 1000 characters.');
401
+ const goal = getGoal(deps, id);
402
+ if (goal.status === 'planning')
403
+ throw new GoalError('Wait for the suggestions first.');
404
+ if (!goal.brief)
405
+ throw new GoalError('This goal hasn\'t been planned yet: generate suggestions first.');
406
+ const brief = { ...goal.brief, ...(goal.focus ? { focus: goal.focus } : {}) };
407
+ const shaped = await shapeJob(await deps.modelCall(), {
408
+ goal: goal.goal,
409
+ brief,
410
+ context: await deps.context(readAbout(deps)),
411
+ saved: goal.jobs.map((w) => ({ title: w.title, lever: w.lever, ...(w.leverId ? { leverId: w.leverId } : {}), state: w.state })),
412
+ idea,
413
+ });
414
+ if (shaped.verdict === 'refused' || !shaped.job) {
415
+ return { goal, verdict: 'refused', note: shaped.note || 'This couldn\'t be shaped into a job: say a little more about what it should do.', alternative: shaped.alternative };
416
+ }
417
+ if (shaped.newLever) {
418
+ try {
419
+ addToLocalPlaybook(deps.projectDir(), { levers: [shaped.newLever] });
420
+ }
421
+ catch (err) {
422
+ console.error('[loopengine] couldn\'t add the job\'s lever to the playbook:', err instanceof Error ? err.message : err);
423
+ }
424
+ }
425
+ const job = {
426
+ ...toJob(shaped.job, goal.rounds || 1, deps),
427
+ state: 'saved',
428
+ ...(input.private === true ? { keepPrivate: true } : {}),
429
+ added: { idea, verdict: shaped.verdict, ...(shaped.note ? { note: shaped.note } : {}), ...(shaped.alternative ? { alternative: shaped.alternative } : {}) },
430
+ };
431
+ const latest = getGoal(deps, id);
432
+ const updated = write(deps, { ...latest, jobs: [...latest.jobs, job], updatedAt: now() });
433
+ recordLeverEvent(deps, updated, job, 'added', { verdict: shaped.verdict });
434
+ return { goal: updated, verdict: shaped.verdict, note: shaped.note, alternative: shaped.alternative, jobId: job.id };
435
+ }
348
436
  const sameRef = (a, b) => a.agent === b.agent && a.workflowId === b.workflowId;
349
437
  const refText = (r) => `${r.agent}/${r.workflowId}`;
350
438
  function refFrom(raw, what) {
@@ -574,7 +662,7 @@ export function editAmount(before, after) {
574
662
  }
575
663
  export function recordLeverEvent(deps, goal, w, type, detail = {}) {
576
664
  const full = {
577
- id: newId('e'), type, at: now(), goal: goal.id, job: w.id, ...(w.leverId ? { leverId: w.leverId } : {}), lever: w.lever, focus: w.focus,
665
+ id: newId('e'), type, at: now(), goal: goal.id, job: w.id, ...(w.keepPrivate ? { private: true } : {}), ...(w.leverId ? { leverId: w.leverId } : {}), lever: w.lever, focus: w.focus,
578
666
  ...(goal.playbookVersion !== undefined ? { playbookVersion: goal.playbookVersion } : {}), detail,
579
667
  };
580
668
  mkdirSync(goalsDir(deps), { recursive: true });