stageflow 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +158 -14
  2. package/dist/agent/activity.d.ts +10 -1
  3. package/dist/agent/activity.js +37 -2
  4. package/dist/agent/activityObserver.d.ts +5 -1
  5. package/dist/agent/activityObserver.js +174 -11
  6. package/dist/agent/fakeAgent.js +4 -0
  7. package/dist/agent/piAdapter.d.ts +16 -0
  8. package/dist/agent/piAdapter.js +88 -21
  9. package/dist/agent/port.d.ts +2 -0
  10. package/dist/agent/providerAuth.js +12 -7
  11. package/dist/catalog/displayCatalogPath.d.ts +12 -0
  12. package/dist/catalog/displayCatalogPath.js +28 -0
  13. package/dist/cli/initCommand.d.ts +9 -0
  14. package/dist/cli/initCommand.js +71 -0
  15. package/dist/cli/initTemplates.d.ts +3 -0
  16. package/dist/cli/initTemplates.js +19 -0
  17. package/dist/cli/operatorCatalog.d.ts +10 -0
  18. package/dist/cli/operatorCatalog.js +16 -0
  19. package/dist/cli/runCommand.d.ts +3 -1
  20. package/dist/cli/runCommand.js +48 -7
  21. package/dist/cli/validateCommand.d.ts +1 -1
  22. package/dist/cli/validateCommand.js +20 -3
  23. package/dist/cli.d.ts +1 -0
  24. package/dist/cli.js +52 -19
  25. package/dist/config/browseCatalog.d.ts +45 -0
  26. package/dist/config/browseCatalog.js +170 -0
  27. package/dist/config/createPipeline.d.ts +12 -3
  28. package/dist/config/createPipeline.js +292 -100
  29. package/dist/config/createStage.d.ts +10 -4
  30. package/dist/config/createStage.js +44 -14
  31. package/dist/config/listConfig.d.ts +14 -19
  32. package/dist/config/listConfig.js +26 -191
  33. package/dist/config/listModelsFromManifest.d.ts +2 -0
  34. package/dist/config/listModelsFromManifest.js +4 -0
  35. package/dist/config/loadOutcome.d.ts +4 -0
  36. package/dist/config/loadPipeline.d.ts +1 -15
  37. package/dist/config/loadPipeline.js +84 -142
  38. package/dist/config/loadStage.d.ts +4 -0
  39. package/dist/config/loadStage.js +60 -32
  40. package/dist/config/loadStageflowManifest.d.ts +5 -0
  41. package/dist/config/loadStageflowManifest.js +157 -0
  42. package/dist/config/mergePipelineIncludes.d.ts +9 -0
  43. package/dist/config/mergePipelineIncludes.js +141 -0
  44. package/dist/config/normalizePipelineStageEntry.d.ts +16 -0
  45. package/dist/config/normalizePipelineStageEntry.js +186 -0
  46. package/dist/config/pipelineStageKeys.d.ts +4 -0
  47. package/dist/config/pipelineStageKeys.js +14 -0
  48. package/dist/config/resolveCatalogContext.d.ts +13 -0
  49. package/dist/config/resolveCatalogContext.js +13 -0
  50. package/dist/config/resolveForkEmitContext.d.ts +3 -0
  51. package/dist/config/resolveForkEmitContext.js +12 -0
  52. package/dist/config/resolvePipelineDag.d.ts +5 -1
  53. package/dist/config/resolvePipelineDag.js +54 -36
  54. package/dist/config/scanCatalogPaths.d.ts +4 -0
  55. package/dist/config/scanCatalogPaths.js +83 -0
  56. package/dist/config/validateCatalog.d.ts +22 -4
  57. package/dist/config/validateCatalog.js +169 -132
  58. package/dist/envelope/check.js +7 -0
  59. package/dist/envelope/forkChoice.d.ts +3 -0
  60. package/dist/envelope/forkChoice.js +47 -0
  61. package/dist/index.d.ts +4 -0
  62. package/dist/index.js +4 -0
  63. package/dist/mcp/projectRun.d.ts +3 -0
  64. package/dist/mcp/projectRun.js +7 -0
  65. package/dist/mcp/tools.js +28 -11
  66. package/dist/project/findProjectRoot.d.ts +2 -0
  67. package/dist/project/findProjectRoot.js +51 -0
  68. package/dist/project/globalHome.d.ts +2 -0
  69. package/dist/project/globalHome.js +19 -0
  70. package/dist/project/resolveProjectContext.d.ts +9 -0
  71. package/dist/project/resolveProjectContext.js +38 -0
  72. package/dist/project/resolveStageflowContext.d.ts +11 -0
  73. package/dist/project/resolveStageflowContext.js +66 -0
  74. package/dist/runstore/normalizeCatalogPath.d.ts +1 -0
  75. package/dist/runstore/normalizeCatalogPath.js +4 -0
  76. package/dist/runstore/port.d.ts +9 -0
  77. package/dist/runstore/runProjection.js +11 -1
  78. package/dist/runstore/sqlite/SqliteRunStore.js +30 -4
  79. package/dist/runstore/sqlite/schema.d.ts +1 -1
  80. package/dist/runstore/sqlite/schema.js +4 -1
  81. package/dist/runtime/credentialBinding.d.ts +8 -6
  82. package/dist/runtime/credentialBinding.js +18 -24
  83. package/dist/runtime/pipelineRunner.d.ts +3 -0
  84. package/dist/runtime/pipelineRunner.js +15 -1
  85. package/dist/runtime/pipelineScheduler.d.ts +2 -0
  86. package/dist/runtime/pipelineScheduler.js +51 -11
  87. package/dist/runtime/reloadRunCatalog.d.ts +5 -0
  88. package/dist/runtime/reloadRunCatalog.js +44 -0
  89. package/dist/runtime/resumeReconstruct.d.ts +1 -0
  90. package/dist/runtime/resumeReconstruct.js +23 -7
  91. package/dist/runtime/runManager.d.ts +4 -0
  92. package/dist/runtime/runManager.js +36 -16
  93. package/dist/runtime/settingsFile.d.ts +12 -0
  94. package/dist/runtime/settingsFile.js +87 -6
  95. package/dist/runtime/stageAttemptBootstrap.js +3 -0
  96. package/dist/runtime/stageProcessLauncher.js +3 -0
  97. package/dist/runtime/stageRecovery.js +3 -1
  98. package/dist/runtime/stageWorker.js +2 -6
  99. package/dist/server/http.js +33 -9
  100. package/dist/tools/emitStageEnvelope.d.ts +3 -1
  101. package/dist/tools/emitStageEnvelope.js +11 -1
  102. package/dist/types/envelope.d.ts +1 -0
  103. package/dist/types/forkChoice.d.ts +8 -0
  104. package/dist/types/forkChoice.js +1 -0
  105. package/dist/types/pipeline.d.ts +51 -2
  106. package/dist/types/stageflowManifest.d.ts +23 -0
  107. package/dist/types/stageflowManifest.js +1 -0
  108. package/dist/ui/assets/index-CFSzDZje.js +118 -0
  109. package/dist/ui/assets/{index-DCsDopak.css → index-DefBlEvN.css} +1 -1
  110. package/dist/ui/index.html +3 -2
  111. package/dist/ui/stageflow-icon.svg +12 -0
  112. package/package.json +7 -5
  113. package/dist/ui/assets/index-Cry0Tpfx.js +0 -118
