@leitwerk-dev/coding 0.4.0 → 0.4.2

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 (46) hide show
  1. package/README.md +67 -11
  2. package/dist/{chunk-Q24RPXOA.js → chunk-3WJRJ3Q7.js} +68 -7
  3. package/dist/chunk-3WJRJ3Q7.js.map +1 -0
  4. package/dist/chunk-B3PE6DPF.js +820 -0
  5. package/dist/chunk-B3PE6DPF.js.map +1 -0
  6. package/dist/chunk-E3DB4TIZ.js +49 -0
  7. package/dist/chunk-E3DB4TIZ.js.map +1 -0
  8. package/dist/{chunk-BI45R2FH.js → chunk-QD6FI4HR.js} +1 -1
  9. package/dist/chunk-QD6FI4HR.js.map +1 -0
  10. package/dist/finalization-git-internal.d.ts +6 -0
  11. package/dist/finalization-git-internal.d.ts.map +1 -1
  12. package/dist/finalization-git.js +2 -1
  13. package/dist/index.js +3 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/pull-request-publication-internal.d.ts +8 -0
  16. package/dist/pull-request-publication-internal.d.ts.map +1 -1
  17. package/dist/repository-change-process.d.ts.map +1 -1
  18. package/dist/repository-change-publication.d.ts +16 -3
  19. package/dist/repository-change-publication.d.ts.map +1 -1
  20. package/dist/repository-change-publication.js +283 -69
  21. package/dist/repository-change-publication.js.map +1 -1
  22. package/dist/repository-publication-receipt.d.ts +23 -0
  23. package/dist/repository-publication-receipt.d.ts.map +1 -0
  24. package/dist/repository-rebase/git.d.ts +8 -0
  25. package/dist/repository-rebase/git.d.ts.map +1 -1
  26. package/dist/repository-reconciliation.d.ts +47 -0
  27. package/dist/repository-reconciliation.d.ts.map +1 -0
  28. package/dist/repository-record.d.ts +6 -0
  29. package/dist/repository-record.d.ts.map +1 -0
  30. package/dist/turns/implement.d.ts +1 -1
  31. package/dist/turns/implement.d.ts.map +1 -1
  32. package/dist/turns/implement.js +1 -1
  33. package/package.json +5 -5
  34. package/src/finalization-git-internal.ts +75 -6
  35. package/src/pull-request-publication-internal.ts +3 -2
  36. package/src/repository-change-process.ts +19 -2
  37. package/src/repository-change-publication.ts +243 -57
  38. package/src/repository-publication-receipt.ts +71 -0
  39. package/src/repository-rebase/git.ts +108 -29
  40. package/src/repository-reconciliation.ts +600 -0
  41. package/src/repository-record.ts +14 -0
  42. package/src/turns/implement.ts +4 -1
  43. package/dist/chunk-BI45R2FH.js.map +0 -1
  44. package/dist/chunk-OM2AMDTJ.js +0 -347
  45. package/dist/chunk-OM2AMDTJ.js.map +0 -1
  46. package/dist/chunk-Q24RPXOA.js.map +0 -1
package/README.md CHANGED
@@ -31,7 +31,7 @@ Worker diagnostics record each command's duration and outcome, with bounded Git
31
31
  Trace2 counters for metadata checks, content scans, and inspection phases. Raw
32
32
  Trace2 events, file contents, and paths are not stored in these diagnostics.
33
33
 
34
- `commitAndPushWorkBranch()` requires an explicit trusted Git identity, commits dirty workspace files, and pushes only the checked-out feature branch. It rejects invalid Git identity, unresolved conflicts, branch mismatches, and remote heads that do not match the committed HEAD.
34
+ `commitAndPushWorkBranch()` requires an explicit trusted Git identity, commits dirty workspace files, and pushes only the checked-out feature branch. Ordinary publication must retain the captured remote head as an ancestor. An exact-SHA lease also rejects concurrent rewinds; a successful push with a lost acknowledgement is recognized without another commit. Invalid identity, unresolved conflicts, branch mismatches and changed remote heads fail without discarding the local commit.
35
35
 
