@installagent/sdk 0.10.0 → 0.12.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.
- package/dist/agent-templates.js +1 -1
- package/dist/build-estimate.d.ts +118 -0
- package/dist/build-estimate.js +480 -0
- package/dist/client-drift.d.ts +6 -0
- package/dist/client-drift.js +30 -28
- package/dist/env-registry.d.ts +3 -2
- package/dist/env-registry.js +4 -3
- package/dist/index.d.ts +5 -2
- package/dist/index.js +5 -2
- package/dist/portal-admin.d.ts +15 -2
- package/dist/portal-admin.js +17 -4
- package/dist/portal-sync-builds.d.ts +18 -1
- package/dist/portal-sync-builds.js +38 -5
- package/dist/roadmap-migrate.d.ts +75 -0
- package/dist/roadmap-migrate.js +328 -0
- package/dist/roadmap-retire.d.ts +61 -0
- package/dist/roadmap-retire.js +416 -0
- package/dist/template-sync.d.ts +38 -11
- package/dist/template-sync.js +88 -21
- package/package.json +1 -1
- package/templates/workspace-root/skills/client-latest/SKILL.md +1 -1
- package/templates/workspace-root/skills/engagement-spec/SKILL.md +47 -21
- package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +40 -17
- package/templates/workspace-root/skills/ia-cli/SKILL.md +1 -0
- package/templates/workspace-root/skills/linear/SKILL.md +32 -0
- package/templates/workspace-root/skills/tech-call-prep/SKILL.md +7 -3
package/dist/agent-templates.js
CHANGED
|
@@ -373,7 +373,7 @@ export async function createFromAgentTemplate(input, opts = {}) {
|
|
|
373
373
|
throw new Error(`No template "${input.template}" in the bank (${source}). Known: ${known}.`);
|
|
374
374
|
}
|
|
375
375
|
if (input.client !== undefined && !CLIENT_SLUG.test(input.client)) {
|
|
376
|
-
throw new Error(`--client "${input.client}" is not a slug (lowercase letters, digits and hyphens, e.g.
|
|
376
|
+
throw new Error(`--client "${input.client}" is not a slug (lowercase letters, digits and hyphens, e.g. acme-hvac).`);
|
|
377
377
|
}
|
|
378
378
|
const workflow = applyClientDefaults(JSON.parse(json), {
|
|
379
379
|
template: input.template,
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { type ManifestBuild } from "./portal-sync-builds.js";
|
|
2
|
+
/** Read by `ia build-estimate`. Lives in 1Password (team-techs); `ia env fill` writes it. */
|
|
3
|
+
export declare const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
|
|
4
|
+
/** The model for the estimate: the one Agent Zero uses for structured extraction. */
|
|
5
|
+
export declare const BUILD_ESTIMATE_MODEL = "gemini-3.8-flash";
|
|
6
|
+
/** The spec text sent per build is cut to this many characters. */
|
|
7
|
+
export declare const SPEC_CHAR_CAP = 24000;
|
|
8
|
+
/** The basis line is cut to this many characters. */
|
|
9
|
+
export declare const BASIS_CHAR_CAP = 300;
|
|
10
|
+
export type HoursRange = [number, number];
|
|
11
|
+
export interface BuildEstimateOptions {
|
|
12
|
+
/** The client repo, or a directory inside it. Default: the current directory. */
|
|
13
|
+
repoDir?: string;
|
|
14
|
+
/** One build slug. Default: every active row with no estimate. */
|
|
15
|
+
build?: string;
|
|
16
|
+
/** Re-estimate a row that already has `est_hours`. */
|
|
17
|
+
force?: boolean;
|
|
18
|
+
/** The spec file to read for `build` (relative to the repo), instead of the lookup. */
|
|
19
|
+
spec?: string;
|
|
20
|
+
/** Write `est_hours` into CLIENT.md for every row estimated. Default false. */
|
|
21
|
+
write?: boolean;
|
|
22
|
+
/** Defaults to $GEMINI_API_KEY. */
|
|
23
|
+
apiKey?: string;
|
|
24
|
+
model?: string;
|
|
25
|
+
fetchImpl?: typeof fetch;
|
|
26
|
+
}
|
|
27
|
+
export type BuildEstimateOutcome =
|
|
28
|
+
/** The model answered with a valid range. */
|
|
29
|
+
"estimated"
|
|
30
|
+
/** Not estimated on purpose (it already has one, without --force). */
|
|
31
|
+
| "skipped"
|
|
32
|
+
/** No estimate: no spec, a failed call, or a bad reply. Never a guessed number. */
|
|
33
|
+
| "error";
|
|
34
|
+
export interface BuildEstimateRow {
|
|
35
|
+
build: string;
|
|
36
|
+
name: string;
|
|
37
|
+
outcome: BuildEstimateOutcome;
|
|
38
|
+
/** The estimate already in CLIENT.md, if any. */
|
|
39
|
+
current: HoursRange | null;
|
|
40
|
+
low?: number;
|
|
41
|
+
high?: number;
|
|
42
|
+
/** One sentence naming the main work, with any amount removed. */
|
|
43
|
+
basis?: string;
|
|
44
|
+
/** Where the spec text came from, e.g. "docs/08-intake-tech-spec.md". */
|
|
45
|
+
spec?: string;
|
|
46
|
+
/** Why it was skipped or failed. */
|
|
47
|
+
reason?: string;
|
|
48
|
+
}
|
|
49
|
+
export interface BuildEstimateResult {
|
|
50
|
+
repoDir: string;
|
|
51
|
+
model: string;
|
|
52
|
+
rows: BuildEstimateRow[];
|
|
53
|
+
/** True when CLIENT.md was changed. */
|
|
54
|
+
written: boolean;
|
|
55
|
+
/** The builds whose `est_hours` was written. */
|
|
56
|
+
writtenBuilds: string[];
|
|
57
|
+
}
|
|
58
|
+
/** Removes email addresses and phone numbers. */
|
|
59
|
+
export declare function redactContactDetails(text: string): string;
|
|
60
|
+
/** Removes money amounts: the CLI never prints dollars. */
|
|
61
|
+
export declare function removeMoney(text: string): string;
|
|
62
|
+
/** `docs/<NN->?<build>(-tech)?-spec.md` → true for this build. */
|
|
63
|
+
export declare function isBuildSpecFile(fileName: string, build: string): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* The section of a tech spec that names the build (its slug, name or
|
|
66
|
+
* workflow id): the first heading that names it, else the first section whose
|
|
67
|
+
* own text does. Null when none does.
|
|
68
|
+
*/
|
|
69
|
+
export declare function specSectionFor(markdown: string, row: Pick<ManifestBuild, "build" | "name" | "workflowId">): {
|
|
70
|
+
heading: string;
|
|
71
|
+
text: string;
|
|
72
|
+
} | null;
|
|
73
|
+
/** An n8n export → its node count and node types, never anything else. */
|
|
74
|
+
export declare function workflowNodeSummary(workflow: unknown): {
|
|
75
|
+
nodeCount: number;
|
|
76
|
+
nodeTypes: Record<string, number>;
|
|
77
|
+
} | null;
|
|
78
|
+
export interface EstimatePromptInput {
|
|
79
|
+
type: "agent" | "app";
|
|
80
|
+
name: string;
|
|
81
|
+
description: string;
|
|
82
|
+
spec: {
|
|
83
|
+
source: string;
|
|
84
|
+
text: string;
|
|
85
|
+
};
|
|
86
|
+
workflow: {
|
|
87
|
+
nodeCount: number;
|
|
88
|
+
nodeTypes: Record<string, number>;
|
|
89
|
+
} | null;
|
|
90
|
+
}
|
|
91
|
+
/** The one prompt per build. Contact details are removed from every text field. */
|
|
92
|
+
export declare function buildEstimatePrompt(input: EstimatePromptInput): string;
|
|
93
|
+
/**
|
|
94
|
+
* The model's reply → a range and a basis, or an error. A reply that is not
|
|
95
|
+
* exactly whole hours with low <= high is refused: never a guessed number.
|
|
96
|
+
*/
|
|
97
|
+
export declare function parseEstimateReply(raw: string): {
|
|
98
|
+
ok: true;
|
|
99
|
+
low: number;
|
|
100
|
+
high: number;
|
|
101
|
+
basis: string;
|
|
102
|
+
} | {
|
|
103
|
+
ok: false;
|
|
104
|
+
error: string;
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* CLIENT.md with `est_hours` set on the given rows and nothing else changed:
|
|
108
|
+
* the block keeps its layout, and the result is re-parsed to prove that only
|
|
109
|
+
* those rows' `estHours` moved. Throws rather than write anything else.
|
|
110
|
+
*/
|
|
111
|
+
export declare function setEstHours(clientMd: string, updates: Map<string, HoursRange>): string;
|
|
112
|
+
/**
|
|
113
|
+
* Estimates the market hours of a client repo's builds: one Gemini call per
|
|
114
|
+
* build, a range of whole hours each. With `write`, sets `est_hours` on the
|
|
115
|
+
* estimated rows of CLIENT.md (only that field moves); the technician commits
|
|
116
|
+
* it. Never knows the rate, never prints a dollar figure.
|
|
117
|
+
*/
|
|
118
|
+
export declare function buildEstimate(options?: BuildEstimateOptions): Promise<BuildEstimateResult>;
|
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { BUILDS_MANIFEST_END, BUILDS_MANIFEST_START, parseBuildsManifest, } from "./portal-sync-builds.js";
|
|
5
|
+
// ─── `ia build-estimate`: market hours per build, for the portal's cost range ──
|
|
6
|
+
//
|
|
7
|
+
// One AI call per build answers: how many hours would a typical US freelance
|
|
8
|
+
// automation developer bill to deliver this, spec to go-live? The answer is a
|
|
9
|
+
// range of whole hours. `--write` puts it in the build's `## Builds` row of
|
|
10
|
+
// CLIENT.md as `"est_hours": [low, high]`; `ia portal sync-builds` carries it
|
|
11
|
+
// to the portal, which multiplies it by the one market rate set in portal
|
|
12
|
+
// admin when it renders the card.
|
|
13
|
+
//
|
|
14
|
+
// Money rule: this module never knows the rate and never prints a dollar
|
|
15
|
+
// figure. It reads only hours, and it removes any amount from the model's
|
|
16
|
+
// one-line basis before it returns it.
|
|
17
|
+
//
|
|
18
|
+
// What leaves the machine (one Gemini request per build): the row's type,
|
|
19
|
+
// name and description; the build's spec text, capped, with email addresses
|
|
20
|
+
// and phone numbers removed; and for an agent, the node count and node types
|
|
21
|
+
// of its workflow export. Never node parameters, credentials, or CLIENT.md.
|
|
22
|
+
/** Read by `ia build-estimate`. Lives in 1Password (team-techs); `ia env fill` writes it. */
|
|
23
|
+
export const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
|
|
24
|
+
/** The model for the estimate: the one Agent Zero uses for structured extraction. */
|
|
25
|
+
export const BUILD_ESTIMATE_MODEL = "gemini-3.8-flash";
|
|
26
|
+
/** The spec text sent per build is cut to this many characters. */
|
|
27
|
+
export const SPEC_CHAR_CAP = 24_000;
|
|
28
|
+
/** The basis line is cut to this many characters. */
|
|
29
|
+
export const BASIS_CHAR_CAP = 300;
|
|
30
|
+
const GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta";
|
|
31
|
+
const GEMINI_TIMEOUT_MS = 120_000;
|
|
32
|
+
/** Gemini's structured-output schema for one estimate. */
|
|
33
|
+
const ESTIMATE_SCHEMA = {
|
|
34
|
+
type: "OBJECT",
|
|
35
|
+
properties: {
|
|
36
|
+
low: { type: "INTEGER" },
|
|
37
|
+
high: { type: "INTEGER" },
|
|
38
|
+
basis: { type: "STRING" },
|
|
39
|
+
},
|
|
40
|
+
required: ["low", "high", "basis"],
|
|
41
|
+
propertyOrdering: ["low", "high", "basis"],
|
|
42
|
+
};
|
|
43
|
+
// ─── Pure helpers (exported for tests) ──────────────────────────────────────
|
|
44
|
+
const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
45
|
+
// A North American or international phone number, as written in docs:
|
|
46
|
+
// +1 (555) 010-0199, 555.010.0199, +44 20 7946 0958. Not part of a longer token.
|
|
47
|
+
const PHONE = /(?<![\w+])(?:\+\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)|\d{2,4})[\s.-]?\d{3,4}[\s.-]?\d{3,4}(?![\w])/g;
|
|
48
|
+
/** Removes email addresses and phone numbers. */
|
|
49
|
+
export function redactContactDetails(text) {
|
|
50
|
+
return text.replace(EMAIL, "[email]").replace(PHONE, (match) => {
|
|
51
|
+
// A run of digits with no separator and fewer than 10 digits is a number, not a phone.
|
|
52
|
+
const digits = match.replace(/\D/g, "");
|
|
53
|
+
return digits.length >= 10 ? "[phone]" : match;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
// 12,000 · 4.5 · 8k · 1.2 M
|
|
57
|
+
const AMOUNT = String.raw `\d[\d,]*(?:\.\d+)?(?:\s?[kKmM]\b)?`;
|
|
58
|
+
// 8k–12k · 8,000 to $12,000
|
|
59
|
+
const AMOUNT_RANGE = String.raw `${AMOUNT}(?:\s?(?:-|–|to)\s?\$?${AMOUNT})?`;
|
|
60
|
+
const MONEY = [
|
|
61
|
+
// $12,000 · US$90 · $90/h · $8k–12k
|
|
62
|
+
new RegExp(String.raw `(?:US)?\$\s?${AMOUNT_RANGE}(?:\s?(?:\/|per\s)\s?(?:h|hr|hour)\b)?`, "g"),
|
|
63
|
+
// 12,000 USD · 8k–12k USD · 90 dollars
|
|
64
|
+
new RegExp(String.raw `\b${AMOUNT_RANGE}\s?(?:USD|dollars?)\b`, "gi"),
|
|
65
|
+
];
|
|
66
|
+
/** Removes money amounts: the CLI never prints dollars. */
|
|
67
|
+
export function removeMoney(text) {
|
|
68
|
+
return MONEY.reduce((out, pattern) => out.replace(pattern, "[amount removed]"), text);
|
|
69
|
+
}
|
|
70
|
+
/** `docs/<NN->?<build>(-tech)?-spec.md` → true for this build. */
|
|
71
|
+
export function isBuildSpecFile(fileName, build) {
|
|
72
|
+
if (!fileName.endsWith("-spec.md"))
|
|
73
|
+
return false;
|
|
74
|
+
const stem = fileName.replace(/^\d+-/, "").replace(/(?:-tech)?-spec\.md$/, "");
|
|
75
|
+
return stem === build;
|
|
76
|
+
}
|
|
77
|
+
function markdownSections(markdown) {
|
|
78
|
+
const lines = markdown.replace(/\r\n/g, "\n").split("\n");
|
|
79
|
+
const headings = [];
|
|
80
|
+
let inFence = false;
|
|
81
|
+
lines.forEach((line, index) => {
|
|
82
|
+
if (/^\s*```/.test(line))
|
|
83
|
+
inFence = !inFence;
|
|
84
|
+
const match = inFence ? null : /^(#{1,6})\s+(.*)$/.exec(line);
|
|
85
|
+
if (match?.[1] && match[2] !== undefined) {
|
|
86
|
+
headings.push({ heading: match[2].trim(), level: match[1].length, line: index });
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
return headings.map((heading, i) => {
|
|
90
|
+
const later = headings.slice(i + 1);
|
|
91
|
+
const sectionEnd = later.find((next) => next.level <= heading.level)?.line ?? lines.length;
|
|
92
|
+
const ownEnd = later[0]?.line ?? lines.length;
|
|
93
|
+
return {
|
|
94
|
+
heading: heading.heading,
|
|
95
|
+
level: heading.level,
|
|
96
|
+
text: lines.slice(heading.line, sectionEnd).join("\n"),
|
|
97
|
+
ownText: lines.slice(heading.line, ownEnd).join("\n"),
|
|
98
|
+
};
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The section of a tech spec that names the build (its slug, name or
|
|
103
|
+
* workflow id): the first heading that names it, else the first section whose
|
|
104
|
+
* own text does. Null when none does.
|
|
105
|
+
*/
|
|
106
|
+
export function specSectionFor(markdown, row) {
|
|
107
|
+
const needles = [row.build, row.name, row.workflowId]
|
|
108
|
+
.filter((value) => Boolean(value))
|
|
109
|
+
.map((value) => value.toLowerCase());
|
|
110
|
+
const names = (text) => needles.some((needle) => text.toLowerCase().includes(needle));
|
|
111
|
+
// Skip the document title (level 1): it holds everything.
|
|
112
|
+
const sections = markdownSections(markdown).filter((section) => section.level > 1);
|
|
113
|
+
const found = sections.find((section) => names(section.heading)) ??
|
|
114
|
+
sections.find((section) => names(section.ownText));
|
|
115
|
+
return found ? { heading: found.heading, text: found.text } : null;
|
|
116
|
+
}
|
|
117
|
+
function cap(text) {
|
|
118
|
+
return text.length > SPEC_CHAR_CAP ? `${text.slice(0, SPEC_CHAR_CAP)}\n[…cut]` : text;
|
|
119
|
+
}
|
|
120
|
+
/** An n8n export → its node count and node types, never anything else. */
|
|
121
|
+
export function workflowNodeSummary(workflow) {
|
|
122
|
+
if (typeof workflow !== "object" || workflow === null)
|
|
123
|
+
return null;
|
|
124
|
+
const nodes = workflow.nodes;
|
|
125
|
+
if (!Array.isArray(nodes))
|
|
126
|
+
return null;
|
|
127
|
+
const nodeTypes = {};
|
|
128
|
+
for (const node of nodes) {
|
|
129
|
+
const type = typeof node === "object" &&
|
|
130
|
+
node !== null &&
|
|
131
|
+
typeof node.type === "string"
|
|
132
|
+
? node.type
|
|
133
|
+
: "unknown";
|
|
134
|
+
nodeTypes[type] = (nodeTypes[type] ?? 0) + 1;
|
|
135
|
+
}
|
|
136
|
+
return { nodeCount: nodes.length, nodeTypes };
|
|
137
|
+
}
|
|
138
|
+
/** The one prompt per build. Contact details are removed from every text field. */
|
|
139
|
+
export function buildEstimatePrompt(input) {
|
|
140
|
+
const nodeTypes = input.workflow
|
|
141
|
+
? Object.entries(input.workflow.nodeTypes)
|
|
142
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
143
|
+
.map(([type, count]) => (count > 1 ? `${type} ×${count}` : type))
|
|
144
|
+
.join(", ")
|
|
145
|
+
: "";
|
|
146
|
+
return [
|
|
147
|
+
"You estimate the effort to deliver a software build.",
|
|
148
|
+
"",
|
|
149
|
+
"Question: how many hours would a typical US freelance automation developer bill to deliver",
|
|
150
|
+
"the build below, from spec to go-live? Count design, build, test, deploy and handoff.",
|
|
151
|
+
"Do not count ongoing support or maintenance. Do not count the client's own time.",
|
|
152
|
+
"",
|
|
153
|
+
"Answer with JSON only, in this shape:",
|
|
154
|
+
'{"low": <whole hours>, "high": <whole hours>, "basis": "<one sentence>"}',
|
|
155
|
+
"- low and high are whole numbers of hours, 1 or more, with low <= high: a realistic range.",
|
|
156
|
+
"- basis is one sentence of at most 30 words that names the main pieces of work.",
|
|
157
|
+
"- Never mention money, rates or prices.",
|
|
158
|
+
"",
|
|
159
|
+
"Build:",
|
|
160
|
+
`- Type: ${input.type === "agent" ? "agent (an automation that runs as an n8n workflow)" : "app (a website or a web app)"}`,
|
|
161
|
+
`- Name: ${redactContactDetails(input.name)}`,
|
|
162
|
+
`- Description: ${redactContactDetails(input.description)}`,
|
|
163
|
+
...(input.workflow
|
|
164
|
+
? [`- Workflow: ${input.workflow.nodeCount} nodes. Node types: ${nodeTypes}`]
|
|
165
|
+
: []),
|
|
166
|
+
"",
|
|
167
|
+
`Spec (${input.spec.source}):`,
|
|
168
|
+
'"""',
|
|
169
|
+
cap(redactContactDetails(input.spec.text)),
|
|
170
|
+
'"""',
|
|
171
|
+
].join("\n");
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The model's reply → a range and a basis, or an error. A reply that is not
|
|
175
|
+
* exactly whole hours with low <= high is refused: never a guessed number.
|
|
176
|
+
*/
|
|
177
|
+
export function parseEstimateReply(raw) {
|
|
178
|
+
const refused = {
|
|
179
|
+
ok: false,
|
|
180
|
+
error: "the model's reply is not {low, high, basis} with whole hours, low ≤ high",
|
|
181
|
+
};
|
|
182
|
+
let parsed;
|
|
183
|
+
try {
|
|
184
|
+
parsed = JSON.parse(raw.replace(/```(?:json)?/g, "").trim());
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return refused;
|
|
188
|
+
}
|
|
189
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
|
190
|
+
return refused;
|
|
191
|
+
const { low, high, basis } = parsed;
|
|
192
|
+
if (!Number.isSafeInteger(low) || !Number.isSafeInteger(high))
|
|
193
|
+
return refused;
|
|
194
|
+
if (low < 1 || low > high)
|
|
195
|
+
return refused;
|
|
196
|
+
const sentence = typeof basis === "string" ? removeMoney(basis.replace(/\s+/g, " ").trim()) : "";
|
|
197
|
+
if (!sentence)
|
|
198
|
+
return refused;
|
|
199
|
+
return {
|
|
200
|
+
ok: true,
|
|
201
|
+
low: low,
|
|
202
|
+
high: high,
|
|
203
|
+
basis: sentence.length > BASIS_CHAR_CAP ? `${sentence.slice(0, BASIS_CHAR_CAP)}…` : sentence,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/** The spans of the top-level objects of a JSON array text, skipping strings. */
|
|
207
|
+
function topLevelObjectSpans(json) {
|
|
208
|
+
const spans = [];
|
|
209
|
+
let depth = 0;
|
|
210
|
+
let inString = false;
|
|
211
|
+
let start = -1;
|
|
212
|
+
for (let i = 0; i < json.length; i++) {
|
|
213
|
+
const char = json[i];
|
|
214
|
+
if (inString) {
|
|
215
|
+
if (char === "\\")
|
|
216
|
+
i++;
|
|
217
|
+
else if (char === '"')
|
|
218
|
+
inString = false;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (char === '"')
|
|
222
|
+
inString = true;
|
|
223
|
+
else if (char === "{" || char === "[") {
|
|
224
|
+
if (char === "{" && depth === 1)
|
|
225
|
+
start = i;
|
|
226
|
+
depth++;
|
|
227
|
+
}
|
|
228
|
+
else if (char === "}" || char === "]") {
|
|
229
|
+
depth--;
|
|
230
|
+
if (char === "}" && depth === 1 && start >= 0) {
|
|
231
|
+
spans.push({ start, end: i + 1 });
|
|
232
|
+
start = -1;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return spans;
|
|
237
|
+
}
|
|
238
|
+
/** Sets `est_hours` in one row object's text, keeping its layout. */
|
|
239
|
+
function setRowHours(objectText, hours) {
|
|
240
|
+
const value = `[${hours[0]}, ${hours[1]}]`;
|
|
241
|
+
const existing = /("est_hours"\s*:\s*)\[[^\]]*\]/;
|
|
242
|
+
if (existing.test(objectText))
|
|
243
|
+
return objectText.replace(existing, `$1${value}`);
|
|
244
|
+
const close = objectText.lastIndexOf("}");
|
|
245
|
+
const body = objectText.slice(0, close).replace(/\s*$/, "");
|
|
246
|
+
const tail = objectText.slice(body.length);
|
|
247
|
+
const keyLine = /\n([ \t]*)"build"\s*:/.exec(objectText);
|
|
248
|
+
if (keyLine)
|
|
249
|
+
return `${body},\n${keyLine[1]}"est_hours": ${value}${tail}`;
|
|
250
|
+
return `${body}, "est_hours": ${value}${tail}`;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* CLIENT.md with `est_hours` set on the given rows and nothing else changed:
|
|
254
|
+
* the block keeps its layout, and the result is re-parsed to prove that only
|
|
255
|
+
* those rows' `estHours` moved. Throws rather than write anything else.
|
|
256
|
+
*/
|
|
257
|
+
export function setEstHours(clientMd, updates) {
|
|
258
|
+
const before = parseBuildsManifest(clientMd);
|
|
259
|
+
if (before.state !== "ok")
|
|
260
|
+
throw new Error("CLIENT.md ## Builds is not valid — fix it first");
|
|
261
|
+
const start = clientMd.indexOf(BUILDS_MANIFEST_START);
|
|
262
|
+
const end = clientMd.indexOf(BUILDS_MANIFEST_END);
|
|
263
|
+
const block = clientMd.slice(start, end);
|
|
264
|
+
const fence = /```json\s*\n([\s\S]*?)\n\s*```/.exec(block);
|
|
265
|
+
if (!fence?.[1])
|
|
266
|
+
throw new Error("CLIENT.md ## Builds has no ```json fence");
|
|
267
|
+
const jsonStart = start + fence.index + fence[0].indexOf(fence[1]);
|
|
268
|
+
const json = fence[1];
|
|
269
|
+
let edited = json;
|
|
270
|
+
const spans = topLevelObjectSpans(json);
|
|
271
|
+
// Right to left, so an edit never moves a span still to come.
|
|
272
|
+
for (const span of [...spans].reverse()) {
|
|
273
|
+
const objectText = json.slice(span.start, span.end);
|
|
274
|
+
const build = JSON.parse(objectText).build;
|
|
275
|
+
const hours = typeof build === "string" ? updates.get(build) : undefined;
|
|
276
|
+
if (!hours)
|
|
277
|
+
continue;
|
|
278
|
+
edited = `${edited.slice(0, span.start)}${setRowHours(objectText, hours)}${edited.slice(span.end)}`;
|
|
279
|
+
}
|
|
280
|
+
const next = `${clientMd.slice(0, jsonStart)}${edited}${clientMd.slice(jsonStart + json.length)}`;
|
|
281
|
+
const after = parseBuildsManifest(next);
|
|
282
|
+
const expected = before.rows.map((row) => {
|
|
283
|
+
const hours = updates.get(row.build);
|
|
284
|
+
return hours ? { ...row, estHours: hours } : row;
|
|
285
|
+
});
|
|
286
|
+
const unsafe = new Error("could not edit the ## Builds block safely — nothing written");
|
|
287
|
+
if (after.state !== "ok" || after.rows.length !== expected.length)
|
|
288
|
+
throw unsafe;
|
|
289
|
+
for (const [index, row] of after.rows.entries()) {
|
|
290
|
+
if (JSON.stringify(sortKeys(row)) !== JSON.stringify(sortKeys(expected[index])))
|
|
291
|
+
throw unsafe;
|
|
292
|
+
}
|
|
293
|
+
for (const build of updates.keys()) {
|
|
294
|
+
if (!before.rows.some((row) => row.build === build))
|
|
295
|
+
throw unsafe;
|
|
296
|
+
}
|
|
297
|
+
return next;
|
|
298
|
+
}
|
|
299
|
+
function sortKeys(value) {
|
|
300
|
+
return value
|
|
301
|
+
? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)))
|
|
302
|
+
: value;
|
|
303
|
+
}
|
|
304
|
+
// ─── I/O ────────────────────────────────────────────────────────────────────
|
|
305
|
+
/** The nearest directory at or above `from` that holds a CLIENT.md. */
|
|
306
|
+
function findClientRepo(from) {
|
|
307
|
+
let dir = resolve(from);
|
|
308
|
+
for (;;) {
|
|
309
|
+
if (existsSync(join(dir, "CLIENT.md")))
|
|
310
|
+
return dir;
|
|
311
|
+
const parent = dirname(dir);
|
|
312
|
+
if (parent === dir)
|
|
313
|
+
return null;
|
|
314
|
+
dir = parent;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async function readSpec(repoDir, row, specOverride) {
|
|
318
|
+
if (specOverride) {
|
|
319
|
+
const path = resolve(repoDir, specOverride);
|
|
320
|
+
if (!existsSync(path))
|
|
321
|
+
throw new Error(`no spec file at ${specOverride}`);
|
|
322
|
+
// Forward slashes on every OS: the source is printed and sent in the prompt.
|
|
323
|
+
const source = relative(repoDir, path).split(sep).join("/");
|
|
324
|
+
return { source, text: await readFile(path, "utf8") };
|
|
325
|
+
}
|
|
326
|
+
const docsDir = join(repoDir, "docs");
|
|
327
|
+
const docs = existsSync(docsDir) ? (await readdir(docsDir)).sort() : [];
|
|
328
|
+
const own = docs.filter((file) => isBuildSpecFile(file, row.build)).pop();
|
|
329
|
+
if (own)
|
|
330
|
+
return { source: `docs/${own}`, text: await readFile(join(docsDir, own), "utf8") };
|
|
331
|
+
const techSpec = join(docsDir, "02-tech-spec.md");
|
|
332
|
+
if (!existsSync(techSpec))
|
|
333
|
+
return null;
|
|
334
|
+
const text = await readFile(techSpec, "utf8");
|
|
335
|
+
const section = specSectionFor(text, row);
|
|
336
|
+
if (section)
|
|
337
|
+
return { source: `docs/02-tech-spec.md § ${section.heading}`, text: section.text };
|
|
338
|
+
return { source: "docs/02-tech-spec.md (first part)", text };
|
|
339
|
+
}
|
|
340
|
+
async function readWorkflowSummary(repoDir, workflowId) {
|
|
341
|
+
if (!workflowId)
|
|
342
|
+
return null;
|
|
343
|
+
const dir = join(repoDir, "workflows");
|
|
344
|
+
if (!existsSync(dir))
|
|
345
|
+
return null;
|
|
346
|
+
for (const file of (await readdir(dir)).filter((name) => name.endsWith(".json")).sort()) {
|
|
347
|
+
let workflow;
|
|
348
|
+
try {
|
|
349
|
+
workflow = JSON.parse(await readFile(join(dir, file), "utf8"));
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (workflow?.id === workflowId) {
|
|
355
|
+
return workflowNodeSummary(workflow);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
async function askGemini(prompt, apiKey, model, fetchImpl) {
|
|
361
|
+
const res = await fetchImpl(`${GEMINI_API_BASE}/models/${encodeURIComponent(model)}:generateContent`, {
|
|
362
|
+
method: "POST",
|
|
363
|
+
headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
|
|
364
|
+
signal: AbortSignal.timeout(GEMINI_TIMEOUT_MS),
|
|
365
|
+
body: JSON.stringify({
|
|
366
|
+
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
367
|
+
generationConfig: {
|
|
368
|
+
responseMimeType: "application/json",
|
|
369
|
+
responseSchema: ESTIMATE_SCHEMA,
|
|
370
|
+
},
|
|
371
|
+
}),
|
|
372
|
+
});
|
|
373
|
+
const body = (await res.json().catch(() => null));
|
|
374
|
+
if (!res.ok) {
|
|
375
|
+
throw new Error(`Gemini answered HTTP ${res.status}: ${body?.error?.message ?? "no detail"}`);
|
|
376
|
+
}
|
|
377
|
+
return (body?.candidates?.[0]?.content?.parts ?? []).map((part) => part.text ?? "").join("");
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Estimates the market hours of a client repo's builds: one Gemini call per
|
|
381
|
+
* build, a range of whole hours each. With `write`, sets `est_hours` on the
|
|
382
|
+
* estimated rows of CLIENT.md (only that field moves); the technician commits
|
|
383
|
+
* it. Never knows the rate, never prints a dollar figure.
|
|
384
|
+
*/
|
|
385
|
+
export async function buildEstimate(options = {}) {
|
|
386
|
+
const repoDir = findClientRepo(options.repoDir ?? process.cwd());
|
|
387
|
+
if (!repoDir)
|
|
388
|
+
throw new Error("no CLIENT.md here or above — run this inside a client repo");
|
|
389
|
+
if (options.spec && !options.build)
|
|
390
|
+
throw new Error("--spec needs --build");
|
|
391
|
+
const clientMdPath = join(repoDir, "CLIENT.md");
|
|
392
|
+
const clientMd = await readFile(clientMdPath, "utf8");
|
|
393
|
+
const manifest = parseBuildsManifest(clientMd);
|
|
394
|
+
if (manifest.state === "invalid") {
|
|
395
|
+
throw new Error(`CLIENT.md ## Builds is invalid: ${manifest.errors.join("; ")}`);
|
|
396
|
+
}
|
|
397
|
+
if (manifest.state !== "ok") {
|
|
398
|
+
throw new Error("CLIENT.md has no filled ## Builds block — list the builds first");
|
|
399
|
+
}
|
|
400
|
+
let candidates;
|
|
401
|
+
if (options.build) {
|
|
402
|
+
const row = manifest.rows.find((r) => r.build === options.build);
|
|
403
|
+
if (!row)
|
|
404
|
+
throw new Error(`no build "${options.build}" in CLIENT.md ## Builds`);
|
|
405
|
+
candidates = [row];
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
candidates = manifest.rows.filter((row) => row.status === "active");
|
|
409
|
+
}
|
|
410
|
+
const model = options.model ?? BUILD_ESTIMATE_MODEL;
|
|
411
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
412
|
+
const needsCall = candidates.some((row) => options.force || !row.estHours);
|
|
413
|
+
const apiKey = options.apiKey ?? process.env[GEMINI_API_KEY_ENV];
|
|
414
|
+
if (needsCall && !apiKey) {
|
|
415
|
+
throw new Error(`${GEMINI_API_KEY_ENV} is not set — run \`ia env fill\` (team-techs vault)`);
|
|
416
|
+
}
|
|
417
|
+
const rows = [];
|
|
418
|
+
for (const row of candidates) {
|
|
419
|
+
const base = { build: row.build, name: row.name, current: row.estHours ?? null };
|
|
420
|
+
if (row.estHours && !options.force) {
|
|
421
|
+
rows.push({ ...base, outcome: "skipped", reason: "has an estimate — --force to redo it" });
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
const spec = await readSpec(repoDir, row, options.spec);
|
|
425
|
+
if (!spec) {
|
|
426
|
+
rows.push({
|
|
427
|
+
...base,
|
|
428
|
+
outcome: "error",
|
|
429
|
+
reason: "no spec found (docs/<build>-spec.md or docs/02-tech-spec.md) — pass --spec",
|
|
430
|
+
});
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
const prompt = buildEstimatePrompt({
|
|
434
|
+
type: row.type,
|
|
435
|
+
name: row.name,
|
|
436
|
+
description: row.description,
|
|
437
|
+
spec,
|
|
438
|
+
workflow: row.type === "agent" ? await readWorkflowSummary(repoDir, row.workflowId) : null,
|
|
439
|
+
});
|
|
440
|
+
try {
|
|
441
|
+
const reply = parseEstimateReply(await askGemini(prompt, apiKey, model, fetchImpl));
|
|
442
|
+
rows.push(reply.ok
|
|
443
|
+
? {
|
|
444
|
+
...base,
|
|
445
|
+
outcome: "estimated",
|
|
446
|
+
low: reply.low,
|
|
447
|
+
high: reply.high,
|
|
448
|
+
basis: reply.basis,
|
|
449
|
+
spec: spec.source,
|
|
450
|
+
}
|
|
451
|
+
: { ...base, outcome: "error", spec: spec.source, reason: reply.error });
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
rows.push({
|
|
455
|
+
...base,
|
|
456
|
+
outcome: "error",
|
|
457
|
+
spec: spec.source,
|
|
458
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const updates = new Map();
|
|
463
|
+
for (const row of rows) {
|
|
464
|
+
if (row.outcome === "estimated" && row.low !== undefined && row.high !== undefined) {
|
|
465
|
+
updates.set(row.build, [row.low, row.high]);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
let written = false;
|
|
469
|
+
if (options.write && updates.size > 0) {
|
|
470
|
+
await writeFile(clientMdPath, setEstHours(clientMd, updates), "utf8");
|
|
471
|
+
written = true;
|
|
472
|
+
}
|
|
473
|
+
return {
|
|
474
|
+
repoDir,
|
|
475
|
+
model,
|
|
476
|
+
rows,
|
|
477
|
+
written,
|
|
478
|
+
writtenBuilds: written ? [...updates.keys()] : [],
|
|
479
|
+
};
|
|
480
|
+
}
|
package/dist/client-drift.d.ts
CHANGED
|
@@ -87,6 +87,12 @@ export interface ClientDriftOptions {
|
|
|
87
87
|
/** Linear API key; defaults to $LINEAR_API_TOKEN. */
|
|
88
88
|
linearToken?: string;
|
|
89
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* The day client-template's repo-lint rule 20 starts: from then on, a log
|
|
92
|
+
* entry's Follow-ups is `none` or INS ids only (owed work, never shipped work).
|
|
93
|
+
* Mirrors FOLLOWUPS_INS_FROM in client-template/ci/repo-lint.mjs.
|
|
94
|
+
*/
|
|
95
|
+
export declare const FOLLOWUPS_INS_FROM = "2026-11-08";
|
|
90
96
|
/**
|
|
91
97
|
* Compare one client repo (or every one) with n8n, git, Linear and its own lint.
|
|
92
98
|
* Never throws for a source it cannot read: the source goes into
|