@@ -0,0 +1,44 @@
1
+ import { access } from "node:fs/promises";
2
+ import { loadPipeline } from "../config/loadPipeline.js";
3
+ import { loadTask } from "../config/loadTask.js";
4
+ import { normalizeCatalogPath } from "../runstore/normalizeCatalogPath.js";
5
+ function missingLocator(field, runId) {
6
+ throw new Error(`Run ${runId} is missing ${field}; reload requires stored catalog locators.`);
7
+ }
8
+ function requireProjectRoot(meta) {
9
+ if (!meta.project_root) {
10
+ missingLocator("project_root", meta.run_id);
11
+ }
12
+ return normalizeCatalogPath(meta.project_root);
13
+ }
14
+ function requirePipelinePath(meta) {
15
+ if (!meta.pipeline_path) {
16
+ missingLocator("pipeline_path", meta.run_id);
17
+ }
18
+ return normalizeCatalogPath(meta.pipeline_path);
19
+ }
20
+ function requireTaskPath(meta) {
21
+ if (!meta.task_path) {
22
+ missingLocator("task_path", meta.run_id);
23
+ }
24
+ return normalizeCatalogPath(meta.task_path);
25
+ }
26
+ async function assertCatalogFileExists(filePath, label) {
27
+ try {
28
+ await access(filePath);
29
+ }
30
+ catch {
31
+ throw new Error(`${label} not found at stored path: ${filePath}`);
32
+ }
33
+ }
34
+ export async function reloadPipelineForRun(meta) {
35
+ const projectRoot = requireProjectRoot(meta);
36
+ const pipelinePath = requirePipelinePath(meta);
37
+ await assertCatalogFileExists(pipelinePath, "Pipeline");
38
+ return loadPipeline(pipelinePath, { cwd: projectRoot });
39
+ }
40
+ export async function reloadTaskForRun(meta) {
41
+ const taskPath = requireTaskPath(meta);
42
+ await assertCatalogFileExists(taskPath, "Task");
43
+ return loadTask(taskPath);
44
+ }
@@ -16,6 +16,7 @@ export type PreparedResumeContext = {
16
16
  executionMode: StageExecutionMode;
17
17
  stageProcessLauncher?: StageProcessLauncher;
18
18
  cwd: string;
19
+ factoryCwd?: string;
19
20
  maxActiveStagesPerRun: number;
20
21
  operatorCatalog?: OperatorCatalog;
21
22
  };
@@ -1,7 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
2
3
  import { fakeHitlResumePath } from "../agent/fakeAgent.js";
3
- import { loadPipeline } from "../config/loadPipeline.js";
4
4
  import { loadTaskFromYaml } from "../config/loadTask.js";
5
+ import { normalizeCatalogPath } from "../runstore/normalizeCatalogPath.js";
6
+ import { reloadPipelineForRun, reloadTaskForRun, } from "./reloadRunCatalog.js";
5
7
  import { WAIT_WITHOUT_WORKER_DISPATCH } from "./answerResume.js";
6
8
  import { resumeRun } from "./pipelineScheduler.js";
7
9
  import { buildStageRoots, withResolvedAuthPath } from "./stageRoots.js";
@@ -10,14 +12,27 @@ import { attemptContext } from "./stageAttemptContext.js";
10
12
  import { openStageAttempt, } from "./stageAttemptBootstrap.js";