36
36
  Turn labels use short task names: Plan, Review Plan, Implement, and Review. Automated assessments use Assess Plan and Assess Implementation so operators can distinguish them from their own decisions. Repository-change processes share these labels and turn ids.
37
37
 
@@ -56,13 +56,64 @@ the existing process flow.
56
56
 
57
57
  ## Shared publication
58
58
 
59
- `createRepositoryChangePublication()` constructs the delivery, feedback, CI repair,
60
- rebase, and operator recovery fragment used by Forgejo, GitHub, and GitLab repository
61
- change processes. Its adapter supplies provider operations, native evidence sources,
62
- repair tools/prompts, pinned identity resolution, and stored names. The shared module
63
- owns Git publication and lifecycle policy without importing provider integrations.
64
- Provider cursors and receipts remain durable in namespaced publication state.
65
- Forgejo retains its original namespace, turn/action identifiers, and write identities.
59
+ `createRepositoryChangePublication()` builds shared delivery, feedback, CI/rebase
60
+ repair, and operator turns for Forgejo, GitHub, and GitLab. Adapters supply provider
61
+ operations, evidence sources, repair tools/prompts, and pinned identities.
62
+ `sourceCancelled`, `reconcileAll`, and `reconcileTerminal` receive
63
+ `PublicationReconciliationContext`: process, projects, params, state, and integration
64
+ calls, without worker filesystem access. Cursors and receipts remain namespaced;
65
+ Forgejo retains its namespace, turn/action IDs, and write identities.
66
+
67
+ ## Source-branch reconciliation
68
+
69
+ The remote source branch is authoritative. Implementation preparation captures the
70
+ local baseline before editing. Feedback and CI preparation fetch the current source
71
+ branch; delivery fetches again before publication. Observed revisions and historical
72
+ publication receipts are separate from the baseline for unpublished local work.
73
+ A developer push or rewritten history does not disable feedback handling.
74
+
75
+ Reconciliation replays only the local work since that baseline onto the current
76
+ remote revision. Previously published commits removed by a developer rewrite are
77
+ not restored. Unpublished commits, staged and unstaged edits, and non-ignored
78
+ untracked files survive synchronization. Dirty submodules, ignored-file collisions,
79
+ missing published branches, unrelated Git operations and unprovable baselines stop
80
+ with an explicit error rather than guessing or discarding files. Fetch and push must
81
+ use the same single origin endpoint. Previously ignored files are protected from
82
+ accidental publication if ignore rules change.
83
+
84
+ Before changing the checkout, private Git refs retain the original HEAD and separate
85
+ index/worktree checkpoint commits. A journal records the operation and its remote
86
+ revision. Git's rebase state and the journal survive worker replacement. After a
87
+ clean reconciliation, checkpoint commits are removed from the work branch and the
88
+ staged/unstaged distinction is restored. Replayed commits preserve original authors
89
+ and sign-offs, with the captured trusted project identity as committer. New integration
90
+ commits use that identity too; checkpoint identities never enter the published branch.
91
+ Recovery refs are retained; they are never included in feature-branch publication. Only the accepted worker may edit the
92
+ workspace. Deterministic reconciliation additionally takes a repository-local lock;
93
+ a lock from another host is not stolen automatically.
94
+
95
+ Conflicts use the existing adjustment turn. Its prompt permits rebase continuation
96
+ but prohibits skipping or removing checkpoint commits, resetting, aborting or
97
+ pushing. Delivery restores the normal checkout after resolution, then requests
98
+ validation of the combined result before publishing. A source change after validation
99
+ starts another reconciliation/validation pass; more than three automatic passes
100
+ require operator action. Explicit retry grants a new budget. No synchronization turns
101
+ are added to the process graph.
102
+
103
+ Publication records local write-ahead intent before sending a push and acceptance
104
+ before checking for subsequent remote movement. This receipt survives a lost server
105
+ acknowledgement: a later developer rewrite does not turn already-published work back
106
+ into an unpublished delta. Remote equality or ancestry can prove uncertain acceptance.
107
+ An explicit Git ref rejection proves no write; an unprovable transport outcome stops
108
+ for operator reconciliation rather than retrying over a possible developer rewind.
109
+ Missing branches with accepted or uncertain publication are never recreated
110
+ automatically. Receipts are recovery evidence on workspace storage; the server remains
111
+ the owner of durable process state.
112
+
113
+ Maintained processes route even `no_changes` through Deliver. It checks the remote
114
+ lease and publishes any retained unpublished work before acknowledging feedback.
115
+ An unchanged checkout creates no commit or push. A watcher may observe an active
116
+ worker's new remote head, but never mutates its checkout or captured baseline.
66
117
 
