hammerkit 1.27.0-next.9 → 2.0.0-next.10

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 (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -1,59 +1,71 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getStateKey = exports.getWorkItemCacheStats = exports.getWorkCacheStats = void 0;
3
+ exports.stateKeyDigest = exports.getStateKey = exports.getWorkItemCheckoutStats = exports.getWorkItemCacheStats = exports.getWorkCacheStats = void 0;
4
4
  const calculate_checksum_1 = require("./calculate-checksum");
5
5
  const path_1 = require("path");
6
6
  const crypto_1 = require("crypto");
7
7
  const promises_1 = require("fs/promises");
8
+ const limit_1 = require("../utils/limit");
8
9
  function isExcluded(path, excluded) {
9
10
  return excluded.some((excludedPath) => path === excludedPath || path.startsWith(excludedPath + path_1.sep));
10
11
  }
11
- async function addWorkCacheStats(result, cwd, path, matcher, context, root, excluded) {
12
+ // What the walk does at once: a stat, a listing or a checksum of a file each. Awaited one
13
+ // after the other, a walk of a thousand files spent most of its time waiting for the disk.
14
+ const WALK_CONCURRENCY = 32;
15
+ async function addWorkCacheStats(result, cwd, path, matcher, context, root, excluded, limit = (0, limit_1.createLimit)(WALK_CONCURRENCY)) {
12
16
  if (isExcluded(path, excluded)) {
13
17
  return 0;
14
18
  }
19
+ // the slot is held for what this path needs of the disk, not while its children are walked
20
+ const visited = await limit(() => visitPath(cwd, path, matcher, context, root));
21
+ if (visited.type === 'file') {
22
+ // '/'-separated on every OS, so a Windows host keys a container task like Linux
23
+ result.files[visited.key] = { lastModified: visited.lastModified, checksum: visited.checksum };
24
+ return 1;
25
+ }
26
+ if (visited.type === 'directory') {
27
+ const counts = await Promise.all(visited.files.map((file) => addWorkCacheStats(result, cwd, (0, path_1.join)(path, file), matcher, context, false, excluded, limit)));
28
+ return counts.reduce((sum, count) => sum + count, 0);
29
+ }
30
+ return 0;
31
+ }
32
+ async function visitPath(cwd, path, matcher, context, root) {
33
+ const key = (0, path_1.relative)(cwd, path).split(path_1.sep).join(path_1.posix.sep);
15
34
  // On a server the files were written by a commit or a task: a link is a source as it is,
16
35
  // its target, and never followed. A `**` would walk `x -> /` through the server's disk.
17
36
  if (context.hosted) {
18
37
  const link = await (0, promises_1.lstat)(path).catch(() => undefined);
19
38
  if (link?.isSymbolicLink()) {
20
39
  if (!matcher(path)) {
21
- return 0;
40
+ return { type: 'none' };
22
41
  }
23
- const checksum = (0, crypto_1.createHash)('sha1')
42
+ const checksum = (0, crypto_1.createHash)('sha256')
24
43
  .update(`link:${await (0, promises_1.readlink)(path)}`)
25
44
  .digest('hex');
26
- result.files[(0, path_1.relative)(cwd, path).split(path_1.sep).join(path_1.posix.sep)] = { lastModified: link.mtimeMs, checksum };
27
- return 1;
45
+ return { type: 'file', key, lastModified: link.mtimeMs, checksum };
28
46
  }
29
47
  }
30
48
  const exists = await context.file.exists(path);
31
49
  if (!exists) {
32
- return 0;
50
+ return { type: 'none' };
33
51
  }
34
52
  const stats = await context.file.stats(path);
35
53
  if (stats.type === 'file') {
36
54
  if (!matcher(path)) {
37
- return 0;
55
+ return { type: 'none' };
38
56
  }
39
- const checksum = await (0, calculate_checksum_1.calculateChecksum)(context, path);
40
- // '/'-separated on every OS, so a Windows host keys a container task like Linux
41
- result.files[(0, path_1.relative)(cwd, path).split(path_1.sep).join(path_1.posix.sep)] = { lastModified: stats.lastModified, checksum };
42
- return 1;
57
+ const checksum = await (0, calculate_checksum_1.calculateChecksum)(context, path, stats);
58
+ return { type: 'file', key, lastModified: stats.lastModified, checksum };
43
59
  }
44
60
  else if (stats.type === 'directory') {
45
61
  // A glob such as src/**/*.ts never matches a directory itself, so a
46
62
  // directory is walked when files inside it could match.
47
63
  if (!root && !matcher(path, true)) {
48
- return 0;
49
- }
50
- let matched = 0;
51
- for (const file of await context.file.listFiles(path)) {
52
- matched += await addWorkCacheStats(result, cwd, (0, path_1.join)(path, file), matcher, context, false, excluded);
64
+ return { type: 'none' };
53
65
  }
54
- return matched;
66
+ return { type: 'directory', files: await context.file.listFiles(path) };
55
67
  }
56
- return 0;
68
+ return { type: 'none' };
57
69
  }
58
70
  async function getWorkCacheStats(work, environment) {
59
71
  return (await collectSourceStats(work, environment, [])).stats;
@@ -66,14 +78,14 @@ async function collectSourceStats(work, environment, excluded) {
66
78
  created: new Date(),
67
79
  files: {},
68
80
  };
69
- const unmatched = [];
70
- for (const src of work.src) {
81
+ // one limit for all its srcs, which are walked at once: an inherited src is often a large
82
+ // part of what a task hashes
83
+ const limit = (0, limit_1.createLimit)(WALK_CONCURRENCY);
84
+ const matches = await Promise.all(work.src.map((src) => {
71
85
  const matcher = (file, partial) => src.matcher(file, work.cwd, partial);
72
- const matched = await addWorkCacheStats(result, work.cwd, src.absolutePath, matcher, environment, true, excluded);
73
- if (matched === 0 && !src.inherited && !isExcluded(src.absolutePath, excluded)) {
74
- unmatched.push(src);
75
- }
76
- }
86
+ return addWorkCacheStats(result, work.cwd, src.absolutePath, matcher, environment, true, excluded, limit);
87
+ }));
88
+ const unmatched = work.src.filter((src, index) => matches[index] === 0 && !src.inherited && !isExcluded(src.absolutePath, excluded));
77
89
  return { stats: result, unmatched };
78
90
  }
79
91
  // The source stats of a task or service, leaving out everything its (transitive)
@@ -85,6 +97,13 @@ function getWorkItemCacheStats(item, environment) {
85
97
  return collectSourceStats(item.data, environment, dependencyOutputs(item));
86
98
  }
87
99
  exports.getWorkItemCacheStats = getWorkItemCacheStats;
100
+ // The source stats of a task with what its dependencies generate: on a checkout nothing ran
101
+ // in, those are the files a commit holds there, see check-key.ts.
102
+ async function getWorkItemCheckoutStats(item, environment) {
103
+ const { stats } = await collectSourceStats(item.data, environment, []);
104
+ return { stats, unmatched: (await getWorkItemCacheStats(item, environment)).unmatched };
105
+ }
106
+ exports.getWorkItemCheckoutStats = getWorkItemCheckoutStats;
88
107
  function dependencyOutputs(item) {
89
108
  const outputs = new Set();
90
109
  const visited = new Set();
@@ -113,7 +132,14 @@ function getStateKey(stats, cacheMethod) {
113
132
  contents.push(`${key}:${stats.files[key].lastModified}`);
114
133
  }
115
134
  }
116
- return (0, crypto_1.createHash)('md5').update(contents.join(',')).digest('hex');
135
+ return stateKeyDigest(contents.join(','));
117
136
  }
118
137
  exports.getStateKey = getStateKey;
138
+ // A state key is also the value of the `hammerkit.dev/state` label on Kubernetes, which
139
+ // takes at most 63 characters: the sha256 in base 36 has 50.
140
+ function stateKeyDigest(content) {
141
+ const hex = (0, crypto_1.createHash)('sha256').update(content).digest('hex');
142
+ return BigInt(`0x${hex}`).toString(36).padStart(50, '0');
143
+ }
144
+ exports.stateKeyDigest = stateKeyDigest;
119
145
  //# sourceMappingURL=get-work-cache-stats.js.map
@@ -1,12 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.storedCacheDescription = exports.getWorkTaskCacheDescription = void 0;
3
+ exports.storedCacheDescription = exports.getWorkServiceCacheIdentity = exports.getWorkTaskCacheDescription = void 0;
4
4
  const os_1 = require("os");
5
5
  const crypto_1 = require("crypto");
6
6
  const replace_env_variables_1 = require("../environment/replace-env-variables");
7
7
  const portable_path_1 = require("../planner/utils/portable-path");
8
8
  const work_secret_1 = require("../planner/work-secret");
9
9
  const claim_layout_1 = require("../kubernetes/claim-layout");
10
+ const work_service_1 = require("../planner/work-service");
11
+ const work_service_id_1 = require("../planner/work-service-id");
12
+ const work_cache_id_1 = require("../planner/work-cache-id");
10
13
  // Every path is made project-relative (portablePath) so the description, and the
11
14
  // task id hashed from it, is identical wherever the project is checked out.
12
15
  //
@@ -42,9 +45,54 @@ function getWorkTaskCacheDescription(item) {
42
45
  deps: item.deps.length > 0 ? item.deps.map((dep) => dep.id()).sort() : undefined,
43
46
  secrets: cachedSecrets.length > 0 ? cachedSecrets : undefined,
44
47
  claimLayout: (0, claim_layout_1.hasPathsEndingAlike)(item) || (0, claim_layout_1.hasOutputsFlatteningAlike)(item) ? 2 : undefined,
48
+ needs: item.needs.length > 0 ? getNeedsIdentities(item) : undefined,
45
49
  };
46
50
  }