11
13
  export async function loadRunContext(store, runId, cwd) {
12
14
  const meta = await store.readRunMeta(runId);
13
- const taskYaml = await store.readTaskYaml(runId);
14
- const task = loadTaskFromYaml(taskYaml, `run ${runId} task`);
15
- const loaded = await loadPipeline(meta.pipeline_id, { cwd });
15
+ const reloadMeta = {
16
+ ...meta,
17
+ project_root: meta.project_root ?? normalizeCatalogPath(cwd),
18
+ };
19
+ const loaded = await reloadPipelineForRun(reloadMeta);
20
+ let taskYaml;
21
+ let task;
22
+ if (meta.task_path) {
23
+ task = await reloadTaskForRun(meta);
24
+ taskYaml = await readFile(normalizeCatalogPath(meta.task_path), "utf8");
25
+ }
26
+ else {
27
+ taskYaml = await store.readTaskYaml(runId);
28
+ task = loadTaskFromYaml(taskYaml, `run ${runId} task`);
29
+ }
16
30
  const workspaceDir = store.getWorkspaceDir(runId);
17
31
  return { meta, taskYaml, task, loaded, workspaceDir };
18
32
  }
19
33
  export async function reconstructAndContinue(ctx) {
20
34
  const { runId, stageId, opaqueAnswer, agent, store, cwd } = ctx;
35
+ const factoryCwd = ctx.factoryCwd ?? cwd;
21
36
  try {
22
37
  const latestExecution = await store.getLatestStageExecution(runId, stageId);
23
38
  const attemptCtx = attemptContext(latestExecution?.attempt ?? 1);
@@ -36,7 +51,7 @@ export async function reconstructAndContinue(ctx) {
36
51
  const stage = loaded.stages[stageIndex];
37
52
  const workspaceDir = store.getWorkspaceDir(runId);
38
53
  const checkoutRoot = meta.checkout_root;
39
- const roots = withResolvedAuthPath(buildStageRoots(workspaceDir, stageId, checkoutRoot, attemptCtx), cwd);
54
+ const roots = withResolvedAuthPath(buildStageRoots(workspaceDir, stageId, checkoutRoot, attemptCtx), factoryCwd);
40
55
  const fakeResume = fakeHitlResumePath(roots, stageId);
41
56
  const piSession = attemptCtx.sessionPath(workspaceDir, stageId);
42
57
  if (!existsSync(fakeResume) && !existsSync(piSession)) {
@@ -57,7 +72,7 @@ export async function reconstructAndContinue(ctx) {
57
72
  dag: loaded.dag,
58
73
  checkoutRoot,
59
74
  workspaceDir,
60
- factoryCwd: cwd,
75
+ factoryCwd,
61
76
  attemptCtx,
62
77
  operatorCatalog: ctx.operatorCatalog,
63
78
  onActivity: (event) => {
@@ -86,7 +101,7 @@ export async function reconstructAndContinue(ctx) {
86
101
  skipStarted: true,
87
102
  existingHandle: opened.handle,
88
103
  attemptCtx,
89
- factoryCwd: cwd,
104
+ factoryCwd,
90
105
  operatorCatalog: ctx.operatorCatalog,
91
106
  });
92
107
  if (isRunStageWaiting(result)) {
@@ -108,6 +123,7 @@ export async function reconstructAndContinue(ctx) {
108
123
  agent,
109
124
  store,
110
125
  cwd,
126
+ projectRoot: factoryCwd,
111
127
  checkoutRoot,
112
128
  hitl: ctx.hitl,
113
129
  operatorCatalog: ctx.operatorCatalog,
@@ -61,10 +61,14 @@ export declare class RunManager {
61
61
  private readonly retryCoordinator;
62
62
  private readonly retryTracking;
63
63
  private readonly cwd;
64
+ private readonly projectRoot;
65
+ private readonly isGitProject;
64
66
  constructor(options: {
65
67
  agent: AgentPort;
66
68
  store: RunStore;
67
69
  cwd?: string;
70
+ projectRoot?: string;
71
+ isGitProject?: boolean;
68
72
  operatorCatalog?: OperatorCatalog;
69
73
  seams?: HitlSeams;
70
74
  maxConcurrent?: number;
@@ -1,14 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { readFile, realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { loadPipeline } from "../config/loadPipeline.js";
4
+ import { normalizeCatalogPath } from "../runstore/normalizeCatalogPath.js";
5
+ import { loadRunContext } from "./resumeReconstruct.js";
5
6
  import { loadTaskFromYaml } from "../config/loadTask.js";
6
7
  import { PipelineValidationError, startPipeline, } from "./pipelineRunner.js";
7
8
  import { resumeRun } from "./pipelineScheduler.js";
8
9
  import { RunRetryCoordinator, } from "./runRetryCoordinator.js";
9
10
  import { readMaxActiveStageProcesses, readMaxActiveStagesPerRun, readStageExecutionMode, } from "./stageConcurrency.js";
10
11
  import { StageProcessLauncher } from "./stageProcessLauncher.js";
11
- import { INVALID_SLOT_COUNT_MESSAGE, parseSlotCount, readMaxConcurrentFromFile, writeMaxConcurrentToFile, } from "./settingsFile.js";
12
+ import { INVALID_SLOT_COUNT_MESSAGE, parseSlotCount, projectSettingsContext, readMaxConcurrentFromContext, writeMaxConcurrentToContext, } from "./settingsFile.js";
12
13
  import { StageHitlController, waitKey, } from "./stageHitl.js";
13
14
  import { resolveAndValidateCheckout, } from "./stageRoots.js";
14
15
  import { orchestrateAnswerResume } from "./answerResume.js";
@@ -79,12 +80,17 @@ export class RunManager {
79
80
  },
80
81
  };
81
82
  cwd;
83
+ projectRoot;
84
+ isGitProject;
82
85
  constructor(options) {
83
86
  this.options = options;
84
87
  this.cwd = options.cwd ?? process.cwd();
88
+ this.projectRoot = options.projectRoot ?? this.cwd;
89
+ this.isGitProject = options.isGitProject ?? false;
90
+ const settingsCtx = projectSettingsContext(this.cwd, this.projectRoot, this.isGitProject);
85
91
  this.maxConcurrent =
86
92
  options.maxConcurrent ??
87
- readMaxConcurrentFromFile(this.cwd) ??
93
+ readMaxConcurrentFromContext(settingsCtx) ??
88
94
  parseMaxConcurrent(process.env.STAGEFLOW_MAX_CONCURRENT_RUNS);
89
95
  this.maxActiveStagesPerRun = readMaxActiveStagesPerRun(process.env, options.maxActiveStagesPerRun);
90
96
  this.executionMode = readStageExecutionMode(process.env, options.executionMode);
@@ -106,7 +112,7 @@ export class RunManager {
106
112
  throw new Error(INVALID_SLOT_COUNT_MESSAGE);
107
113
  }
108
114
  this.maxConcurrent = parsed;
109
- writeMaxConcurrentToFile(this.cwd, parsed);
115
+ writeMaxConcurrentToContext(projectSettingsContext(this.cwd, this.projectRoot, this.isGitProject), parsed);
110
116
  return this.getHealth();
111
117
  }
112
118
  getActiveCount() {
@@ -355,17 +361,32 @@ export class RunManager {
355
361
  }
356
362
  async rerun(runId) {
357
363
  const cwd = this.options.cwd ?? process.cwd();
358
- let pipelineId;
364
+ let pipeline;
359
365
  let taskYaml;
366
+ let rerunCwd = cwd;
367
+ let rerunProjectRoot;
360
368
  try {
361
369
  const meta = await this.options.store.readRunMeta(runId);
362
- pipelineId = meta.pipeline_id;
370
+ if (!meta.pipeline_path) {
371
+ return {
372
+ ok: false,
373
+ reason: `Run ${runId} is missing pipeline_path; re-run requires stored catalog locators.`,
374
+ status: 400,
375
+ };
376
+ }
377
+ pipeline = normalizeCatalogPath(meta.pipeline_path);
378
+ rerunCwd = meta.project_root
379
+ ? normalizeCatalogPath(meta.project_root)
380
+ : cwd;
381
+ rerunProjectRoot = meta.project_root
382
+ ? normalizeCatalogPath(meta.project_root)
383
+ : undefined;
363
384
  taskYaml = await this.options.store.readTaskYaml(runId);
364
385
  }
365
386
  catch {
366
387
  return { ok: false, reason: `Run not found: ${runId}`, status: 404 };
367
388
  }
368
- return this.reserveAndStartPipeline(taskYaml, pipelineId, `run ${runId} task`, cwd);
389
+ return this.reserveAndStartPipeline(taskYaml, pipeline, `run ${runId} task`, rerunCwd, undefined, undefined, undefined, rerunProjectRoot);
369
390
  }
370
391
  async retryStage(runId, stageId) {
371
392
  const retryKey = waitKey(runId, stageId);
@@ -489,7 +510,6 @@ export class RunManager {
489
510
  }
490
511
  }
491
512
  async resumeViaSubprocess(runId, stageId, opaqueAnswer) {
492
- const cwd = this.options.cwd ?? process.cwd();
493
513
  const store = this.options.store;
494
514
  const launcher = this.stageProcessLauncher;
495
515
  if (!launcher) {
@@ -504,7 +524,7 @@ export class RunManager {
504
524
  const launchResult = await launcher.launch({
505
525
  runId,
506
526
  stageId,
507
- rootDir: cwd,
527
+ rootDir: this.projectRoot,
508
528
  mode: "resume",
509
529
  resumeAnswer: opaqueAnswer,
510
530
  attempt,
@@ -531,10 +551,7 @@ export class RunManager {
531
551
  catch {
532
552
  // downstream resume may read envelope from store
533
553
  }
534
- const meta = await store.readRunMeta(runId);
535
- const taskYaml = await store.readTaskYaml(runId);
536
- const task = loadTaskFromYaml(taskYaml, `run ${runId} task`);
537
- const loaded = await loadPipeline(meta.pipeline_id, { cwd });
554
+ const { meta, task, loaded } = await loadRunContext(store, runId, this.cwd);
538
555
  const rest = await resumeRun({
539
556
  prepared: {
540
557
  task,
@@ -542,7 +559,8 @@ export class RunManager {
542
559
  run: { runId, workspaceDir: store.getWorkspaceDir(runId) },
543
560
  agent: this.options.agent,
544
561
  store,
545
- cwd,
562
+ cwd: this.cwd,
563
+ projectRoot: this.projectRoot,
546
564
  checkoutRoot: meta.checkout_root,
547
565
  hitl: this.hitl,
548
566
  operatorCatalog: this.options.operatorCatalog,
@@ -590,6 +608,7 @@ export class RunManager {
590
608
  executionMode: this.executionMode,
591
609
  stageProcessLauncher: this.stageProcessLauncher,
592
610
  cwd: this.cwd,
611
+ factoryCwd: this.projectRoot,
593
612
  maxActiveStagesPerRun: this.maxActiveStagesPerRun,
594
613
  operatorCatalog: this.options.operatorCatalog,
595
614
  });
@@ -598,7 +617,7 @@ export class RunManager {
598
617
  this.attachedWaiting.delete(`${runId}\0${stageId}`);
599
618
  }
600
619
  }
601
- async reserveAndStartPipeline(taskYaml, pipelineId, taskLabel, cwd, checkoutOverride, skipGates, ciIdentity) {
620
+ async reserveAndStartPipeline(taskYaml, pipeline, taskLabel, cwd, checkoutOverride, skipGates, ciIdentity, projectRoot) {
602
621
  let checkoutKey;
603
622
  try {
604
623
  const task = loadTaskFromYaml(taskYaml, taskLabel);
@@ -623,8 +642,9 @@ export class RunManager {
623
642
  agent: this.options.agent,
624
643
  store: this.options.store,
625
644
  taskYaml,
626
- pipeline: pipelineId,
645
+ pipeline,
627
646
  cwd,
647
+ projectRoot: projectRoot ?? this.projectRoot,
628
648
  checkoutOverride,
629
649
  gitSha: ciIdentity?.gitSha,
630
650
  ciPrUrl: ciIdentity?.ciPrUrl,
@@ -1,3 +1,5 @@
1
+ import type { ProjectContext } from "../project/resolveProjectContext.js";
2
+ import type { StageflowContext } from "../project/resolveStageflowContext.js";
1
3
  export declare const SETTINGS_FILE_NAME = "settings.json";
2
4
  export declare const INVALID_SLOT_COUNT_MESSAGE = "maxConcurrent must be an integer >= 1";
3
5
  export declare const INVALID_CREDENTIAL_SOURCE_MESSAGE = "credentialSource must be \"pi_home\" or \"sf_owned\"";
@@ -6,12 +8,22 @@ export type FactorySettings = {
6
8
  maxConcurrent?: number;
7
9
  credentialSource?: CredentialSource;
8
10
  };
11
+ export declare function globalSettingsFilePath(): string;
12
+ export declare function settingsFilePathForContext(ctx: ProjectContext | StageflowContext): string;
9
13
  export declare function settingsFilePath(cwd: string): string;
10
14
  export declare function parseSlotCount(value: unknown): number | undefined;
11
15
  export declare function parseCredentialSource(value: unknown): CredentialSource | undefined;
16
+ export declare function readCredentialSourceFromContext(ctx: ProjectContext): CredentialSource | undefined;
17
+ export declare function readPersistedCredentialSourceFromContext(ctx: ProjectContext): CredentialSource | undefined;
18
+ export declare function readFactorySettingsForContext(ctx: ProjectContext): FactorySettings;
12
19
  export declare function readFactorySettings(cwd: string): FactorySettings;
20
+ export declare function writeFactorySettingsForContext(ctx: ProjectContext, patch: FactorySettings): void;
13
21
  export declare function writeFactorySettings(cwd: string, patch: FactorySettings): void;
22
+ export declare function readMaxConcurrentFromContext(ctx: ProjectContext): number | undefined;
14
23
  export declare function readMaxConcurrentFromFile(cwd: string): number | undefined;
24
+ export declare function writeMaxConcurrentToContext(ctx: ProjectContext, maxConcurrent: number): void;
15
25
  export declare function writeMaxConcurrentToFile(cwd: string, maxConcurrent: number): void;
16
26
  export declare function readCredentialSourceFromFile(cwd: string): CredentialSource | undefined;
27
+ export declare function writeCredentialSourceToContext(ctx: ProjectContext, credentialSource: CredentialSource): void;
17
28
  export declare function writeCredentialSourceToFile(cwd: string, credentialSource: CredentialSource): void;
29
+ export declare function projectSettingsContext(cwd: string, projectRoot: string, isGitProject: boolean): ProjectContext;
@@ -1,11 +1,25 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import os from "node:os";
2
3
  import path from "node:path";
4
+ import { globalStageflowHome } from "../project/globalHome.js";
3
5
  import { storeRootFor } from "../runstore/paths.js";
4
6
  export const SETTINGS_FILE_NAME = "settings.json";
5
7
  export const INVALID_SLOT_COUNT_MESSAGE = "maxConcurrent must be an integer >= 1";
6
8
  export const INVALID_CREDENTIAL_SOURCE_MESSAGE = 'credentialSource must be "pi_home" or "sf_owned"';
9
+ export function globalSettingsFilePath() {
10
+ return path.join(globalStageflowHome(), SETTINGS_FILE_NAME);
11
+ }
12
+ export function settingsFilePathForContext(ctx) {
13
+ if (ctx.isGitProject) {
14
+ return path.join(storeRootFor(ctx.projectRoot), SETTINGS_FILE_NAME);
15
+ }
16
+ if (path.resolve(ctx.projectRoot) === path.resolve(os.homedir())) {
17
+ return path.join(ctx.globalHome, SETTINGS_FILE_NAME);
18
+ }
19
+ return path.join(storeRootFor(ctx.projectRoot), SETTINGS_FILE_NAME);
20
+ }
7
21
  export function settingsFilePath(cwd) {
8
- return path.join(storeRootFor(cwd), SETTINGS_FILE_NAME);
22
+ return path.join(storeRootFor(path.resolve(cwd)), SETTINGS_FILE_NAME);
9
23
  }
10
24
  export function parseSlotCount(value) {
11
25
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
@@ -19,8 +33,7 @@ export function parseCredentialSource(value) {
19
33
  }
20
34
  return undefined;
21
35
  }
22
- function readRawSettings(cwd) {
23
- const filePath = settingsFilePath(cwd);
36
+ function readRawSettingsFromFile(filePath) {
24
37
  if (!existsSync(filePath))
25
38
  return {};
26
39
  try {
@@ -34,8 +47,10 @@ function readRawSettings(cwd) {
34
47
  return {};
35
48
  }
36
49
  }
37
- export function readFactorySettings(cwd) {
38
- const raw = readRawSettings(cwd);
50
+ function readRawSettings(ctx) {
51
+ return readRawSettingsFromFile(settingsFilePathForContext(ctx));
52
+ }
53
+ function parseFactorySettingsFromRaw(raw) {
39
54
  const settings = {};
40
55
  const maxConcurrent = parseSlotCount(raw.maxConcurrent);
41
56
  if (maxConcurrent !== undefined) {
@@ -47,6 +62,54 @@ export function readFactorySettings(cwd) {
47
62
  }
48
63
  return settings;
49
64
  }
65
+ export function readCredentialSourceFromContext(ctx) {
66
+ if (ctx.isGitProject) {
67
+ const fromProject = parseCredentialSource(readRawSettingsFromFile(settingsFilePathForContext(ctx)).credentialSource);
68
+ if (fromProject !== undefined) {
69
+ return fromProject;
70
+ }
71
+ }
72
+ return parseCredentialSource(readRawSettingsFromFile(globalSettingsFilePath()).credentialSource);
73
+ }
74
+ export function readPersistedCredentialSourceFromContext(ctx) {
75
+ return parseCredentialSource(readRawSettingsFromFile(settingsFilePathForContext(ctx)).credentialSource);
76
+ }
77
+ export function readFactorySettingsForContext(ctx) {
78
+ return parseFactorySettingsFromRaw(readRawSettings(ctx));
79
+ }
80
+ export function readFactorySettings(cwd) {
81
+ return parseFactorySettingsFromRaw(readRawSettingsFromFile(settingsFilePath(cwd)));
82
+ }
83
+ function ensureSettingsDirForContext(ctx) {
84
+ mkdirSync(path.dirname(settingsFilePathForContext(ctx)), { recursive: true });
85
+ }
86
+ export function writeFactorySettingsForContext(ctx, patch) {
87
+ if (patch.credentialSource !== undefined &&
88
+ parseCredentialSource(patch.credentialSource) === undefined) {
89
+ throw new Error(INVALID_CREDENTIAL_SOURCE_MESSAGE);
90
+ }
91
+ if (patch.maxConcurrent !== undefined &&
92
+ parseSlotCount(patch.maxConcurrent) === undefined) {
93
+ throw new Error(INVALID_SLOT_COUNT_MESSAGE);
94
+ }
95
+ const current = readFactorySettingsForContext(ctx);
96
+ const next = { ...current };
97
+ if (patch.maxConcurrent !== undefined) {
98
+ next.maxConcurrent = patch.maxConcurrent;
99
+ }
100
+ if (patch.credentialSource !== undefined) {
101
+ next.credentialSource = patch.credentialSource;
102
+ }
103
+ const out = {};
104
+ if (next.maxConcurrent !== undefined) {
105
+ out.maxConcurrent = next.maxConcurrent;
106
+ }
107
+ if (next.credentialSource !== undefined) {
108
+ out.credentialSource = next.credentialSource;
109
+ }
110
+ ensureSettingsDirForContext(ctx);
111
+ writeFileSync(settingsFilePathForContext(ctx), `${JSON.stringify(out, null, 2)}\n`, "utf8");
112
+ }
50
113
  export function writeFactorySettings(cwd, patch) {
51
114
  if (patch.credentialSource !== undefined &&
52
115
  parseCredentialSource(patch.credentialSource) === undefined) {
@@ -71,18 +134,36 @@ export function writeFactorySettings(cwd, patch) {
71
134
  if (next.credentialSource !== undefined) {
72
135
  out.credentialSource = next.credentialSource;
73
136
  }
74
- mkdirSync(storeRootFor(cwd), { recursive: true });
137
+ const root = path.resolve(cwd);
138
+ mkdirSync(storeRootFor(root), { recursive: true });
75
139
  writeFileSync(settingsFilePath(cwd), `${JSON.stringify(out, null, 2)}\n`, "utf8");
76
140
  }
141
+ export function readMaxConcurrentFromContext(ctx) {
142
+ return readFactorySettingsForContext(ctx).maxConcurrent;
143
+ }
77
144
  export function readMaxConcurrentFromFile(cwd) {
78
145
  return readFactorySettings(cwd).maxConcurrent;
79
146
  }
147
+ export function writeMaxConcurrentToContext(ctx, maxConcurrent) {
148
+ writeFactorySettingsForContext(ctx, { maxConcurrent });
149
+ }
80
150
  export function writeMaxConcurrentToFile(cwd, maxConcurrent) {
81
151
  writeFactorySettings(cwd, { maxConcurrent });
82
152
  }
83
153
  export function readCredentialSourceFromFile(cwd) {
84
154
  return readFactorySettings(cwd).credentialSource;
85
155
  }
156
+ export function writeCredentialSourceToContext(ctx, credentialSource) {
157
+ writeFactorySettingsForContext(ctx, { credentialSource });
158
+ }
86
159
  export function writeCredentialSourceToFile(cwd, credentialSource) {
87
160
  writeFactorySettings(cwd, { credentialSource });
88
161
  }
162
+ export function projectSettingsContext(cwd, projectRoot, isGitProject) {
163
+ return {
164
+ invocationCwd: path.resolve(cwd),
165
+ projectRoot: path.resolve(projectRoot),
166
+ globalHome: globalStageflowHome(),
167
+ isGitProject,
168
+ };
169
+ }
@@ -1,4 +1,5 @@
1
1
  import { resolveSkillByName } from "../config/listSkills.js";
2
+ import { resolveForkEmitContext } from "../config/resolveForkEmitContext.js";
2
3
  import { buildCompletedEnvelopesFromRun, resolvePriorEnvelope, } from "./envelopeRouting.js";
3
4
  import { resumeSessionFilePath } from "./stageAttemptContext.js";
4
5
  import { buildStageRoots, rootsForStageWorker, withResolvedAuthPath, } from "./stageRoots.js";
@@ -63,6 +64,7 @@ export async function openStageAttempt(input) {
63
64
  const attempt = input.attemptCtx?.attempt ?? 1;
64
65
  const resumeToken = input.resumeToken ??
65
66
  resumeSessionFilePath(input.workspaceDir, input.stage.id, attempt);
67
+ const forkEmitContext = resolveForkEmitContext(input.dag, input.stage.id);
66
68
  const opened = await openStageWithOperatorCatalog(input.agent, {
67
69
  roots,
68
70
  stage: input.stage,
@@ -70,6 +72,7 @@ export async function openStageAttempt(input) {
70
72
  priorEnvelope: priorResult.prior,
71
73
  resumeToken,
72
74
  onActivity: input.onActivity,
75
+ forkEmitContext,
73
76
  }, input.operatorCatalog);
74
77
  if (!opened.ok)
75
78
  return opened;
@@ -132,6 +132,9 @@ export class StageProcessLauncher {
132
132
  if (input.sessionFilePath !== undefined) {
133
133
  args.push("--session-file", input.sessionFilePath);
134
134
  }
135
+ if (input.operatorCatalog?.cwd !== undefined) {
136
+ args.push("--operator-cwd", input.operatorCatalog.cwd);
137
+ }
135
138
  if (input.operatorCatalog?.agentDir !== undefined) {
136
139
  args.push("--operator-agent-dir", input.operatorCatalog.agentDir);
137
140
  }
@@ -34,9 +34,11 @@ export async function failStageAsInterrupted(options) {
34
34
  }
35
35
  }
36
36
  export async function syncRunStatusFromStages(store, runId) {
37
+ const meta = await store.readRunMeta(runId);
38
+ if (meta.status === "succeeded")
39
+ return;
37
40
  const run = await store.readRun(runId);
38
41
  const derived = deriveStatusFromStages(run.stages);
39
- const meta = await store.readRunMeta(runId);
40
42
  if ((meta.status ?? "created") !== derived) {
41
43
  await store.updateRunStatus(runId, derived);
42
44
  }
@@ -1,7 +1,6 @@
1
1
  import { PiAgentAdapter } from "../agent/piAdapter.js";
2
- import { loadPipeline } from "../config/loadPipeline.js";
3
- import { loadTaskFromYaml } from "../config/loadTask.js";
4
2
  import { createRunStore } from "../runstore/createStore.js";
3
+ import { loadRunContext } from "./resumeReconstruct.js";
5
4
  import { bindPiAgentDirEnv, rootsForStageWorker, withResolvedAuthPath, } from "./stageRoots.js";
6
5
  import { runStage, isRunStageWaiting, } from "./stageRunner.js";
7
6
  import { openStageAttempt } from "./stageAttemptBootstrap.js";
@@ -9,10 +8,7 @@ import { attemptContext } from "./stageAttemptContext.js";
9
8
  import { outcomeToWorkerResult, STAGE_WORKER_EXIT, } from "./stageWorkerProtocol.js";
10
9
  export async function runStageWorker(input) {
11
10
  const store = createRunStore({ rootDir: input.rootDir });
12
- const meta = await store.readRunMeta(input.runId);
13
- const taskYaml = await store.readTaskYaml(input.runId);
14
- const task = loadTaskFromYaml(taskYaml, `run ${input.runId} task`);
15
- const loaded = await loadPipeline(meta.pipeline_id, { cwd: input.rootDir });
11
+ const { meta, task, loaded } = await loadRunContext(store, input.runId, input.rootDir);
16
12
  const stage = loaded.stages.find((s) => s.id === input.stageId);
17
13
  if (!stage) {
18
14
  return {
@@ -8,12 +8,14 @@ import { getCredentialSourceSettings, setCredentialSource, } from "../agent/prov
8
8
  import { handleProviderRoutes, providerAuthErrorBody, } from "./providerRoutes.js";
9
9
  import { createPipeline, parseCreatePipelineBody } from "../config/createPipeline.js";
10
10
  import { createStage, parseCreateStageBody } from "../config/createStage.js";
11
- import { listModels, listPipelines, listStages, listTasks, } from "../config/listConfig.js";
11
+ import { browseCatalog } from "../config/browseCatalog.js";
12
12
  import { listExtensions } from "../config/listExtensions.js";
13
13
  import { listSkills } from "../config/listSkills.js";
14
14
  import { readRunArtifact } from "../mcp/readArtifact.js";
15
15
  import { handleMcpHttpRequest } from "../mcp/server.js";
16
16
  import { createRunStore } from "../runstore/createStore.js";
17
+ import { resolveStageflowContext } from "../project/resolveStageflowContext.js";
18
+ import { findProjectRoot } from "../project/findProjectRoot.js";
17
19
  import { RunManager, } from "../runtime/runManager.js";
18
20
  import { INVALID_SLOT_COUNT_MESSAGE, parseSlotCount, } from "../runtime/settingsFile.js";
19
21
  import { isTaskFile } from "../runtime/taskInput.js";
@@ -202,9 +204,14 @@ export function defaultUiDistDir() {
202
204
  return path.resolve(here, "../ui");
203
205
  }
204
206
  export async function startUiServer(options) {
205
- const cwd = options.cwd ?? process.cwd();
207
+ const invocationCwd = options.cwd ?? process.cwd();
208
+ const ctx = await resolveStageflowContext(invocationCwd);
209
+ const cwd = ctx.invocationCwd;
206
210
  const agentDir = options.agentDir ?? getAgentDir();
207
- const rootDir = options.rootDir ?? cwd;
211
+ const rootDir = options.rootDir ?? ctx.projectRoot;
212
+ const isGitProject = options.rootDir !== undefined
213
+ ? findProjectRoot(rootDir) !== null
214
+ : ctx.isGitProject;
208
215
  const host = options.host ?? "127.0.0.1";
209
216
  const port = options.port ?? DEFAULT_PORT;
210
217
  const providerAuthContext = options.providerAuthContext;
@@ -214,6 +221,8 @@ export async function startUiServer(options) {
214
221
  const manager = new RunManager({
215
222
  agent: options.agent,
216
223
  cwd,
224
+ projectRoot: rootDir,
225
+ isGitProject,
217
226
  store,
218
227
  maxConcurrent: options.maxConcurrent,
219
228
  operatorCatalog: { cwd, agentDir },
@@ -388,15 +397,19 @@ export async function startUiServer(options) {
388
397
  return;
389
398
  }
390
399
  if (method === "GET" && pathname === "/api/tasks") {
391
- json(res, 200, { tasks: await listTasks(cwd) });
400
+ const catalog = await browseCatalog(cwd);
401
+ json(res, 200, { tasks: catalog.tasks });
392
402
  return;
393
403
  }
394
404
  if (method === "GET" && pathname === "/api/pipelines") {
395
- json(res, 200, { pipelines: await listPipelines(cwd) });
405
+ const catalog = await browseCatalog(cwd);
406
+ json(res, 200, { pipelines: catalog.pipelines });
396
407
  return;
397
408
  }
398
409
  if (method === "GET" && pathname === "/api/stages") {
399
- json(res, 200, { stages: await listStages(cwd) });
410
+ json(res, 404, {
411
+ error: "Global stage library removed; stages are pipeline-scoped",
412
+ });
400
413
  return;
401
414
  }
402
415
  if (method === "POST" && pathname === "/api/stages") {
@@ -413,7 +426,12 @@ export async function startUiServer(options) {
413
426
  json(res, parsed.status, { error: parsed.error });
414
427
  return;
415
428
  }
416
- const result = await createStage(cwd, parsed);
429
+ const ctx = await resolveStageflowContext(cwd);
430
+ if (!ctx.isGitProject) {
431
+ json(res, 400, { error: "Project root not found; initialize stageflow.yaml in a git repo" });
432
+ return;
433
+ }
434
+ const result = await createStage(ctx.projectRoot, parsed);
417
435
  if (!result.ok) {
418
436
  json(res, result.status, { error: result.error });
419
437
  return;
@@ -435,7 +453,12 @@ export async function startUiServer(options) {
435
453
  json(res, parsed.status, { error: parsed.error });
436
454
  return;
437
455
  }
438
- const result = await createPipeline(cwd, parsed);
456
+ const ctx = await resolveStageflowContext(cwd);
457
+ if (!ctx.isGitProject) {
458
+ json(res, 400, { error: "Project root not found; initialize stageflow.yaml in a git repo" });
459
+ return;
460
+ }
461
+ const result = await createPipeline(ctx.projectRoot, parsed);
439
462
  if (!result.ok) {
440
463
  json(res, result.status, { error: result.error });
441
464
  return;
@@ -444,7 +467,8 @@ export async function startUiServer(options) {
444
467
  return;
445
468
  }
446
469
  if (method === "GET" && pathname === "/api/models") {
447
- json(res, 200, { models: await listModels(cwd) });
470
+ const catalog = await browseCatalog(cwd);
471
+ json(res, 200, { models: catalog.models });
448
472
  return;
449
473
  }
450
474
  if (await handleProviderRoutes(req, res, {
@@ -11,11 +11,12 @@
11
11
  */
12
12
  import { Type } from "typebox";
13
13
  import type { StageEnvelope } from "../types/envelope.js";
14
+ import type { ForkEmitContext } from "../types/forkChoice.js";
14
15
  export type EmitCapture = {
15
16
  envelope?: StageEnvelope;
16
17
  error?: string;
17
18
  };
18
- export declare function createEmitStageEnvelopeTool(capture: EmitCapture, payloadSchema?: unknown): {
19
+ export declare function createEmitStageEnvelopeTool(capture: EmitCapture, payloadSchema?: unknown, forkEmitContext?: ForkEmitContext): {
19
20
  name: string;
20
21
  label: string;
21
22
  description: string;
@@ -24,6 +25,7 @@ export declare function createEmitStageEnvelopeTool(capture: EmitCapture, payloa
24
25
  summary: Type.TString;
25
26
  artifacts: Type.TArray<Type.TString>;
26
27
  payload: Type.TSchema;
28
+ fork_choice: Type.TArray<Type.TString>;
27
29
  stage_id: Type.TOptional<Type.TString>;
28
30
  notes: Type.TOptional<Type.TString>;
29
31
  }>;