67
118
  ## Git rebase repair
68
119
 
@@ -93,8 +144,13 @@ incorporate the fetched base even if merging is clean. Interrupted rebases resum
93
144
  Git's existing state and preserve authors and sign-offs. Continuation verification
94
145
  rejects unfinished/aborted rebases, wrong branches and dirty results. Publication
95
146
  uses the original recorded head as an explicit lease, rejects concurrent pushes,
96
- and recognizes an already-published result after a lost response. Retained state
97
- and refs are not deleted on success or failure.
147
+ and recognizes an already-published result after a lost response. When its source
148
+ lease changes, shared delivery retains the completed repair and reconciles its net
149
+ change relative to the original source snapshot onto the latest remote branch.
150
+ Developer deletions and the agent's conflict resolutions both survive. The combined
151
+ result retains target-branch ancestry and requires validation before ordinary
152
+ leased fast-forward publication; delivery never substitutes a new lease into the
153
+ old force push. Retained state and refs are not deleted on success or failure.
98
154
 
99
155
  ## API support
100
156
 
@@ -104,7 +160,7 @@ The following exported declarations are `@public`:
104
160
  - `@leitwerk-dev/coding/auto-work-branch`: `buildAutoWorkBranchFromSeed`.
105
161
  - `@leitwerk-dev/coding/finalization-git`: `GitIdentity`, `commitAndPushWorkBranch`.
106
162
  - `@leitwerk-dev/coding/repository-change-launch`: `NormalizedRepositoryChangeParamsInput`, `RepositoryChangeLaunchParams`, `RepositoryChangeParamsBase`, `RepositoryIssueOriginParams`, `RepositoryUiOriginParams`, `createRepositoryChangeParamsCodec`, `normalizeRepositoryChangeParamsInput`, `repositoryChangeParamsRecord`.
107
- - `@leitwerk-dev/coding/repository-change-publication`: `DeliveryState`, `PublicationContext`, `PublicationEvidence`, `PublicationFeedbackId`, `PublicationParams`, `PublicationPipeline`, `PublicationRequest`, `PublicationSource`, `PublicationState`, `RepositoryChangePublicationAdapter`, `applyPublicationEvidence`, `createRepositoryChangePublication`, `patchPublicationState`, `publicationObject`, `readPublicationState`.
163
+ - `@leitwerk-dev/coding/repository-change-publication`: `DeliveryState`, `PublicationContext`, `PublicationReconciliationContext`, `PublicationEvidence`, `PublicationFeedbackId`, `PublicationParams`, `PublicationPipeline`, `PublicationRequest`, `PublicationSource`, `PublicationState`, `RepositoryChangePublicationAdapter`, `applyPublicationEvidence`, `createRepositoryChangePublication`, `patchPublicationState`, `publicationObject`, `readPublicationState`.
108
164
  - `@leitwerk-dev/coding/repository-rebase`: `ConflictEvidence`, `conflictEvidence`, `validateConflict`, `describeConflict`, `conflictKey`, `createConflictReporter`.
109
165
  - `@leitwerk-dev/coding/repository-change-state`: `RepositoryChangeState`.
110
166
 