47
51
  exports.getWorkTaskCacheDescription = getWorkTaskCacheDescription;
52
+ // `visiting` holds the services on the way here: services that need each other in a loop
53
+ // fail to plan (checkForLoop), the identity only has to come back to say so
54
+ function getNeedsIdentities(item, visiting = new Set()) {
55
+ return (item.needs
56
+ // an init task needs the service it initializes, whose identity holds the init's id
57
+ .filter((need) => !isInitOf(item, need.service))
58
+ .map((need) => visiting.has(need.service)
59
+ ? `${need.name}=loop`
60
+ : `${need.name}=${getWorkServiceCacheIdentity(need.service, visiting)}`)
61
+ .sort());
62
+ }
63
+ function isInitOf(item, service) {
64
+ return (0, work_service_1.isContainerWorkService)(service.data) && service.data.init?.task.data === item.data;
65
+ }
66
+ // Everything that makes a service what a task needing it talks to: its definition, the ids of
67
+ // the tasks it depends on and of its init task, and the services it needs in turn. The source
68
+ // of those tasks and of the service is in the state key (computeStateKey), like a dependency's.
69
+ // Not the service id, which leaves out what a service runs (getWorkServiceId).
70
+ function getWorkServiceCacheIdentity(item, visiting = new Set()) {
71
+ const service = item.data;
72
+ const definition = (0, work_service_1.isContainerWorkService)(service)
73
+ ? {
74
+ cmd: service.cmd?.cmd ?? null,
75
+ envs: (0, replace_env_variables_1.getEnvironmentVariables)(service.envs),
76
+ healthcheck: service.healthcheck?.cmd.cmd ?? null,
77
+ secrets: service.secrets
78
+ .filter((secret) => secret.cache)
79
+ .map((secret) => `${(0, work_secret_1.getPortableSecretName)(service.projectRoot, secret)}=${secret.digest()}`)
80
+ .sort(),
81
+ // as declared: arguments after -- of a run of the init leave the service as it is
82
+ init: service.init ? (0, work_cache_id_1.getDeclaredWorkTaskId)(service.init.task) : null,
83
+ }
84
+ : { namespace: service.namespace };
85
+ return (0, crypto_1.createHash)('sha256')
86
+ .update(JSON.stringify({
87
+ id: (0, work_service_id_1.getWorkServiceId)(service),
88
+ ...definition,
89
+ ports: service.ports.map((port) => `${port.hostPort ?? ''}:${port.containerPort}`).sort(),
90
+ deps: item.deps.map((dep) => dep.id()).sort(),
91
+ needs: getNeedsIdentities(item, new Set([...visiting, item])),
92
+ }))
93
+ .digest('hex');
94
+ }
95
+ exports.getWorkServiceCacheIdentity = getWorkServiceCacheIdentity;
48
96
  // The form written to disk: description.json in a cache entry (pushed to remote