@@ -1,3 +1,11 @@
1
+ import {
2
+ pushWasRejected,
3
+ readPublicationReceipt,
4
+ readRepositoryBinding,
5
+ repositoryBindingMatches,
6
+ savePublicationReceipt
7
+ } from "./chunk-E3DB4TIZ.js";
8
+
1
9
  // src/finalization-git-internal.ts
2
10
  import { execFileSync } from "child_process";
3
11
  import { existsSync } from "fs";
@@ -14,6 +22,11 @@ var DeterministicGitError = class extends Error {
14
22
  this.name = "DeterministicGitError";
15
23
  }
16
24
  };
25
+ var RemoteBranchChangedError = class extends DeterministicGitError {
26
+ constructor() {
27
+ super("The remote source branch changed before publication; reconcile and validate again");
28
+ }
29
+ };
17
30
  function gitConfigIdentityEnv(projectKey) {
18
31
  const env = repositoryGitSubprocessEnv(projectKey, { GIT_TERMINAL_PROMPT: "0" });
19
32
  for (const key of [
@@ -100,16 +113,63 @@ function repositoryGit(projectKey, repoPath) {
100
113
  }
101
114
  return git("rev-parse", "HEAD");
102
115
  }
103
- function pushAndVerify(branch, expectedHeadSha) {
116
+ function pushAndVerify(branch, expectedHeadSha, expectedRemoteHead) {
104
117
  const ref = `refs/heads/${branch}`;
105
118
  const pushTarget = `origin/${branch}`;
106
- checkedGit(["push", "origin", `HEAD:${ref}`], `Failed to push HEAD to '${pushTarget}'`);
107
- const remoteHead = gitOrNull("ls-remote", "--heads", "origin", ref)?.split(/\s+/)[0]?.trim();
108
- if (remoteHead !== expectedHeadSha) {
119
+ const observed = git("ls-remote", "--heads", "origin", ref).split(/\s+/)[0] || null;
120
+ const lease = expectedRemoteHead === void 0 ? observed : expectedRemoteHead;
121
+ const directory = git("rev-parse", "--absolute-git-dir");
122
+ const binding = readRepositoryBinding(git, branch);
123
+ if (binding.origin !== binding.pushOrigin)
124
+ throw new DeterministicGitError("Fetch and push endpoints must match for publication");
125
+ const previous = readPublicationReceipt(directory);
126
+ if (!repositoryBindingMatches(previous, binding))
127
+ throw new DeterministicGitError("Repository publication receipt binding changed");
128
+ const receipt = {
129
+ ...binding,
130
+ expectedHead: lease,
131
+ candidate: expectedHeadSha,
132
+ status: "attempting"
133
+ };
134
+ if (observed === expectedHeadSha) {
135
+ savePublicationReceipt(directory, { ...receipt, status: "accepted" });
136
+ return pushTarget;
137
+ }
138
+ if (previous?.status === "attempting")
139
+ throw new DeterministicGitError(
140
+ "A prior publication is unresolved; retain local work and reconcile its exact candidate first"
141
+ );
142
+ if (previous?.status === "accepted" && previous.candidate === expectedHeadSha)
143
+ throw new RemoteBranchChangedError();
144
+ if (observed !== lease) throw new RemoteBranchChangedError();
145
+ if (lease && !runGit(["merge-base", "--is-ancestor", lease, expectedHeadSha]).ok)
109
146
  throw new DeterministicGitError(
110
- `Published '${pushTarget}' resolved to '${remoteHead ?? "missing"}', expected '${expectedHeadSha}'`
147
+ "Ordinary publication must preserve the captured remote head"
111
148
  );
149
+ savePublicationReceipt(directory, receipt);
150
+ const pushed = runGit([
151
+ "push",
152
+ "--porcelain",
153
+ "--no-follow-tags",
154
+ "--recurse-submodules=no",
155
+ `--force-with-lease=${ref}:${lease ?? ""}`,
156
+ "origin",
157
+ `${expectedHeadSha}:${ref}`
158
+ ]);
159
+ if (!pushed.ok) {
160
+ if (pushWasRejected(pushed.stdout))
161
+ savePublicationReceipt(directory, { ...receipt, status: "rejected" });
162
+ const latest = git("ls-remote", "--heads", "origin", ref).split(/\s+/)[0] || null;
163
+ if (latest === expectedHeadSha) {
164
+ savePublicationReceipt(directory, { ...receipt, status: "accepted" });
165
+ return pushTarget;
166
+ }
167
+ if (latest !== lease) throw new RemoteBranchChangedError();
168
+ throw new DeterministicGitError(`Failed to push HEAD to '${pushTarget}': ${pushed.stderr}`);
112
169
  }
170
+ savePublicationReceipt(directory, { ...receipt, status: "accepted" });
171
+ const remoteHead = gitOrNull("ls-remote", "--heads", "origin", ref)?.split(/\s+/)[0]?.trim();
172
+ if (remoteHead !== expectedHeadSha) throw new RemoteBranchChangedError();
113
173
  return pushTarget;
114
174
  }
115
175
  return { runGit, git, conflictedFiles, mergeInProgress, commitIfDirty, pushAndVerify };
@@ -148,12 +208,13 @@ function commitAndPushWorkBranch(input) {
148
208
  /** @public */
149
209
  headSha,
150
210
  /** @internal */
151
- pushTarget: pushAndVerify(input.workBranch, headSha)
211
+ pushTarget: pushAndVerify(input.workBranch, headSha, input.expectedRemoteHead)
152
212
  };
153
213
  }
154
214
 
155
215
  export {
216
+ RemoteBranchChangedError,
156
217
  repositoryHasChanges,
157
218
  commitAndPushWorkBranch
158
219
  };
159
- //# sourceMappingURL=chunk-Q24RPXOA.js.map
220
+ //# sourceMappingURL=chunk-3WJRJ3Q7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/finalization-git-internal.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { trimToNull, type WorkerErrorClass } from \"@leitwerk-dev/domain\";\nimport { repositoryGitArgs, repositoryGitSubprocessEnv } from \"@leitwerk-dev/process-sdk\";\nimport { resolveGitBinary } from \"@leitwerk-dev/process-sdk/git-binary\";\nimport {\n\tpushWasRejected,\n\ttype RepositoryPublicationReceipt,\n\treadPublicationReceipt,\n\treadRepositoryBinding,\n\trepositoryBindingMatches,\n\tsavePublicationReceipt,\n} from \"./repository-publication-receipt.js\";\n\n/** @public */\nexport interface GitIdentity {\n\t/** @public */\n\tname: string;\n\t/** @public */\n\temail: string;\n}\n\n/** @internal */\nexport class DeterministicGitError extends Error {\n\t/** @internal */\n\treadonly errorClass: WorkerErrorClass = \"git_error\";\n\n\t/** @internal */\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"DeterministicGitError\";\n\t}\n}\n\n/** @internal */\nexport class RemoteBranchChangedError extends DeterministicGitError {\n\tconstructor() {\n\t\tsuper(\"The remote source branch changed before publication; reconcile and validate again\");\n\t}\n}\n\ninterface GitExecResult {\n\tok: boolean;\n\tstdout: string;\n\tstderr: string;\n}\n\nfunction gitConfigIdentityEnv(projectKey: string): NodeJS.ProcessEnv {\n\tconst env = repositoryGitSubprocessEnv(projectKey, { GIT_TERMINAL_PROMPT: \"0\" });\n\tfor (const key of [\n\t\t\"GIT_AUTHOR_NAME\",\n\t\t\"GIT_AUTHOR_EMAIL\",\n\t\t\"GIT_AUTHOR_DATE\",\n\t\t\"GIT_COMMITTER_NAME\",\n\t\t\"GIT_COMMITTER_EMAIL\",\n\t\t\"GIT_COMMITTER_DATE\",\n\t])\n\t\tdelete env[key];\n\treturn env;\n}\n\nfunction gitIdentityArgs(identity: GitIdentity): string[] {\n\tconst name = trimToNull(identity.name);\n\tconst email = trimToNull(identity.email);\n\tif (!name || !email || /[\\r\\n\\0]/.test(name) || /[\\r\\n\\0]/.test(email)) {\n\t\tthrow new DeterministicGitError(\"Git identity requires a valid name and email\");\n\t}\n\treturn [\"-c\", `user.name=${name}`, \"-c\", `user.email=${email}`];\n}\n\nfunction repositoryGit(projectKey: string, repoPath: string) {\n\tfunction runGit(args: readonly string[], identity?: GitIdentity): GitExecResult {\n\t\tconst trustedArgs = identity ? [...gitIdentityArgs(identity), ...args] : args;\n\t\ttry {\n\t\t\tconst stdout = execFileSync(resolveGitBinary(), repositoryGitArgs(trustedArgs), {\n\t\t\t\tcwd: repoPath,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tenv: gitConfigIdentityEnv(projectKey),\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t});\n\t\t\treturn { ok: true, stdout, stderr: \"\" };\n\t\t} catch (error) {\n\t\t\tconst execError = error as {\n\t\t\t\tstdout?: string | Buffer;\n\t\t\t\tstderr?: string | Buffer;\n\t\t\t\tmessage?: string;\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tstdout: execError.stdout?.toString() ?? \"\",\n\t\t\t\tstderr: execError.stderr?.toString() ?? trimToNull(execError.message) ?? \"\",\n\t\t\t};\n\t\t}\n\t}\n\n\tfunction checkedGit(\n\t\targs: readonly string[],\n\t\tfailureMessage: string,\n\t\tidentity?: GitIdentity,\n\t): string {\n\t\tconst result = runGit(args, identity);\n\t\tif (!result.ok) {\n\t\t\tconst detail = trimToNull(result.stderr) ?? trimToNull(result.stdout) ?? \"unknown git error\";\n\t\t\tthrow new DeterministicGitError(`${failureMessage}: ${detail}`);\n\t\t}\n\t\treturn result.stdout.trim();\n\t}\n\n\tfunction git(...args: string[]): string {\n\t\treturn checkedGit(args, `git ${args.join(\" \")} failed in '${repoPath}'`);\n\t}\n\n\tfunction gitOrNull(...args: string[]): string | null {\n\t\tconst result = runGit(args);\n\t\treturn result.ok ? trimToNull(result.stdout) : null;\n\t}\n\n\tfunction workingTreeStatus(): string[] {\n\t\treturn (gitOrNull(\"status\", \"--porcelain\") ?? \"\")\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((line) => line.replace(/\\s+$/, \"\"))\n\t\t\t.filter(Boolean)\n\t\t\t.map((line) => line.slice(2).trim())\n\t\t\t.filter(Boolean);\n\t}\n\n\tfunction conflictedFiles(): string[] {\n\t\treturn (gitOrNull(\"diff\", \"--name-only\", \"--diff-filter=U\") ?? \"\")\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((line) => line.trim())\n\t\t\t.filter(Boolean);\n\t}\n\n\tfunction mergeInProgress(): boolean {\n\t\tconst gitDir = git(\"rev-parse\", \"--git-dir\");\n\t\treturn existsSync(path.resolve(repoPath, gitDir, \"MERGE_HEAD\"));\n\t}\n\n\tfunction assertGitIdentity(identity: GitIdentity): void {\n\t\tif (\n\t\t\t!runGit([\"var\", \"GIT_AUTHOR_IDENT\"], identity).ok ||\n\t\t\t!runGit([\"var\", \"GIT_COMMITTER_IDENT\"], identity).ok\n\t\t) {\n\t\t\tthrow new DeterministicGitError(\"Git author/committer identity is not configured\");\n\t\t}\n\t}\n\n\tfunction commitIfDirty(commitMessage: string, identity: GitIdentity): string {\n\t\tif (workingTreeStatus().length === 0) return git(\"rev-parse\", \"HEAD\");\n\t\tassertGitIdentity(identity);\n\t\tcheckedGit([\"add\", \"--all\"], \"Failed to stage the completed change\");\n\t\tcheckedGit(\n\t\t\t[\"-c\", \"core.hooksPath=/dev/null\", \"commit\", \"--no-gpg-sign\", \"-m\", commitMessage],\n\t\t\t\"Failed to commit the completed change\",\n\t\t\tidentity,\n\t\t);\n\t\tconst remaining = workingTreeStatus();\n\t\tif (remaining.length > 0) {\n\t\t\tthrow new DeterministicGitError(`Commit left uncommitted changes: ${remaining.join(\", \")}`);\n\t\t}\n\t\treturn git(\"rev-parse\", \"HEAD\");\n\t}\n\n\tfunction pushAndVerify(\n\t\tbranch: string,\n\t\texpectedHeadSha: string,\n\t\texpectedRemoteHead?: string | null,\n\t): string {\n\t\tconst ref = `refs/heads/${branch}`;\n\t\tconst pushTarget = `origin/${branch}`;\n\t\tconst observed = git(\"ls-remote\", \"--heads\", \"origin\", ref).split(/\\s+/)[0] || null;\n\t\tconst lease = expectedRemoteHead === undefined ? observed : expectedRemoteHead;\n\t\tconst directory = git(\"rev-parse\", \"--absolute-git-dir\");\n\t\tconst binding = readRepositoryBinding(git, branch);\n\t\tif (binding.origin !== binding.pushOrigin)\n\t\t\tthrow new DeterministicGitError(\"Fetch and push endpoints must match for publication\");\n\t\tconst previous = readPublicationReceipt(directory);\n\t\tif (!repositoryBindingMatches(previous, binding))\n\t\t\tthrow new DeterministicGitError(\"Repository publication receipt binding changed\");\n\t\tconst receipt: RepositoryPublicationReceipt = {\n\t\t\t...binding,\n\t\t\texpectedHead: lease,\n\t\t\tcandidate: expectedHeadSha,\n\t\t\tstatus: \"attempting\",\n\t\t};\n\t\t// Recover a successful push whose acknowledgement was lost.\n\t\tif (observed === expectedHeadSha) {\n\t\t\tsavePublicationReceipt(directory, { ...receipt, status: \"accepted\" });\n\t\t\treturn pushTarget;\n\t\t}\n\t\tif (previous?.status === \"attempting\")\n\t\t\tthrow new DeterministicGitError(\n\t\t\t\t\"A prior publication is unresolved; retain local work and reconcile its exact candidate first\",\n\t\t\t);\n\t\tif (previous?.status === \"accepted\" && previous.candidate === expectedHeadSha)\n\t\t\tthrow new RemoteBranchChangedError();\n\t\tif (observed !== lease) throw new RemoteBranchChangedError();\n\t\tif (lease && !runGit([\"merge-base\", \"--is-ancestor\", lease, expectedHeadSha]).ok)\n\t\t\tthrow new DeterministicGitError(\n\t\t\t\t\"Ordinary publication must preserve the captured remote head\",\n\t\t\t);\n\t\tsavePublicationReceipt(directory, receipt);\n\t\tconst pushed = runGit([\n\t\t\t\"push\",\n\t\t\t\"--porcelain\",\n\t\t\t\"--no-follow-tags\",\n\t\t\t\"--recurse-submodules=no\",\n\t\t\t`--force-with-lease=${ref}:${lease ?? \"\"}`,\n\t\t\t\"origin\",\n\t\t\t`${expectedHeadSha}:${ref}`,\n\t\t]);\n\t\tif (!pushed.ok) {\n\t\t\tif (pushWasRejected(pushed.stdout))\n\t\t\t\tsavePublicationReceipt(directory, { ...receipt, status: \"rejected\" });\n\t\t\tconst latest = git(\"ls-remote\", \"--heads\", \"origin\", ref).split(/\\s+/)[0] || null;\n\t\t\tif (latest === expectedHeadSha) {\n\t\t\t\tsavePublicationReceipt(directory, { ...receipt, status: \"accepted\" });\n\t\t\t\treturn pushTarget;\n\t\t\t}\n\t\t\tif (latest !== lease) throw new RemoteBranchChangedError();\n\t\t\tthrow new DeterministicGitError(`Failed to push HEAD to '${pushTarget}': ${pushed.stderr}`);\n\t\t}\n\t\tsavePublicationReceipt(directory, { ...receipt, status: \"accepted\" });\n\t\tconst remoteHead = gitOrNull(\"ls-remote\", \"--heads\", \"origin\", ref)?.split(/\\s+/)[0]?.trim();\n\t\tif (remoteHead !== expectedHeadSha) throw new RemoteBranchChangedError();\n\t\treturn pushTarget;\n\t}\n\n\treturn { runGit, git, conflictedFiles, mergeInProgress, commitIfDirty, pushAndVerify };\n}\n\n/** Inspect staged, unstaged, untracked, and already committed unpublished changes. @public */\nexport function repositoryHasChanges(\n\trepoPath: string,\n\tbaseBranch: string,\n\tprojectKey = \"repo\",\n): boolean {\n\tconst { git } = repositoryGit(projectKey, repoPath);\n\treturn Boolean(\n\t\tgit(\"status\", \"--porcelain\") || git(\"diff\", \"--name-only\", `origin/${baseBranch}...HEAD`),\n\t);\n}\n\n/** Commit the current workspace change and non-force push only the feature branch. */\n/** @public */\nexport function commitAndPushWorkBranch(input: {\n\t/** @public */ projectKey?: string;\n\t/** @public */\n\trepoPath: string;\n\t/** @public */\n\tworkBranch: string;\n\t/** @public */\n\tcommitMessage: string;\n\t/** @public */\n\tgitIdentity: GitIdentity;\n\t/** Captured remote head; null requires branch creation. @internal */\n\texpectedRemoteHead?: string | null;\n}) {\n\tconst repoPath = path.resolve(input.repoPath);\n\tconst { runGit, git, conflictedFiles, mergeInProgress, commitIfDirty, pushAndVerify } =\n\t\trepositoryGit(input.projectKey ?? \"repo\", repoPath);\n\tif (!existsSync(repoPath) || !runGit([\"rev-parse\", \"--git-dir\"]).ok) {\n\t\tthrow new DeterministicGitError(\n\t\t\t`Repository workspace '${repoPath}' does not exist or is not a git repository`,\n\t\t);\n\t}\n\tconst branch = git(\"branch\", \"--show-current\");\n\tif (branch !== input.workBranch) {\n\t\tthrow new DeterministicGitError(\n\t\t\t`Expected '${repoPath}' to be checked out on '${input.workBranch}', but found '${branch || \"detached HEAD\"}'`,\n\t\t);\n\t}\n\tif (!trimToNull(input.commitMessage)) {\n\t\tthrow new DeterministicGitError(\"A generated commit message is required before publication\");\n\t}\n\tconst conflicts = conflictedFiles();\n\tif (mergeInProgress() || conflicts.length > 0) {\n\t\tthrow new DeterministicGitError(\n\t\t\t`Cannot publish a work branch with unresolved conflicts: ${conflicts.join(\", \") || \"merge in progress\"}`,\n\t\t);\n\t}\n\tconst headSha = commitIfDirty(input.commitMessage, input.gitIdentity);\n\treturn {\n\t\t/** @public */\n\t\theadSha,\n\t\t/** @internal */\n\t\tpushTarget: pushAndVerify(input.workBranch, headSha, input.expectedRemoteHead),\n\t};\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,kBAAyC;AAClD,SAAS,mBAAmB,kCAAkC;AAC9D,SAAS,wBAAwB;AAmB1B,IAAM,wBAAN,cAAoC,MAAM;AAAA;AAAA,EAEvC,aAA+B;AAAA;AAAA,EAGxC,YAAY,SAAiB;AAC5B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACb;AACD;AAGO,IAAM,2BAAN,cAAuC,sBAAsB;AAAA,EACnE,cAAc;AACb,UAAM,mFAAmF;AAAA,EAC1F;AACD;AAQA,SAAS,qBAAqB,YAAuC;AACpE,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