49
97
  // backends, readable by everyone who can pull) and the local explain record.
50
98
  // Env is where tokens get passed, so each value is stored as a digest; the task
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.read = exports.write = void 0;
3
+ exports.readSized = exports.read = exports.write = void 0;
4
4
  const yaml_1 = require("yaml");
5
5
  async function write(filename, content, context) {
6
6
  await context.file.writeFile(filename, (0, yaml_1.stringify)(content));
7
7
  }
8
8
  exports.write = write;
9
9
  async function read(fileName, context) {
10
+ return (await readSized(fileName, context)).value;
11
+ }
12
+ exports.read = read;
13
+ // The parsed file and the bytes it took.
14
+ async function readSized(fileName, context) {
10
15
  context.status.context({ type: 'cli', name: 'hammerkit' }).write('debug', `read ${fileName} build file`);
11
16
  let content;
12
17
  try {
@@ -16,7 +21,7 @@ async function read(fileName, context) {
16
21
  throw new Error(`unable to read ${fileName}`);
17
22
  }
18
23
  try {
19
- return (0, yaml_1.parse)(content);
24
+ return { value: (0, yaml_1.parse)(content), bytes: Buffer.byteLength(content, 'utf8') };
20
25
  }
21
26
  catch (e) {
22
27
  if (e instanceof Error) {
@@ -27,5 +32,5 @@ async function read(fileName, context) {
27
32
  }
28
33
  }
29
34
  }
30
- exports.read = read;
35
+ exports.readSized = readSized;
31
36
  //# sourceMappingURL=read-build-file.js.map
@@ -6,6 +6,7 @@ const work_secret_1 = require("./work-secret");
6
6
  const work_service_1 = require("./work-service");
7
7
  const work_network_1 = require("./work-network");
8
8
  const work_cache_id_1 = require("./work-cache-id");
9
+ const portable_path_1 = require("./utils/portable-path");
9
10
  // Everything a running container of the service was created from, plus the
10
11
  // definitions of the services it needs: a dependent links to the container it
11
12
  // started with, so a recreated need means a recreated dependent too. Stored as
@@ -14,19 +15,23 @@ const work_cache_id_1 = require("./work-cache-id");
14
15
  function getServiceDefinitionHash(item) {
15
16
  const service = item.data;
16
17
  const network = (0, work_network_1.getEffectiveNetwork)(service);
18
+ const portable = (path) => (0, portable_path_1.portablePath)(service.projectRoot, path);
17
19
  const definition = {
18
20
  image: service.image,
19
21
  cmd: service.cmd?.cmd ?? null,
20
22
  shell: service.shell,
21
- workdir: service.workdir,
23
+ // where the checkout is does not count: a service run that moves to another commit runs
24
+ // from another directory beside the first, and keeps what did not change
25
+ workdir: service.workdir ? portable(service.workdir) : null,
22
26
  envs: {
23
27
  variables: service.envs.variables,
24
28
  replacements: service.envs.replacements.map((r) => [r.key, r.name, r.value]),
25
29
  },
26
30
  ports: service.ports.map((p) => `${p.hostPort ?? ''}:${p.containerPort}`),
27
- mounts: service.mounts.map((m) => `${m.localPath}:${m.containerPath}:${m.readOnly ? 'ro' : 'rw'}`),
28
- volumes: service.volumes.map((v) => `${v.name}:${v.containerPath}:${v.readOnly ? 'ro' : 'rw'}`),
29
- src: service.src.map((s) => s.absolutePath),
31
+ mounts: service.mounts.map((m) => `${portable(m.localPath)}:${m.containerPath}:${m.readOnly ? 'ro' : 'rw'}`),
32
+ // the volume of a dep's output is named by where it is, which its path says already
33
+ volumes: service.volumes.map((v) => `${v.inherited ? '' : v.name}:${portable(v.containerPath)}:${v.readOnly ? 'ro' : 'rw'}`),
34
+ src: service.src.map((s) => portable(s.absolutePath)),
30
35
  healthcheck: service.healthcheck?.cmd.cmd ?? null,
31
36
  // where secrets go, never their values: a rotated value needs a `down`
32
37
  secrets: service.secrets.map((s) => s.source.type === 'provider'
@@ -17,8 +17,10 @@ function appendWorkDependencies(workTree, referenced, item, environment, context
17
17
  }
18
18
  }
19
19
  }
20
- if (((0, work_task_1.isContainerWorkTask)(depNode.data) || (0, work_service_1.isContainerWorkService)(depNode.data)) &&
21
- ((0, work_task_1.isContainerWorkTask)(item.data) || (0, work_service_1.isContainerWorkService)(item.data))) {
20
+ // an aggregate hands on what its dependencies generate, as if what depends on it
21
+ // depended on them
22
+ if (((0, work_task_1.isContainerWorkTask)(depNode.data) || (0, work_service_1.isContainerWorkService)(depNode.data) || (0, work_task_1.isAggregateTask)(depNode.data)) &&
23
+ ((0, work_task_1.isContainerWorkTask)(item.data) || (0, work_service_1.isContainerWorkService)(item.data) || (0, work_task_1.isAggregateTask)(item.data))) {
22
24
  // the outputs of the dep's own deps too, which stay those of the task that made them
23
25
  // (on Kubernetes, they are in its claim)
24
26
  for (const generate of depNode.data.generates) {
@@ -39,7 +41,7 @@ function appendWorkDependencies(workTree, referenced, item, environment, context
39
41
  });
40
42
  }
41
43
  }
42
- else {
44
+ else if ((0, work_task_1.isWorkTask)(item.data)) {
43
45
  if (!item.data.generates.some((v) => v.volumeName === generate.volumeName)) {
44
46
  item.data.generates.push({
45
47
  volumeName: generate.volumeName,
@@ -118,6 +118,7 @@ function parseService(workTree, service, environment, context) {
118
118
  secrets: (0, work_secret_1.parseWorkSecrets)(service.cwd, context.projectRoot, service.schema.secrets, envs, environment, context.secrets, service.schema.account),
119
119
  resources: (0, work_resources_1.parseWorkResources)(service.schema.resources),
120
120
  volumeSize: service.schema.volumeSize ?? null,
121
+ restarts: service.schema.restarts ?? null,
121
122
  network: (0, work_network_1.parseWorkNetwork)(service.schema.network),
122
123
  networkCeiling: null,
123
124
  args: service.schema.args ?? null,
@@ -143,7 +144,11 @@ function appendServiceInit(workTree, service, item, environment, context) {
143
144
  task.needs[selfNeed] = { name: task.needs[selfNeed].name, service: view };
144
145
  }
145
146
  else {
146
- task.needs.push({ name: item.name, service: view });
147
+ const name = getInitNeedName(service);
148
+ if (task.needs.some((need) => need.name === name)) {
149
+ throw new Error(`${task.name} needs two services as ${name}, give one another name with name:`);
150
+ }
151
+ task.needs.push({ name, service: view });
147
152
  }
148
153
  removeRequirer(item, task.name);
149
154
  // explicit, so neither the default method nor `--cache` turns it back on
@@ -153,6 +158,18 @@ function appendServiceInit(workTree, service, item, environment, context) {
153
158
  }
154
159
  item.data.init = { task, state };
155
160
  }
161
+ // The host name the init reaches its service by: the name its task declares the
162
+ // need by, else the service's name in its own build file. Planning the task
163
+ // skips that need (it is the init's), and the full name of a service of an
164
+ // include, `services:db`, is no host name: Docker and DNS take no colon.
165
+ function getInitNeedName(service) {
166
+ const declared = service.init?.task.needs.find((need) => need.service.relativeName === service.relativeName);
167
+ if (declared) {
168
+ return declared.relativeName;
169
+ }
170
+ const prefix = service.scope.namePrefix;
171
+ return prefix.length > 0 ? service.relativeName.slice(prefix.length + 1) : service.relativeName;
172
+ }
156
173
  const initViews = new WeakMap();
157
174
  // The service itself for the view its init task needs, else the item.
158
175
  function getPlannedService(item) {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.appendWorkTask = void 0;
4
4
  const work_secret_1 = require("../work-secret");
5
+ const work_task_1 = require("../work-task");
5
6
  const parse_work_generate_1 = require("./parse-work-generate");
6
7
  const template_value_1 = require("./template-value");
7
8
  const parse_work_mounts_1 = require("./parse-work-mounts");
@@ -25,7 +26,8 @@ function appendWorkTask(workTree, cwd, referenceTask, environment, context) {
25
26
  const parsed = parseTask(cwd, referenceTask, environment, context);
26
27
  // on a server's cluster a local task runs in a tool image like a container task
27
28
  const server = workTree.environment.type === 'kubernetes' ? workTree.environment.server : undefined;
28
- const task = !server
29
+ // an aggregate runs nothing, so it needs no pod either
30
+ const task = !server || (0, work_task_1.isAggregateTask)(parsed)
29
31
  ? parsed
30
32
  : parsed.type === 'local-task'
31
33
  ? (0, job_placement_1.runInToolImage)(parsed, server, referenceTask.schema.platform)
@@ -77,7 +79,6 @@ function parseTask(cwd, task, environment, context) {
77
79
  labels: task.labels,
78
80
  caching: (0, resolve_cache_1.resolveCache)(task.schema.cache ?? null, context.caches, task.relativeName),
79
81
  shell: task.schema.shell ? (0, template_value_1.templateValue)(task.schema.shell, envs) : '/bin/sh',
80
- continuous: task.schema.continuous ?? false,
81
82
  timeout: task.schema.timeout ? (0, units_1.parseDuration)(task.schema.timeout) : null,
82
83
  secrets: (0, work_secret_1.parseWorkSecrets)(cwd, context.projectRoot, task.schema.secrets, envs, environment, context.secrets, task.schema.account),
83
84
  resources: (0, work_resources_1.parseWorkResources)(task.schema.resources),
@@ -90,10 +91,12 @@ function parseTask(cwd, task, environment, context) {
90
91
  return {
91
92
  ...baseWorkNode,
92
93
  type: 'container-task',
93
- user: (0, get_container_user_1.getContainerUser)(),
94
+ // a capability holds for root only: a task that adds some runs as its image's user
95
+ user: task.schema.capAdd?.length ? null : (0, get_container_user_1.getContainerUser)(),
94
96
  image: (0, template_value_1.templateValue)(task.schema.image, envs),
95
97
  mounts: (0, parse_work_mounts_1.parseWorkMounts)(cwd, task.schema, envs),
96
98
  volumeSize: task.schema.volumeSize ?? null,
99
+ capAdd: task.schema.capAdd ?? [],
97
100
  };
98
101
  }
99
102
  else {
@@ -107,9 +110,16 @@ function parseTask(cwd, task, environment, context) {
107
110
  throw new Error(`task ${task.relativeName}: network ${(0, work_network_1.formatNetwork)(baseWorkNode.network)} needs a container, ` +
108
111
  `hammerkit can't limit the network of a local task`);
109
112
  }
113
+ const aggregate = task.deps.length > 0 &&
114
+ task.needs.length === 0 &&
115
+ baseWorkNode.src.length === 0 &&
116
+ baseWorkNode.cmds.length === 0 &&
117
+ baseWorkNode.generates.length === 0 &&
118
+ baseWorkNode.secrets.length === 0;
110
119
  return {
111
120
  ...baseWorkNode,
112
121
  type: 'local-task',
122
+ ...(aggregate ? { aggregate } : {}),
113
123
  };
114
124
  }
115
125
  }
@@ -4,6 +4,8 @@ exports.getWorkTaskRuntime = exports.getWorkServiceRuntime = void 0;
4
4
  const work_runtime_docker_1 = require("../work-runtime-docker");
5
5
  const work_runtime_kubernetes_1 = require("../work-runtime-kubernetes");
6
6
  const work_runtime_local_1 = require("../work-runtime-local");
7
+ const work_runtime_aggregate_1 = require("../work-runtime-aggregate");
8
+ const work_task_1 = require("../work-task");
7
9
  const work_item_1 = require("../work-item");
8
10
  function getWorkServiceRuntime(workTree, service) {
9
11
  if ((0, work_item_1.isContainerWorkServiceItem)(service)) {
@@ -24,7 +26,10 @@ function getWorkServiceRuntime(workTree, service) {
24
26
  }
25
27
  exports.getWorkServiceRuntime = getWorkServiceRuntime;
26
28
  function getWorkTaskRuntime(workTree, task) {
27
- if ((0, work_item_1.isLocalWorkTaskItem)(task)) {
29
+ if ((0, work_task_1.isAggregateTask)(task.data)) {
30
+ return (0, work_runtime_aggregate_1.aggregateWorkRuntime)();
31
+ }
32
+ else if ((0, work_item_1.isLocalWorkTaskItem)(task)) {
28
33
  return (0, work_runtime_local_1.getLocalWorkRuntime)(task);
29
34
  }
30
35
  else if ((0, work_item_1.isContainerWorkTaskItem)(task)) {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.normalizePath = void 0;
3
+ exports.normalizeHostPath = exports.getHomeReference = exports.normalizePath = void 0;
4
4
  const path_1 = require("path");
5
5
  function normalizePath(cwd, pwd, path) {
6
6
  if (path.startsWith('/')) {
@@ -14,4 +14,22 @@ function normalizePath(cwd, pwd, path) {
14
14
  }
15
15
  }
16
16
  exports.normalizePath = normalizePath;
17
+ // What a path of the host starts with to name the home directory: `~` and `$HOME`, and
18
+ // `$PWD`, which in a mount has always meant the home directory, not the project it reads like
19
+ function getHomeReference(path) {
20
+ for (const reference of ['~', '$HOME']) {
21
+ if (path === reference || path.startsWith(`${reference}/`) || path.startsWith(`${reference}\\`)) {
22
+ return reference;
23
+ }
24
+ }
25
+ return path.startsWith('$PWD') ? '$PWD' : null;
26
+ }
27
+ exports.getHomeReference = getHomeReference;
28
+ // A path of the host in a mount: in the home directory when it starts with one of the
29
+ // references above, else in the directory of the build file unless it is absolute
30
+ function normalizeHostPath(cwd, home, path) {
31
+ const reference = getHomeReference(path);
32
+ return reference ? (0, path_1.join)(home, path.substring(reference.length)) : normalizePath(cwd, home, path);
33
+ }
34
+ exports.normalizeHostPath = normalizeHostPath;
17
35
  //# sourceMappingURL=normalize-path.js.map
@@ -7,6 +7,12 @@ const path_1 = require("path");
7
7
  function parseWorkMount(cwd, dir) {
8
8
  const parts = dir.split(':');
9
9
  if (parts.length === 1) {
10
+ const home = (0, normalize_path_1.getHomeReference)(dir);
11
+ if (home === '~' || home === '$HOME') {
12
+ // the container has no such directory: the same path on both sides would be one of the
13
+ // project there (`$PWD` has always been, so it stays)
14
+ throw new Error(`mount ${dir} is in the home directory, name where it goes in the container (${dir}:/path)`);
15
+ }
10
16
  return parseLocalMount(cwd, dir, dir, dir, false);
11
17
  }
12
18
  else if (parts.length === 2) {
@@ -22,7 +28,7 @@ function parseWorkMount(cwd, dir) {
22
28
  exports.parseWorkMount = parseWorkMount;
23
29
  function parseLocalMount(cwd, localPath, containerPath, mount, readOnly) {
24
30
  return {
25
- localPath: (0, normalize_path_1.normalizePath)(cwd, (0, os_1.homedir)(), localPath),
31
+ localPath: (0, normalize_path_1.normalizeHostPath)(cwd, (0, os_1.homedir)(), localPath),
26
32
  containerPath: (0, normalize_path_1.normalizePath)(cwd, cwd, containerPath),
27
33
  isFile: (0, path_1.extname)(localPath).length > 1,
28
34
  mount,
@@ -8,7 +8,10 @@ function parseWorkPort(port) {
8
8
  return { containerPort: port, hostPort: port };
9
9
  }
10
10
  else if (parts.length === 2) {
11
- return { containerPort: parsePort(parts[1], false), hostPort: parsePort(parts[0], true) };
11
+ // `0:80` is not published, as an empty host port: 0 (a free port) is for the endpoints
12
+ // of a server only
13
+ const hostPort = parsePort(parts[0], true);
14
+ return { containerPort: parsePort(parts[1], false), hostPort: hostPort === 0 ? null : hostPort };
12
15
  }
13
16
  else {
14
17
  throw new Error(`invalid port ${port}`);
@@ -5,11 +5,27 @@ function templateValue(value, envs) {
5
5
  if (!value || !envs) {
6
6
  return value;
7
7
  }
8
- let result = value;
9
- for (const [key, envValue] of Object.entries(envs.variables)) {
10
- result = result.replace(new RegExp(`\\$\\{${key}\\}|\\$${key}`, 'gi'), envValue);
8
+ // A name is matched as the text it is, in any case; when two names match the same `$`, the
9
+ // one listed first wins. One pass over the value: a value put in is not read again.
10
+ const names = Object.keys(envs.variables).filter((name) => name.length > 0);
11
+ if (names.length === 0) {
12
+ return value;
13
+ }
14
+ const values = new Map();
15
+ for (const name of names) {
16
+ const key = name.toLowerCase();
17
+ if (!values.has(key)) {
18
+ values.set(key, envs.variables[name]);
19
+ }
11
20
  }
12
- return result;
21
+ const alternatives = names.map(escapeRegExp).join('|');
22
+ const pattern = new RegExp(`\\$\\{(${alternatives})\\}|\\$(${alternatives})`, 'gi');
23
+ return value.replace(pattern, (match, braced, bare) => {
24
+ return values.get((braced ?? bare ?? '').toLowerCase()) ?? match;
25
+ });
13
26
  }
14
27
  exports.templateValue = templateValue;
28
+ function escapeRegExp(text) {
29
+ return text.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&');
30
+ }
15
31
  //# sourceMappingURL=template-value.js.map
@@ -4,6 +4,7 @@ exports.checkIfContextExists = exports.hasDependencyCycle = exports.hasNeedCycle
4
4
  const read_build_file_1 = require("../parser/read-build-file");
5
5
  const plan_work_tasks_1 = require("./utils/plan-work-tasks");
6
6
  const unreferenced_build_file_envs_1 = require("./unreferenced-build-file-envs");
7
+ const normalize_path_1 = require("./utils/normalize-path");
7
8
  async function* validate(workTree, context) {
8
9
  const cycleItems = [];
9
10
  for (const item of (0, plan_work_tasks_1.iterateWorkServices)(workTree)) {
@@ -16,6 +17,10 @@ async function* validate(workTree, context) {
16
17
  yield { type: 'warn', message: 'missing healthcheck', item: service };
17
18
  }
18
19
  for (const mount of service.mounts) {
20
+ const pwd = getPwdMountWarning(mount);
21
+ if (pwd) {
22
+ yield { type: 'warn', message: pwd, item: service };
23
+ }
19
24
  if (!(await context.file.exists(mount.localPath))) {
20
25
  yield {
21
26
  type: 'warn',
@@ -62,6 +67,12 @@ async function* validate(workTree, context) {
62
67
  item: task,
63
68
  };
64
69
  }
70
+ for (const mount of task.type === 'container-task' ? task.mounts : []) {
71
+ const pwd = getPwdMountWarning(mount);
72
+ if (pwd) {
73
+ yield { type: 'warn', message: pwd, item: task };
74
+ }
75
+ }
65
76
  for (const src of task.src) {
66
77
  if (!(await context.file.exists(src.absolutePath))) {
67
78
  yield {
@@ -146,4 +157,15 @@ async function checkIfContextExists(service, context) {
146
157
  return false;
147
158
  }
148
159
  exports.checkIfContextExists = checkIfContextExists;
160
+ // `$PWD` in a mount is the home directory, which reads like a path of the project
161
+ function getPwdMountWarning(mount) {
162
+ const source = mount.mount.split(':')[0];
163
+ if ((0, normalize_path_1.getHomeReference)(source) !== '$PWD') {
164
+ return null;
165
+ }
166
+ const rest = source.substring('$PWD'.length);
167
+ const home = rest === '' || rest.startsWith('/') || rest.startsWith('\\') ? `~${rest}` : '~/…';
168
+ return (`mount ${source} is ${mount.localPath}: $PWD in a mount is the home directory, not the project. ` +
169
+ `Write ${home} for the home directory, or a relative path for the project`);
170
+ }
149
171
  //# sourceMappingURL=validate.js.map
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readExecutions = exports.clearExecutions = exports.recordExecution = void 0;
4
+ // kept by the task, not its item: the runtime and the scheduler hold copies of the item
5
+ const executions = new WeakMap();
6
+ function recordExecution(task, startedAt, finishedAt) {
7
+ if (Number.isNaN(startedAt.getTime()) || Number.isNaN(finishedAt.getTime()) || finishedAt < startedAt) {
8
+ return;
9
+ }
10
+ let list = executions.get(task);
11
+ if (!list) {
12
+ list = [];
13
+ executions.set(task, list);
14
+ }
15
+ list.push({ startedAt, finishedAt });
16
+ }
17
+ exports.recordExecution = recordExecution;
18
+ // a task that runs again (watch) starts with none
19
+ function clearExecutions(task) {
20
+ executions.delete(task);
21
+ }
22
+ exports.clearExecutions = clearExecutions;
23
+ function readExecutions(task) {
24
+ return executions.get(task) ?? [];
25
+ }
26
+ exports.readExecutions = readExecutions;
27
+ //# sourceMappingURL=work-item-executions.js.map
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.applyNetworkCeiling = exports.formatNetwork = exports.getTcpForwards = exports.matchesHost = exports.isLimitedNetwork = exports.toNetworkSchema = exports.exceedsNetwork = exports.getEffectiveNetwork = exports.limitNetwork = exports.parseNetworkOption = exports.parseWorkNetwork = exports.OPEN_NETWORK = void 0;
4
4
  const network_schema_1 = require("../schema/network-schema");
5
+ const work_task_1 = require("./work-task");
5
6
  exports.OPEN_NETWORK = { type: 'open' };
6
7
  function parseWorkNetwork(schema) {
7
8
  if (!schema || schema === 'open') {
@@ -153,7 +154,8 @@ exports.formatNetwork = formatNetwork;
153
154
  function applyNetworkCeiling(workTree, ceiling) {
154
155
  const limit = ceiling && isLimitedNetwork(ceiling) ? ceiling : null;
155
156
  if (limit) {
156
- const local = Object.values(workTree.tasks).find((task) => task.data.type === 'local-task');
157
+ // an aggregate runs nothing, so there is nothing of it to limit
158
+ const local = Object.values(workTree.tasks).find((task) => task.data.type === 'local-task' && !(0, work_task_1.isAggregateTask)(task.data));
157
159
  if (local) {
158
160
  throw new Error(`--network ${formatNetwork(limit)} needs every task in a container, ` +
159
161
  `hammerkit can't limit the network of the local task ${local.name}`);